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

Commit

Permalink
fix parse arrays with const length correctly (#520)
Browse files Browse the repository at this point in the history
Fixes #294
  • Loading branch information
fsmiamoto committed Feb 24, 2021
1 parent 2421472 commit 6ff1070
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 1 deletion.
10 changes: 10 additions & 0 deletions mockgen/internal/tests/const_array_length/input.go
@@ -0,0 +1,10 @@
package const_length

//go:generate mockgen -package const_length -destination mock.go -source input.go

const C = 2

type I interface {
Foo() [C]int
Bar() [2]int
}
62 changes: 62 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("got %v; expected %v", got, expect)
}
}

0 comments on commit 6ff1070

Please sign in to comment.