lint.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  1. package simple
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "go/constant"
  6. "go/token"
  7. "go/types"
  8. "path/filepath"
  9. "reflect"
  10. "sort"
  11. "strings"
  12. "honnef.co/go/tools/analysis/code"
  13. "honnef.co/go/tools/analysis/edit"
  14. "honnef.co/go/tools/analysis/lint"
  15. "honnef.co/go/tools/analysis/report"
  16. "honnef.co/go/tools/go/ast/astutil"
  17. "honnef.co/go/tools/go/types/typeutil"
  18. "honnef.co/go/tools/internal/passes/buildir"
  19. "honnef.co/go/tools/internal/sharedcheck"
  20. "honnef.co/go/tools/knowledge"
  21. "honnef.co/go/tools/pattern"
  22. "golang.org/x/exp/typeparams"
  23. "golang.org/x/tools/go/analysis"
  24. )
  25. var (
  26. checkSingleCaseSelectQ1 = pattern.MustParse(`
  27. (ForStmt
  28. nil nil nil
  29. select@(SelectStmt
  30. (CommClause
  31. (Or
  32. (UnaryExpr "<-" _)
  33. (AssignStmt _ _ (UnaryExpr "<-" _)))
  34. _)))`)
  35. checkSingleCaseSelectQ2 = pattern.MustParse(`(SelectStmt (CommClause _ _))`)
  36. )
  37. func CheckSingleCaseSelect(pass *analysis.Pass) (interface{}, error) {
  38. seen := map[ast.Node]struct{}{}
  39. fn := func(node ast.Node) {
  40. if m, ok := code.Match(pass, checkSingleCaseSelectQ1, node); ok {
  41. seen[m.State["select"].(ast.Node)] = struct{}{}
  42. report.Report(pass, node, "should use for range instead of for { select {} }", report.FilterGenerated())
  43. } else if _, ok := code.Match(pass, checkSingleCaseSelectQ2, node); ok {
  44. if _, ok := seen[node]; !ok {
  45. report.Report(pass, node, "should use a simple channel send/receive instead of select with a single case",
  46. report.ShortRange(),
  47. report.FilterGenerated())
  48. }
  49. }
  50. }
  51. code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.SelectStmt)(nil))
  52. return nil, nil
  53. }
  54. var (
  55. checkLoopCopyQ = pattern.MustParse(`
  56. (Or
  57. (RangeStmt
  58. key@(Ident _) value@(Ident _) ":=" src
  59. [(AssignStmt (IndexExpr dst key) "=" value)])
  60. (RangeStmt
  61. key@(Ident _) nil ":=" src
  62. [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))])
  63. (ForStmt
  64. (AssignStmt key@(Ident _) ":=" (IntegerLiteral "0"))
  65. (BinaryExpr key "<" (CallExpr (Function "len") [src]))
  66. (IncDecStmt key "++")
  67. [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]))`)
  68. )
  69. func CheckLoopCopy(pass *analysis.Pass) (interface{}, error) {
  70. // TODO revisit once range doesn't require a structural type
  71. isInvariant := func(k, v types.Object, node ast.Expr) bool {
  72. if code.MayHaveSideEffects(pass, node, nil) {
  73. return false
  74. }
  75. invariant := true
  76. ast.Inspect(node, func(node ast.Node) bool {
  77. if node, ok := node.(*ast.Ident); ok {
  78. obj := pass.TypesInfo.ObjectOf(node)
  79. if obj == k || obj == v {
  80. // don't allow loop bodies like 'a[i][i] = v'
  81. invariant = false
  82. return false
  83. }
  84. }
  85. return true
  86. })
  87. return invariant
  88. }
  89. var elType func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool)
  90. elType = func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool) {
  91. switch typ := T.Underlying().(type) {
  92. case *types.Slice:
  93. return typ.Elem(), false, false, true
  94. case *types.Array:
  95. return typ.Elem(), true, false, true
  96. case *types.Pointer:
  97. el, isArray, _, ok = elType(typ.Elem())
  98. return el, isArray, true, ok
  99. default:
  100. return nil, false, false, false
  101. }
  102. }
  103. fn := func(node ast.Node) {
  104. m, ok := code.Match(pass, checkLoopCopyQ, node)
  105. if !ok {
  106. return
  107. }
  108. src := m.State["src"].(ast.Expr)
  109. dst := m.State["dst"].(ast.Expr)
  110. k := pass.TypesInfo.ObjectOf(m.State["key"].(*ast.Ident))
  111. var v types.Object
  112. if value, ok := m.State["value"]; ok {
  113. v = pass.TypesInfo.ObjectOf(value.(*ast.Ident))
  114. }
  115. if !isInvariant(k, v, dst) {
  116. return
  117. }
  118. if !isInvariant(k, v, src) {
  119. // For example: 'for i := range foo()'
  120. return
  121. }
  122. Tsrc := pass.TypesInfo.TypeOf(src)
  123. Tdst := pass.TypesInfo.TypeOf(dst)
  124. TsrcElem, TsrcArray, TsrcPointer, ok := elType(Tsrc)
  125. if !ok {
  126. return
  127. }
  128. if TsrcPointer {
  129. Tsrc = Tsrc.Underlying().(*types.Pointer).Elem()
  130. }
  131. TdstElem, TdstArray, TdstPointer, ok := elType(Tdst)
  132. if !ok {
  133. return
  134. }
  135. if TdstPointer {
  136. Tdst = Tdst.Underlying().(*types.Pointer).Elem()
  137. }
  138. if !types.Identical(TsrcElem, TdstElem) {
  139. return
  140. }
  141. if TsrcArray && TdstArray && types.Identical(Tsrc, Tdst) {
  142. if TsrcPointer {
  143. src = &ast.StarExpr{
  144. X: src,
  145. }
  146. }
  147. if TdstPointer {
  148. dst = &ast.StarExpr{
  149. X: dst,
  150. }
  151. }
  152. r := &ast.AssignStmt{
  153. Lhs: []ast.Expr{dst},
  154. Rhs: []ast.Expr{src},
  155. Tok: token.ASSIGN,
  156. }
  157. report.Report(pass, node, "should copy arrays using assignment instead of using a loop",
  158. report.FilterGenerated(),
  159. report.ShortRange(),
  160. report.Fixes(edit.Fix("replace loop with assignment", edit.ReplaceWithNode(pass.Fset, node, r))))
  161. } else {
  162. opts := []report.Option{
  163. report.ShortRange(),
  164. report.FilterGenerated(),
  165. }
  166. tv, err := types.Eval(pass.Fset, pass.Pkg, node.Pos(), "copy")
  167. if err == nil && tv.IsBuiltin() {
  168. src := m.State["src"].(ast.Expr)
  169. if TsrcArray {
  170. src = &ast.SliceExpr{
  171. X: src,
  172. }
  173. }
  174. dst := m.State["dst"].(ast.Expr)
  175. if TdstArray {
  176. dst = &ast.SliceExpr{
  177. X: dst,
  178. }
  179. }
  180. r := &ast.CallExpr{
  181. Fun: &ast.Ident{Name: "copy"},
  182. Args: []ast.Expr{dst, src},
  183. }
  184. opts = append(opts, report.Fixes(edit.Fix("replace loop with call to copy()", edit.ReplaceWithNode(pass.Fset, node, r))))
  185. }
  186. report.Report(pass, node, "should use copy() instead of a loop", opts...)
  187. }
  188. }
  189. code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil))
  190. return nil, nil
  191. }
  192. func CheckIfBoolCmp(pass *analysis.Pass) (interface{}, error) {
  193. fn := func(node ast.Node) {
  194. if code.IsInTest(pass, node) {
  195. return
  196. }
  197. expr := node.(*ast.BinaryExpr)
  198. if expr.Op != token.EQL && expr.Op != token.NEQ {
  199. return
  200. }
  201. x := code.IsBoolConst(pass, expr.X)
  202. y := code.IsBoolConst(pass, expr.Y)
  203. if !x && !y {
  204. return
  205. }
  206. var other ast.Expr
  207. var val bool
  208. if x {
  209. val = code.BoolConst(pass, expr.X)
  210. other = expr.Y
  211. } else {
  212. val = code.BoolConst(pass, expr.Y)
  213. other = expr.X
  214. }
  215. ok := typeutil.All(pass.TypesInfo.TypeOf(other), func(term *typeparams.Term) bool {
  216. basic, ok := term.Type().Underlying().(*types.Basic)
  217. return ok && basic.Kind() == types.Bool
  218. })
  219. if !ok {
  220. return
  221. }
  222. op := ""
  223. if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) {
  224. op = "!"
  225. }
  226. r := op + report.Render(pass, other)
  227. l1 := len(r)
  228. r = strings.TrimLeft(r, "!")
  229. if (l1-len(r))%2 == 1 {
  230. r = "!" + r
  231. }
  232. report.Report(pass, expr, fmt.Sprintf("should omit comparison to bool constant, can be simplified to %s", r),
  233. report.FilterGenerated(),
  234. report.Fixes(edit.Fix("simplify bool comparison", edit.ReplaceWithString(expr, r))))
  235. }
  236. code.Preorder(pass, fn, (*ast.BinaryExpr)(nil))
  237. return nil, nil
  238. }
  239. var (
  240. checkBytesBufferConversionsQ = pattern.MustParse(`(CallExpr _ [(CallExpr sel@(SelectorExpr recv _) [])])`)
  241. checkBytesBufferConversionsRs = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "String")) [])`)
  242. checkBytesBufferConversionsRb = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "Bytes")) [])`)
  243. )
  244. func CheckBytesBufferConversions(pass *analysis.Pass) (interface{}, error) {
  245. if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" {
  246. // The bytes package can use itself however it wants
  247. return nil, nil
  248. }
  249. fn := func(node ast.Node, stack []ast.Node) {
  250. m, ok := code.Match(pass, checkBytesBufferConversionsQ, node)
  251. if !ok {
  252. return
  253. }
  254. call := node.(*ast.CallExpr)
  255. sel := m.State["sel"].(*ast.SelectorExpr)
  256. typ := pass.TypesInfo.TypeOf(call.Fun)
  257. if typ == types.Universe.Lookup("string").Type() && code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).Bytes") {
  258. if _, ok := stack[len(stack)-2].(*ast.IndexExpr); ok {
  259. // Don't flag m[string(buf.Bytes())] – thanks to a
  260. // compiler optimization, this is actually faster than
  261. // m[buf.String()]
  262. return
  263. }
  264. report.Report(pass, call, fmt.Sprintf("should use %v.String() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)),
  265. report.FilterGenerated(),
  266. report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRs, m.State))))
  267. } else if typ, ok := typ.(*types.Slice); ok && typ.Elem() == types.Universe.Lookup("byte").Type() && code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).String") {
  268. report.Report(pass, call, fmt.Sprintf("should use %v.Bytes() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)),
  269. report.FilterGenerated(),
  270. report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRb, m.State))))
  271. }
  272. }
  273. code.PreorderStack(pass, fn, (*ast.CallExpr)(nil))
  274. return nil, nil
  275. }
  276. func CheckStringsContains(pass *analysis.Pass) (interface{}, error) {
  277. // map of value to token to bool value
  278. allowed := map[int64]map[token.Token]bool{
  279. -1: {token.GTR: true, token.NEQ: true, token.EQL: false},
  280. 0: {token.GEQ: true, token.LSS: false},
  281. }
  282. fn := func(node ast.Node) {
  283. expr := node.(*ast.BinaryExpr)
  284. switch expr.Op {
  285. case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL:
  286. default:
  287. return
  288. }
  289. value, ok := code.ExprToInt(pass, expr.Y)
  290. if !ok {
  291. return
  292. }
  293. allowedOps, ok := allowed[value]
  294. if !ok {
  295. return
  296. }
  297. b, ok := allowedOps[expr.Op]
  298. if !ok {
  299. return
  300. }
  301. call, ok := expr.X.(*ast.CallExpr)
  302. if !ok {
  303. return
  304. }
  305. sel, ok := call.Fun.(*ast.SelectorExpr)
  306. if !ok {
  307. return
  308. }
  309. pkgIdent, ok := sel.X.(*ast.Ident)
  310. if !ok {
  311. return
  312. }
  313. funIdent := sel.Sel
  314. if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" {
  315. return
  316. }
  317. var r ast.Expr
  318. switch funIdent.Name {
  319. case "IndexRune":
  320. r = &ast.SelectorExpr{
  321. X: pkgIdent,
  322. Sel: &ast.Ident{Name: "ContainsRune"},
  323. }
  324. case "IndexAny":
  325. r = &ast.SelectorExpr{
  326. X: pkgIdent,
  327. Sel: &ast.Ident{Name: "ContainsAny"},
  328. }
  329. case "Index":
  330. r = &ast.SelectorExpr{
  331. X: pkgIdent,
  332. Sel: &ast.Ident{Name: "Contains"},
  333. }
  334. default:
  335. return
  336. }
  337. r = &ast.CallExpr{
  338. Fun: r,
  339. Args: call.Args,
  340. }
  341. if !b {
  342. r = &ast.UnaryExpr{
  343. Op: token.NOT,
  344. X: r,
  345. }
  346. }
  347. report.Report(pass, node, fmt.Sprintf("should use %s instead", report.Render(pass, r)),
  348. report.FilterGenerated(),
  349. report.Fixes(edit.Fix(fmt.Sprintf("simplify use of %s", report.Render(pass, call.Fun)), edit.ReplaceWithNode(pass.Fset, node, r))))
  350. }
  351. code.Preorder(pass, fn, (*ast.BinaryExpr)(nil))
  352. return nil, nil
  353. }
  354. var (
  355. checkBytesCompareQ = pattern.MustParse(`(BinaryExpr (CallExpr (Function "bytes.Compare") args) op@(Or "==" "!=") (IntegerLiteral "0"))`)
  356. checkBytesCompareRe = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args)`)
  357. checkBytesCompareRn = pattern.MustParse(`(UnaryExpr "!" (CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args))`)
  358. )
  359. func CheckBytesCompare(pass *analysis.Pass) (interface{}, error) {
  360. if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" {
  361. // the bytes package is free to use bytes.Compare as it sees fit
  362. return nil, nil
  363. }
  364. fn := func(node ast.Node) {
  365. m, ok := code.Match(pass, checkBytesCompareQ, node)
  366. if !ok {
  367. return
  368. }
  369. args := report.RenderArgs(pass, m.State["args"].([]ast.Expr))
  370. prefix := ""
  371. if m.State["op"].(token.Token) == token.NEQ {
  372. prefix = "!"
  373. }
  374. var fix analysis.SuggestedFix
  375. switch tok := m.State["op"].(token.Token); tok {
  376. case token.EQL:
  377. fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRe, m.State))
  378. case token.NEQ:
  379. fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRn, m.State))
  380. default:
  381. panic(fmt.Sprintf("unexpected token %v", tok))
  382. }
  383. report.Report(pass, node, fmt.Sprintf("should use %sbytes.Equal(%s) instead", prefix, args), report.FilterGenerated(), report.Fixes(fix))
  384. }
  385. code.Preorder(pass, fn, (*ast.BinaryExpr)(nil))
  386. return nil, nil
  387. }
  388. func CheckForTrue(pass *analysis.Pass) (interface{}, error) {
  389. fn := func(node ast.Node) {
  390. loop := node.(*ast.ForStmt)
  391. if loop.Init != nil || loop.Post != nil {
  392. return
  393. }
  394. if !code.IsBoolConst(pass, loop.Cond) || !code.BoolConst(pass, loop.Cond) {
  395. return
  396. }
  397. report.Report(pass, loop, "should use for {} instead of for true {}",
  398. report.ShortRange(),
  399. report.FilterGenerated())
  400. }
  401. code.Preorder(pass, fn, (*ast.ForStmt)(nil))
  402. return nil, nil
  403. }
  404. func CheckRegexpRaw(pass *analysis.Pass) (interface{}, error) {
  405. fn := func(node ast.Node) {
  406. call := node.(*ast.CallExpr)
  407. if !code.IsCallToAny(pass, call, "regexp.MustCompile", "regexp.Compile") {
  408. return
  409. }
  410. sel, ok := call.Fun.(*ast.SelectorExpr)
  411. if !ok {
  412. return
  413. }
  414. lit, ok := call.Args[knowledge.Arg("regexp.Compile.expr")].(*ast.BasicLit)
  415. if !ok {
  416. // TODO(dominikh): support string concat, maybe support constants
  417. return
  418. }
  419. if lit.Kind != token.STRING {
  420. // invalid function call
  421. return
  422. }
  423. if lit.Value[0] != '"' {
  424. // already a raw string
  425. return
  426. }
  427. val := lit.Value
  428. if !strings.Contains(val, `\\`) {
  429. return
  430. }
  431. if strings.Contains(val, "`") {
  432. return
  433. }
  434. bs := false
  435. for _, c := range val {
  436. if !bs && c == '\\' {
  437. bs = true
  438. continue
  439. }
  440. if bs && c == '\\' {
  441. bs = false
  442. continue
  443. }
  444. if bs {
  445. // backslash followed by non-backslash -> escape sequence
  446. return
  447. }
  448. }
  449. report.Report(pass, call, fmt.Sprintf("should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name), report.FilterGenerated())
  450. }
  451. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  452. return nil, nil
  453. }
  454. var (
  455. checkIfReturnQIf = pattern.MustParse(`(IfStmt nil cond [(ReturnStmt [ret@(Builtin (Or "true" "false"))])] nil)`)
  456. checkIfReturnQRet = pattern.MustParse(`(ReturnStmt [ret@(Builtin (Or "true" "false"))])`)
  457. )
  458. func CheckIfReturn(pass *analysis.Pass) (interface{}, error) {
  459. fn := func(node ast.Node) {
  460. block := node.(*ast.BlockStmt)
  461. l := len(block.List)
  462. if l < 2 {
  463. return
  464. }
  465. n1, n2 := block.List[l-2], block.List[l-1]
  466. if len(block.List) >= 3 {
  467. if _, ok := block.List[l-3].(*ast.IfStmt); ok {
  468. // Do not flag a series of if statements
  469. return
  470. }
  471. }
  472. m1, ok := code.Match(pass, checkIfReturnQIf, n1)
  473. if !ok {
  474. return
  475. }
  476. m2, ok := code.Match(pass, checkIfReturnQRet, n2)
  477. if !ok {
  478. return
  479. }
  480. if op, ok := m1.State["cond"].(*ast.BinaryExpr); ok {
  481. switch op.Op {
  482. case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ:
  483. default:
  484. return
  485. }
  486. }
  487. ret1 := m1.State["ret"].(*ast.Ident)
  488. ret2 := m2.State["ret"].(*ast.Ident)
  489. if ret1.Name == ret2.Name {
  490. // we want the function to return true and false, not the
  491. // same value both times.
  492. return
  493. }
  494. cond := m1.State["cond"].(ast.Expr)
  495. origCond := cond
  496. if ret1.Name == "false" {
  497. cond = negate(cond)
  498. }
  499. report.Report(pass, n1,
  500. fmt.Sprintf("should use 'return %s' instead of 'if %s { return %s }; return %s'",
  501. report.Render(pass, cond),
  502. report.Render(pass, origCond), report.Render(pass, ret1), report.Render(pass, ret2)),
  503. report.FilterGenerated())
  504. }
  505. code.Preorder(pass, fn, (*ast.BlockStmt)(nil))
  506. return nil, nil
  507. }
  508. func negate(expr ast.Expr) ast.Expr {
  509. switch expr := expr.(type) {
  510. case *ast.BinaryExpr:
  511. out := *expr
  512. switch expr.Op {
  513. case token.EQL:
  514. out.Op = token.NEQ
  515. case token.LSS:
  516. out.Op = token.GEQ
  517. case token.GTR:
  518. out.Op = token.LEQ
  519. case token.NEQ:
  520. out.Op = token.EQL
  521. case token.LEQ:
  522. out.Op = token.GTR
  523. case token.GEQ:
  524. out.Op = token.LSS
  525. }
  526. return &out
  527. case *ast.Ident, *ast.CallExpr, *ast.IndexExpr, *ast.StarExpr:
  528. return &ast.UnaryExpr{
  529. Op: token.NOT,
  530. X: expr,
  531. }
  532. case *ast.UnaryExpr:
  533. if expr.Op == token.NOT {
  534. return expr.X
  535. }
  536. return &ast.UnaryExpr{
  537. Op: token.NOT,
  538. X: expr,
  539. }
  540. default:
  541. return &ast.UnaryExpr{
  542. Op: token.NOT,
  543. X: &ast.ParenExpr{
  544. X: expr,
  545. },
  546. }
  547. }
  548. }
  549. // CheckRedundantNilCheckWithLen checks for the following redundant nil-checks:
  550. //
  551. // if x == nil || len(x) == 0 {}
  552. // if x != nil && len(x) != 0 {}
  553. // if x != nil && len(x) == N {} (where N != 0)
  554. // if x != nil && len(x) > N {}
  555. // if x != nil && len(x) >= N {} (where N != 0)
  556. //
  557. func CheckRedundantNilCheckWithLen(pass *analysis.Pass) (interface{}, error) {
  558. isConstZero := func(expr ast.Expr) (isConst bool, isZero bool) {
  559. _, ok := expr.(*ast.BasicLit)
  560. if ok {
  561. return true, code.IsIntegerLiteral(pass, expr, constant.MakeInt64(0))
  562. }
  563. id, ok := expr.(*ast.Ident)
  564. if !ok {
  565. return false, false
  566. }
  567. c, ok := pass.TypesInfo.ObjectOf(id).(*types.Const)
  568. if !ok {
  569. return false, false
  570. }
  571. return true, c.Val().Kind() == constant.Int && c.Val().String() == "0"
  572. }
  573. fn := func(node ast.Node) {
  574. // check that expr is "x || y" or "x && y"
  575. expr := node.(*ast.BinaryExpr)
  576. if expr.Op != token.LOR && expr.Op != token.LAND {
  577. return
  578. }
  579. eqNil := expr.Op == token.LOR
  580. // check that x is "xx == nil" or "xx != nil"
  581. x, ok := expr.X.(*ast.BinaryExpr)
  582. if !ok {
  583. return
  584. }
  585. if eqNil && x.Op != token.EQL {
  586. return
  587. }
  588. if !eqNil && x.Op != token.NEQ {
  589. return
  590. }
  591. xx, ok := x.X.(*ast.Ident)
  592. if !ok {
  593. return
  594. }
  595. if !code.IsNil(pass, x.Y) {
  596. return
  597. }
  598. // check that y is "len(xx) == 0" or "len(xx) ... "
  599. y, ok := expr.Y.(*ast.BinaryExpr)
  600. if !ok {
  601. return
  602. }
  603. if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0
  604. return
  605. }
  606. yx, ok := y.X.(*ast.CallExpr)
  607. if !ok {
  608. return
  609. }
  610. yxFun, ok := yx.Fun.(*ast.Ident)
  611. if !ok || yxFun.Name != "len" || len(yx.Args) != 1 {
  612. return
  613. }
  614. yxArg, ok := yx.Args[knowledge.Arg("len.v")].(*ast.Ident)
  615. if !ok {
  616. return
  617. }
  618. if yxArg.Name != xx.Name {
  619. return
  620. }
  621. if eqNil && !code.IsIntegerLiteral(pass, y.Y, constant.MakeInt64(0)) { // must be len(x) == *0*
  622. return
  623. }
  624. if !eqNil {
  625. isConst, isZero := isConstZero(y.Y)
  626. if !isConst {
  627. return
  628. }
  629. switch y.Op {
  630. case token.EQL:
  631. // avoid false positive for "xx != nil && len(xx) == 0"
  632. if isZero {
  633. return
  634. }
  635. case token.GEQ:
  636. // avoid false positive for "xx != nil && len(xx) >= 0"
  637. if isZero {
  638. return
  639. }
  640. case token.NEQ:
  641. // avoid false positive for "xx != nil && len(xx) != <non-zero>"
  642. if !isZero {
  643. return
  644. }
  645. case token.GTR:
  646. // ok
  647. default:
  648. return
  649. }
  650. }
  651. // finally check that xx type is one of array, slice, map or chan
  652. // this is to prevent false positive in case if xx is a pointer to an array
  653. typ := pass.TypesInfo.TypeOf(xx)
  654. ok = typeutil.All(typ, func(term *typeparams.Term) bool {
  655. switch term.Type().Underlying().(type) {
  656. case *types.Slice:
  657. return true
  658. case *types.Map:
  659. return true
  660. case *types.Chan:
  661. return true
  662. case *types.Pointer:
  663. return false
  664. case *typeparams.TypeParam:
  665. return false
  666. default:
  667. lint.ExhaustiveTypeSwitch(term.Type().Underlying())
  668. return false
  669. }
  670. })
  671. if !ok {
  672. return
  673. }
  674. report.Report(pass, expr, fmt.Sprintf("should omit nil check; len() for %s is defined as zero", typ), report.FilterGenerated())
  675. }
  676. code.Preorder(pass, fn, (*ast.BinaryExpr)(nil))
  677. return nil, nil
  678. }
  679. var checkSlicingQ = pattern.MustParse(`(SliceExpr x@(Object _) low (CallExpr (Builtin "len") [x]) nil)`)
  680. func CheckSlicing(pass *analysis.Pass) (interface{}, error) {
  681. fn := func(node ast.Node) {
  682. if _, ok := code.Match(pass, checkSlicingQ, node); ok {
  683. expr := node.(*ast.SliceExpr)
  684. report.Report(pass, expr.High,
  685. "should omit second index in slice, s[a:len(s)] is identical to s[a:]",
  686. report.FilterGenerated(),
  687. report.Fixes(edit.Fix("simplify slice expression", edit.Delete(expr.High))))
  688. }
  689. }
  690. code.Preorder(pass, fn, (*ast.SliceExpr)(nil))
  691. return nil, nil
  692. }
  693. func refersTo(pass *analysis.Pass, expr ast.Expr, ident types.Object) bool {
  694. found := false
  695. fn := func(node ast.Node) bool {
  696. ident2, ok := node.(*ast.Ident)
  697. if !ok {
  698. return true
  699. }
  700. if ident == pass.TypesInfo.ObjectOf(ident2) {
  701. found = true
  702. return false
  703. }
  704. return true
  705. }
  706. ast.Inspect(expr, fn)
  707. return found
  708. }
  709. var checkLoopAppendQ = pattern.MustParse(`
  710. (RangeStmt
  711. (Ident "_")
  712. val@(Object _)
  713. _
  714. x
  715. [(AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs val])])]) `)
  716. func CheckLoopAppend(pass *analysis.Pass) (interface{}, error) {
  717. fn := func(node ast.Node) {
  718. m, ok := code.Match(pass, checkLoopAppendQ, node)
  719. if !ok {
  720. return
  721. }
  722. val := m.State["val"].(types.Object)
  723. if refersTo(pass, m.State["lhs"].(ast.Expr), val) {
  724. return
  725. }
  726. src := pass.TypesInfo.TypeOf(m.State["x"].(ast.Expr))
  727. dst := pass.TypesInfo.TypeOf(m.State["lhs"].(ast.Expr))
  728. if !types.Identical(src, dst) {
  729. return
  730. }
  731. r := &ast.AssignStmt{
  732. Lhs: []ast.Expr{m.State["lhs"].(ast.Expr)},
  733. Tok: token.ASSIGN,
  734. Rhs: []ast.Expr{
  735. &ast.CallExpr{
  736. Fun: &ast.Ident{Name: "append"},
  737. Args: []ast.Expr{
  738. m.State["lhs"].(ast.Expr),
  739. m.State["x"].(ast.Expr),
  740. },
  741. Ellipsis: 1,
  742. },
  743. },
  744. }
  745. report.Report(pass, node, fmt.Sprintf("should replace loop with %s", report.Render(pass, r)),
  746. report.ShortRange(),
  747. report.FilterGenerated(),
  748. report.Fixes(edit.Fix("replace loop with call to append", edit.ReplaceWithNode(pass.Fset, node, r))))
  749. }
  750. code.Preorder(pass, fn, (*ast.RangeStmt)(nil))
  751. return nil, nil
  752. }
  753. var (
  754. checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Function "time.Now") []) (Function "(time.Time).Sub")) [arg])`)
  755. checkTimeSinceR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Since")) [arg])`)
  756. )
  757. func CheckTimeSince(pass *analysis.Pass) (interface{}, error) {
  758. fn := func(node ast.Node) {
  759. if _, edits, ok := code.MatchAndEdit(pass, checkTimeSinceQ, checkTimeSinceR, node); ok {
  760. report.Report(pass, node, "should use time.Since instead of time.Now().Sub",
  761. report.FilterGenerated(),
  762. report.Fixes(edit.Fix("replace with call to time.Since", edits...)))
  763. }
  764. }
  765. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  766. return nil, nil
  767. }
  768. var (
  769. checkTimeUntilQ = pattern.MustParse(`(CallExpr (Function "(time.Time).Sub") [(CallExpr (Function "time.Now") [])])`)
  770. checkTimeUntilR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Until")) [arg])`)
  771. )
  772. func CheckTimeUntil(pass *analysis.Pass) (interface{}, error) {
  773. if !code.IsGoVersion(pass, 8) {
  774. return nil, nil
  775. }
  776. fn := func(node ast.Node) {
  777. if _, ok := code.Match(pass, checkTimeUntilQ, node); ok {
  778. if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok {
  779. r := pattern.NodeToAST(checkTimeUntilR.Root, map[string]interface{}{"arg": sel.X}).(ast.Node)
  780. report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())",
  781. report.FilterGenerated(),
  782. report.Fixes(edit.Fix("replace with call to time.Until", edit.ReplaceWithNode(pass.Fset, node, r))))
  783. } else {
  784. report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())", report.FilterGenerated())
  785. }
  786. }
  787. }
  788. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  789. return nil, nil
  790. }
  791. var (
  792. checkUnnecessaryBlankQ1 = pattern.MustParse(`
  793. (AssignStmt
  794. [_ (Ident "_")]
  795. _
  796. (Or
  797. (IndexExpr _ _)
  798. (UnaryExpr "<-" _))) `)
  799. checkUnnecessaryBlankQ2 = pattern.MustParse(`
  800. (AssignStmt
  801. (Ident "_") _ recv@(UnaryExpr "<-" _))`)
  802. )
  803. func CheckUnnecessaryBlank(pass *analysis.Pass) (interface{}, error) {
  804. fn1 := func(node ast.Node) {
  805. if _, ok := code.Match(pass, checkUnnecessaryBlankQ1, node); ok {
  806. r := *node.(*ast.AssignStmt)
  807. r.Lhs = r.Lhs[0:1]
  808. report.Report(pass, node, "unnecessary assignment to the blank identifier",
  809. report.FilterGenerated(),
  810. report.Fixes(edit.Fix("remove assignment to blank identifier", edit.ReplaceWithNode(pass.Fset, node, &r))))
  811. } else if m, ok := code.Match(pass, checkUnnecessaryBlankQ2, node); ok {
  812. report.Report(pass, node, "unnecessary assignment to the blank identifier",
  813. report.FilterGenerated(),
  814. report.Fixes(edit.Fix("simplify channel receive operation", edit.ReplaceWithNode(pass.Fset, node, m.State["recv"].(ast.Node)))))
  815. }
  816. }
  817. fn3 := func(node ast.Node) {
  818. rs := node.(*ast.RangeStmt)
  819. // for _
  820. if rs.Value == nil && astutil.IsBlank(rs.Key) {
  821. report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier",
  822. report.FilterGenerated(),
  823. report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1}))))
  824. }
  825. // for _, _
  826. if astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) {
  827. // FIXME we should mark both key and value
  828. report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier",
  829. report.FilterGenerated(),
  830. report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1}))))
  831. }
  832. // for x, _
  833. if !astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) {
  834. report.Report(pass, rs.Value, "unnecessary assignment to the blank identifier",
  835. report.FilterGenerated(),
  836. report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.End(), rs.Value.End()}))))
  837. }
  838. }
  839. code.Preorder(pass, fn1, (*ast.AssignStmt)(nil))
  840. if code.IsGoVersion(pass, 4) {
  841. code.Preorder(pass, fn3, (*ast.RangeStmt)(nil))
  842. }
  843. return nil, nil
  844. }
  845. func CheckSimplerStructConversion(pass *analysis.Pass) (interface{}, error) {
  846. // TODO(dh): support conversions between type parameters
  847. fn := func(node ast.Node, stack []ast.Node) {
  848. if unary, ok := stack[len(stack)-2].(*ast.UnaryExpr); ok && unary.Op == token.AND {
  849. // Do not suggest type conversion between pointers
  850. return
  851. }
  852. lit := node.(*ast.CompositeLit)
  853. typ1, _ := pass.TypesInfo.TypeOf(lit.Type).(*types.Named)
  854. if typ1 == nil {
  855. return
  856. }
  857. s1, ok := typ1.Underlying().(*types.Struct)
  858. if !ok {
  859. return
  860. }
  861. var typ2 *types.Named
  862. var ident *ast.Ident
  863. getSelType := func(expr ast.Expr) (types.Type, *ast.Ident, bool) {
  864. sel, ok := expr.(*ast.SelectorExpr)
  865. if !ok {
  866. return nil, nil, false
  867. }
  868. ident, ok := sel.X.(*ast.Ident)
  869. if !ok {
  870. return nil, nil, false
  871. }
  872. typ := pass.TypesInfo.TypeOf(sel.X)
  873. return typ, ident, typ != nil
  874. }
  875. if len(lit.Elts) == 0 {
  876. return
  877. }
  878. if s1.NumFields() != len(lit.Elts) {
  879. return
  880. }
  881. for i, elt := range lit.Elts {
  882. var t types.Type
  883. var id *ast.Ident
  884. var ok bool
  885. switch elt := elt.(type) {
  886. case *ast.SelectorExpr:
  887. t, id, ok = getSelType(elt)
  888. if !ok {
  889. return
  890. }
  891. if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name {
  892. return
  893. }
  894. case *ast.KeyValueExpr:
  895. var sel *ast.SelectorExpr
  896. sel, ok = elt.Value.(*ast.SelectorExpr)
  897. if !ok {
  898. return
  899. }
  900. if elt.Key.(*ast.Ident).Name != sel.Sel.Name {
  901. return
  902. }
  903. t, id, ok = getSelType(elt.Value)
  904. }
  905. if !ok {
  906. return
  907. }
  908. // All fields must be initialized from the same object
  909. if ident != nil && ident.Obj != id.Obj {
  910. return
  911. }
  912. typ2, _ = t.(*types.Named)
  913. if typ2 == nil {
  914. return
  915. }
  916. ident = id
  917. }
  918. if typ2 == nil {
  919. return
  920. }
  921. if typ1.Obj().Pkg() != typ2.Obj().Pkg() {
  922. // Do not suggest type conversions between different
  923. // packages. Types in different packages might only match
  924. // by coincidence. Furthermore, if the dependency ever
  925. // adds more fields to its type, it could break the code
  926. // that relies on the type conversion to work.
  927. return
  928. }
  929. s2, ok := typ2.Underlying().(*types.Struct)
  930. if !ok {
  931. return
  932. }
  933. if typ1 == typ2 {
  934. return
  935. }
  936. if code.IsGoVersion(pass, 8) {
  937. if !types.IdenticalIgnoreTags(s1, s2) {
  938. return
  939. }
  940. } else {
  941. if !types.Identical(s1, s2) {
  942. return
  943. }
  944. }
  945. r := &ast.CallExpr{
  946. Fun: lit.Type,
  947. Args: []ast.Expr{ident},
  948. }
  949. report.Report(pass, node,
  950. fmt.Sprintf("should convert %s (type %s) to %s instead of using struct literal", ident.Name, types.TypeString(typ2, types.RelativeTo(pass.Pkg)), types.TypeString(typ1, types.RelativeTo(pass.Pkg))),
  951. report.FilterGenerated(),
  952. report.Fixes(edit.Fix("use type conversion", edit.ReplaceWithNode(pass.Fset, node, r))))
  953. }
  954. code.PreorderStack(pass, fn, (*ast.CompositeLit)(nil))
  955. return nil, nil
  956. }
  957. func CheckTrim(pass *analysis.Pass) (interface{}, error) {
  958. sameNonDynamic := func(node1, node2 ast.Node) bool {
  959. if reflect.TypeOf(node1) != reflect.TypeOf(node2) {
  960. return false
  961. }
  962. switch node1 := node1.(type) {
  963. case *ast.Ident:
  964. return node1.Obj == node2.(*ast.Ident).Obj
  965. case *ast.SelectorExpr, *ast.IndexExpr:
  966. return astutil.Equal(node1, node2)
  967. case *ast.BasicLit:
  968. return astutil.Equal(node1, node2)
  969. }
  970. return false
  971. }
  972. isLenOnIdent := func(fn ast.Expr, ident ast.Expr) bool {
  973. call, ok := fn.(*ast.CallExpr)
  974. if !ok {
  975. return false
  976. }
  977. if !code.IsCallTo(pass, call, "len") {
  978. return false
  979. }
  980. if len(call.Args) != 1 {
  981. return false
  982. }
  983. return sameNonDynamic(call.Args[knowledge.Arg("len.v")], ident)
  984. }
  985. fn := func(node ast.Node) {
  986. var pkg string
  987. var fun string
  988. ifstmt := node.(*ast.IfStmt)
  989. if ifstmt.Init != nil {
  990. return
  991. }
  992. if ifstmt.Else != nil {
  993. return
  994. }
  995. if len(ifstmt.Body.List) != 1 {
  996. return
  997. }
  998. condCall, ok := ifstmt.Cond.(*ast.CallExpr)
  999. if !ok {
  1000. return
  1001. }
  1002. condCallName := code.CallName(pass, condCall)
  1003. switch condCallName {
  1004. case "strings.HasPrefix":
  1005. pkg = "strings"
  1006. fun = "HasPrefix"
  1007. case "strings.HasSuffix":
  1008. pkg = "strings"
  1009. fun = "HasSuffix"
  1010. case "strings.Contains":
  1011. pkg = "strings"
  1012. fun = "Contains"
  1013. case "bytes.HasPrefix":
  1014. pkg = "bytes"
  1015. fun = "HasPrefix"
  1016. case "bytes.HasSuffix":
  1017. pkg = "bytes"
  1018. fun = "HasSuffix"
  1019. case "bytes.Contains":
  1020. pkg = "bytes"
  1021. fun = "Contains"
  1022. default:
  1023. return
  1024. }
  1025. assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt)
  1026. if !ok {
  1027. return
  1028. }
  1029. if assign.Tok != token.ASSIGN {
  1030. return
  1031. }
  1032. if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
  1033. return
  1034. }
  1035. if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) {
  1036. return
  1037. }
  1038. switch rhs := assign.Rhs[0].(type) {
  1039. case *ast.CallExpr:
  1040. if len(rhs.Args) < 2 || !sameNonDynamic(condCall.Args[0], rhs.Args[0]) || !sameNonDynamic(condCall.Args[1], rhs.Args[1]) {
  1041. return
  1042. }
  1043. rhsName := code.CallName(pass, rhs)
  1044. if condCallName == "strings.HasPrefix" && rhsName == "strings.TrimPrefix" ||
  1045. condCallName == "strings.HasSuffix" && rhsName == "strings.TrimSuffix" ||
  1046. condCallName == "strings.Contains" && rhsName == "strings.Replace" ||
  1047. condCallName == "bytes.HasPrefix" && rhsName == "bytes.TrimPrefix" ||
  1048. condCallName == "bytes.HasSuffix" && rhsName == "bytes.TrimSuffix" ||
  1049. condCallName == "bytes.Contains" && rhsName == "bytes.Replace" {
  1050. report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s", rhsName), report.FilterGenerated())
  1051. }
  1052. case *ast.SliceExpr:
  1053. slice := rhs
  1054. if !ok {
  1055. return
  1056. }
  1057. if slice.Slice3 {
  1058. return
  1059. }
  1060. if !sameNonDynamic(slice.X, condCall.Args[0]) {
  1061. return
  1062. }
  1063. validateOffset := func(off ast.Expr) bool {
  1064. switch off := off.(type) {
  1065. case *ast.CallExpr:
  1066. return isLenOnIdent(off, condCall.Args[1])
  1067. case *ast.BasicLit:
  1068. if pkg != "strings" {
  1069. return false
  1070. }
  1071. if _, ok := condCall.Args[1].(*ast.BasicLit); !ok {
  1072. // Only allow manual slicing with an integer
  1073. // literal if the second argument to HasPrefix
  1074. // was a string literal.
  1075. return false
  1076. }
  1077. s, ok1 := code.ExprToString(pass, condCall.Args[1])
  1078. n, ok2 := code.ExprToInt(pass, off)
  1079. if !ok1 || !ok2 || n != int64(len(s)) {
  1080. return false
  1081. }
  1082. return true
  1083. default:
  1084. return false
  1085. }
  1086. }
  1087. switch fun {
  1088. case "HasPrefix":
  1089. // TODO(dh) We could detect a High that is len(s), but another
  1090. // rule will already flag that, anyway.
  1091. if slice.High != nil {
  1092. return
  1093. }
  1094. if !validateOffset(slice.Low) {
  1095. return
  1096. }
  1097. case "HasSuffix":
  1098. if slice.Low != nil {
  1099. n, ok := code.ExprToInt(pass, slice.Low)
  1100. if !ok || n != 0 {
  1101. return
  1102. }
  1103. }
  1104. switch index := slice.High.(type) {
  1105. case *ast.BinaryExpr:
  1106. if index.Op != token.SUB {
  1107. return
  1108. }
  1109. if !isLenOnIdent(index.X, condCall.Args[0]) {
  1110. return
  1111. }
  1112. if !validateOffset(index.Y) {
  1113. return
  1114. }
  1115. default:
  1116. return
  1117. }
  1118. default:
  1119. return
  1120. }
  1121. var replacement string
  1122. switch fun {
  1123. case "HasPrefix":
  1124. replacement = "TrimPrefix"
  1125. case "HasSuffix":
  1126. replacement = "TrimSuffix"
  1127. }
  1128. report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s.%s", pkg, replacement),
  1129. report.ShortRange(),
  1130. report.FilterGenerated())
  1131. }
  1132. }
  1133. code.Preorder(pass, fn, (*ast.IfStmt)(nil))
  1134. return nil, nil
  1135. }
  1136. var (
  1137. checkLoopSlideQ = pattern.MustParse(`
  1138. (ForStmt
  1139. (AssignStmt initvar@(Ident _) _ (IntegerLiteral "0"))
  1140. (BinaryExpr initvar "<" limit@(Ident _))
  1141. (IncDecStmt initvar "++")
  1142. [(AssignStmt
  1143. (IndexExpr slice@(Ident _) initvar)
  1144. "="
  1145. (IndexExpr slice (BinaryExpr offset@(Ident _) "+" initvar)))])`)
  1146. checkLoopSlideR = pattern.MustParse(`
  1147. (CallExpr
  1148. (Ident "copy")
  1149. [(SliceExpr slice nil limit nil)
  1150. (SliceExpr slice offset nil nil)])`)
  1151. )
  1152. func CheckLoopSlide(pass *analysis.Pass) (interface{}, error) {
  1153. // TODO(dh): detect bs[i+offset] in addition to bs[offset+i]
  1154. // TODO(dh): consider merging this function with LintLoopCopy
  1155. // TODO(dh): detect length that is an expression, not a variable name
  1156. // TODO(dh): support sliding to a different offset than the beginning of the slice
  1157. fn := func(node ast.Node) {
  1158. loop := node.(*ast.ForStmt)
  1159. m, edits, ok := code.MatchAndEdit(pass, checkLoopSlideQ, checkLoopSlideR, loop)
  1160. if !ok {
  1161. return
  1162. }
  1163. typ := pass.TypesInfo.TypeOf(m.State["slice"].(*ast.Ident))
  1164. // The pattern probably needs a core type, but All is fine, too. Either way we only accept slices.
  1165. if !typeutil.All(typ, typeutil.IsSlice) {
  1166. return
  1167. }
  1168. report.Report(pass, loop, "should use copy() instead of loop for sliding slice elements",
  1169. report.ShortRange(),
  1170. report.FilterGenerated(),
  1171. report.Fixes(edit.Fix("use copy() instead of loop", edits...)))
  1172. }
  1173. code.Preorder(pass, fn, (*ast.ForStmt)(nil))
  1174. return nil, nil
  1175. }
  1176. var (
  1177. checkMakeLenCapQ1 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size@(IntegerLiteral "0")])`)
  1178. checkMakeLenCapQ2 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size size])`)
  1179. )
  1180. func CheckMakeLenCap(pass *analysis.Pass) (interface{}, error) {
  1181. fn := func(node ast.Node) {
  1182. if pass.Pkg.Path() == "runtime_test" && filepath.Base(pass.Fset.Position(node.Pos()).Filename) == "map_test.go" {
  1183. // special case of runtime tests testing map creation
  1184. return
  1185. }
  1186. if m, ok := code.Match(pass, checkMakeLenCapQ1, node); ok {
  1187. T := m.State["typ"].(ast.Expr)
  1188. size := m.State["size"].(ast.Node)
  1189. if _, ok := typeutil.CoreType(pass.TypesInfo.TypeOf(T)).Underlying().(*types.Chan); ok {
  1190. report.Report(pass, size, fmt.Sprintf("should use make(%s) instead", report.Render(pass, T)), report.FilterGenerated())
  1191. }
  1192. } else if m, ok := code.Match(pass, checkMakeLenCapQ2, node); ok {
  1193. // TODO(dh): don't consider sizes identical if they're
  1194. // dynamic. for example: make(T, <-ch, <-ch).
  1195. T := m.State["typ"].(ast.Expr)
  1196. size := m.State["size"].(ast.Node)
  1197. report.Report(pass, size,
  1198. fmt.Sprintf("should use make(%s, %s) instead", report.Render(pass, T), report.Render(pass, size)),
  1199. report.FilterGenerated())
  1200. }
  1201. }
  1202. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1203. return nil, nil
  1204. }
  1205. var (
  1206. checkAssertNotNilFn1Q = pattern.MustParse(`
  1207. (IfStmt
  1208. (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr assert@(Object _) _)])
  1209. (Or
  1210. (BinaryExpr ok "&&" (BinaryExpr assert "!=" (Builtin "nil")))
  1211. (BinaryExpr (BinaryExpr assert "!=" (Builtin "nil")) "&&" ok))
  1212. _
  1213. _)`)
  1214. checkAssertNotNilFn2Q = pattern.MustParse(`
  1215. (IfStmt
  1216. nil
  1217. (BinaryExpr lhs@(Object _) "!=" (Builtin "nil"))
  1218. [
  1219. ifstmt@(IfStmt
  1220. (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr lhs _)])
  1221. ok
  1222. _
  1223. nil)
  1224. ]
  1225. nil)`)
  1226. )
  1227. func CheckAssertNotNil(pass *analysis.Pass) (interface{}, error) {
  1228. fn1 := func(node ast.Node) {
  1229. m, ok := code.Match(pass, checkAssertNotNilFn1Q, node)
  1230. if !ok {
  1231. return
  1232. }
  1233. assert := m.State["assert"].(types.Object)
  1234. assign := m.State["ok"].(types.Object)
  1235. report.Report(pass, node, fmt.Sprintf("when %s is true, %s can't be nil", assign.Name(), assert.Name()),
  1236. report.ShortRange(),
  1237. report.FilterGenerated())
  1238. }
  1239. fn2 := func(node ast.Node) {
  1240. m, ok := code.Match(pass, checkAssertNotNilFn2Q, node)
  1241. if !ok {
  1242. return
  1243. }
  1244. ifstmt := m.State["ifstmt"].(*ast.IfStmt)
  1245. lhs := m.State["lhs"].(types.Object)
  1246. assignIdent := m.State["ok"].(types.Object)
  1247. report.Report(pass, ifstmt, fmt.Sprintf("when %s is true, %s can't be nil", assignIdent.Name(), lhs.Name()),
  1248. report.ShortRange(),
  1249. report.FilterGenerated())
  1250. }
  1251. // OPT(dh): merge fn1 and fn2
  1252. code.Preorder(pass, fn1, (*ast.IfStmt)(nil))
  1253. code.Preorder(pass, fn2, (*ast.IfStmt)(nil))
  1254. return nil, nil
  1255. }
  1256. func CheckDeclareAssign(pass *analysis.Pass) (interface{}, error) {
  1257. hasMultipleAssignments := func(root ast.Node, ident *ast.Ident) bool {
  1258. num := 0
  1259. ast.Inspect(root, func(node ast.Node) bool {
  1260. if num >= 2 {
  1261. return false
  1262. }
  1263. assign, ok := node.(*ast.AssignStmt)
  1264. if !ok {
  1265. return true
  1266. }
  1267. for _, lhs := range assign.Lhs {
  1268. if oident, ok := lhs.(*ast.Ident); ok {
  1269. if oident.Obj == ident.Obj {
  1270. num++
  1271. }
  1272. }
  1273. }
  1274. return true
  1275. })
  1276. return num >= 2
  1277. }
  1278. fn := func(node ast.Node) {
  1279. block := node.(*ast.BlockStmt)
  1280. if len(block.List) < 2 {
  1281. return
  1282. }
  1283. for i, stmt := range block.List[:len(block.List)-1] {
  1284. _ = i
  1285. decl, ok := stmt.(*ast.DeclStmt)
  1286. if !ok {
  1287. continue
  1288. }
  1289. gdecl, ok := decl.Decl.(*ast.GenDecl)
  1290. if !ok || gdecl.Tok != token.VAR || len(gdecl.Specs) != 1 {
  1291. continue
  1292. }
  1293. vspec, ok := gdecl.Specs[0].(*ast.ValueSpec)
  1294. if !ok || len(vspec.Names) != 1 || len(vspec.Values) != 0 {
  1295. continue
  1296. }
  1297. assign, ok := block.List[i+1].(*ast.AssignStmt)
  1298. if !ok || assign.Tok != token.ASSIGN {
  1299. continue
  1300. }
  1301. if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
  1302. continue
  1303. }
  1304. ident, ok := assign.Lhs[0].(*ast.Ident)
  1305. if !ok {
  1306. continue
  1307. }
  1308. if vspec.Names[0].Obj != ident.Obj {
  1309. continue
  1310. }
  1311. if refersTo(pass, assign.Rhs[0], pass.TypesInfo.ObjectOf(ident)) {
  1312. continue
  1313. }
  1314. if hasMultipleAssignments(block, ident) {
  1315. continue
  1316. }
  1317. r := &ast.GenDecl{
  1318. Specs: []ast.Spec{
  1319. &ast.ValueSpec{
  1320. Names: vspec.Names,
  1321. Values: []ast.Expr{assign.Rhs[0]},
  1322. Type: vspec.Type,
  1323. },
  1324. },
  1325. Tok: gdecl.Tok,
  1326. }
  1327. report.Report(pass, decl, "should merge variable declaration with assignment on next line",
  1328. report.FilterGenerated(),
  1329. report.Fixes(edit.Fix("merge declaration with assignment", edit.ReplaceWithNode(pass.Fset, edit.Range{decl.Pos(), assign.End()}, r))))
  1330. }
  1331. }
  1332. code.Preorder(pass, fn, (*ast.BlockStmt)(nil))
  1333. return nil, nil
  1334. }
  1335. func CheckRedundantBreak(pass *analysis.Pass) (interface{}, error) {
  1336. fn1 := func(node ast.Node) {
  1337. clause := node.(*ast.CaseClause)
  1338. if len(clause.Body) < 2 {
  1339. return
  1340. }
  1341. branch, ok := clause.Body[len(clause.Body)-1].(*ast.BranchStmt)
  1342. if !ok || branch.Tok != token.BREAK || branch.Label != nil {
  1343. return
  1344. }
  1345. report.Report(pass, branch, "redundant break statement", report.FilterGenerated())
  1346. }
  1347. fn2 := func(node ast.Node) {
  1348. var ret *ast.FieldList
  1349. var body *ast.BlockStmt
  1350. switch x := node.(type) {
  1351. case *ast.FuncDecl:
  1352. ret = x.Type.Results
  1353. body = x.Body
  1354. case *ast.FuncLit:
  1355. ret = x.Type.Results
  1356. body = x.Body
  1357. default:
  1358. lint.ExhaustiveTypeSwitch(node)
  1359. }
  1360. // if the func has results, a return can't be redundant.
  1361. // similarly, if there are no statements, there can be
  1362. // no return.
  1363. if ret != nil || body == nil || len(body.List) < 1 {
  1364. return
  1365. }
  1366. rst, ok := body.List[len(body.List)-1].(*ast.ReturnStmt)
  1367. if !ok {
  1368. return
  1369. }
  1370. // we don't need to check rst.Results as we already
  1371. // checked x.Type.Results to be nil.
  1372. report.Report(pass, rst, "redundant return statement", report.FilterGenerated())
  1373. }
  1374. code.Preorder(pass, fn1, (*ast.CaseClause)(nil))
  1375. code.Preorder(pass, fn2, (*ast.FuncDecl)(nil), (*ast.FuncLit)(nil))
  1376. return nil, nil
  1377. }
  1378. func isStringer(T types.Type, msCache *typeutil.MethodSetCache) bool {
  1379. ms := msCache.MethodSet(T)
  1380. sel := ms.Lookup(nil, "String")
  1381. if sel == nil {
  1382. return false
  1383. }
  1384. fn, ok := sel.Obj().(*types.Func)
  1385. if !ok {
  1386. // should be unreachable
  1387. return false
  1388. }
  1389. sig := fn.Type().(*types.Signature)
  1390. if sig.Params().Len() != 0 {
  1391. return false
  1392. }
  1393. if sig.Results().Len() != 1 {
  1394. return false
  1395. }
  1396. if !typeutil.IsType(sig.Results().At(0).Type(), "string") {
  1397. return false
  1398. }
  1399. return true
  1400. }
  1401. func isFormatter(T types.Type, msCache *typeutil.MethodSetCache) bool {
  1402. // TODO(dh): this function also exists in staticcheck/lint.go – deduplicate.
  1403. ms := msCache.MethodSet(T)
  1404. sel := ms.Lookup(nil, "Format")
  1405. if sel == nil {
  1406. return false
  1407. }
  1408. fn, ok := sel.Obj().(*types.Func)
  1409. if !ok {
  1410. // should be unreachable
  1411. return false
  1412. }
  1413. sig := fn.Type().(*types.Signature)
  1414. if sig.Params().Len() != 2 {
  1415. return false
  1416. }
  1417. // TODO(dh): check the types of the arguments for more
  1418. // precision
  1419. if sig.Results().Len() != 0 {
  1420. return false
  1421. }
  1422. return true
  1423. }
  1424. var checkRedundantSprintfQ = pattern.MustParse(`(CallExpr (Function "fmt.Sprintf") [format arg])`)
  1425. func CheckRedundantSprintf(pass *analysis.Pass) (interface{}, error) {
  1426. fn := func(node ast.Node) {
  1427. m, ok := code.Match(pass, checkRedundantSprintfQ, node)
  1428. if !ok {
  1429. return
  1430. }
  1431. format := m.State["format"].(ast.Expr)
  1432. arg := m.State["arg"].(ast.Expr)
  1433. // TODO(dh): should we really support named constants here?
  1434. // shouldn't we only look for string literals? to avoid false
  1435. // positives via build tags?
  1436. if s, ok := code.ExprToString(pass, format); !ok || s != "%s" {
  1437. return
  1438. }
  1439. typ := pass.TypesInfo.TypeOf(arg)
  1440. if typeparams.IsTypeParam(typ) {
  1441. return
  1442. }
  1443. irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg
  1444. if types.TypeString(typ, nil) == "reflect.Value" {
  1445. // printing with %s produces output different from using
  1446. // the String method
  1447. return
  1448. }
  1449. if isFormatter(typ, &irpkg.Prog.MethodSets) {
  1450. // the type may choose to handle %s in arbitrary ways
  1451. return
  1452. }
  1453. if isStringer(typ, &irpkg.Prog.MethodSets) {
  1454. replacement := &ast.CallExpr{
  1455. Fun: &ast.SelectorExpr{
  1456. X: arg,
  1457. Sel: &ast.Ident{Name: "String"},
  1458. },
  1459. }
  1460. report.Report(pass, node, "should use String() instead of fmt.Sprintf",
  1461. report.Fixes(edit.Fix("replace with call to String method", edit.ReplaceWithNode(pass.Fset, node, replacement))))
  1462. } else if typ == types.Universe.Lookup("string").Type() {
  1463. report.Report(pass, node, "the argument is already a string, there's no need to use fmt.Sprintf",
  1464. report.FilterGenerated(),
  1465. report.Fixes(edit.Fix("remove unnecessary call to fmt.Sprintf", edit.ReplaceWithNode(pass.Fset, node, arg))))
  1466. } else if typ.Underlying() == types.Universe.Lookup("string").Type() {
  1467. replacement := &ast.CallExpr{
  1468. Fun: &ast.Ident{Name: "string"},
  1469. Args: []ast.Expr{arg},
  1470. }
  1471. report.Report(pass, node, "the argument's underlying type is a string, should use a simple conversion instead of fmt.Sprintf",
  1472. report.FilterGenerated(),
  1473. report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement))))
  1474. } else if slice, ok := typ.Underlying().(*types.Slice); ok && slice.Elem() == types.Universe.Lookup("byte").Type() {
  1475. // Note that we check slice.Elem(), not slice.Elem().Underlying, because of https://github.com/golang/go/issues/23536
  1476. replacement := &ast.CallExpr{
  1477. Fun: &ast.Ident{Name: "string"},
  1478. Args: []ast.Expr{arg},
  1479. }
  1480. report.Report(pass, node, "the argument's underlying type is a slice of bytes, should use a simple conversion instead of fmt.Sprintf",
  1481. report.FilterGenerated(),
  1482. report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement))))
  1483. }
  1484. }
  1485. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1486. return nil, nil
  1487. }
  1488. var (
  1489. checkErrorsNewSprintfQ = pattern.MustParse(`(CallExpr (Function "errors.New") [(CallExpr (Function "fmt.Sprintf") args)])`)
  1490. checkErrorsNewSprintfR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "fmt") (Ident "Errorf")) args)`)
  1491. )
  1492. func CheckErrorsNewSprintf(pass *analysis.Pass) (interface{}, error) {
  1493. fn := func(node ast.Node) {
  1494. if _, edits, ok := code.MatchAndEdit(pass, checkErrorsNewSprintfQ, checkErrorsNewSprintfR, node); ok {
  1495. // TODO(dh): the suggested fix may leave an unused import behind
  1496. report.Report(pass, node, "should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...))",
  1497. report.FilterGenerated(),
  1498. report.Fixes(edit.Fix("use fmt.Errorf", edits...)))
  1499. }
  1500. }
  1501. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1502. return nil, nil
  1503. }
  1504. func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) {
  1505. return sharedcheck.CheckRangeStringRunes(pass)
  1506. }
  1507. var checkNilCheckAroundRangeQ = pattern.MustParse(`
  1508. (IfStmt
  1509. nil
  1510. (BinaryExpr x@(Object _) "!=" (Builtin "nil"))
  1511. [(RangeStmt _ _ _ x _)]
  1512. nil)`)
  1513. func CheckNilCheckAroundRange(pass *analysis.Pass) (interface{}, error) {
  1514. fn := func(node ast.Node) {
  1515. m, ok := code.Match(pass, checkNilCheckAroundRangeQ, node)
  1516. if !ok {
  1517. return
  1518. }
  1519. ok = typeutil.All(m.State["x"].(types.Object).Type(), func(term *typeparams.Term) bool {
  1520. switch term.Type().Underlying().(type) {
  1521. case *types.Slice, *types.Map:
  1522. return true
  1523. case *typeparams.TypeParam, *types.Chan, *types.Pointer:
  1524. return false
  1525. default:
  1526. lint.ExhaustiveTypeSwitch(term.Type().Underlying())
  1527. return false
  1528. }
  1529. })
  1530. if !ok {
  1531. return
  1532. }
  1533. report.Report(pass, node, "unnecessary nil check around range", report.ShortRange(), report.FilterGenerated())
  1534. }
  1535. code.Preorder(pass, fn, (*ast.IfStmt)(nil))
  1536. return nil, nil
  1537. }
  1538. func isPermissibleSort(pass *analysis.Pass, node ast.Node) bool {
  1539. call := node.(*ast.CallExpr)
  1540. typeconv, ok := call.Args[0].(*ast.CallExpr)
  1541. if !ok {
  1542. return true
  1543. }
  1544. sel, ok := typeconv.Fun.(*ast.SelectorExpr)
  1545. if !ok {
  1546. return true
  1547. }
  1548. name := code.SelectorName(pass, sel)
  1549. switch name {
  1550. case "sort.IntSlice", "sort.Float64Slice", "sort.StringSlice":
  1551. default:
  1552. return true
  1553. }
  1554. return false
  1555. }
  1556. func CheckSortHelpers(pass *analysis.Pass) (interface{}, error) {
  1557. type Error struct {
  1558. node ast.Node
  1559. msg string
  1560. }
  1561. var allErrors []Error
  1562. fn := func(node ast.Node) {
  1563. var body *ast.BlockStmt
  1564. switch node := node.(type) {
  1565. case *ast.FuncLit:
  1566. body = node.Body
  1567. case *ast.FuncDecl:
  1568. body = node.Body
  1569. default:
  1570. lint.ExhaustiveTypeSwitch(node)
  1571. }
  1572. if body == nil {
  1573. return
  1574. }
  1575. var errors []Error
  1576. permissible := false
  1577. fnSorts := func(node ast.Node) bool {
  1578. if permissible {
  1579. return false
  1580. }
  1581. if !code.IsCallTo(pass, node, "sort.Sort") {
  1582. return true
  1583. }
  1584. if isPermissibleSort(pass, node) {
  1585. permissible = true
  1586. return false
  1587. }
  1588. call := node.(*ast.CallExpr)
  1589. // isPermissibleSort guarantees that this type assertion will succeed
  1590. typeconv := call.Args[knowledge.Arg("sort.Sort.data")].(*ast.CallExpr)
  1591. sel := typeconv.Fun.(*ast.SelectorExpr)
  1592. name := code.SelectorName(pass, sel)
  1593. switch name {
  1594. case "sort.IntSlice":
  1595. errors = append(errors, Error{node, "should use sort.Ints(...) instead of sort.Sort(sort.IntSlice(...))"})
  1596. case "sort.Float64Slice":
  1597. errors = append(errors, Error{node, "should use sort.Float64s(...) instead of sort.Sort(sort.Float64Slice(...))"})
  1598. case "sort.StringSlice":
  1599. errors = append(errors, Error{node, "should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...))"})
  1600. }
  1601. return true
  1602. }
  1603. ast.Inspect(body, fnSorts)
  1604. if permissible {
  1605. return
  1606. }
  1607. allErrors = append(allErrors, errors...)
  1608. }
  1609. code.Preorder(pass, fn, (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil))
  1610. sort.Slice(allErrors, func(i, j int) bool {
  1611. return allErrors[i].node.Pos() < allErrors[j].node.Pos()
  1612. })
  1613. var prev token.Pos
  1614. for _, err := range allErrors {
  1615. if err.node.Pos() == prev {
  1616. continue
  1617. }
  1618. prev = err.node.Pos()
  1619. report.Report(pass, err.node, err.msg, report.FilterGenerated())
  1620. }
  1621. return nil, nil
  1622. }
  1623. var checkGuardedDeleteQ = pattern.MustParse(`
  1624. (IfStmt
  1625. (AssignStmt
  1626. [(Ident "_") ok@(Ident _)]
  1627. ":="
  1628. (IndexExpr m key))
  1629. ok
  1630. [call@(CallExpr (Builtin "delete") [m key])]
  1631. nil)`)
  1632. func CheckGuardedDelete(pass *analysis.Pass) (interface{}, error) {
  1633. fn := func(node ast.Node) {
  1634. if m, ok := code.Match(pass, checkGuardedDeleteQ, node); ok {
  1635. report.Report(pass, node, "unnecessary guard around call to delete",
  1636. report.ShortRange(),
  1637. report.FilterGenerated(),
  1638. report.Fixes(edit.Fix("remove guard", edit.ReplaceWithNode(pass.Fset, node, m.State["call"].(ast.Node)))))
  1639. }
  1640. }
  1641. code.Preorder(pass, fn, (*ast.IfStmt)(nil))
  1642. return nil, nil
  1643. }
  1644. var (
  1645. checkSimplifyTypeSwitchQ = pattern.MustParse(`
  1646. (TypeSwitchStmt
  1647. nil
  1648. expr@(TypeAssertExpr ident@(Ident _) _)
  1649. body)`)
  1650. checkSimplifyTypeSwitchR = pattern.MustParse(`(AssignStmt ident ":=" expr)`)
  1651. )
  1652. func CheckSimplifyTypeSwitch(pass *analysis.Pass) (interface{}, error) {
  1653. fn := func(node ast.Node) {
  1654. m, ok := code.Match(pass, checkSimplifyTypeSwitchQ, node)
  1655. if !ok {
  1656. return
  1657. }
  1658. stmt := node.(*ast.TypeSwitchStmt)
  1659. expr := m.State["expr"].(ast.Node)
  1660. ident := m.State["ident"].(*ast.Ident)
  1661. x := pass.TypesInfo.ObjectOf(ident)
  1662. var allOffenders []*ast.TypeAssertExpr
  1663. canSuggestFix := true
  1664. for _, clause := range stmt.Body.List {
  1665. clause := clause.(*ast.CaseClause)
  1666. if len(clause.List) != 1 {
  1667. continue
  1668. }
  1669. hasUnrelatedAssertion := false
  1670. var offenders []*ast.TypeAssertExpr
  1671. ast.Inspect(clause, func(node ast.Node) bool {
  1672. assert2, ok := node.(*ast.TypeAssertExpr)
  1673. if !ok {
  1674. return true
  1675. }
  1676. ident, ok := assert2.X.(*ast.Ident)
  1677. if !ok {
  1678. hasUnrelatedAssertion = true
  1679. return false
  1680. }
  1681. if pass.TypesInfo.ObjectOf(ident) != x {
  1682. hasUnrelatedAssertion = true
  1683. return false
  1684. }
  1685. if !types.Identical(pass.TypesInfo.TypeOf(clause.List[0]), pass.TypesInfo.TypeOf(assert2.Type)) {
  1686. hasUnrelatedAssertion = true
  1687. return false
  1688. }
  1689. offenders = append(offenders, assert2)
  1690. return true
  1691. })
  1692. if !hasUnrelatedAssertion {
  1693. // don't flag cases that have other type assertions
  1694. // unrelated to the one in the case clause. often
  1695. // times, this is done for symmetry, when two
  1696. // different values have to be asserted to the same
  1697. // type.
  1698. allOffenders = append(allOffenders, offenders...)
  1699. }
  1700. canSuggestFix = canSuggestFix && !hasUnrelatedAssertion
  1701. }
  1702. if len(allOffenders) != 0 {
  1703. var opts []report.Option
  1704. for _, offender := range allOffenders {
  1705. opts = append(opts, report.Related(offender, "could eliminate this type assertion"))
  1706. }
  1707. opts = append(opts, report.FilterGenerated())
  1708. msg := fmt.Sprintf("assigning the result of this type assertion to a variable (switch %s := %s.(type)) could eliminate type assertions in switch cases",
  1709. report.Render(pass, ident), report.Render(pass, ident))
  1710. if canSuggestFix {
  1711. var edits []analysis.TextEdit
  1712. edits = append(edits, edit.ReplaceWithPattern(pass.Fset, expr, checkSimplifyTypeSwitchR, m.State))
  1713. for _, offender := range allOffenders {
  1714. edits = append(edits, edit.ReplaceWithNode(pass.Fset, offender, offender.X))
  1715. }
  1716. opts = append(opts, report.Fixes(edit.Fix("simplify type switch", edits...)))
  1717. report.Report(pass, expr, msg, opts...)
  1718. } else {
  1719. report.Report(pass, expr, msg, opts...)
  1720. }
  1721. }
  1722. }
  1723. code.Preorder(pass, fn, (*ast.TypeSwitchStmt)(nil))
  1724. return nil, nil
  1725. }
  1726. func CheckRedundantCanonicalHeaderKey(pass *analysis.Pass) (interface{}, error) {
  1727. fn := func(node ast.Node) {
  1728. call := node.(*ast.CallExpr)
  1729. callName := code.CallName(pass, call)
  1730. switch callName {
  1731. case "(net/http.Header).Add", "(net/http.Header).Del", "(net/http.Header).Get", "(net/http.Header).Set":
  1732. default:
  1733. return
  1734. }
  1735. if !code.IsCallTo(pass, call.Args[0], "net/http.CanonicalHeaderKey") {
  1736. return
  1737. }
  1738. report.Report(pass, call,
  1739. fmt.Sprintf("calling net/http.CanonicalHeaderKey on the 'key' argument of %s is redundant", callName),
  1740. report.FilterGenerated(),
  1741. report.Fixes(edit.Fix("remove call to CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, call.Args[0], call.Args[0].(*ast.CallExpr).Args[0]))))
  1742. }
  1743. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1744. return nil, nil
  1745. }
  1746. var checkUnnecessaryGuardQ = pattern.MustParse(`
  1747. (Or
  1748. (IfStmt
  1749. (AssignStmt [(Ident "_") ok@(Ident _)] ":=" indexexpr@(IndexExpr _ _))
  1750. ok
  1751. set@(AssignStmt indexexpr "=" (CallExpr (Builtin "append") indexexpr:values))
  1752. (AssignStmt indexexpr "=" (CompositeLit _ values)))
  1753. (IfStmt
  1754. (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _))
  1755. ok
  1756. set@(AssignStmt indexexpr "+=" value)
  1757. (AssignStmt indexexpr "=" value))
  1758. (IfStmt
  1759. (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _))
  1760. ok
  1761. set@(IncDecStmt indexexpr "++")
  1762. (AssignStmt indexexpr "=" (IntegerLiteral "1"))))`)
  1763. func CheckUnnecessaryGuard(pass *analysis.Pass) (interface{}, error) {
  1764. fn := func(node ast.Node) {
  1765. if m, ok := code.Match(pass, checkUnnecessaryGuardQ, node); ok {
  1766. if code.MayHaveSideEffects(pass, m.State["indexexpr"].(ast.Expr), nil) {
  1767. return
  1768. }
  1769. report.Report(pass, node, "unnecessary guard around map access",
  1770. report.ShortRange(),
  1771. report.Fixes(edit.Fix("simplify map access", edit.ReplaceWithNode(pass.Fset, node, m.State["set"].(ast.Node)))))
  1772. }
  1773. }
  1774. code.Preorder(pass, fn, (*ast.IfStmt)(nil))
  1775. return nil, nil
  1776. }
  1777. var (
  1778. checkElaborateSleepQ = pattern.MustParse(`(SelectStmt (CommClause (UnaryExpr "<-" (CallExpr (Function "time.After") [arg])) body))`)
  1779. checkElaborateSleepR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Sleep")) [arg])`)
  1780. )
  1781. func CheckElaborateSleep(pass *analysis.Pass) (interface{}, error) {
  1782. fn := func(node ast.Node) {
  1783. if m, ok := code.Match(pass, checkElaborateSleepQ, node); ok {
  1784. if body, ok := m.State["body"].([]ast.Stmt); ok && len(body) == 0 {
  1785. report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping",
  1786. report.ShortRange(),
  1787. report.FilterGenerated(),
  1788. report.Fixes(edit.Fix("Use time.Sleep", edit.ReplaceWithPattern(pass.Fset, node, checkElaborateSleepR, m.State))))
  1789. } else {
  1790. // TODO(dh): we could make a suggested fix if the body
  1791. // doesn't declare or shadow any identifiers
  1792. report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping",
  1793. report.ShortRange(),
  1794. report.FilterGenerated())
  1795. }
  1796. }
  1797. }
  1798. code.Preorder(pass, fn, (*ast.SelectStmt)(nil))
  1799. return nil, nil
  1800. }
  1801. var (
  1802. checkPrintSprintQ = pattern.MustParse(`
  1803. (Or
  1804. (CallExpr
  1805. fn@(Or
  1806. (Function "fmt.Print")
  1807. (Function "fmt.Sprint")
  1808. (Function "fmt.Println")
  1809. (Function "fmt.Sprintln"))
  1810. [(CallExpr (Function "fmt.Sprintf") f:_)])
  1811. (CallExpr
  1812. fn@(Or
  1813. (Function "fmt.Fprint")
  1814. (Function "fmt.Fprintln"))
  1815. [_ (CallExpr (Function "fmt.Sprintf") f:_)]))`)
  1816. checkTestingErrorSprintfQ = pattern.MustParse(`
  1817. (CallExpr
  1818. sel@(SelectorExpr
  1819. recv
  1820. (Ident
  1821. name@(Or
  1822. "Error"
  1823. "Fatal"
  1824. "Fatalln"
  1825. "Log"
  1826. "Panic"
  1827. "Panicln"
  1828. "Print"
  1829. "Println"
  1830. "Skip")))
  1831. [(CallExpr (Function "fmt.Sprintf") args)])`)
  1832. checkLogSprintfQ = pattern.MustParse(`
  1833. (CallExpr
  1834. (Function
  1835. (Or
  1836. "log.Fatal"
  1837. "log.Fatalln"
  1838. "log.Panic"
  1839. "log.Panicln"
  1840. "log.Print"
  1841. "log.Println"))
  1842. [(CallExpr (Function "fmt.Sprintf") args)])`)
  1843. checkSprintfMapping = map[string]struct {
  1844. recv string
  1845. alternative string
  1846. }{
  1847. "(*testing.common).Error": {"(*testing.common)", "Errorf"},
  1848. "(testing.TB).Error": {"(testing.TB)", "Errorf"},
  1849. "(*testing.common).Fatal": {"(*testing.common)", "Fatalf"},
  1850. "(testing.TB).Fatal": {"(testing.TB)", "Fatalf"},
  1851. "(*testing.common).Log": {"(*testing.common)", "Logf"},
  1852. "(testing.TB).Log": {"(testing.TB)", "Logf"},
  1853. "(*testing.common).Skip": {"(*testing.common)", "Skipf"},
  1854. "(testing.TB).Skip": {"(testing.TB)", "Skipf"},
  1855. "(*log.Logger).Fatal": {"(*log.Logger)", "Fatalf"},
  1856. "(*log.Logger).Fatalln": {"(*log.Logger)", "Fatalf"},
  1857. "(*log.Logger).Panic": {"(*log.Logger)", "Panicf"},
  1858. "(*log.Logger).Panicln": {"(*log.Logger)", "Panicf"},
  1859. "(*log.Logger).Print": {"(*log.Logger)", "Printf"},
  1860. "(*log.Logger).Println": {"(*log.Logger)", "Printf"},
  1861. "log.Fatal": {"", "log.Fatalf"},
  1862. "log.Fatalln": {"", "log.Fatalf"},
  1863. "log.Panic": {"", "log.Panicf"},
  1864. "log.Panicln": {"", "log.Panicf"},
  1865. "log.Print": {"", "log.Printf"},
  1866. "log.Println": {"", "log.Printf"},
  1867. }
  1868. )
  1869. func CheckPrintSprintf(pass *analysis.Pass) (interface{}, error) {
  1870. fmtPrintf := func(node ast.Node) {
  1871. m, ok := code.Match(pass, checkPrintSprintQ, node)
  1872. if !ok {
  1873. return
  1874. }
  1875. name := m.State["fn"].(*types.Func).Name()
  1876. var msg string
  1877. switch name {
  1878. case "Print", "Fprint", "Sprint":
  1879. newname := name + "f"
  1880. msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...))", newname, name)
  1881. case "Println", "Fprintln", "Sprintln":
  1882. if _, ok := m.State["f"].(*ast.BasicLit); !ok {
  1883. // This may be an instance of
  1884. // fmt.Println(fmt.Sprintf(arg, ...)) where arg is an
  1885. // externally provided format string and the caller
  1886. // cannot guarantee that the format string ends with a
  1887. // newline.
  1888. return
  1889. }
  1890. newname := name[:len(name)-2] + "f"
  1891. msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...)) (but don't forget the newline)", newname, name)
  1892. }
  1893. report.Report(pass, node, msg,
  1894. report.FilterGenerated())
  1895. }
  1896. methSprintf := func(node ast.Node) {
  1897. m, ok := code.Match(pass, checkTestingErrorSprintfQ, node)
  1898. if !ok {
  1899. return
  1900. }
  1901. mapped, ok := checkSprintfMapping[code.CallName(pass, node.(*ast.CallExpr))]
  1902. if !ok {
  1903. return
  1904. }
  1905. // Ensure that Errorf/Fatalf refer to the right method
  1906. recvTV, ok := pass.TypesInfo.Types[m.State["recv"].(ast.Expr)]
  1907. if !ok {
  1908. return
  1909. }
  1910. obj, _, _ := types.LookupFieldOrMethod(recvTV.Type, recvTV.Addressable(), nil, mapped.alternative)
  1911. f, ok := obj.(*types.Func)
  1912. if !ok {
  1913. return
  1914. }
  1915. if typeutil.FuncName(f) != mapped.recv+"."+mapped.alternative {
  1916. return
  1917. }
  1918. alt := &ast.SelectorExpr{
  1919. X: m.State["recv"].(ast.Expr),
  1920. Sel: &ast.Ident{Name: mapped.alternative},
  1921. }
  1922. report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", report.Render(pass, alt), report.Render(pass, m.State["sel"].(*ast.SelectorExpr))))
  1923. }
  1924. pkgSprintf := func(node ast.Node) {
  1925. _, ok := code.Match(pass, checkLogSprintfQ, node)
  1926. if !ok {
  1927. return
  1928. }
  1929. callName := code.CallName(pass, node.(*ast.CallExpr))
  1930. mapped, ok := checkSprintfMapping[callName]
  1931. if !ok {
  1932. return
  1933. }
  1934. report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", mapped.alternative, callName))
  1935. }
  1936. fn := func(node ast.Node) {
  1937. fmtPrintf(node)
  1938. // TODO(dh): add suggested fixes
  1939. methSprintf(node)
  1940. pkgSprintf(node)
  1941. }
  1942. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1943. return nil, nil
  1944. }
  1945. var checkSprintLiteralQ = pattern.MustParse(`
  1946. (CallExpr
  1947. fn@(Or
  1948. (Function "fmt.Sprint")
  1949. (Function "fmt.Sprintf"))
  1950. [lit@(BasicLit "STRING" _)])`)
  1951. func CheckSprintLiteral(pass *analysis.Pass) (interface{}, error) {
  1952. // We only flag calls with string literals, not expressions of
  1953. // type string, because some people use fmt.Sprint(s) as a pattern
  1954. // for copying strings, which may be useful when extracting a small
  1955. // substring from a large string.
  1956. fn := func(node ast.Node) {
  1957. m, ok := code.Match(pass, checkSprintLiteralQ, node)
  1958. if !ok {
  1959. return
  1960. }
  1961. callee := m.State["fn"].(*types.Func)
  1962. lit := m.State["lit"].(*ast.BasicLit)
  1963. if callee.Name() == "Sprintf" {
  1964. if strings.ContainsRune(lit.Value, '%') {
  1965. // This might be a format string
  1966. return
  1967. }
  1968. }
  1969. report.Report(pass, node, fmt.Sprintf("unnecessary use of fmt.%s", callee.Name()),
  1970. report.FilterGenerated(),
  1971. report.Fixes(edit.Fix("Replace with string literal", edit.ReplaceWithNode(pass.Fset, node, lit))))
  1972. }
  1973. code.Preorder(pass, fn, (*ast.CallExpr)(nil))
  1974. return nil, nil
  1975. }
  1976. func CheckSameTypeTypeAssertion(pass *analysis.Pass) (interface{}, error) {
  1977. fn := func(node ast.Node) {
  1978. expr := node.(*ast.TypeAssertExpr)
  1979. if expr.Type == nil {
  1980. // skip type switches
  1981. //
  1982. // TODO(dh): we could flag type switches, too, when a case
  1983. // statement has the same type as expr.X – however,
  1984. // depending on the location of that case, it might behave
  1985. // identically to a default branch. we need to think
  1986. // carefully about the instances we want to flag. We also
  1987. // have to take nil interface values into consideration.
  1988. //
  1989. // It might make more sense to extend SA4020 to handle
  1990. // this.
  1991. return
  1992. }
  1993. t1 := pass.TypesInfo.TypeOf(expr.Type)
  1994. t2 := pass.TypesInfo.TypeOf(expr.X)
  1995. if types.IsInterface(t1) && types.Identical(t1, t2) {
  1996. report.Report(pass, expr,
  1997. fmt.Sprintf("type assertion to the same type: %s already has type %s", report.Render(pass, expr.X), report.Render(pass, expr.Type)),
  1998. report.FilterGenerated())
  1999. }
  2000. }
  2001. // TODO(dh): add suggested fixes. we need different fixes depending on the context:
  2002. // - assignment with 1 or 2 lhs
  2003. // - assignment to blank identifiers (as the first, second or both lhs)
  2004. // - initializers in if statements, with the same variations as above
  2005. code.Preorder(pass, fn, (*ast.TypeAssertExpr)(nil))
  2006. return nil, nil
  2007. }