Design a static analyzer candidate
Design a static analyzer candidate
Static analysis reports suspicious code without running that code. In x/tools/go/analysis an Analyzer defines a rule and a Run function; a driver supplies an analysis.Pass with AST files, positions and type facts. Start by designing a narrow, testable rule. The following standard-library prototype flags explicit blank assignments of a call to a local function named risky. It is intentionally not an unused-error analyzer.
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func count(src string) int { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", src, 0) if e != nil { panic(e) } info := types.Info{Uses: map[*ast.Ident]types.Object{}} pkg, e := new(types.Config).Check("p", fs, []*ast.File{f}, &info) if e != nil { panic(e) } target, ok := pkg.Scope().Lookup("risky").(*types.Func) if !ok { return 0 } n := 0 ast.Inspect(f, func(node ast.Node) bool { a, ok := node.(*ast.AssignStmt) if !ok || len(a.Lhs) != 1 || len(a.Rhs) != 1 { return true } lhs, ok := a.Lhs[0].(*ast.Ident) call, cok := a.Rhs[0].(*ast.CallExpr) if !ok || lhs.Name != "_" || !cok { return true } id, ok := call.Fun.(*ast.Ident) if ok && info.Uses[id] == target { n++ } return true }) return n}func main() { fmt.Println(count("package p; func risky()error{return nil}; func f(){_=risky()}")) fmt.Println(count("package p; func risky()error{return nil}; func f(){e:=risky();_=e}"))}The object check excludes unrelated declarations with the same spelling. The rule deliberately ignores bare calls, method calls, tuple assignments and transitive wrappers. Its diagnostic must describe exactly what it recognizes. Tests need both positive and negative examples; a rule with too many false positives will be ignored.
Expected output:
10Give a diagnostic a precise range
package main
import ( "fmt" "go/ast" "go/parser" "go/token")
func main() { src := []byte("package p; func f(){_ = 1}") fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", src, 0) if e != nil { panic(e) } ast.Inspect(f, func(n ast.Node) bool { if a, ok := n.(*ast.AssignStmt); ok { file := fs.File(a.Pos()) fmt.Println(string(src[file.Offset(a.Pos()):file.Offset(a.End())])) } return true })}An analysis.Pass can report a Diagnostic with Pos, End and Message. To integrate the prototype, put the rule into Analyzer.Run, use Pass.Files and Pass.TypesInfo, and call Pass.Report for matches. Use singlechecker.Main for a standalone driver and analysistest.Run for fixture-based expectations. The integration contract is documentation-based; x/tools is not installed as a standalone dependency here. The following practice tests a narrow syntax rule, not a full analyzer driver.
Expected output:
_ = 1External integration sketch: after selecting and pinning a compatible x/tools module in a separate analyzer module, build this driver and run it against a separate fixture package containing func f(){_=1}. Expect one diagnostic and none for _=1+2; use analysistest to assert both. This rule is intentionally narrow. Documentation-verified API shape only; not compiled or executed here.
package main
import ( "go/ast" "go/token" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/singlechecker")
var rule = &analysis.Analyzer{Name: "blankint", Doc: "reports direct blank assignments of integer literals", Run: func(pass *analysis.Pass) (any, error) { for _, f := range pass.Files { ast.Inspect(f, func(n ast.Node) bool { a, ok := n.(*ast.AssignStmt) if !ok || len(a.Lhs) != 1 || len(a.Rhs) != 1 { return true } id, ok := a.Lhs[0].(*ast.Ident) lit, lok := a.Rhs[0].(*ast.BasicLit) if ok && id.Name == "_" && lok && lit.Kind == token.INT { pass.Report(analysis.Diagnostic{Pos: a.Pos(), End: a.End(), Message: "integer literal assigned to blank identifier"}) } return true }) } return nil, nil}}
func main() { singlechecker.Main(rule) }Try it locally
Count blank assignments of integer literals, excluding other expressions: package p; func f(){_=1; _="x"; _=2+3}. Print one diagnostic count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Developer tooling 06: Design a static analyzer candidate
Check the lesson objective before moving on.
What does an analysis.Pass provide?
Why test non-matching cases?