1package checkers 2 3import ( 4 "go/ast" 5 6 "github.com/go-critic/go-critic/checkers/internal/astwalk" 7 "github.com/go-critic/go-critic/framework/linter" 8) 9 10func init() { 11 var info linter.CheckerInfo 12 info.Name = "switchTrue" 13 info.Tags = []string{"style"} 14 info.Summary = "Detects switch-over-bool statements that use explicit `true` tag value" 15 info.Before = ` 16switch true { 17case x > y: 18}` 19 info.After = ` 20switch { 21case x > y: 22}` 23 24 collection.AddChecker(&info, func(ctx *linter.CheckerContext) (linter.FileWalker, error) { 25 return astwalk.WalkerForStmt(&switchTrueChecker{ctx: ctx}), nil 26 }) 27} 28 29type switchTrueChecker struct { 30 astwalk.WalkHandler 31 ctx *linter.CheckerContext 32} 33 34func (c *switchTrueChecker) VisitStmt(stmt ast.Stmt) { 35 if stmt, ok := stmt.(*ast.SwitchStmt); ok { 36 if qualifiedName(stmt.Tag) == "true" { 37 c.warn(stmt) 38 } 39 } 40} 41 42func (c *switchTrueChecker) warn(cause *ast.SwitchStmt) { 43 if cause.Init == nil { 44 c.ctx.Warn(cause, "replace 'switch true {}' with 'switch {}'") 45 } else { 46 c.ctx.Warn(cause, "replace 'switch %s; true {}' with 'switch %s; {}'", 47 cause.Init, cause.Init) 48 } 49} 50