Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

fix parse arrays with const length correctly #520

Merged
merged 6 commits into from Feb 24, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions mockgen/internal/tests/const_array_length/input.go
@@ -0,0 +1,8 @@
//go:generate mockgen -package const_length -destination mock.go -source input.go
fsmiamoto marked this conversation as resolved.
Show resolved Hide resolved
package const_length

const C = 2

type I interface {
F() [C]int
fsmiamoto marked this conversation as resolved.
Show resolved Hide resolved
}
48 changes: 48 additions & 0 deletions mockgen/internal/tests/const_array_length/mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion mockgen/parse.go
Expand Up @@ -410,7 +410,16 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) {
case *ast.ArrayType:
ln := -1
if v.Len != nil {
x, err := strconv.Atoi(v.Len.(*ast.BasicLit).Value)
var value string
switch val := v.Len.(type) {
case (*ast.BasicLit):
value = val.Value
case (*ast.Ident):
// when the length is a const
value = val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value
}

x, err := strconv.Atoi(value)
if err != nil {
return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err)
}
Expand Down
24 changes: 24 additions & 0 deletions mockgen/parse_test.go
Expand Up @@ -263,3 +263,27 @@ func TestParsePackageImport_FallbackMultiGoPath(t *testing.T) {
t.Errorf("expect %s, got %s", expected, pkgPath)
}
}

func TestParseArrayWithConstLength(t *testing.T) {
fs := token.NewFileSet()

file, err := parser.ParseFile(fs, "internal/tests/const_array_length/input.go", nil, 0)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

p := fileParser{
fileSet: fs,
}

pkg, err := p.parseFile("", file)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

expect := "[2]int"
got := pkg.Interfaces[0].Methods[0].Out[0].Type.String(nil, "")
if got != expect {
t.Fatalf("Expected return type %v but got %v", expect, got)
fsmiamoto marked this conversation as resolved.
Show resolved Hide resolved
}
}