Skip to content

Commit

Permalink
fix #824 (#829)
Browse files Browse the repository at this point in the history
  • Loading branch information
chavacava committed May 16, 2023
1 parent ed6d9ce commit 81d85b5
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 36 deletions.
70 changes: 34 additions & 36 deletions rule/nested-structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ func (*NestedStructs) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure

walker := &lintNestedStructs{
fileAST: file.AST,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
Expand All @@ -31,47 +30,46 @@ func (*NestedStructs) Name() string {
}

type lintNestedStructs struct {
fileAST *ast.File
onFailure func(lint.Failure)
}

func (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {
switch v := n.(type) {
case *ast.TypeSpec:
_, isInterface := v.Type.(*ast.InterfaceType)
if isInterface {
return nil // do not analyze interface declarations
}
case *ast.FuncDecl:
if v.Body != nil {
ast.Walk(l, v.Body)
}
return nil
case *ast.Field:
_, isChannelField := v.Type.(*ast.ChanType)
if isChannelField {
return nil
}
if v, ok := n.(*ast.StructType); ok {
ls := &lintStruct{l.onFailure}
ast.Walk(ls, v.Fields)
}

filter := func(n ast.Node) bool {
switch n.(type) {
case *ast.StructType:
return true
default:
return false
}
}
structs := pick(v, filter, nil)
for _, s := range structs {
l.onFailure(lint.Failure{
Failure: "no nested structs are allowed",
Category: "style",
Node: s,
Confidence: 1,
})
return l
}

type lintStruct struct {
onFailure func(lint.Failure)
}

func (l *lintStruct) Visit(n ast.Node) ast.Visitor {
switch s := n.(type) {
case *ast.StructType:
l.fail(s)
return nil
case *ast.ArrayType:
if _, ok := s.Elt.(*ast.StructType); ok {
l.fail(s)
}
return nil // no need to visit (again) the field
return nil
case *ast.ChanType:
return nil
case *ast.MapType:
return nil
default:
return l
}
}

return l
func (l *lintStruct) fail(n ast.Node) {
l.onFailure(lint.Failure{
Failure: "no nested structs are allowed",
Category: "style",
Node: n,
Confidence: 1,
})
}
17 changes: 17 additions & 0 deletions testdata/nested-structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ type Quux struct {
type Quuz struct {
}

type Quiz struct {
s struct{} // MATCH /no nested structs are allowed/
}

type nestedStructInChan struct {
c chan struct {
a int
b struct{ c int } // MATCH /no nested structs are allowed/
}
}

func waldo() (s struct{ b bool }) { return s }

func fred() interface{} {
Expand Down Expand Up @@ -45,3 +56,9 @@ type issue744 struct {
type mySetInterface interface {
GetSet() map[string]struct{}
}

// issue 824
type test struct {
foo []chan struct{} // Must not match
bar map[string]struct{} // Must not match
}

0 comments on commit 81d85b5

Please sign in to comment.