Skip to content

Commit 317429e

Browse files
fix: recognize directives within slices and maps (#138)
1 parent 71cb085 commit 317429e

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

analyzer/analyzer.go

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,21 @@ func getCompositeLitRelatedComments(stack []ast.Node, cm ast.CommentMap) []*ast.
129129
for i := len(stack) - 1; i >= 0; i-- {
130130
node := stack[i]
131131

132-
switch node.(type) {
133-
case *ast.CompositeLit, // stack[len(stack)-1]
134-
*ast.ReturnStmt, // return ...
135-
*ast.IndexExpr, // map[enum]...{...}[key]
136-
*ast.CallExpr, // myfunc(map...)
137-
*ast.UnaryExpr, // &map...
138-
*ast.AssignStmt, // variable assignment (without var keyword)
139-
*ast.DeclStmt, // var declaration, parent of *ast.GenDecl
140-
*ast.GenDecl, // var declaration, parent of *ast.ValueSpec
141-
*ast.ValueSpec, // var declaration
132+
switch tn := node.(type) {
133+
case *ast.CompositeLit:
134+
// comments on the lines prior to literal
135+
comments = append(comments, cm[node]...)
136+
// comments on the same line as literal type definition
137+
// worth noting that event "typeless" literals have a type
138+
comments = append(comments, cm[tn.Type]...)
139+
case *ast.ReturnStmt, // return ...
140+
*ast.IndexExpr, // map[enum]...{...}[key]
141+
*ast.CallExpr, // myfunc(map...)
142+
*ast.UnaryExpr, // &map...
143+
*ast.AssignStmt, // variable assignment (without var keyword)
144+
*ast.DeclStmt, // var declaration, parent of *ast.GenDecl
145+
*ast.GenDecl, // var declaration, parent of *ast.ValueSpec
146+
*ast.ValueSpec, // var declaration
142147
*ast.KeyValueExpr: // field declaration
143148
comments = append(comments, cm[node]...)
144149

analyzer/testdata/src/i/directives.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,25 @@ func shouldNotFailOnIgnoreDirective() (Test, error) {
2828
B: 0,
2929
} //exhaustruct:ignore
3030

31+
// directive in a slice with type
32+
_ = []any{
33+
Test{}, // want "i.Test is missing fields A, B, C, D"
34+
Test{}, //exhaustruct:ignore
35+
Test{}, // want "i.Test is missing fields A, B, C, D"
36+
}
37+
// directive in a slice without type
38+
_ = []Test{
39+
{}, // want "i.Test is missing fields A, B, C, D"
40+
{}, //exhaustruct:ignore
41+
{}, // want "i.Test is missing fields A, B, C, D"
42+
}
43+
// directive in a map
44+
_ = map[string]any{
45+
"a": Test{}, // want "i.Test is missing fields A, B, C, D"
46+
"b": Test{}, //exhaustruct:ignore
47+
"c": Test{}, // want "i.Test is missing fields A, B, C, D"
48+
}
49+
3150
//exhaustruct:ignore
3251
return Test{}, nil
3352
}

0 commit comments

Comments
 (0)