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

Commit 6ff1070

Browse files
authored
fix parse arrays with const length correctly (#520)
Fixes #294
1 parent 2421472 commit 6ff1070

File tree

4 files changed

+106
-1
lines changed

4 files changed

+106
-1
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package const_length
2+
3+
//go:generate mockgen -package const_length -destination mock.go -source input.go
4+
5+
const C = 2
6+
7+
type I interface {
8+
Foo() [C]int
9+
Bar() [2]int
10+
}

mockgen/internal/tests/const_array_length/mock.go

Lines changed: 62 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mockgen/parse.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,16 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) {
410410
case *ast.ArrayType:
411411
ln := -1
412412
if v.Len != nil {
413-
x, err := strconv.Atoi(v.Len.(*ast.BasicLit).Value)
413+
var value string
414+
switch val := v.Len.(type) {
415+
case (*ast.BasicLit):
416+
value = val.Value
417+
case (*ast.Ident):
418+
// when the length is a const
419+
value = val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value
420+
}
421+
422+
x, err := strconv.Atoi(value)
414423
if err != nil {
415424
return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err)
416425
}

mockgen/parse_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,27 @@ func TestParsePackageImport_FallbackMultiGoPath(t *testing.T) {
263263
t.Errorf("expect %s, got %s", expected, pkgPath)
264264
}
265265
}
266+
267+
func TestParseArrayWithConstLength(t *testing.T) {
268+
fs := token.NewFileSet()
269+
270+
file, err := parser.ParseFile(fs, "internal/tests/const_array_length/input.go", nil, 0)
271+
if err != nil {
272+
t.Fatalf("Unexpected error: %v", err)
273+
}
274+
275+
p := fileParser{
276+
fileSet: fs,
277+
}
278+
279+
pkg, err := p.parseFile("", file)
280+
if err != nil {
281+
t.Fatalf("Unexpected error: %v", err)
282+
}
283+
284+
expect := "[2]int"
285+
got := pkg.Interfaces[0].Methods[0].Out[0].Type.String(nil, "")
286+
if got != expect {
287+
t.Fatalf("got %v; expected %v", got, expect)
288+
}
289+
}

0 commit comments

Comments
 (0)