github.com/prysmaticlabs/prysm@v1.4.4/tools/analyzers/ineffassign/analyzer.go (about)

     1  // Package ineffassign implements a static analyzer to ensure that there are no ineffectual
     2  // assignments in source code.
     3  package ineffassign
     4  
     5  import (
     6  	"errors"
     7  	"go/ast"
     8  	"sort"
     9  
    10  	"golang.org/x/tools/go/analysis"
    11  	"golang.org/x/tools/go/analysis/passes/inspect"
    12  	"golang.org/x/tools/go/ast/inspector"
    13  )
    14  
    15  // Doc explaining the tool.
    16  const Doc = "Tool to make sure there are no ineffectual assignments in source code"
    17  
    18  // Analyzer runs static analysis.
    19  var Analyzer = &analysis.Analyzer{
    20  	Name:     "ineffassign",
    21  	Doc:      Doc,
    22  	Requires: []*analysis.Analyzer{inspect.Analyzer},
    23  	Run:      run,
    24  }
    25  
    26  func run(pass *analysis.Pass) (interface{}, error) {
    27  	insp, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
    28  	if !ok {
    29  		return nil, errors.New("analyzer is not type *inspector.Inspector")
    30  	}
    31  
    32  	nodeFilter := []ast.Node{
    33  		(*ast.File)(nil),
    34  	}
    35  	insp.Preorder(nodeFilter, func(node ast.Node) {
    36  		f, ok := node.(*ast.File)
    37  		if !ok {
    38  			return
    39  		}
    40  		bld := &builder{vars: map[*ast.Object]*variable{}}
    41  		bld.walk(f)
    42  		chk := &checker{vars: bld.vars, seen: map[*block]bool{}}
    43  		for _, b := range bld.roots {
    44  			chk.check(b)
    45  		}
    46  		sort.Sort(chk.ineff)
    47  		// Report ineffectual assignments if any.
    48  		for _, id := range chk.ineff {
    49  			if id.Name != "ctx" { // We allow ineffectual assignment to ctx (to override ctx).
    50  				pass.Reportf(id.Pos(), "ineffectual assignment to %q", id.Name)
    51  			}
    52  		}
    53  	})
    54  
    55  	return nil, nil
    56  }