src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

sa4025.go (2141B)


      1 package sa4025
      2 
      3 import (
      4 	"fmt"
      5 	"go/ast"
      6 	"go/constant"
      7 
      8 	"honnef.co/go/tools/analysis/code"
      9 	"honnef.co/go/tools/analysis/lint"
     10 	"honnef.co/go/tools/analysis/report"
     11 	"honnef.co/go/tools/pattern"
     12 
     13 	"golang.org/x/tools/go/analysis"
     14 )
     15 
     16 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
     17 	Analyzer: &analysis.Analyzer{
     18 		Name:     "SA4025",
     19 		Run:      run,
     20 		Requires: code.RequiredAnalyzers,
     21 	},
     22 	Doc: &lint.RawDocumentation{
     23 		Title: "Integer division of literals that results in zero",
     24 		Text: `When dividing two integer constants, the result will
     25 also be an integer. Thus, a division such as \'2 / 3\' results in \'0\'.
     26 This is true for all of the following examples:
     27 
     28 	_ = 2 / 3
     29 	const _ = 2 / 3
     30 	const _ float64 = 2 / 3
     31 	_ = float64(2 / 3)
     32 
     33 Staticcheck will flag such divisions if both sides of the division are
     34 integer literals, as it is highly unlikely that the division was
     35 intended to truncate to zero. Staticcheck will not flag integer
     36 division involving named constants, to avoid noisy positives.
     37 `,
     38 		Since:    "2021.1",
     39 		Severity: lint.SeverityWarning,
     40 		MergeIf:  lint.MergeIfAny,
     41 	},
     42 })
     43 
     44 var Analyzer = SCAnalyzer.Analyzer
     45 
     46 var integerDivisionQ = pattern.MustParse(`(BinaryExpr (IntegerLiteral _) "/" (IntegerLiteral _))`)
     47 
     48 func run(pass *analysis.Pass) (any, error) {
     49 	for node := range code.Matches(pass, integerDivisionQ) {
     50 		val := constant.ToInt(pass.TypesInfo.Types[node.(ast.Expr)].Value)
     51 		if v, ok := constant.Uint64Val(val); ok && v == 0 {
     52 			report.Report(pass, node, fmt.Sprintf("the integer division '%s' results in zero", report.Render(pass, node)))
     53 		}
     54 
     55 		// TODO: we could offer a suggested fix here, but I am not
     56 		// sure what it should be. There are many options to choose
     57 		// from.
     58 
     59 		// Note: we experimented with flagging divisions that truncate
     60 		// (e.g. 4 / 3), but it ran into false positives in Go's
     61 		// 'time' package, which does this, deliberately:
     62 		//
     63 		//   unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
     64 		//
     65 		// The check also found a real bug in other code, but I don't
     66 		// think we can outright ban this kind of division.
     67 	}
     68 	return nil, nil
     69 }