lint.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817
  1. // Package simple contains a linter for Go source code.
  2. package simple // import "honnef.co/go/tools/simple"
  3. import (
  4. "fmt"
  5. "go/ast"
  6. "go/constant"
  7. "go/token"
  8. "go/types"
  9. "reflect"
  10. "sort"
  11. "strings"
  12. "golang.org/x/tools/go/analysis"
  13. "golang.org/x/tools/go/analysis/passes/inspect"
  14. "golang.org/x/tools/go/ast/inspector"
  15. "golang.org/x/tools/go/types/typeutil"
  16. . "honnef.co/go/tools/arg"
  17. "honnef.co/go/tools/internal/passes/buildssa"
  18. "honnef.co/go/tools/internal/sharedcheck"
  19. "honnef.co/go/tools/lint"
  20. . "honnef.co/go/tools/lint/lintdsl"
  21. )
  22. func LintSingleCaseSelect(pass *analysis.Pass) (interface{}, error) {
  23. isSingleSelect := func(node ast.Node) bool {
  24. v, ok := node.(*ast.SelectStmt)
  25. if !ok {
  26. return false
  27. }
  28. return len(v.Body.List) == 1
  29. }
  30. seen := map[ast.Node]struct{}{}
  31. fn := func(node ast.Node) {
  32. switch v := node.(type) {
  33. case *ast.ForStmt:
  34. if len(v.Body.List) != 1 {
  35. return
  36. }
  37. if !isSingleSelect(v.Body.List[0]) {
  38. return
  39. }
  40. if _, ok := v.Body.List[0].(*ast.SelectStmt).Body.List[0].(*ast.CommClause).Comm.(*ast.SendStmt); ok {
  41. // Don't suggest using range for channel sends
  42. return
  43. }
  44. seen[v.Body.List[0]] = struct{}{}
  45. ReportNodefFG(pass, node, "should use for range instead of for { select {} }")
  46. case *ast.SelectStmt:
  47. if _, ok := seen[v]; ok {
  48. return
  49. }
  50. if !isSingleSelect(v) {
  51. return
  52. }
  53. ReportNodefFG(pass, node, "should use a simple channel send/receive instead of select with a single case")
  54. }
  55. }
  56. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil), (*ast.SelectStmt)(nil)}, fn)
  57. return nil, nil
  58. }
  59. func LintLoopCopy(pass *analysis.Pass) (interface{}, error) {
  60. fn := func(node ast.Node) {
  61. loop := node.(*ast.RangeStmt)
  62. if loop.Key == nil {
  63. return
  64. }
  65. if len(loop.Body.List) != 1 {
  66. return
  67. }
  68. stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
  69. if !ok {
  70. return
  71. }
  72. if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
  73. return
  74. }
  75. lhs, ok := stmt.Lhs[0].(*ast.IndexExpr)
  76. if !ok {
  77. return
  78. }
  79. if _, ok := pass.TypesInfo.TypeOf(lhs.X).(*types.Slice); !ok {
  80. return
  81. }
  82. lidx, ok := lhs.Index.(*ast.Ident)
  83. if !ok {
  84. return
  85. }
  86. key, ok := loop.Key.(*ast.Ident)
  87. if !ok {
  88. return
  89. }
  90. if pass.TypesInfo.TypeOf(lhs) == nil || pass.TypesInfo.TypeOf(stmt.Rhs[0]) == nil {
  91. return
  92. }
  93. if pass.TypesInfo.ObjectOf(lidx) != pass.TypesInfo.ObjectOf(key) {
  94. return
  95. }
  96. if !types.Identical(pass.TypesInfo.TypeOf(lhs), pass.TypesInfo.TypeOf(stmt.Rhs[0])) {
  97. return
  98. }
  99. if _, ok := pass.TypesInfo.TypeOf(loop.X).(*types.Slice); !ok {
  100. return
  101. }
  102. if rhs, ok := stmt.Rhs[0].(*ast.IndexExpr); ok {
  103. rx, ok := rhs.X.(*ast.Ident)
  104. _ = rx
  105. if !ok {
  106. return
  107. }
  108. ridx, ok := rhs.Index.(*ast.Ident)
  109. if !ok {
  110. return
  111. }
  112. if pass.TypesInfo.ObjectOf(ridx) != pass.TypesInfo.ObjectOf(key) {
  113. return
  114. }
  115. } else if rhs, ok := stmt.Rhs[0].(*ast.Ident); ok {
  116. value, ok := loop.Value.(*ast.Ident)
  117. if !ok {
  118. return
  119. }
  120. if pass.TypesInfo.ObjectOf(rhs) != pass.TypesInfo.ObjectOf(value) {
  121. return
  122. }
  123. } else {
  124. return
  125. }
  126. ReportNodefFG(pass, loop, "should use copy() instead of a loop")
  127. }
  128. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
  129. return nil, nil
  130. }
  131. func LintIfBoolCmp(pass *analysis.Pass) (interface{}, error) {
  132. fn := func(node ast.Node) {
  133. expr := node.(*ast.BinaryExpr)
  134. if expr.Op != token.EQL && expr.Op != token.NEQ {
  135. return
  136. }
  137. x := IsBoolConst(pass, expr.X)
  138. y := IsBoolConst(pass, expr.Y)
  139. if !x && !y {
  140. return
  141. }
  142. var other ast.Expr
  143. var val bool
  144. if x {
  145. val = BoolConst(pass, expr.X)
  146. other = expr.Y
  147. } else {
  148. val = BoolConst(pass, expr.Y)
  149. other = expr.X
  150. }
  151. basic, ok := pass.TypesInfo.TypeOf(other).Underlying().(*types.Basic)
  152. if !ok || basic.Kind() != types.Bool {
  153. return
  154. }
  155. op := ""
  156. if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) {
  157. op = "!"
  158. }
  159. r := op + Render(pass, other)
  160. l1 := len(r)
  161. r = strings.TrimLeft(r, "!")
  162. if (l1-len(r))%2 == 1 {
  163. r = "!" + r
  164. }
  165. if IsInTest(pass, node) {
  166. return
  167. }
  168. ReportNodefFG(pass, expr, "should omit comparison to bool constant, can be simplified to %s", r)
  169. }
  170. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
  171. return nil, nil
  172. }
  173. func LintBytesBufferConversions(pass *analysis.Pass) (interface{}, error) {
  174. fn := func(node ast.Node) {
  175. call := node.(*ast.CallExpr)
  176. if len(call.Args) != 1 {
  177. return
  178. }
  179. argCall, ok := call.Args[0].(*ast.CallExpr)
  180. if !ok {
  181. return
  182. }
  183. sel, ok := argCall.Fun.(*ast.SelectorExpr)
  184. if !ok {
  185. return
  186. }
  187. typ := pass.TypesInfo.TypeOf(call.Fun)
  188. if typ == types.Universe.Lookup("string").Type() && IsCallToAST(pass, call.Args[0], "(*bytes.Buffer).Bytes") {
  189. ReportNodefFG(pass, call, "should use %v.String() instead of %v", Render(pass, sel.X), Render(pass, call))
  190. } else if typ, ok := typ.(*types.Slice); ok && typ.Elem() == types.Universe.Lookup("byte").Type() && IsCallToAST(pass, call.Args[0], "(*bytes.Buffer).String") {
  191. ReportNodefFG(pass, call, "should use %v.Bytes() instead of %v", Render(pass, sel.X), Render(pass, call))
  192. }
  193. }
  194. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  195. return nil, nil
  196. }
  197. func LintStringsContains(pass *analysis.Pass) (interface{}, error) {
  198. // map of value to token to bool value
  199. allowed := map[int64]map[token.Token]bool{
  200. -1: {token.GTR: true, token.NEQ: true, token.EQL: false},
  201. 0: {token.GEQ: true, token.LSS: false},
  202. }
  203. fn := func(node ast.Node) {
  204. expr := node.(*ast.BinaryExpr)
  205. switch expr.Op {
  206. case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL:
  207. default:
  208. return
  209. }
  210. value, ok := ExprToInt(pass, expr.Y)
  211. if !ok {
  212. return
  213. }
  214. allowedOps, ok := allowed[value]
  215. if !ok {
  216. return
  217. }
  218. b, ok := allowedOps[expr.Op]
  219. if !ok {
  220. return
  221. }
  222. call, ok := expr.X.(*ast.CallExpr)
  223. if !ok {
  224. return
  225. }
  226. sel, ok := call.Fun.(*ast.SelectorExpr)
  227. if !ok {
  228. return
  229. }
  230. pkgIdent, ok := sel.X.(*ast.Ident)
  231. if !ok {
  232. return
  233. }
  234. funIdent := sel.Sel
  235. if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" {
  236. return
  237. }
  238. newFunc := ""
  239. switch funIdent.Name {
  240. case "IndexRune":
  241. newFunc = "ContainsRune"
  242. case "IndexAny":
  243. newFunc = "ContainsAny"
  244. case "Index":
  245. newFunc = "Contains"
  246. default:
  247. return
  248. }
  249. prefix := ""
  250. if !b {
  251. prefix = "!"
  252. }
  253. ReportNodefFG(pass, node, "should use %s%s.%s(%s) instead", prefix, pkgIdent.Name, newFunc, RenderArgs(pass, call.Args))
  254. }
  255. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
  256. return nil, nil
  257. }
  258. func LintBytesCompare(pass *analysis.Pass) (interface{}, error) {
  259. fn := func(node ast.Node) {
  260. expr := node.(*ast.BinaryExpr)
  261. if expr.Op != token.NEQ && expr.Op != token.EQL {
  262. return
  263. }
  264. call, ok := expr.X.(*ast.CallExpr)
  265. if !ok {
  266. return
  267. }
  268. if !IsCallToAST(pass, call, "bytes.Compare") {
  269. return
  270. }
  271. value, ok := ExprToInt(pass, expr.Y)
  272. if !ok || value != 0 {
  273. return
  274. }
  275. args := RenderArgs(pass, call.Args)
  276. prefix := ""
  277. if expr.Op == token.NEQ {
  278. prefix = "!"
  279. }
  280. ReportNodefFG(pass, node, "should use %sbytes.Equal(%s) instead", prefix, args)
  281. }
  282. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
  283. return nil, nil
  284. }
  285. func LintForTrue(pass *analysis.Pass) (interface{}, error) {
  286. fn := func(node ast.Node) {
  287. loop := node.(*ast.ForStmt)
  288. if loop.Init != nil || loop.Post != nil {
  289. return
  290. }
  291. if !IsBoolConst(pass, loop.Cond) || !BoolConst(pass, loop.Cond) {
  292. return
  293. }
  294. ReportNodefFG(pass, loop, "should use for {} instead of for true {}")
  295. }
  296. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
  297. return nil, nil
  298. }
  299. func LintRegexpRaw(pass *analysis.Pass) (interface{}, error) {
  300. fn := func(node ast.Node) {
  301. call := node.(*ast.CallExpr)
  302. if !IsCallToAST(pass, call, "regexp.MustCompile") &&
  303. !IsCallToAST(pass, call, "regexp.Compile") {
  304. return
  305. }
  306. sel, ok := call.Fun.(*ast.SelectorExpr)
  307. if !ok {
  308. return
  309. }
  310. if len(call.Args) != 1 {
  311. // invalid function call
  312. return
  313. }
  314. lit, ok := call.Args[Arg("regexp.Compile.expr")].(*ast.BasicLit)
  315. if !ok {
  316. // TODO(dominikh): support string concat, maybe support constants
  317. return
  318. }
  319. if lit.Kind != token.STRING {
  320. // invalid function call
  321. return
  322. }
  323. if lit.Value[0] != '"' {
  324. // already a raw string
  325. return
  326. }
  327. val := lit.Value
  328. if !strings.Contains(val, `\\`) {
  329. return
  330. }
  331. if strings.Contains(val, "`") {
  332. return
  333. }
  334. bs := false
  335. for _, c := range val {
  336. if !bs && c == '\\' {
  337. bs = true
  338. continue
  339. }
  340. if bs && c == '\\' {
  341. bs = false
  342. continue
  343. }
  344. if bs {
  345. // backslash followed by non-backslash -> escape sequence
  346. return
  347. }
  348. }
  349. ReportNodefFG(pass, call, "should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name)
  350. }
  351. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  352. return nil, nil
  353. }
  354. func LintIfReturn(pass *analysis.Pass) (interface{}, error) {
  355. fn := func(node ast.Node) {
  356. block := node.(*ast.BlockStmt)
  357. l := len(block.List)
  358. if l < 2 {
  359. return
  360. }
  361. n1, n2 := block.List[l-2], block.List[l-1]
  362. if len(block.List) >= 3 {
  363. if _, ok := block.List[l-3].(*ast.IfStmt); ok {
  364. // Do not flag a series of if statements
  365. return
  366. }
  367. }
  368. // if statement with no init, no else, a single condition
  369. // checking an identifier or function call and just a return
  370. // statement in the body, that returns a boolean constant
  371. ifs, ok := n1.(*ast.IfStmt)
  372. if !ok {
  373. return
  374. }
  375. if ifs.Else != nil || ifs.Init != nil {
  376. return
  377. }
  378. if len(ifs.Body.List) != 1 {
  379. return
  380. }
  381. if op, ok := ifs.Cond.(*ast.BinaryExpr); ok {
  382. switch op.Op {
  383. case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ:
  384. default:
  385. return
  386. }
  387. }
  388. ret1, ok := ifs.Body.List[0].(*ast.ReturnStmt)
  389. if !ok {
  390. return
  391. }
  392. if len(ret1.Results) != 1 {
  393. return
  394. }
  395. if !IsBoolConst(pass, ret1.Results[0]) {
  396. return
  397. }
  398. ret2, ok := n2.(*ast.ReturnStmt)
  399. if !ok {
  400. return
  401. }
  402. if len(ret2.Results) != 1 {
  403. return
  404. }
  405. if !IsBoolConst(pass, ret2.Results[0]) {
  406. return
  407. }
  408. if ret1.Results[0].(*ast.Ident).Name == ret2.Results[0].(*ast.Ident).Name {
  409. // we want the function to return true and false, not the
  410. // same value both times.
  411. return
  412. }
  413. ReportNodefFG(pass, n1, "should use 'return <expr>' instead of 'if <expr> { return <bool> }; return <bool>'")
  414. }
  415. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BlockStmt)(nil)}, fn)
  416. return nil, nil
  417. }
  418. // LintRedundantNilCheckWithLen checks for the following reduntant nil-checks:
  419. //
  420. // if x == nil || len(x) == 0 {}
  421. // if x != nil && len(x) != 0 {}
  422. // if x != nil && len(x) == N {} (where N != 0)
  423. // if x != nil && len(x) > N {}
  424. // if x != nil && len(x) >= N {} (where N != 0)
  425. //
  426. func LintRedundantNilCheckWithLen(pass *analysis.Pass) (interface{}, error) {
  427. isConstZero := func(expr ast.Expr) (isConst bool, isZero bool) {
  428. _, ok := expr.(*ast.BasicLit)
  429. if ok {
  430. return true, IsZero(expr)
  431. }
  432. id, ok := expr.(*ast.Ident)
  433. if !ok {
  434. return false, false
  435. }
  436. c, ok := pass.TypesInfo.ObjectOf(id).(*types.Const)
  437. if !ok {
  438. return false, false
  439. }
  440. return true, c.Val().Kind() == constant.Int && c.Val().String() == "0"
  441. }
  442. fn := func(node ast.Node) {
  443. // check that expr is "x || y" or "x && y"
  444. expr := node.(*ast.BinaryExpr)
  445. if expr.Op != token.LOR && expr.Op != token.LAND {
  446. return
  447. }
  448. eqNil := expr.Op == token.LOR
  449. // check that x is "xx == nil" or "xx != nil"
  450. x, ok := expr.X.(*ast.BinaryExpr)
  451. if !ok {
  452. return
  453. }
  454. if eqNil && x.Op != token.EQL {
  455. return
  456. }
  457. if !eqNil && x.Op != token.NEQ {
  458. return
  459. }
  460. xx, ok := x.X.(*ast.Ident)
  461. if !ok {
  462. return
  463. }
  464. if !IsNil(pass, x.Y) {
  465. return
  466. }
  467. // check that y is "len(xx) == 0" or "len(xx) ... "
  468. y, ok := expr.Y.(*ast.BinaryExpr)
  469. if !ok {
  470. return
  471. }
  472. if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0
  473. return
  474. }
  475. yx, ok := y.X.(*ast.CallExpr)
  476. if !ok {
  477. return
  478. }
  479. yxFun, ok := yx.Fun.(*ast.Ident)
  480. if !ok || yxFun.Name != "len" || len(yx.Args) != 1 {
  481. return
  482. }
  483. yxArg, ok := yx.Args[Arg("len.v")].(*ast.Ident)
  484. if !ok {
  485. return
  486. }
  487. if yxArg.Name != xx.Name {
  488. return
  489. }
  490. if eqNil && !IsZero(y.Y) { // must be len(x) == *0*
  491. return
  492. }
  493. if !eqNil {
  494. isConst, isZero := isConstZero(y.Y)
  495. if !isConst {
  496. return
  497. }
  498. switch y.Op {
  499. case token.EQL:
  500. // avoid false positive for "xx != nil && len(xx) == 0"
  501. if isZero {
  502. return
  503. }
  504. case token.GEQ:
  505. // avoid false positive for "xx != nil && len(xx) >= 0"
  506. if isZero {
  507. return
  508. }
  509. case token.NEQ:
  510. // avoid false positive for "xx != nil && len(xx) != <non-zero>"
  511. if !isZero {
  512. return
  513. }
  514. case token.GTR:
  515. // ok
  516. default:
  517. return
  518. }
  519. }
  520. // finally check that xx type is one of array, slice, map or chan
  521. // this is to prevent false positive in case if xx is a pointer to an array
  522. var nilType string
  523. switch pass.TypesInfo.TypeOf(xx).(type) {
  524. case *types.Slice:
  525. nilType = "nil slices"
  526. case *types.Map:
  527. nilType = "nil maps"
  528. case *types.Chan:
  529. nilType = "nil channels"
  530. default:
  531. return
  532. }
  533. ReportNodefFG(pass, expr, "should omit nil check; len() for %s is defined as zero", nilType)
  534. }
  535. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
  536. return nil, nil
  537. }
  538. func LintSlicing(pass *analysis.Pass) (interface{}, error) {
  539. fn := func(node ast.Node) {
  540. n := node.(*ast.SliceExpr)
  541. if n.Max != nil {
  542. return
  543. }
  544. s, ok := n.X.(*ast.Ident)
  545. if !ok || s.Obj == nil {
  546. return
  547. }
  548. call, ok := n.High.(*ast.CallExpr)
  549. if !ok || len(call.Args) != 1 || call.Ellipsis.IsValid() {
  550. return
  551. }
  552. fun, ok := call.Fun.(*ast.Ident)
  553. if !ok || fun.Name != "len" {
  554. return
  555. }
  556. if _, ok := pass.TypesInfo.ObjectOf(fun).(*types.Builtin); !ok {
  557. return
  558. }
  559. arg, ok := call.Args[Arg("len.v")].(*ast.Ident)
  560. if !ok || arg.Obj != s.Obj {
  561. return
  562. }
  563. ReportNodefFG(pass, n, "should omit second index in slice, s[a:len(s)] is identical to s[a:]")
  564. }
  565. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.SliceExpr)(nil)}, fn)
  566. return nil, nil
  567. }
  568. func refersTo(pass *analysis.Pass, expr ast.Expr, ident *ast.Ident) bool {
  569. found := false
  570. fn := func(node ast.Node) bool {
  571. ident2, ok := node.(*ast.Ident)
  572. if !ok {
  573. return true
  574. }
  575. if pass.TypesInfo.ObjectOf(ident) == pass.TypesInfo.ObjectOf(ident2) {
  576. found = true
  577. return false
  578. }
  579. return true
  580. }
  581. ast.Inspect(expr, fn)
  582. return found
  583. }
  584. func LintLoopAppend(pass *analysis.Pass) (interface{}, error) {
  585. fn := func(node ast.Node) {
  586. loop := node.(*ast.RangeStmt)
  587. if !IsBlank(loop.Key) {
  588. return
  589. }
  590. val, ok := loop.Value.(*ast.Ident)
  591. if !ok {
  592. return
  593. }
  594. if len(loop.Body.List) != 1 {
  595. return
  596. }
  597. stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
  598. if !ok {
  599. return
  600. }
  601. if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
  602. return
  603. }
  604. if refersTo(pass, stmt.Lhs[0], val) {
  605. return
  606. }
  607. call, ok := stmt.Rhs[0].(*ast.CallExpr)
  608. if !ok {
  609. return
  610. }
  611. if len(call.Args) != 2 || call.Ellipsis.IsValid() {
  612. return
  613. }
  614. fun, ok := call.Fun.(*ast.Ident)
  615. if !ok {
  616. return
  617. }
  618. obj := pass.TypesInfo.ObjectOf(fun)
  619. fn, ok := obj.(*types.Builtin)
  620. if !ok || fn.Name() != "append" {
  621. return
  622. }
  623. src := pass.TypesInfo.TypeOf(loop.X)
  624. dst := pass.TypesInfo.TypeOf(call.Args[Arg("append.slice")])
  625. // TODO(dominikh) remove nil check once Go issue #15173 has
  626. // been fixed
  627. if src == nil {
  628. return
  629. }
  630. if !types.Identical(src, dst) {
  631. return
  632. }
  633. if Render(pass, stmt.Lhs[0]) != Render(pass, call.Args[Arg("append.slice")]) {
  634. return
  635. }
  636. el, ok := call.Args[Arg("append.elems")].(*ast.Ident)
  637. if !ok {
  638. return
  639. }
  640. if pass.TypesInfo.ObjectOf(val) != pass.TypesInfo.ObjectOf(el) {
  641. return
  642. }
  643. ReportNodefFG(pass, loop, "should replace loop with %s = append(%s, %s...)",
  644. Render(pass, stmt.Lhs[0]), Render(pass, call.Args[Arg("append.slice")]), Render(pass, loop.X))
  645. }
  646. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
  647. return nil, nil
  648. }
  649. func LintTimeSince(pass *analysis.Pass) (interface{}, error) {
  650. fn := func(node ast.Node) {
  651. call := node.(*ast.CallExpr)
  652. sel, ok := call.Fun.(*ast.SelectorExpr)
  653. if !ok {
  654. return
  655. }
  656. if !IsCallToAST(pass, sel.X, "time.Now") {
  657. return
  658. }
  659. if sel.Sel.Name != "Sub" {
  660. return
  661. }
  662. ReportNodefFG(pass, call, "should use time.Since instead of time.Now().Sub")
  663. }
  664. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  665. return nil, nil
  666. }
  667. func LintTimeUntil(pass *analysis.Pass) (interface{}, error) {
  668. if !IsGoVersion(pass, 8) {
  669. return nil, nil
  670. }
  671. fn := func(node ast.Node) {
  672. call := node.(*ast.CallExpr)
  673. if !IsCallToAST(pass, call, "(time.Time).Sub") {
  674. return
  675. }
  676. if !IsCallToAST(pass, call.Args[Arg("(time.Time).Sub.u")], "time.Now") {
  677. return
  678. }
  679. ReportNodefFG(pass, call, "should use time.Until instead of t.Sub(time.Now())")
  680. }
  681. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  682. return nil, nil
  683. }
  684. func LintUnnecessaryBlank(pass *analysis.Pass) (interface{}, error) {
  685. fn1 := func(node ast.Node) {
  686. assign := node.(*ast.AssignStmt)
  687. if len(assign.Lhs) != 2 || len(assign.Rhs) != 1 {
  688. return
  689. }
  690. if !IsBlank(assign.Lhs[1]) {
  691. return
  692. }
  693. switch rhs := assign.Rhs[0].(type) {
  694. case *ast.IndexExpr:
  695. // The type-checker should make sure that it's a map, but
  696. // let's be safe.
  697. if _, ok := pass.TypesInfo.TypeOf(rhs.X).Underlying().(*types.Map); !ok {
  698. return
  699. }
  700. case *ast.UnaryExpr:
  701. if rhs.Op != token.ARROW {
  702. return
  703. }
  704. default:
  705. return
  706. }
  707. cp := *assign
  708. cp.Lhs = cp.Lhs[0:1]
  709. ReportNodefFG(pass, assign, "should write %s instead of %s", Render(pass, &cp), Render(pass, assign))
  710. }
  711. fn2 := func(node ast.Node) {
  712. stmt := node.(*ast.AssignStmt)
  713. if len(stmt.Lhs) != len(stmt.Rhs) {
  714. return
  715. }
  716. for i, lh := range stmt.Lhs {
  717. rh := stmt.Rhs[i]
  718. if !IsBlank(lh) {
  719. continue
  720. }
  721. expr, ok := rh.(*ast.UnaryExpr)
  722. if !ok {
  723. continue
  724. }
  725. if expr.Op != token.ARROW {
  726. continue
  727. }
  728. ReportNodefFG(pass, lh, "'_ = <-ch' can be simplified to '<-ch'")
  729. }
  730. }
  731. fn3 := func(node ast.Node) {
  732. rs := node.(*ast.RangeStmt)
  733. // for x, _
  734. if !IsBlank(rs.Key) && IsBlank(rs.Value) {
  735. ReportNodefFG(pass, rs.Value, "should omit value from range; this loop is equivalent to `for %s %s range ...`", Render(pass, rs.Key), rs.Tok)
  736. }
  737. // for _, _ || for _
  738. if IsBlank(rs.Key) && (IsBlank(rs.Value) || rs.Value == nil) {
  739. ReportNodefFG(pass, rs.Key, "should omit values from range; this loop is equivalent to `for range ...`")
  740. }
  741. }
  742. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.AssignStmt)(nil)}, fn1)
  743. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.AssignStmt)(nil)}, fn2)
  744. if IsGoVersion(pass, 4) {
  745. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn3)
  746. }
  747. return nil, nil
  748. }
  749. func LintSimplerStructConversion(pass *analysis.Pass) (interface{}, error) {
  750. var skip ast.Node
  751. fn := func(node ast.Node) {
  752. // Do not suggest type conversion between pointers
  753. if unary, ok := node.(*ast.UnaryExpr); ok && unary.Op == token.AND {
  754. if lit, ok := unary.X.(*ast.CompositeLit); ok {
  755. skip = lit
  756. }
  757. return
  758. }
  759. if node == skip {
  760. return
  761. }
  762. lit, ok := node.(*ast.CompositeLit)
  763. if !ok {
  764. return
  765. }
  766. typ1, _ := pass.TypesInfo.TypeOf(lit.Type).(*types.Named)
  767. if typ1 == nil {
  768. return
  769. }
  770. s1, ok := typ1.Underlying().(*types.Struct)
  771. if !ok {
  772. return
  773. }
  774. var typ2 *types.Named
  775. var ident *ast.Ident
  776. getSelType := func(expr ast.Expr) (types.Type, *ast.Ident, bool) {
  777. sel, ok := expr.(*ast.SelectorExpr)
  778. if !ok {
  779. return nil, nil, false
  780. }
  781. ident, ok := sel.X.(*ast.Ident)
  782. if !ok {
  783. return nil, nil, false
  784. }
  785. typ := pass.TypesInfo.TypeOf(sel.X)
  786. return typ, ident, typ != nil
  787. }
  788. if len(lit.Elts) == 0 {
  789. return
  790. }
  791. if s1.NumFields() != len(lit.Elts) {
  792. return
  793. }
  794. for i, elt := range lit.Elts {
  795. var t types.Type
  796. var id *ast.Ident
  797. var ok bool
  798. switch elt := elt.(type) {
  799. case *ast.SelectorExpr:
  800. t, id, ok = getSelType(elt)
  801. if !ok {
  802. return
  803. }
  804. if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name {
  805. return
  806. }
  807. case *ast.KeyValueExpr:
  808. var sel *ast.SelectorExpr
  809. sel, ok = elt.Value.(*ast.SelectorExpr)
  810. if !ok {
  811. return
  812. }
  813. if elt.Key.(*ast.Ident).Name != sel.Sel.Name {
  814. return
  815. }
  816. t, id, ok = getSelType(elt.Value)
  817. }
  818. if !ok {
  819. return
  820. }
  821. // All fields must be initialized from the same object
  822. if ident != nil && ident.Obj != id.Obj {
  823. return
  824. }
  825. typ2, _ = t.(*types.Named)
  826. if typ2 == nil {
  827. return
  828. }
  829. ident = id
  830. }
  831. if typ2 == nil {
  832. return
  833. }
  834. if typ1.Obj().Pkg() != typ2.Obj().Pkg() {
  835. // Do not suggest type conversions between different
  836. // packages. Types in different packages might only match
  837. // by coincidence. Furthermore, if the dependency ever
  838. // adds more fields to its type, it could break the code
  839. // that relies on the type conversion to work.
  840. return
  841. }
  842. s2, ok := typ2.Underlying().(*types.Struct)
  843. if !ok {
  844. return
  845. }
  846. if typ1 == typ2 {
  847. return
  848. }
  849. if IsGoVersion(pass, 8) {
  850. if !types.IdenticalIgnoreTags(s1, s2) {
  851. return
  852. }
  853. } else {
  854. if !types.Identical(s1, s2) {
  855. return
  856. }
  857. }
  858. ReportNodefFG(pass, node, "should convert %s (type %s) to %s instead of using struct literal",
  859. ident.Name, typ2.Obj().Name(), typ1.Obj().Name())
  860. }
  861. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.UnaryExpr)(nil), (*ast.CompositeLit)(nil)}, fn)
  862. return nil, nil
  863. }
  864. func LintTrim(pass *analysis.Pass) (interface{}, error) {
  865. sameNonDynamic := func(node1, node2 ast.Node) bool {
  866. if reflect.TypeOf(node1) != reflect.TypeOf(node2) {
  867. return false
  868. }
  869. switch node1 := node1.(type) {
  870. case *ast.Ident:
  871. return node1.Obj == node2.(*ast.Ident).Obj
  872. case *ast.SelectorExpr:
  873. return Render(pass, node1) == Render(pass, node2)
  874. case *ast.IndexExpr:
  875. return Render(pass, node1) == Render(pass, node2)
  876. }
  877. return false
  878. }
  879. isLenOnIdent := func(fn ast.Expr, ident ast.Expr) bool {
  880. call, ok := fn.(*ast.CallExpr)
  881. if !ok {
  882. return false
  883. }
  884. if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "len" {
  885. return false
  886. }
  887. if len(call.Args) != 1 {
  888. return false
  889. }
  890. return sameNonDynamic(call.Args[Arg("len.v")], ident)
  891. }
  892. fn := func(node ast.Node) {
  893. var pkg string
  894. var fun string
  895. ifstmt := node.(*ast.IfStmt)
  896. if ifstmt.Init != nil {
  897. return
  898. }
  899. if ifstmt.Else != nil {
  900. return
  901. }
  902. if len(ifstmt.Body.List) != 1 {
  903. return
  904. }
  905. condCall, ok := ifstmt.Cond.(*ast.CallExpr)
  906. if !ok {
  907. return
  908. }
  909. switch {
  910. case IsCallToAST(pass, condCall, "strings.HasPrefix"):
  911. pkg = "strings"
  912. fun = "HasPrefix"
  913. case IsCallToAST(pass, condCall, "strings.HasSuffix"):
  914. pkg = "strings"
  915. fun = "HasSuffix"
  916. case IsCallToAST(pass, condCall, "strings.Contains"):
  917. pkg = "strings"
  918. fun = "Contains"
  919. case IsCallToAST(pass, condCall, "bytes.HasPrefix"):
  920. pkg = "bytes"
  921. fun = "HasPrefix"
  922. case IsCallToAST(pass, condCall, "bytes.HasSuffix"):
  923. pkg = "bytes"
  924. fun = "HasSuffix"
  925. case IsCallToAST(pass, condCall, "bytes.Contains"):
  926. pkg = "bytes"
  927. fun = "Contains"
  928. default:
  929. return
  930. }
  931. assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt)
  932. if !ok {
  933. return
  934. }
  935. if assign.Tok != token.ASSIGN {
  936. return
  937. }
  938. if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
  939. return
  940. }
  941. if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) {
  942. return
  943. }
  944. switch rhs := assign.Rhs[0].(type) {
  945. case *ast.CallExpr:
  946. if len(rhs.Args) < 2 || !sameNonDynamic(condCall.Args[0], rhs.Args[0]) || !sameNonDynamic(condCall.Args[1], rhs.Args[1]) {
  947. return
  948. }
  949. if IsCallToAST(pass, condCall, "strings.HasPrefix") && IsCallToAST(pass, rhs, "strings.TrimPrefix") ||
  950. IsCallToAST(pass, condCall, "strings.HasSuffix") && IsCallToAST(pass, rhs, "strings.TrimSuffix") ||
  951. IsCallToAST(pass, condCall, "strings.Contains") && IsCallToAST(pass, rhs, "strings.Replace") ||
  952. IsCallToAST(pass, condCall, "bytes.HasPrefix") && IsCallToAST(pass, rhs, "bytes.TrimPrefix") ||
  953. IsCallToAST(pass, condCall, "bytes.HasSuffix") && IsCallToAST(pass, rhs, "bytes.TrimSuffix") ||
  954. IsCallToAST(pass, condCall, "bytes.Contains") && IsCallToAST(pass, rhs, "bytes.Replace") {
  955. ReportNodefFG(pass, ifstmt, "should replace this if statement with an unconditional %s", CallNameAST(pass, rhs))
  956. }
  957. return
  958. case *ast.SliceExpr:
  959. slice := rhs
  960. if !ok {
  961. return
  962. }
  963. if slice.Slice3 {
  964. return
  965. }
  966. if !sameNonDynamic(slice.X, condCall.Args[0]) {
  967. return
  968. }
  969. var index ast.Expr
  970. switch fun {
  971. case "HasPrefix":
  972. // TODO(dh) We could detect a High that is len(s), but another
  973. // rule will already flag that, anyway.
  974. if slice.High != nil {
  975. return
  976. }
  977. index = slice.Low
  978. case "HasSuffix":
  979. if slice.Low != nil {
  980. n, ok := ExprToInt(pass, slice.Low)
  981. if !ok || n != 0 {
  982. return
  983. }
  984. }
  985. index = slice.High
  986. }
  987. switch index := index.(type) {
  988. case *ast.CallExpr:
  989. if fun != "HasPrefix" {
  990. return
  991. }
  992. if fn, ok := index.Fun.(*ast.Ident); !ok || fn.Name != "len" {
  993. return
  994. }
  995. if len(index.Args) != 1 {
  996. return
  997. }
  998. id3 := index.Args[Arg("len.v")]
  999. switch oid3 := condCall.Args[1].(type) {
  1000. case *ast.BasicLit:
  1001. if pkg != "strings" {
  1002. return
  1003. }
  1004. lit, ok := id3.(*ast.BasicLit)
  1005. if !ok {
  1006. return
  1007. }
  1008. s1, ok1 := ExprToString(pass, lit)
  1009. s2, ok2 := ExprToString(pass, condCall.Args[1])
  1010. if !ok1 || !ok2 || s1 != s2 {
  1011. return
  1012. }
  1013. default:
  1014. if !sameNonDynamic(id3, oid3) {
  1015. return
  1016. }
  1017. }
  1018. case *ast.BasicLit, *ast.Ident:
  1019. if fun != "HasPrefix" {
  1020. return
  1021. }
  1022. if pkg != "strings" {
  1023. return
  1024. }
  1025. string, ok1 := ExprToString(pass, condCall.Args[1])
  1026. int, ok2 := ExprToInt(pass, slice.Low)
  1027. if !ok1 || !ok2 || int != int64(len(string)) {
  1028. return
  1029. }
  1030. case *ast.BinaryExpr:
  1031. if fun != "HasSuffix" {
  1032. return
  1033. }
  1034. if index.Op != token.SUB {
  1035. return
  1036. }
  1037. if !isLenOnIdent(index.X, condCall.Args[0]) ||
  1038. !isLenOnIdent(index.Y, condCall.Args[1]) {
  1039. return
  1040. }
  1041. default:
  1042. return
  1043. }
  1044. var replacement string
  1045. switch fun {
  1046. case "HasPrefix":
  1047. replacement = "TrimPrefix"
  1048. case "HasSuffix":
  1049. replacement = "TrimSuffix"
  1050. }
  1051. ReportNodefFG(pass, ifstmt, "should replace this if statement with an unconditional %s.%s", pkg, replacement)
  1052. }
  1053. }
  1054. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
  1055. return nil, nil
  1056. }
  1057. func LintLoopSlide(pass *analysis.Pass) (interface{}, error) {
  1058. // TODO(dh): detect bs[i+offset] in addition to bs[offset+i]
  1059. // TODO(dh): consider merging this function with LintLoopCopy
  1060. // TODO(dh): detect length that is an expression, not a variable name
  1061. // TODO(dh): support sliding to a different offset than the beginning of the slice
  1062. fn := func(node ast.Node) {
  1063. /*
  1064. for i := 0; i < n; i++ {
  1065. bs[i] = bs[offset+i]
  1066. }
  1067. copy(bs[:n], bs[offset:offset+n])
  1068. */
  1069. loop := node.(*ast.ForStmt)
  1070. if len(loop.Body.List) != 1 || loop.Init == nil || loop.Cond == nil || loop.Post == nil {
  1071. return
  1072. }
  1073. assign, ok := loop.Init.(*ast.AssignStmt)
  1074. if !ok || len(assign.Lhs) != 1 || len(assign.Rhs) != 1 || !IsZero(assign.Rhs[0]) {
  1075. return
  1076. }
  1077. initvar, ok := assign.Lhs[0].(*ast.Ident)
  1078. if !ok {
  1079. return
  1080. }
  1081. post, ok := loop.Post.(*ast.IncDecStmt)
  1082. if !ok || post.Tok != token.INC {
  1083. return
  1084. }
  1085. postvar, ok := post.X.(*ast.Ident)
  1086. if !ok || pass.TypesInfo.ObjectOf(postvar) != pass.TypesInfo.ObjectOf(initvar) {
  1087. return
  1088. }
  1089. bin, ok := loop.Cond.(*ast.BinaryExpr)
  1090. if !ok || bin.Op != token.LSS {
  1091. return
  1092. }
  1093. binx, ok := bin.X.(*ast.Ident)
  1094. if !ok || pass.TypesInfo.ObjectOf(binx) != pass.TypesInfo.ObjectOf(initvar) {
  1095. return
  1096. }
  1097. biny, ok := bin.Y.(*ast.Ident)
  1098. if !ok {
  1099. return
  1100. }
  1101. assign, ok = loop.Body.List[0].(*ast.AssignStmt)
  1102. if !ok || len(assign.Lhs) != 1 || len(assign.Rhs) != 1 || assign.Tok != token.ASSIGN {
  1103. return
  1104. }
  1105. lhs, ok := assign.Lhs[0].(*ast.IndexExpr)
  1106. if !ok {
  1107. return
  1108. }
  1109. rhs, ok := assign.Rhs[0].(*ast.IndexExpr)
  1110. if !ok {
  1111. return
  1112. }
  1113. bs1, ok := lhs.X.(*ast.Ident)
  1114. if !ok {
  1115. return
  1116. }
  1117. bs2, ok := rhs.X.(*ast.Ident)
  1118. if !ok {
  1119. return
  1120. }
  1121. obj1 := pass.TypesInfo.ObjectOf(bs1)
  1122. obj2 := pass.TypesInfo.ObjectOf(bs2)
  1123. if obj1 != obj2 {
  1124. return
  1125. }
  1126. if _, ok := obj1.Type().Underlying().(*types.Slice); !ok {
  1127. return
  1128. }
  1129. index1, ok := lhs.Index.(*ast.Ident)
  1130. if !ok || pass.TypesInfo.ObjectOf(index1) != pass.TypesInfo.ObjectOf(initvar) {
  1131. return
  1132. }
  1133. index2, ok := rhs.Index.(*ast.BinaryExpr)
  1134. if !ok || index2.Op != token.ADD {
  1135. return
  1136. }
  1137. add1, ok := index2.X.(*ast.Ident)
  1138. if !ok {
  1139. return
  1140. }
  1141. add2, ok := index2.Y.(*ast.Ident)
  1142. if !ok || pass.TypesInfo.ObjectOf(add2) != pass.TypesInfo.ObjectOf(initvar) {
  1143. return
  1144. }
  1145. ReportNodefFG(pass, loop, "should use copy(%s[:%s], %s[%s:]) instead", Render(pass, bs1), Render(pass, biny), Render(pass, bs1), Render(pass, add1))
  1146. }
  1147. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
  1148. return nil, nil
  1149. }
  1150. func LintMakeLenCap(pass *analysis.Pass) (interface{}, error) {
  1151. fn := func(node ast.Node) {
  1152. call := node.(*ast.CallExpr)
  1153. if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "make" {
  1154. // FIXME check whether make is indeed the built-in function
  1155. return
  1156. }
  1157. switch len(call.Args) {
  1158. case 2:
  1159. // make(T, len)
  1160. if _, ok := pass.TypesInfo.TypeOf(call.Args[Arg("make.t")]).Underlying().(*types.Slice); ok {
  1161. break
  1162. }
  1163. if IsZero(call.Args[Arg("make.size[0]")]) {
  1164. ReportNodefFG(pass, call.Args[Arg("make.size[0]")], "should use make(%s) instead", Render(pass, call.Args[Arg("make.t")]))
  1165. }
  1166. case 3:
  1167. // make(T, len, cap)
  1168. if Render(pass, call.Args[Arg("make.size[0]")]) == Render(pass, call.Args[Arg("make.size[1]")]) {
  1169. ReportNodefFG(pass, call.Args[Arg("make.size[0]")],
  1170. "should use make(%s, %s) instead",
  1171. Render(pass, call.Args[Arg("make.t")]), Render(pass, call.Args[Arg("make.size[0]")]))
  1172. }
  1173. }
  1174. }
  1175. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  1176. return nil, nil
  1177. }
  1178. func LintAssertNotNil(pass *analysis.Pass) (interface{}, error) {
  1179. isNilCheck := func(ident *ast.Ident, expr ast.Expr) bool {
  1180. xbinop, ok := expr.(*ast.BinaryExpr)
  1181. if !ok || xbinop.Op != token.NEQ {
  1182. return false
  1183. }
  1184. xident, ok := xbinop.X.(*ast.Ident)
  1185. if !ok || xident.Obj != ident.Obj {
  1186. return false
  1187. }
  1188. if !IsNil(pass, xbinop.Y) {
  1189. return false
  1190. }
  1191. return true
  1192. }
  1193. isOKCheck := func(ident *ast.Ident, expr ast.Expr) bool {
  1194. yident, ok := expr.(*ast.Ident)
  1195. if !ok || yident.Obj != ident.Obj {
  1196. return false
  1197. }
  1198. return true
  1199. }
  1200. fn1 := func(node ast.Node) {
  1201. ifstmt := node.(*ast.IfStmt)
  1202. assign, ok := ifstmt.Init.(*ast.AssignStmt)
  1203. if !ok || len(assign.Lhs) != 2 || len(assign.Rhs) != 1 || !IsBlank(assign.Lhs[0]) {
  1204. return
  1205. }
  1206. assert, ok := assign.Rhs[0].(*ast.TypeAssertExpr)
  1207. if !ok {
  1208. return
  1209. }
  1210. binop, ok := ifstmt.Cond.(*ast.BinaryExpr)
  1211. if !ok || binop.Op != token.LAND {
  1212. return
  1213. }
  1214. assertIdent, ok := assert.X.(*ast.Ident)
  1215. if !ok {
  1216. return
  1217. }
  1218. assignIdent, ok := assign.Lhs[1].(*ast.Ident)
  1219. if !ok {
  1220. return
  1221. }
  1222. if !(isNilCheck(assertIdent, binop.X) && isOKCheck(assignIdent, binop.Y)) &&
  1223. !(isNilCheck(assertIdent, binop.Y) && isOKCheck(assignIdent, binop.X)) {
  1224. return
  1225. }
  1226. ReportNodefFG(pass, ifstmt, "when %s is true, %s can't be nil", Render(pass, assignIdent), Render(pass, assertIdent))
  1227. }
  1228. fn2 := func(node ast.Node) {
  1229. // Check that outer ifstmt is an 'if x != nil {}'
  1230. ifstmt := node.(*ast.IfStmt)
  1231. if ifstmt.Init != nil {
  1232. return
  1233. }
  1234. if ifstmt.Else != nil {
  1235. return
  1236. }
  1237. if len(ifstmt.Body.List) != 1 {
  1238. return
  1239. }
  1240. binop, ok := ifstmt.Cond.(*ast.BinaryExpr)
  1241. if !ok {
  1242. return
  1243. }
  1244. if binop.Op != token.NEQ {
  1245. return
  1246. }
  1247. lhs, ok := binop.X.(*ast.Ident)
  1248. if !ok {
  1249. return
  1250. }
  1251. if !IsNil(pass, binop.Y) {
  1252. return
  1253. }
  1254. // Check that inner ifstmt is an `if _, ok := x.(T); ok {}`
  1255. ifstmt, ok = ifstmt.Body.List[0].(*ast.IfStmt)
  1256. if !ok {
  1257. return
  1258. }
  1259. assign, ok := ifstmt.Init.(*ast.AssignStmt)
  1260. if !ok || len(assign.Lhs) != 2 || len(assign.Rhs) != 1 || !IsBlank(assign.Lhs[0]) {
  1261. return
  1262. }
  1263. assert, ok := assign.Rhs[0].(*ast.TypeAssertExpr)
  1264. if !ok {
  1265. return
  1266. }
  1267. assertIdent, ok := assert.X.(*ast.Ident)
  1268. if !ok {
  1269. return
  1270. }
  1271. if lhs.Obj != assertIdent.Obj {
  1272. return
  1273. }
  1274. assignIdent, ok := assign.Lhs[1].(*ast.Ident)
  1275. if !ok {
  1276. return
  1277. }
  1278. if !isOKCheck(assignIdent, ifstmt.Cond) {
  1279. return
  1280. }
  1281. ReportNodefFG(pass, ifstmt, "when %s is true, %s can't be nil", Render(pass, assignIdent), Render(pass, assertIdent))
  1282. }
  1283. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn1)
  1284. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn2)
  1285. return nil, nil
  1286. }
  1287. func LintDeclareAssign(pass *analysis.Pass) (interface{}, error) {
  1288. hasMultipleAssignments := func(root ast.Node, ident *ast.Ident) bool {
  1289. num := 0
  1290. ast.Inspect(root, func(node ast.Node) bool {
  1291. if num >= 2 {
  1292. return false
  1293. }
  1294. assign, ok := node.(*ast.AssignStmt)
  1295. if !ok {
  1296. return true
  1297. }
  1298. for _, lhs := range assign.Lhs {
  1299. if oident, ok := lhs.(*ast.Ident); ok {
  1300. if oident.Obj == ident.Obj {
  1301. num++
  1302. }
  1303. }
  1304. }
  1305. return true
  1306. })
  1307. return num >= 2
  1308. }
  1309. fn := func(node ast.Node) {
  1310. block := node.(*ast.BlockStmt)
  1311. if len(block.List) < 2 {
  1312. return
  1313. }
  1314. for i, stmt := range block.List[:len(block.List)-1] {
  1315. _ = i
  1316. decl, ok := stmt.(*ast.DeclStmt)
  1317. if !ok {
  1318. continue
  1319. }
  1320. gdecl, ok := decl.Decl.(*ast.GenDecl)
  1321. if !ok || gdecl.Tok != token.VAR || len(gdecl.Specs) != 1 {
  1322. continue
  1323. }
  1324. vspec, ok := gdecl.Specs[0].(*ast.ValueSpec)
  1325. if !ok || len(vspec.Names) != 1 || len(vspec.Values) != 0 {
  1326. continue
  1327. }
  1328. assign, ok := block.List[i+1].(*ast.AssignStmt)
  1329. if !ok || assign.Tok != token.ASSIGN {
  1330. continue
  1331. }
  1332. if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
  1333. continue
  1334. }
  1335. ident, ok := assign.Lhs[0].(*ast.Ident)
  1336. if !ok {
  1337. continue
  1338. }
  1339. if vspec.Names[0].Obj != ident.Obj {
  1340. continue
  1341. }
  1342. if refersTo(pass, assign.Rhs[0], ident) {
  1343. continue
  1344. }
  1345. if hasMultipleAssignments(block, ident) {
  1346. continue
  1347. }
  1348. ReportNodefFG(pass, decl, "should merge variable declaration with assignment on next line")
  1349. }
  1350. }
  1351. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BlockStmt)(nil)}, fn)
  1352. return nil, nil
  1353. }
  1354. func LintRedundantBreak(pass *analysis.Pass) (interface{}, error) {
  1355. fn1 := func(node ast.Node) {
  1356. clause := node.(*ast.CaseClause)
  1357. if len(clause.Body) < 2 {
  1358. return
  1359. }
  1360. branch, ok := clause.Body[len(clause.Body)-1].(*ast.BranchStmt)
  1361. if !ok || branch.Tok != token.BREAK || branch.Label != nil {
  1362. return
  1363. }
  1364. ReportNodefFG(pass, branch, "redundant break statement")
  1365. }
  1366. fn2 := func(node ast.Node) {
  1367. var ret *ast.FieldList
  1368. var body *ast.BlockStmt
  1369. switch x := node.(type) {
  1370. case *ast.FuncDecl:
  1371. ret = x.Type.Results
  1372. body = x.Body
  1373. case *ast.FuncLit:
  1374. ret = x.Type.Results
  1375. body = x.Body
  1376. default:
  1377. panic(fmt.Sprintf("unreachable: %T", node))
  1378. }
  1379. // if the func has results, a return can't be redundant.
  1380. // similarly, if there are no statements, there can be
  1381. // no return.
  1382. if ret != nil || body == nil || len(body.List) < 1 {
  1383. return
  1384. }
  1385. rst, ok := body.List[len(body.List)-1].(*ast.ReturnStmt)
  1386. if !ok {
  1387. return
  1388. }
  1389. // we don't need to check rst.Results as we already
  1390. // checked x.Type.Results to be nil.
  1391. ReportNodefFG(pass, rst, "redundant return statement")
  1392. }
  1393. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CaseClause)(nil)}, fn1)
  1394. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)}, fn2)
  1395. return nil, nil
  1396. }
  1397. func isStringer(T types.Type, msCache *typeutil.MethodSetCache) bool {
  1398. ms := msCache.MethodSet(T)
  1399. sel := ms.Lookup(nil, "String")
  1400. if sel == nil {
  1401. return false
  1402. }
  1403. fn, ok := sel.Obj().(*types.Func)
  1404. if !ok {
  1405. // should be unreachable
  1406. return false
  1407. }
  1408. sig := fn.Type().(*types.Signature)
  1409. if sig.Params().Len() != 0 {
  1410. return false
  1411. }
  1412. if sig.Results().Len() != 1 {
  1413. return false
  1414. }
  1415. if !IsType(sig.Results().At(0).Type(), "string") {
  1416. return false
  1417. }
  1418. return true
  1419. }
  1420. func LintRedundantSprintf(pass *analysis.Pass) (interface{}, error) {
  1421. fn := func(node ast.Node) {
  1422. call := node.(*ast.CallExpr)
  1423. if !IsCallToAST(pass, call, "fmt.Sprintf") {
  1424. return
  1425. }
  1426. if len(call.Args) != 2 {
  1427. return
  1428. }
  1429. if s, ok := ExprToString(pass, call.Args[Arg("fmt.Sprintf.format")]); !ok || s != "%s" {
  1430. return
  1431. }
  1432. arg := call.Args[Arg("fmt.Sprintf.a[0]")]
  1433. typ := pass.TypesInfo.TypeOf(arg)
  1434. ssapkg := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).Pkg
  1435. if isStringer(typ, &ssapkg.Prog.MethodSets) {
  1436. ReportNodef(pass, call, "should use String() instead of fmt.Sprintf")
  1437. return
  1438. }
  1439. if typ.Underlying() == types.Universe.Lookup("string").Type() {
  1440. if typ == types.Universe.Lookup("string").Type() {
  1441. ReportNodefFG(pass, call, "the argument is already a string, there's no need to use fmt.Sprintf")
  1442. } else {
  1443. ReportNodefFG(pass, call, "the argument's underlying type is a string, should use a simple conversion instead of fmt.Sprintf")
  1444. }
  1445. }
  1446. }
  1447. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  1448. return nil, nil
  1449. }
  1450. func LintErrorsNewSprintf(pass *analysis.Pass) (interface{}, error) {
  1451. fn := func(node ast.Node) {
  1452. if !IsCallToAST(pass, node, "errors.New") {
  1453. return
  1454. }
  1455. call := node.(*ast.CallExpr)
  1456. if !IsCallToAST(pass, call.Args[Arg("errors.New.text")], "fmt.Sprintf") {
  1457. return
  1458. }
  1459. ReportNodefFG(pass, node, "should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...))")
  1460. }
  1461. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
  1462. return nil, nil
  1463. }
  1464. func LintRangeStringRunes(pass *analysis.Pass) (interface{}, error) {
  1465. return sharedcheck.CheckRangeStringRunes(pass)
  1466. }
  1467. func LintNilCheckAroundRange(pass *analysis.Pass) (interface{}, error) {
  1468. fn := func(node ast.Node) {
  1469. ifstmt := node.(*ast.IfStmt)
  1470. cond, ok := ifstmt.Cond.(*ast.BinaryExpr)
  1471. if !ok {
  1472. return
  1473. }
  1474. if cond.Op != token.NEQ || !IsNil(pass, cond.Y) || len(ifstmt.Body.List) != 1 {
  1475. return
  1476. }
  1477. loop, ok := ifstmt.Body.List[0].(*ast.RangeStmt)
  1478. if !ok {
  1479. return
  1480. }
  1481. ifXIdent, ok := cond.X.(*ast.Ident)
  1482. if !ok {
  1483. return
  1484. }
  1485. rangeXIdent, ok := loop.X.(*ast.Ident)
  1486. if !ok {
  1487. return
  1488. }
  1489. if ifXIdent.Obj != rangeXIdent.Obj {
  1490. return
  1491. }
  1492. switch pass.TypesInfo.TypeOf(rangeXIdent).(type) {
  1493. case *types.Slice, *types.Map:
  1494. ReportNodefFG(pass, node, "unnecessary nil check around range")
  1495. }
  1496. }
  1497. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
  1498. return nil, nil
  1499. }
  1500. func isPermissibleSort(pass *analysis.Pass, node ast.Node) bool {
  1501. call := node.(*ast.CallExpr)
  1502. typeconv, ok := call.Args[0].(*ast.CallExpr)
  1503. if !ok {
  1504. return true
  1505. }
  1506. sel, ok := typeconv.Fun.(*ast.SelectorExpr)
  1507. if !ok {
  1508. return true
  1509. }
  1510. name := SelectorName(pass, sel)
  1511. switch name {
  1512. case "sort.IntSlice", "sort.Float64Slice", "sort.StringSlice":
  1513. default:
  1514. return true
  1515. }
  1516. return false
  1517. }
  1518. func LintSortHelpers(pass *analysis.Pass) (interface{}, error) {
  1519. type Error struct {
  1520. node ast.Node
  1521. msg string
  1522. }
  1523. var allErrors []Error
  1524. fn := func(node ast.Node) {
  1525. var body *ast.BlockStmt
  1526. switch node := node.(type) {
  1527. case *ast.FuncLit:
  1528. body = node.Body
  1529. case *ast.FuncDecl:
  1530. body = node.Body
  1531. default:
  1532. panic(fmt.Sprintf("unreachable: %T", node))
  1533. }
  1534. if body == nil {
  1535. return
  1536. }
  1537. var errors []Error
  1538. permissible := false
  1539. fnSorts := func(node ast.Node) bool {
  1540. if permissible {
  1541. return false
  1542. }
  1543. if !IsCallToAST(pass, node, "sort.Sort") {
  1544. return true
  1545. }
  1546. if isPermissibleSort(pass, node) {
  1547. permissible = true
  1548. return false
  1549. }
  1550. call := node.(*ast.CallExpr)
  1551. typeconv := call.Args[Arg("sort.Sort.data")].(*ast.CallExpr)
  1552. sel := typeconv.Fun.(*ast.SelectorExpr)
  1553. name := SelectorName(pass, sel)
  1554. switch name {
  1555. case "sort.IntSlice":
  1556. errors = append(errors, Error{node, "should use sort.Ints(...) instead of sort.Sort(sort.IntSlice(...))"})
  1557. case "sort.Float64Slice":
  1558. errors = append(errors, Error{node, "should use sort.Float64s(...) instead of sort.Sort(sort.Float64Slice(...))"})
  1559. case "sort.StringSlice":
  1560. errors = append(errors, Error{node, "should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...))"})
  1561. }
  1562. return true
  1563. }
  1564. ast.Inspect(body, fnSorts)
  1565. if permissible {
  1566. return
  1567. }
  1568. allErrors = append(allErrors, errors...)
  1569. }
  1570. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn)
  1571. sort.Slice(allErrors, func(i, j int) bool {
  1572. return allErrors[i].node.Pos() < allErrors[j].node.Pos()
  1573. })
  1574. var prev token.Pos
  1575. for _, err := range allErrors {
  1576. if err.node.Pos() == prev {
  1577. continue
  1578. }
  1579. prev = err.node.Pos()
  1580. ReportNodefFG(pass, err.node, "%s", err.msg)
  1581. }
  1582. return nil, nil
  1583. }
  1584. func LintGuardedDelete(pass *analysis.Pass) (interface{}, error) {
  1585. isCommaOkMapIndex := func(stmt ast.Stmt) (b *ast.Ident, m ast.Expr, key ast.Expr, ok bool) {
  1586. // Has to be of the form `_, <b:*ast.Ident> = <m:*types.Map>[<key>]
  1587. assign, ok := stmt.(*ast.AssignStmt)
  1588. if !ok {
  1589. return nil, nil, nil, false
  1590. }
  1591. if len(assign.Lhs) != 2 || len(assign.Rhs) != 1 {
  1592. return nil, nil, nil, false
  1593. }
  1594. if !IsBlank(assign.Lhs[0]) {
  1595. return nil, nil, nil, false
  1596. }
  1597. ident, ok := assign.Lhs[1].(*ast.Ident)
  1598. if !ok {
  1599. return nil, nil, nil, false
  1600. }
  1601. index, ok := assign.Rhs[0].(*ast.IndexExpr)
  1602. if !ok {
  1603. return nil, nil, nil, false
  1604. }
  1605. if _, ok := pass.TypesInfo.TypeOf(index.X).(*types.Map); !ok {
  1606. return nil, nil, nil, false
  1607. }
  1608. key = index.Index
  1609. return ident, index.X, key, true
  1610. }
  1611. fn := func(node ast.Node) {
  1612. stmt := node.(*ast.IfStmt)
  1613. if len(stmt.Body.List) != 1 {
  1614. return
  1615. }
  1616. if stmt.Else != nil {
  1617. return
  1618. }
  1619. expr, ok := stmt.Body.List[0].(*ast.ExprStmt)
  1620. if !ok {
  1621. return
  1622. }
  1623. call, ok := expr.X.(*ast.CallExpr)
  1624. if !ok {
  1625. return
  1626. }
  1627. if !IsCallToAST(pass, call, "delete") {
  1628. return
  1629. }
  1630. b, m, key, ok := isCommaOkMapIndex(stmt.Init)
  1631. if !ok {
  1632. return
  1633. }
  1634. if cond, ok := stmt.Cond.(*ast.Ident); !ok || pass.TypesInfo.ObjectOf(cond) != pass.TypesInfo.ObjectOf(b) {
  1635. return
  1636. }
  1637. if Render(pass, call.Args[0]) != Render(pass, m) || Render(pass, call.Args[1]) != Render(pass, key) {
  1638. return
  1639. }
  1640. ReportNodefFG(pass, stmt, "unnecessary guard around call to delete")
  1641. }
  1642. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
  1643. return nil, nil
  1644. }
  1645. func LintSimplifyTypeSwitch(pass *analysis.Pass) (interface{}, error) {
  1646. fn := func(node ast.Node) {
  1647. stmt := node.(*ast.TypeSwitchStmt)
  1648. if stmt.Init != nil {
  1649. // bailing out for now, can't anticipate how type switches with initializers are being used
  1650. return
  1651. }
  1652. expr, ok := stmt.Assign.(*ast.ExprStmt)
  1653. if !ok {
  1654. // the user is in fact assigning the result
  1655. return
  1656. }
  1657. assert := expr.X.(*ast.TypeAssertExpr)
  1658. ident, ok := assert.X.(*ast.Ident)
  1659. if !ok {
  1660. return
  1661. }
  1662. x := pass.TypesInfo.ObjectOf(ident)
  1663. var allOffenders []ast.Node
  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.Node
  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. }
  1701. if len(allOffenders) != 0 {
  1702. at := ""
  1703. for _, offender := range allOffenders {
  1704. pos := lint.DisplayPosition(pass.Fset, offender.Pos())
  1705. at += "\n\t" + pos.String()
  1706. }
  1707. ReportNodefFG(pass, expr, "assigning the result of this type assertion to a variable (switch %s := %s.(type)) could eliminate the following type assertions:%s", Render(pass, ident), Render(pass, ident), at)
  1708. }
  1709. }
  1710. pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.TypeSwitchStmt)(nil)}, fn)
  1711. return nil, nil
  1712. }