github.com/Johnny2210/revive@v1.0.8-0.20210625134200-febf37ccd0f5/rule/nested-structs.go (about)

     1  package rule
     2  
     3  import (
     4  	"go/ast"
     5  
     6  	"github.com/mgechev/revive/lint"
     7  )
     8  
     9  // NestedStructs lints nested structs.
    10  type NestedStructs struct{}
    11  
    12  // Apply applies the rule to given file.
    13  func (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    14  	var failures []lint.Failure
    15  
    16  	if len(arguments) > 0 {
    17  		panic(r.Name() + " doesn't take any arguments")
    18  	}
    19  
    20  	walker := &lintNestedStructs{
    21  		fileAST: file.AST,
    22  		onFailure: func(failure lint.Failure) {
    23  			failures = append(failures, failure)
    24  		},
    25  	}
    26  
    27  	ast.Walk(walker, file.AST)
    28  
    29  	return failures
    30  }
    31  
    32  // Name returns the rule name.
    33  func (r *NestedStructs) Name() string {
    34  	return "nested-structs"
    35  }
    36  
    37  type lintNestedStructs struct {
    38  	fileAST   *ast.File
    39  	onFailure func(lint.Failure)
    40  }
    41  
    42  func (l *lintNestedStructs) Visit(n ast.Node) ast.Visitor {
    43  	switch v := n.(type) {
    44  	case *ast.FuncDecl:
    45  		if v.Body != nil {
    46  			ast.Walk(l, v.Body)
    47  		}
    48  		return nil
    49  	case *ast.Field:
    50  		if _, ok := v.Type.(*ast.StructType); ok {
    51  			l.onFailure(lint.Failure{
    52  				Failure:    "no nested structs are allowed",
    53  				Category:   "style",
    54  				Node:       v,
    55  				Confidence: 1,
    56  			})
    57  			break
    58  		}
    59  	}
    60  	return l
    61  }