Debian Codegraph @

stylecheck/st1017/st1017.go

raw
1 package st1017
2
3 import (
4 "honnef.co/go/tools/analysis/code"
5 "honnef.co/go/tools/analysis/edit"
6 "honnef.co/go/tools/analysis/facts/generated"
7 "honnef.co/go/tools/analysis/lint"
8 "honnef.co/go/tools/analysis/report"
9 "honnef.co/go/tools/pattern"
10
11 "golang.org/x/tools/go/analysis"
12 )
13
14 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
15 Analyzer: &analysis.Analyzer{
16 Name: "ST1017",
17 Run: run,
18 Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...),
19 },
20 Doc: &lint.RawDocumentation{
21 Title: `Don't use Yoda conditions`,
22 Text: `Yoda conditions are conditions of the kind \"if 42 == x\", where the
23 literal is on the left side of the comparison. These are a common
24 idiom in languages in which assignment is an expression, to avoid bugs
25 of the kind \"if (x = 42)\". In Go, which doesn't allow for this kind of
26 bug, we prefer the more idiomatic \"if x == 42\".`,
27 Since: "2019.2",
28 MergeIf: lint.MergeIfAny,
29 },
30 })
31
32 var Analyzer = SCAnalyzer.Analyzer
33
34 var (
35 checkYodaConditionsQ = pattern.MustParse(`(BinaryExpr left@(TrulyConstantExpression _) tok@(Or "==" "!=") right@(Not (TrulyConstantExpression _)))`)
36 checkYodaConditionsR = pattern.MustParse(`(BinaryExpr right tok left)`)
37 )
38
39 func run(pass *analysis.Pass) (any, error) {
40 for node, m := range code.Matches(pass, checkYodaConditionsQ) {
41 edits := code.EditMatch(pass, node, m, checkYodaConditionsR)
42 report.Report(pass, node, "don't use Yoda conditions",
43 report.FilterGenerated(),
44 report.Fixes(edit.Fix("Un-Yoda-fy", edits...)))
45 }
46 return nil, nil
47 }