github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/simple/s1006/s1006.go (about)

     1  package s1006
     2  
     3  import (
     4  	"go/ast"
     5  
     6  	"github.com/amarpal/go-tools/analysis/code"
     7  	"github.com/amarpal/go-tools/analysis/facts/generated"
     8  	"github.com/amarpal/go-tools/analysis/lint"
     9  	"github.com/amarpal/go-tools/analysis/report"
    10  
    11  	"golang.org/x/tools/go/analysis"
    12  	"golang.org/x/tools/go/analysis/passes/inspect"
    13  )
    14  
    15  var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
    16  	Analyzer: &analysis.Analyzer{
    17  		Name:     "S1006",
    18  		Run:      run,
    19  		Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer},
    20  	},
    21  	Doc: &lint.Documentation{
    22  		Title:   `Use \"for { ... }\" for infinite loops`,
    23  		Text:    `For infinite loops, using \'for { ... }\' is the most idiomatic choice.`,
    24  		Since:   "2017.1",
    25  		MergeIf: lint.MergeIfAny,
    26  	},
    27  })
    28  
    29  var Analyzer = SCAnalyzer.Analyzer
    30  
    31  func run(pass *analysis.Pass) (interface{}, error) {
    32  	fn := func(node ast.Node) {
    33  		loop := node.(*ast.ForStmt)
    34  		if loop.Init != nil || loop.Post != nil {
    35  			return
    36  		}
    37  		if !code.IsBoolConst(pass, loop.Cond) || !code.BoolConst(pass, loop.Cond) {
    38  			return
    39  		}
    40  		report.Report(pass, loop, "should use for {} instead of for true {}",
    41  			report.ShortRange(),
    42  			report.FilterGenerated())
    43  	}
    44  	code.Preorder(pass, fn, (*ast.ForStmt)(nil))
    45  	return nil, nil
    46  }