lint.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. // Copyright (c) 2013 The Go Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file or at
  5. // https://developers.google.com/open-source/licenses/bsd.
  6. // Package lint contains a linter for Go source code.
  7. package lint // import "golang.org/x/lint"
  8. import (
  9. "bufio"
  10. "bytes"
  11. "fmt"
  12. "go/ast"
  13. "go/parser"
  14. "go/printer"
  15. "go/token"
  16. "go/types"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "unicode"
  22. "unicode/utf8"
  23. "golang.org/x/tools/go/ast/astutil"
  24. "golang.org/x/tools/go/gcexportdata"
  25. )
  26. const styleGuideBase = "https://golang.org/wiki/CodeReviewComments"
  27. // A Linter lints Go source code.
  28. type Linter struct {
  29. }
  30. // Problem represents a problem in some source code.
  31. type Problem struct {
  32. Position token.Position // position in source file
  33. Text string // the prose that describes the problem
  34. Link string // (optional) the link to the style guide for the problem
  35. Confidence float64 // a value in (0,1] estimating the confidence in this problem's correctness
  36. LineText string // the source line
  37. Category string // a short name for the general category of the problem
  38. // If the problem has a suggested fix (the minority case),
  39. // ReplacementLine is a full replacement for the relevant line of the source file.
  40. ReplacementLine string
  41. }
  42. func (p *Problem) String() string {
  43. if p.Link != "" {
  44. return p.Text + "\n\n" + p.Link
  45. }
  46. return p.Text
  47. }
  48. type byPosition []Problem
  49. func (p byPosition) Len() int { return len(p) }
  50. func (p byPosition) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  51. func (p byPosition) Less(i, j int) bool {
  52. pi, pj := p[i].Position, p[j].Position
  53. if pi.Filename != pj.Filename {
  54. return pi.Filename < pj.Filename
  55. }
  56. if pi.Line != pj.Line {
  57. return pi.Line < pj.Line
  58. }
  59. if pi.Column != pj.Column {
  60. return pi.Column < pj.Column
  61. }
  62. return p[i].Text < p[j].Text
  63. }
  64. // Lint lints src.
  65. func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) {
  66. return l.LintFiles(map[string][]byte{filename: src})
  67. }
  68. // LintFiles lints a set of files of a single package.
  69. // The argument is a map of filename to source.
  70. func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) {
  71. pkg := &pkg{
  72. fset: token.NewFileSet(),
  73. files: make(map[string]*file),
  74. }
  75. var pkgName string
  76. for filename, src := range files {
  77. if isGenerated(src) {
  78. continue // See issue #239
  79. }
  80. f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments)
  81. if err != nil {
  82. return nil, err
  83. }
  84. if pkgName == "" {
  85. pkgName = f.Name.Name
  86. } else if f.Name.Name != pkgName {
  87. return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName)
  88. }
  89. pkg.files[filename] = &file{
  90. pkg: pkg,
  91. f: f,
  92. fset: pkg.fset,
  93. src: src,
  94. filename: filename,
  95. }
  96. }
  97. if len(pkg.files) == 0 {
  98. return nil, nil
  99. }
  100. return pkg.lint(), nil
  101. }
  102. var (
  103. genHdr = []byte("// Code generated ")
  104. genFtr = []byte(" DO NOT EDIT.")
  105. )
  106. // isGenerated reports whether the source file is generated code
  107. // according the rules from https://golang.org/s/generatedcode.
  108. func isGenerated(src []byte) bool {
  109. sc := bufio.NewScanner(bytes.NewReader(src))
  110. for sc.Scan() {
  111. b := sc.Bytes()
  112. if bytes.HasPrefix(b, genHdr) && bytes.HasSuffix(b, genFtr) && len(b) >= len(genHdr)+len(genFtr) {
  113. return true
  114. }
  115. }
  116. return false
  117. }
  118. // pkg represents a package being linted.
  119. type pkg struct {
  120. fset *token.FileSet
  121. files map[string]*file
  122. typesPkg *types.Package
  123. typesInfo *types.Info
  124. // sortable is the set of types in the package that implement sort.Interface.
  125. sortable map[string]bool
  126. // main is whether this is a "main" package.
  127. main bool
  128. problems []Problem
  129. }
  130. func (p *pkg) lint() []Problem {
  131. if err := p.typeCheck(); err != nil {
  132. /* TODO(dsymonds): Consider reporting these errors when golint operates on entire packages.
  133. if e, ok := err.(types.Error); ok {
  134. pos := p.fset.Position(e.Pos)
  135. conf := 1.0
  136. if strings.Contains(e.Msg, "can't find import: ") {
  137. // Golint is probably being run in a context that doesn't support
  138. // typechecking (e.g. package files aren't found), so don't warn about it.
  139. conf = 0
  140. }
  141. if conf > 0 {
  142. p.errorfAt(pos, conf, category("typechecking"), e.Msg)
  143. }
  144. // TODO(dsymonds): Abort if !e.Soft?
  145. }
  146. */
  147. }
  148. p.scanSortable()
  149. p.main = p.isMain()
  150. for _, f := range p.files {
  151. f.lint()
  152. }
  153. sort.Sort(byPosition(p.problems))
  154. return p.problems
  155. }
  156. // file represents a file being linted.
  157. type file struct {
  158. pkg *pkg
  159. f *ast.File
  160. fset *token.FileSet
  161. src []byte
  162. filename string
  163. }
  164. func (f *file) isTest() bool { return strings.HasSuffix(f.filename, "_test.go") }
  165. func (f *file) lint() {
  166. f.lintPackageComment()
  167. f.lintImports()
  168. f.lintBlankImports()
  169. f.lintExported()
  170. f.lintNames()
  171. f.lintVarDecls()
  172. f.lintElses()
  173. f.lintRanges()
  174. f.lintErrorf()
  175. f.lintErrors()
  176. f.lintErrorStrings()
  177. f.lintReceiverNames()
  178. f.lintIncDec()
  179. f.lintErrorReturn()
  180. f.lintUnexportedReturn()
  181. f.lintTimeNames()
  182. f.lintContextKeyTypes()
  183. f.lintContextArgs()
  184. }
  185. type link string
  186. type category string
  187. // The variadic arguments may start with link and category types,
  188. // and must end with a format string and any arguments.
  189. // It returns the new Problem.
  190. func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem {
  191. pos := f.fset.Position(n.Pos())
  192. if pos.Filename == "" {
  193. pos.Filename = f.filename
  194. }
  195. return f.pkg.errorfAt(pos, confidence, args...)
  196. }
  197. func (p *pkg) errorfAt(pos token.Position, confidence float64, args ...interface{}) *Problem {
  198. problem := Problem{
  199. Position: pos,
  200. Confidence: confidence,
  201. }
  202. if pos.Filename != "" {
  203. // The file might not exist in our mapping if a //line directive was encountered.
  204. if f, ok := p.files[pos.Filename]; ok {
  205. problem.LineText = srcLine(f.src, pos)
  206. }
  207. }
  208. argLoop:
  209. for len(args) > 1 { // always leave at least the format string in args
  210. switch v := args[0].(type) {
  211. case link:
  212. problem.Link = string(v)
  213. case category:
  214. problem.Category = string(v)
  215. default:
  216. break argLoop
  217. }
  218. args = args[1:]
  219. }
  220. problem.Text = fmt.Sprintf(args[0].(string), args[1:]...)
  221. p.problems = append(p.problems, problem)
  222. return &p.problems[len(p.problems)-1]
  223. }
  224. var newImporter = func(fset *token.FileSet) types.ImporterFrom {
  225. return gcexportdata.NewImporter(fset, make(map[string]*types.Package))
  226. }
  227. func (p *pkg) typeCheck() error {
  228. config := &types.Config{
  229. // By setting a no-op error reporter, the type checker does as much work as possible.
  230. Error: func(error) {},
  231. Importer: newImporter(p.fset),
  232. }
  233. info := &types.Info{
  234. Types: make(map[ast.Expr]types.TypeAndValue),
  235. Defs: make(map[*ast.Ident]types.Object),
  236. Uses: make(map[*ast.Ident]types.Object),
  237. Scopes: make(map[ast.Node]*types.Scope),
  238. }
  239. var anyFile *file
  240. var astFiles []*ast.File
  241. for _, f := range p.files {
  242. anyFile = f
  243. astFiles = append(astFiles, f.f)
  244. }
  245. pkg, err := config.Check(anyFile.f.Name.Name, p.fset, astFiles, info)
  246. // Remember the typechecking info, even if config.Check failed,
  247. // since we will get partial information.
  248. p.typesPkg = pkg
  249. p.typesInfo = info
  250. return err
  251. }
  252. func (p *pkg) typeOf(expr ast.Expr) types.Type {
  253. if p.typesInfo == nil {
  254. return nil
  255. }
  256. return p.typesInfo.TypeOf(expr)
  257. }
  258. func (p *pkg) isNamedType(typ types.Type, importPath, name string) bool {
  259. n, ok := typ.(*types.Named)
  260. if !ok {
  261. return false
  262. }
  263. tn := n.Obj()
  264. return tn != nil && tn.Pkg() != nil && tn.Pkg().Path() == importPath && tn.Name() == name
  265. }
  266. // scopeOf returns the tightest scope encompassing id.
  267. func (p *pkg) scopeOf(id *ast.Ident) *types.Scope {
  268. var scope *types.Scope
  269. if obj := p.typesInfo.ObjectOf(id); obj != nil {
  270. scope = obj.Parent()
  271. }
  272. if scope == p.typesPkg.Scope() {
  273. // We were given a top-level identifier.
  274. // Use the file-level scope instead of the package-level scope.
  275. pos := id.Pos()
  276. for _, f := range p.files {
  277. if f.f.Pos() <= pos && pos < f.f.End() {
  278. scope = p.typesInfo.Scopes[f.f]
  279. break
  280. }
  281. }
  282. }
  283. return scope
  284. }
  285. func (p *pkg) scanSortable() {
  286. p.sortable = make(map[string]bool)
  287. // bitfield for which methods exist on each type.
  288. const (
  289. Len = 1 << iota
  290. Less
  291. Swap
  292. )
  293. nmap := map[string]int{"Len": Len, "Less": Less, "Swap": Swap}
  294. has := make(map[string]int)
  295. for _, f := range p.files {
  296. f.walk(func(n ast.Node) bool {
  297. fn, ok := n.(*ast.FuncDecl)
  298. if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
  299. return true
  300. }
  301. // TODO(dsymonds): We could check the signature to be more precise.
  302. recv := receiverType(fn)
  303. if i, ok := nmap[fn.Name.Name]; ok {
  304. has[recv] |= i
  305. }
  306. return false
  307. })
  308. }
  309. for typ, ms := range has {
  310. if ms == Len|Less|Swap {
  311. p.sortable[typ] = true
  312. }
  313. }
  314. }
  315. func (p *pkg) isMain() bool {
  316. for _, f := range p.files {
  317. if f.isMain() {
  318. return true
  319. }
  320. }
  321. return false
  322. }
  323. func (f *file) isMain() bool {
  324. if f.f.Name.Name == "main" {
  325. return true
  326. }
  327. return false
  328. }
  329. // lintPackageComment checks package comments. It complains if
  330. // there is no package comment, or if it is not of the right form.
  331. // This has a notable false positive in that a package comment
  332. // could rightfully appear in a different file of the same package,
  333. // but that's not easy to fix since this linter is file-oriented.
  334. func (f *file) lintPackageComment() {
  335. if f.isTest() {
  336. return
  337. }
  338. const ref = styleGuideBase + "#package-comments"
  339. prefix := "Package " + f.f.Name.Name + " "
  340. // Look for a detached package comment.
  341. // First, scan for the last comment that occurs before the "package" keyword.
  342. var lastCG *ast.CommentGroup
  343. for _, cg := range f.f.Comments {
  344. if cg.Pos() > f.f.Package {
  345. // Gone past "package" keyword.
  346. break
  347. }
  348. lastCG = cg
  349. }
  350. if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) {
  351. endPos := f.fset.Position(lastCG.End())
  352. pkgPos := f.fset.Position(f.f.Package)
  353. if endPos.Line+1 < pkgPos.Line {
  354. // There isn't a great place to anchor this error;
  355. // the start of the blank lines between the doc and the package statement
  356. // is at least pointing at the location of the problem.
  357. pos := token.Position{
  358. Filename: endPos.Filename,
  359. // Offset not set; it is non-trivial, and doesn't appear to be needed.
  360. Line: endPos.Line + 1,
  361. Column: 1,
  362. }
  363. f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement")
  364. return
  365. }
  366. }
  367. if f.f.Doc == nil {
  368. f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package")
  369. return
  370. }
  371. s := f.f.Doc.Text()
  372. if ts := strings.TrimLeft(s, " \t"); ts != s {
  373. f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space")
  374. s = ts
  375. }
  376. // Only non-main packages need to keep to this form.
  377. if !f.pkg.main && !strings.HasPrefix(s, prefix) {
  378. f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix)
  379. }
  380. }
  381. // lintBlankImports complains if a non-main package has blank imports that are
  382. // not documented.
  383. func (f *file) lintBlankImports() {
  384. // In package main and in tests, we don't complain about blank imports.
  385. if f.pkg.main || f.isTest() {
  386. return
  387. }
  388. // The first element of each contiguous group of blank imports should have
  389. // an explanatory comment of some kind.
  390. for i, imp := range f.f.Imports {
  391. pos := f.fset.Position(imp.Pos())
  392. if !isBlank(imp.Name) {
  393. continue // Ignore non-blank imports.
  394. }
  395. if i > 0 {
  396. prev := f.f.Imports[i-1]
  397. prevPos := f.fset.Position(prev.Pos())
  398. if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
  399. continue // A subsequent blank in a group.
  400. }
  401. }
  402. // This is the first blank import of a group.
  403. if imp.Doc == nil && imp.Comment == nil {
  404. ref := ""
  405. f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it")
  406. }
  407. }
  408. }
  409. // lintImports examines import blocks.
  410. func (f *file) lintImports() {
  411. for i, is := range f.f.Imports {
  412. _ = i
  413. if is.Name != nil && is.Name.Name == "." && !f.isTest() {
  414. f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports")
  415. }
  416. }
  417. }
  418. const docCommentsLink = styleGuideBase + "#doc-comments"
  419. // lintExported examines the exported names.
  420. // It complains if any required doc comments are missing,
  421. // or if they are not of the right form. The exact rules are in
  422. // lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function
  423. // also tracks the GenDecl structure being traversed to permit
  424. // doc comments for constants to be on top of the const block.
  425. // It also complains if the names stutter when combined with
  426. // the package name.
  427. func (f *file) lintExported() {
  428. if f.isTest() {
  429. return
  430. }
  431. var lastGen *ast.GenDecl // last GenDecl entered.
  432. // Set of GenDecls that have already had missing comments flagged.
  433. genDeclMissingComments := make(map[*ast.GenDecl]bool)
  434. f.walk(func(node ast.Node) bool {
  435. switch v := node.(type) {
  436. case *ast.GenDecl:
  437. if v.Tok == token.IMPORT {
  438. return false
  439. }
  440. // token.CONST, token.TYPE or token.VAR
  441. lastGen = v
  442. return true
  443. case *ast.FuncDecl:
  444. f.lintFuncDoc(v)
  445. if v.Recv == nil {
  446. // Only check for stutter on functions, not methods.
  447. // Method names are not used package-qualified.
  448. f.checkStutter(v.Name, "func")
  449. }
  450. // Don't proceed inside funcs.
  451. return false
  452. case *ast.TypeSpec:
  453. // inside a GenDecl, which usually has the doc
  454. doc := v.Doc
  455. if doc == nil {
  456. doc = lastGen.Doc
  457. }
  458. f.lintTypeDoc(v, doc)
  459. f.checkStutter(v.Name, "type")
  460. // Don't proceed inside types.
  461. return false
  462. case *ast.ValueSpec:
  463. f.lintValueSpecDoc(v, lastGen, genDeclMissingComments)
  464. return false
  465. }
  466. return true
  467. })
  468. }
  469. var (
  470. allCapsRE = regexp.MustCompile(`^[A-Z0-9_]+$`)
  471. anyCapsRE = regexp.MustCompile(`[A-Z]`)
  472. )
  473. // knownNameExceptions is a set of names that are known to be exempt from naming checks.
  474. // This is usually because they are constrained by having to match names in the
  475. // standard library.
  476. var knownNameExceptions = map[string]bool{
  477. "LastInsertId": true, // must match database/sql
  478. "kWh": true,
  479. }
  480. func isInTopLevel(f *ast.File, ident *ast.Ident) bool {
  481. path, _ := astutil.PathEnclosingInterval(f, ident.Pos(), ident.End())
  482. for _, f := range path {
  483. switch f.(type) {
  484. case *ast.File, *ast.GenDecl, *ast.ValueSpec, *ast.Ident:
  485. continue
  486. }
  487. return false
  488. }
  489. return true
  490. }
  491. // lintNames examines all names in the file.
  492. // It complains if any use underscores or incorrect known initialisms.
  493. func (f *file) lintNames() {
  494. // Package names need slightly different handling than other names.
  495. if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") {
  496. f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("naming"), "don't use an underscore in package name")
  497. }
  498. if anyCapsRE.MatchString(f.f.Name.Name) {
  499. f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("mixed-caps"), "don't use MixedCaps in package name; %s should be %s", f.f.Name.Name, strings.ToLower(f.f.Name.Name))
  500. }
  501. check := func(id *ast.Ident, thing string) {
  502. if id.Name == "_" {
  503. return
  504. }
  505. if knownNameExceptions[id.Name] {
  506. return
  507. }
  508. // Handle two common styles from other languages that don't belong in Go.
  509. if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") {
  510. capCount := 0
  511. for _, c := range id.Name {
  512. if 'A' <= c && c <= 'Z' {
  513. capCount++
  514. }
  515. }
  516. if capCount >= 2 {
  517. f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use ALL_CAPS in Go names; use CamelCase")
  518. return
  519. }
  520. }
  521. if thing == "const" || (thing == "var" && isInTopLevel(f.f, id)) {
  522. if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' {
  523. should := string(id.Name[1]+'a'-'A') + id.Name[2:]
  524. f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use leading k in Go names; %s %s should be %s", thing, id.Name, should)
  525. }
  526. }
  527. should := lintName(id.Name)
  528. if id.Name == should {
  529. return
  530. }
  531. if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
  532. f.errorf(id, 0.9, link("http://golang.org/doc/effective_go.html#mixed-caps"), category("naming"), "don't use underscores in Go names; %s %s should be %s", thing, id.Name, should)
  533. return
  534. }
  535. f.errorf(id, 0.8, link(styleGuideBase+"#initialisms"), category("naming"), "%s %s should be %s", thing, id.Name, should)
  536. }
  537. checkList := func(fl *ast.FieldList, thing string) {
  538. if fl == nil {
  539. return
  540. }
  541. for _, f := range fl.List {
  542. for _, id := range f.Names {
  543. check(id, thing)
  544. }
  545. }
  546. }
  547. f.walk(func(node ast.Node) bool {
  548. switch v := node.(type) {
  549. case *ast.AssignStmt:
  550. if v.Tok == token.ASSIGN {
  551. return true
  552. }
  553. for _, exp := range v.Lhs {
  554. if id, ok := exp.(*ast.Ident); ok {
  555. check(id, "var")
  556. }
  557. }
  558. case *ast.FuncDecl:
  559. if f.isTest() && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
  560. return true
  561. }
  562. thing := "func"
  563. if v.Recv != nil {
  564. thing = "method"
  565. }
  566. // Exclude naming warnings for functions that are exported to C but
  567. // not exported in the Go API.
  568. // See https://github.com/golang/lint/issues/144.
  569. if ast.IsExported(v.Name.Name) || !isCgoExported(v) {
  570. check(v.Name, thing)
  571. }
  572. checkList(v.Type.Params, thing+" parameter")
  573. checkList(v.Type.Results, thing+" result")
  574. case *ast.GenDecl:
  575. if v.Tok == token.IMPORT {
  576. return true
  577. }
  578. var thing string
  579. switch v.Tok {
  580. case token.CONST:
  581. thing = "const"
  582. case token.TYPE:
  583. thing = "type"
  584. case token.VAR:
  585. thing = "var"
  586. }
  587. for _, spec := range v.Specs {
  588. switch s := spec.(type) {
  589. case *ast.TypeSpec:
  590. check(s.Name, thing)
  591. case *ast.ValueSpec:
  592. for _, id := range s.Names {
  593. check(id, thing)
  594. }
  595. }
  596. }
  597. case *ast.InterfaceType:
  598. // Do not check interface method names.
  599. // They are often constrainted by the method names of concrete types.
  600. for _, x := range v.Methods.List {
  601. ft, ok := x.Type.(*ast.FuncType)
  602. if !ok { // might be an embedded interface name
  603. continue
  604. }
  605. checkList(ft.Params, "interface method parameter")
  606. checkList(ft.Results, "interface method result")
  607. }
  608. case *ast.RangeStmt:
  609. if v.Tok == token.ASSIGN {
  610. return true
  611. }
  612. if id, ok := v.Key.(*ast.Ident); ok {
  613. check(id, "range var")
  614. }
  615. if id, ok := v.Value.(*ast.Ident); ok {
  616. check(id, "range var")
  617. }
  618. case *ast.StructType:
  619. for _, f := range v.Fields.List {
  620. for _, id := range f.Names {
  621. check(id, "struct field")
  622. }
  623. }
  624. }
  625. return true
  626. })
  627. }
  628. // lintName returns a different name if it should be different.
  629. func lintName(name string) (should string) {
  630. // Fast path for simple cases: "_" and all lowercase.
  631. if name == "_" {
  632. return name
  633. }
  634. allLower := true
  635. for _, r := range name {
  636. if !unicode.IsLower(r) {
  637. allLower = false
  638. break
  639. }
  640. }
  641. if allLower {
  642. return name
  643. }
  644. // Split camelCase at any lower->upper transition, and split on underscores.
  645. // Check each word for common initialisms.
  646. runes := []rune(name)
  647. w, i := 0, 0 // index of start of word, scan
  648. for i+1 <= len(runes) {
  649. eow := false // whether we hit the end of a word
  650. if i+1 == len(runes) {
  651. eow = true
  652. } else if runes[i+1] == '_' {
  653. // underscore; shift the remainder forward over any run of underscores
  654. eow = true
  655. n := 1
  656. for i+n+1 < len(runes) && runes[i+n+1] == '_' {
  657. n++
  658. }
  659. // Leave at most one underscore if the underscore is between two digits
  660. if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
  661. n--
  662. }
  663. copy(runes[i+1:], runes[i+n+1:])
  664. runes = runes[:len(runes)-n]
  665. } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
  666. // lower->non-lower
  667. eow = true
  668. }
  669. i++
  670. if !eow {
  671. continue
  672. }
  673. // [w,i) is a word.
  674. word := string(runes[w:i])
  675. if u := strings.ToUpper(word); commonInitialisms[u] {
  676. // Keep consistent case, which is lowercase only at the start.
  677. if w == 0 && unicode.IsLower(runes[w]) {
  678. u = strings.ToLower(u)
  679. }
  680. // All the common initialisms are ASCII,
  681. // so we can replace the bytes exactly.
  682. copy(runes[w:], []rune(u))
  683. } else if w > 0 && strings.ToLower(word) == word {
  684. // already all lowercase, and not the first word, so uppercase the first character.
  685. runes[w] = unicode.ToUpper(runes[w])
  686. }
  687. w = i
  688. }
  689. return string(runes)
  690. }
  691. // commonInitialisms is a set of common initialisms.
  692. // Only add entries that are highly unlikely to be non-initialisms.
  693. // For instance, "ID" is fine (Freudian code is rare), but "AND" is not.
  694. var commonInitialisms = map[string]bool{
  695. "ACL": true,
  696. "API": true,
  697. "ASCII": true,
  698. "CPU": true,
  699. "CSS": true,
  700. "DNS": true,
  701. "EOF": true,
  702. "GUID": true,
  703. "HTML": true,
  704. "HTTP": true,
  705. "HTTPS": true,
  706. "ID": true,
  707. "IP": true,
  708. "JSON": true,
  709. "LHS": true,
  710. "QPS": true,
  711. "RAM": true,
  712. "RHS": true,
  713. "RPC": true,
  714. "SLA": true,
  715. "SMTP": true,
  716. "SQL": true,
  717. "SSH": true,
  718. "TCP": true,
  719. "TLS": true,
  720. "TTL": true,
  721. "UDP": true,
  722. "UI": true,
  723. "UID": true,
  724. "UUID": true,
  725. "URI": true,
  726. "URL": true,
  727. "UTF8": true,
  728. "VM": true,
  729. "XML": true,
  730. "XMPP": true,
  731. "XSRF": true,
  732. "XSS": true,
  733. }
  734. // lintTypeDoc examines the doc comment on a type.
  735. // It complains if they are missing from an exported type,
  736. // or if they are not of the standard form.
  737. func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) {
  738. if !ast.IsExported(t.Name.Name) {
  739. return
  740. }
  741. if doc == nil {
  742. f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name)
  743. return
  744. }
  745. s := doc.Text()
  746. articles := [...]string{"A", "An", "The"}
  747. for _, a := range articles {
  748. if strings.HasPrefix(s, a+" ") {
  749. s = s[len(a)+1:]
  750. break
  751. }
  752. }
  753. if !strings.HasPrefix(s, t.Name.Name+" ") {
  754. f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name)
  755. }
  756. }
  757. var commonMethods = map[string]bool{
  758. "Error": true,
  759. "Read": true,
  760. "ServeHTTP": true,
  761. "String": true,
  762. "Write": true,
  763. }
  764. // lintFuncDoc examines doc comments on functions and methods.
  765. // It complains if they are missing, or not of the right form.
  766. // It has specific exclusions for well-known methods (see commonMethods above).
  767. func (f *file) lintFuncDoc(fn *ast.FuncDecl) {
  768. if !ast.IsExported(fn.Name.Name) {
  769. // func is unexported
  770. return
  771. }
  772. kind := "function"
  773. name := fn.Name.Name
  774. if fn.Recv != nil && len(fn.Recv.List) > 0 {
  775. // method
  776. kind = "method"
  777. recv := receiverType(fn)
  778. if !ast.IsExported(recv) {
  779. // receiver is unexported
  780. return
  781. }
  782. if commonMethods[name] {
  783. return
  784. }
  785. switch name {
  786. case "Len", "Less", "Swap":
  787. if f.pkg.sortable[recv] {
  788. return
  789. }
  790. }
  791. name = recv + "." + name
  792. }
  793. if fn.Doc == nil {
  794. f.errorf(fn, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment or be unexported", kind, name)
  795. return
  796. }
  797. s := fn.Doc.Text()
  798. prefix := fn.Name.Name + " "
  799. if !strings.HasPrefix(s, prefix) {
  800. f.errorf(fn.Doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix)
  801. }
  802. }
  803. // lintValueSpecDoc examines package-global variables and constants.
  804. // It complains if they are not individually declared,
  805. // or if they are not suitably documented in the right form (unless they are in a block that is commented).
  806. func (f *file) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genDeclMissingComments map[*ast.GenDecl]bool) {
  807. kind := "var"
  808. if gd.Tok == token.CONST {
  809. kind = "const"
  810. }
  811. if len(vs.Names) > 1 {
  812. // Check that none are exported except for the first.
  813. for _, n := range vs.Names[1:] {
  814. if ast.IsExported(n.Name) {
  815. f.errorf(vs, 1, category("comments"), "exported %s %s should have its own declaration", kind, n.Name)
  816. return
  817. }
  818. }
  819. }
  820. // Only one name.
  821. name := vs.Names[0].Name
  822. if !ast.IsExported(name) {
  823. return
  824. }
  825. if vs.Doc == nil && gd.Doc == nil {
  826. if genDeclMissingComments[gd] {
  827. return
  828. }
  829. block := ""
  830. if kind == "const" && gd.Lparen.IsValid() {
  831. block = " (or a comment on this block)"
  832. }
  833. f.errorf(vs, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment%s or be unexported", kind, name, block)
  834. genDeclMissingComments[gd] = true
  835. return
  836. }
  837. // If this GenDecl has parens and a comment, we don't check its comment form.
  838. if gd.Lparen.IsValid() && gd.Doc != nil {
  839. return
  840. }
  841. // The relevant text to check will be on either vs.Doc or gd.Doc.
  842. // Use vs.Doc preferentially.
  843. doc := vs.Doc
  844. if doc == nil {
  845. doc = gd.Doc
  846. }
  847. prefix := name + " "
  848. if !strings.HasPrefix(doc.Text(), prefix) {
  849. f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix)
  850. }
  851. }
  852. func (f *file) checkStutter(id *ast.Ident, thing string) {
  853. pkg, name := f.f.Name.Name, id.Name
  854. if !ast.IsExported(name) {
  855. // unexported name
  856. return
  857. }
  858. // A name stutters if the package name is a strict prefix
  859. // and the next character of the name starts a new word.
  860. if len(name) <= len(pkg) {
  861. // name is too short to stutter.
  862. // This permits the name to be the same as the package name.
  863. return
  864. }
  865. if !strings.EqualFold(pkg, name[:len(pkg)]) {
  866. return
  867. }
  868. // We can assume the name is well-formed UTF-8.
  869. // If the next rune after the package name is uppercase or an underscore
  870. // the it's starting a new word and thus this name stutters.
  871. rem := name[len(pkg):]
  872. if next, _ := utf8.DecodeRuneInString(rem); next == '_' || unicode.IsUpper(next) {
  873. f.errorf(id, 0.8, link(styleGuideBase+"#package-names"), category("naming"), "%s name will be used as %s.%s by other packages, and that stutters; consider calling this %s", thing, pkg, name, rem)
  874. }
  875. }
  876. // zeroLiteral is a set of ast.BasicLit values that are zero values.
  877. // It is not exhaustive.
  878. var zeroLiteral = map[string]bool{
  879. "false": true, // bool
  880. // runes
  881. `'\x00'`: true,
  882. `'\000'`: true,
  883. // strings
  884. `""`: true,
  885. "``": true,
  886. // numerics
  887. "0": true,
  888. "0.": true,
  889. "0.0": true,
  890. "0i": true,
  891. }
  892. // lintVarDecls examines variable declarations. It complains about declarations with
  893. // redundant LHS types that can be inferred from the RHS.
  894. func (f *file) lintVarDecls() {
  895. var lastGen *ast.GenDecl // last GenDecl entered.
  896. f.walk(func(node ast.Node) bool {
  897. switch v := node.(type) {
  898. case *ast.GenDecl:
  899. if v.Tok != token.CONST && v.Tok != token.VAR {
  900. return false
  901. }
  902. lastGen = v
  903. return true
  904. case *ast.ValueSpec:
  905. if lastGen.Tok == token.CONST {
  906. return false
  907. }
  908. if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 {
  909. return false
  910. }
  911. rhs := v.Values[0]
  912. // An underscore var appears in a common idiom for compile-time interface satisfaction,
  913. // as in "var _ Interface = (*Concrete)(nil)".
  914. if isIdent(v.Names[0], "_") {
  915. return false
  916. }
  917. // If the RHS is a zero value, suggest dropping it.
  918. zero := false
  919. if lit, ok := rhs.(*ast.BasicLit); ok {
  920. zero = zeroLiteral[lit.Value]
  921. } else if isIdent(rhs, "nil") {
  922. zero = true
  923. }
  924. if zero {
  925. f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0])
  926. return false
  927. }
  928. lhsTyp := f.pkg.typeOf(v.Type)
  929. rhsTyp := f.pkg.typeOf(rhs)
  930. if !validType(lhsTyp) || !validType(rhsTyp) {
  931. // Type checking failed (often due to missing imports).
  932. return false
  933. }
  934. if !types.Identical(lhsTyp, rhsTyp) {
  935. // Assignment to a different type is not redundant.
  936. return false
  937. }
  938. // The next three conditions are for suppressing the warning in situations
  939. // where we were unable to typecheck.
  940. // If the LHS type is an interface, don't warn, since it is probably a
  941. // concrete type on the RHS. Note that our feeble lexical check here
  942. // will only pick up interface{} and other literal interface types;
  943. // that covers most of the cases we care to exclude right now.
  944. if _, ok := v.Type.(*ast.InterfaceType); ok {
  945. return false
  946. }
  947. // If the RHS is an untyped const, only warn if the LHS type is its default type.
  948. if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) {
  949. return false
  950. }
  951. f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0])
  952. return false
  953. }
  954. return true
  955. })
  956. }
  957. func validType(T types.Type) bool {
  958. return T != nil &&
  959. T != types.Typ[types.Invalid] &&
  960. !strings.Contains(T.String(), "invalid type") // good but not foolproof
  961. }
  962. // lintElses examines else blocks. It complains about any else block whose if block ends in a return.
  963. func (f *file) lintElses() {
  964. // We don't want to flag if { } else if { } else { } constructions.
  965. // They will appear as an IfStmt whose Else field is also an IfStmt.
  966. // Record such a node so we ignore it when we visit it.
  967. ignore := make(map[*ast.IfStmt]bool)
  968. f.walk(func(node ast.Node) bool {
  969. ifStmt, ok := node.(*ast.IfStmt)
  970. if !ok || ifStmt.Else == nil {
  971. return true
  972. }
  973. if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
  974. ignore[elseif] = true
  975. return true
  976. }
  977. if ignore[ifStmt] {
  978. return true
  979. }
  980. if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
  981. // only care about elses without conditions
  982. return true
  983. }
  984. if len(ifStmt.Body.List) == 0 {
  985. return true
  986. }
  987. shortDecl := false // does the if statement have a ":=" initialization statement?
  988. if ifStmt.Init != nil {
  989. if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
  990. shortDecl = true
  991. }
  992. }
  993. lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
  994. if _, ok := lastStmt.(*ast.ReturnStmt); ok {
  995. extra := ""
  996. if shortDecl {
  997. extra = " (move short variable declaration to its own line if necessary)"
  998. }
  999. f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra)
  1000. }
  1001. return true
  1002. })
  1003. }
  1004. // lintRanges examines range clauses. It complains about redundant constructions.
  1005. func (f *file) lintRanges() {
  1006. f.walk(func(node ast.Node) bool {
  1007. rs, ok := node.(*ast.RangeStmt)
  1008. if !ok {
  1009. return true
  1010. }
  1011. if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
  1012. p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`")
  1013. newRS := *rs // shallow copy
  1014. newRS.Value = nil
  1015. newRS.Key = nil
  1016. p.ReplacementLine = f.firstLineOf(&newRS, rs)
  1017. return true
  1018. }
  1019. if isIdent(rs.Value, "_") {
  1020. p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok)
  1021. newRS := *rs // shallow copy
  1022. newRS.Value = nil
  1023. p.ReplacementLine = f.firstLineOf(&newRS, rs)
  1024. }
  1025. return true
  1026. })
  1027. }
  1028. // lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
  1029. func (f *file) lintErrorf() {
  1030. f.walk(func(node ast.Node) bool {
  1031. ce, ok := node.(*ast.CallExpr)
  1032. if !ok || len(ce.Args) != 1 {
  1033. return true
  1034. }
  1035. isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
  1036. var isTestingError bool
  1037. se, ok := ce.Fun.(*ast.SelectorExpr)
  1038. if ok && se.Sel.Name == "Error" {
  1039. if typ := f.pkg.typeOf(se.X); typ != nil {
  1040. isTestingError = typ.String() == "*testing.T"
  1041. }
  1042. }
  1043. if !isErrorsNew && !isTestingError {
  1044. return true
  1045. }
  1046. if !f.imports("errors") {
  1047. return true
  1048. }
  1049. arg := ce.Args[0]
  1050. ce, ok = arg.(*ast.CallExpr)
  1051. if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
  1052. return true
  1053. }
  1054. errorfPrefix := "fmt"
  1055. if isTestingError {
  1056. errorfPrefix = f.render(se.X)
  1057. }
  1058. p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix)
  1059. m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`)
  1060. if m != nil {
  1061. p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3]
  1062. }
  1063. return true
  1064. })
  1065. }
  1066. // lintErrors examines global error vars. It complains if they aren't named in the standard way.
  1067. func (f *file) lintErrors() {
  1068. for _, decl := range f.f.Decls {
  1069. gd, ok := decl.(*ast.GenDecl)
  1070. if !ok || gd.Tok != token.VAR {
  1071. continue
  1072. }
  1073. for _, spec := range gd.Specs {
  1074. spec := spec.(*ast.ValueSpec)
  1075. if len(spec.Names) != 1 || len(spec.Values) != 1 {
  1076. continue
  1077. }
  1078. ce, ok := spec.Values[0].(*ast.CallExpr)
  1079. if !ok {
  1080. continue
  1081. }
  1082. if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
  1083. continue
  1084. }
  1085. id := spec.Names[0]
  1086. prefix := "err"
  1087. if id.IsExported() {
  1088. prefix = "Err"
  1089. }
  1090. if !strings.HasPrefix(id.Name, prefix) {
  1091. f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix)
  1092. }
  1093. }
  1094. }
  1095. }
  1096. func lintErrorString(s string) (isClean bool, conf float64) {
  1097. const basicConfidence = 0.8
  1098. const capConfidence = basicConfidence - 0.2
  1099. first, firstN := utf8.DecodeRuneInString(s)
  1100. last, _ := utf8.DecodeLastRuneInString(s)
  1101. if last == '.' || last == ':' || last == '!' || last == '\n' {
  1102. return false, basicConfidence
  1103. }
  1104. if unicode.IsUpper(first) {
  1105. // People use proper nouns and exported Go identifiers in error strings,
  1106. // so decrease the confidence of warnings for capitalization.
  1107. if len(s) <= firstN {
  1108. return false, capConfidence
  1109. }
  1110. // Flag strings starting with something that doesn't look like an initialism.
  1111. if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) {
  1112. return false, capConfidence
  1113. }
  1114. }
  1115. return true, 0
  1116. }
  1117. // lintErrorStrings examines error strings.
  1118. // It complains if they are capitalized or end in punctuation or a newline.
  1119. func (f *file) lintErrorStrings() {
  1120. f.walk(func(node ast.Node) bool {
  1121. ce, ok := node.(*ast.CallExpr)
  1122. if !ok {
  1123. return true
  1124. }
  1125. if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
  1126. return true
  1127. }
  1128. if len(ce.Args) < 1 {
  1129. return true
  1130. }
  1131. str, ok := ce.Args[0].(*ast.BasicLit)
  1132. if !ok || str.Kind != token.STRING {
  1133. return true
  1134. }
  1135. s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
  1136. if s == "" {
  1137. return true
  1138. }
  1139. clean, conf := lintErrorString(s)
  1140. if clean {
  1141. return true
  1142. }
  1143. f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"),
  1144. "error strings should not be capitalized or end with punctuation or a newline")
  1145. return true
  1146. })
  1147. }
  1148. // lintReceiverNames examines receiver names. It complains about inconsistent
  1149. // names used for the same type and names such as "this".
  1150. func (f *file) lintReceiverNames() {
  1151. typeReceiver := map[string]string{}
  1152. f.walk(func(n ast.Node) bool {
  1153. fn, ok := n.(*ast.FuncDecl)
  1154. if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
  1155. return true
  1156. }
  1157. names := fn.Recv.List[0].Names
  1158. if len(names) < 1 {
  1159. return true
  1160. }
  1161. name := names[0].Name
  1162. const ref = styleGuideBase + "#receiver-names"
  1163. if name == "_" {
  1164. f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`)
  1165. return true
  1166. }
  1167. if name == "this" || name == "self" {
  1168. f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`)
  1169. return true
  1170. }
  1171. recv := receiverType(fn)
  1172. if prev, ok := typeReceiver[recv]; ok && prev != name {
  1173. f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv)
  1174. return true
  1175. }
  1176. typeReceiver[recv] = name
  1177. return true
  1178. })
  1179. }
  1180. // lintIncDec examines statements that increment or decrement a variable.
  1181. // It complains if they don't use x++ or x--.
  1182. func (f *file) lintIncDec() {
  1183. f.walk(func(n ast.Node) bool {
  1184. as, ok := n.(*ast.AssignStmt)
  1185. if !ok {
  1186. return true
  1187. }
  1188. if len(as.Lhs) != 1 {
  1189. return true
  1190. }
  1191. if !isOne(as.Rhs[0]) {
  1192. return true
  1193. }
  1194. var suffix string
  1195. switch as.Tok {
  1196. case token.ADD_ASSIGN:
  1197. suffix = "++"
  1198. case token.SUB_ASSIGN:
  1199. suffix = "--"
  1200. default:
  1201. return true
  1202. }
  1203. f.errorf(as, 0.8, category("unary-op"), "should replace %s with %s%s", f.render(as), f.render(as.Lhs[0]), suffix)
  1204. return true
  1205. })
  1206. }
  1207. // lintErrorReturn examines function declarations that return an error.
  1208. // It complains if the error isn't the last parameter.
  1209. func (f *file) lintErrorReturn() {
  1210. f.walk(func(n ast.Node) bool {
  1211. fn, ok := n.(*ast.FuncDecl)
  1212. if !ok || fn.Type.Results == nil {
  1213. return true
  1214. }
  1215. ret := fn.Type.Results.List
  1216. if len(ret) <= 1 {
  1217. return true
  1218. }
  1219. if isIdent(ret[len(ret)-1].Type, "error") {
  1220. return true
  1221. }
  1222. // An error return parameter should be the last parameter.
  1223. // Flag any error parameters found before the last.
  1224. for _, r := range ret[:len(ret)-1] {
  1225. if isIdent(r.Type, "error") {
  1226. f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items")
  1227. break // only flag one
  1228. }
  1229. }
  1230. return true
  1231. })
  1232. }
  1233. // lintUnexportedReturn examines exported function declarations.
  1234. // It complains if any return an unexported type.
  1235. func (f *file) lintUnexportedReturn() {
  1236. f.walk(func(n ast.Node) bool {
  1237. fn, ok := n.(*ast.FuncDecl)
  1238. if !ok {
  1239. return true
  1240. }
  1241. if fn.Type.Results == nil {
  1242. return false
  1243. }
  1244. if !fn.Name.IsExported() {
  1245. return false
  1246. }
  1247. thing := "func"
  1248. if fn.Recv != nil && len(fn.Recv.List) > 0 {
  1249. thing = "method"
  1250. if !ast.IsExported(receiverType(fn)) {
  1251. // Don't report exported methods of unexported types,
  1252. // such as private implementations of sort.Interface.
  1253. return false
  1254. }
  1255. }
  1256. for _, ret := range fn.Type.Results.List {
  1257. typ := f.pkg.typeOf(ret.Type)
  1258. if exportedType(typ) {
  1259. continue
  1260. }
  1261. f.errorf(ret.Type, 0.8, category("unexported-type-in-api"),
  1262. "exported %s %s returns unexported type %s, which can be annoying to use",
  1263. thing, fn.Name.Name, typ)
  1264. break // only flag one
  1265. }
  1266. return false
  1267. })
  1268. }
  1269. // exportedType reports whether typ is an exported type.
  1270. // It is imprecise, and will err on the side of returning true,
  1271. // such as for composite types.
  1272. func exportedType(typ types.Type) bool {
  1273. switch T := typ.(type) {
  1274. case *types.Named:
  1275. // Builtin types have no package.
  1276. return T.Obj().Pkg() == nil || T.Obj().Exported()
  1277. case *types.Map:
  1278. return exportedType(T.Key()) && exportedType(T.Elem())
  1279. case interface {
  1280. Elem() types.Type
  1281. }: // array, slice, pointer, chan
  1282. return exportedType(T.Elem())
  1283. }
  1284. // Be conservative about other types, such as struct, interface, etc.
  1285. return true
  1286. }
  1287. // timeSuffixes is a list of name suffixes that imply a time unit.
  1288. // This is not an exhaustive list.
  1289. var timeSuffixes = []string{
  1290. "Sec", "Secs", "Seconds",
  1291. "Msec", "Msecs",
  1292. "Milli", "Millis", "Milliseconds",
  1293. "Usec", "Usecs", "Microseconds",
  1294. "MS", "Ms",
  1295. }
  1296. func (f *file) lintTimeNames() {
  1297. f.walk(func(node ast.Node) bool {
  1298. v, ok := node.(*ast.ValueSpec)
  1299. if !ok {
  1300. return true
  1301. }
  1302. for _, name := range v.Names {
  1303. origTyp := f.pkg.typeOf(name)
  1304. // Look for time.Duration or *time.Duration;
  1305. // the latter is common when using flag.Duration.
  1306. typ := origTyp
  1307. if pt, ok := typ.(*types.Pointer); ok {
  1308. typ = pt.Elem()
  1309. }
  1310. if !f.pkg.isNamedType(typ, "time", "Duration") {
  1311. continue
  1312. }
  1313. suffix := ""
  1314. for _, suf := range timeSuffixes {
  1315. if strings.HasSuffix(name.Name, suf) {
  1316. suffix = suf
  1317. break
  1318. }
  1319. }
  1320. if suffix == "" {
  1321. continue
  1322. }
  1323. f.errorf(v, 0.9, category("time"), "var %s is of type %v; don't use unit-specific suffix %q", name.Name, origTyp, suffix)
  1324. }
  1325. return true
  1326. })
  1327. }
  1328. // lintContextKeyTypes checks for call expressions to context.WithValue with
  1329. // basic types used for the key argument.
  1330. // See: https://golang.org/issue/17293
  1331. func (f *file) lintContextKeyTypes() {
  1332. f.walk(func(node ast.Node) bool {
  1333. switch node := node.(type) {
  1334. case *ast.CallExpr:
  1335. f.checkContextKeyType(node)
  1336. }
  1337. return true
  1338. })
  1339. }
  1340. // checkContextKeyType reports an error if the call expression calls
  1341. // context.WithValue with a key argument of basic type.
  1342. func (f *file) checkContextKeyType(x *ast.CallExpr) {
  1343. sel, ok := x.Fun.(*ast.SelectorExpr)
  1344. if !ok {
  1345. return
  1346. }
  1347. pkg, ok := sel.X.(*ast.Ident)
  1348. if !ok || pkg.Name != "context" {
  1349. return
  1350. }
  1351. if sel.Sel.Name != "WithValue" {
  1352. return
  1353. }
  1354. // key is second argument to context.WithValue
  1355. if len(x.Args) != 3 {
  1356. return
  1357. }
  1358. key := f.pkg.typesInfo.Types[x.Args[1]]
  1359. if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid {
  1360. f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type))
  1361. }
  1362. }
  1363. // lintContextArgs examines function declarations that contain an
  1364. // argument with a type of context.Context
  1365. // It complains if that argument isn't the first parameter.
  1366. func (f *file) lintContextArgs() {
  1367. f.walk(func(n ast.Node) bool {
  1368. fn, ok := n.(*ast.FuncDecl)
  1369. if !ok || len(fn.Type.Params.List) <= 1 {
  1370. return true
  1371. }
  1372. // A context.Context should be the first parameter of a function.
  1373. // Flag any that show up after the first.
  1374. for _, arg := range fn.Type.Params.List[1:] {
  1375. if isPkgDot(arg.Type, "context", "Context") {
  1376. f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function")
  1377. break // only flag one
  1378. }
  1379. }
  1380. return true
  1381. })
  1382. }
  1383. // containsComments returns whether the interval [start, end) contains any
  1384. // comments without "// MATCH " prefix.
  1385. func (f *file) containsComments(start, end token.Pos) bool {
  1386. for _, cgroup := range f.f.Comments {
  1387. comments := cgroup.List
  1388. if comments[0].Slash >= end {
  1389. // All comments starting with this group are after end pos.
  1390. return false
  1391. }
  1392. if comments[len(comments)-1].Slash < start {
  1393. // Comments group ends before start pos.
  1394. continue
  1395. }
  1396. for _, c := range comments {
  1397. if start <= c.Slash && c.Slash < end && !strings.HasPrefix(c.Text, "// MATCH ") {
  1398. return true
  1399. }
  1400. }
  1401. }
  1402. return false
  1403. }
  1404. // receiverType returns the named type of the method receiver, sans "*",
  1405. // or "invalid-type" if fn.Recv is ill formed.
  1406. func receiverType(fn *ast.FuncDecl) string {
  1407. switch e := fn.Recv.List[0].Type.(type) {
  1408. case *ast.Ident:
  1409. return e.Name
  1410. case *ast.StarExpr:
  1411. if id, ok := e.X.(*ast.Ident); ok {
  1412. return id.Name
  1413. }
  1414. }
  1415. // The parser accepts much more than just the legal forms.
  1416. return "invalid-type"
  1417. }
  1418. func (f *file) walk(fn func(ast.Node) bool) {
  1419. ast.Walk(walker(fn), f.f)
  1420. }
  1421. func (f *file) render(x interface{}) string {
  1422. var buf bytes.Buffer
  1423. if err := printer.Fprint(&buf, f.fset, x); err != nil {
  1424. panic(err)
  1425. }
  1426. return buf.String()
  1427. }
  1428. func (f *file) debugRender(x interface{}) string {
  1429. var buf bytes.Buffer
  1430. if err := ast.Fprint(&buf, f.fset, x, nil); err != nil {
  1431. panic(err)
  1432. }
  1433. return buf.String()
  1434. }
  1435. // walker adapts a function to satisfy the ast.Visitor interface.
  1436. // The function return whether the walk should proceed into the node's children.
  1437. type walker func(ast.Node) bool
  1438. func (w walker) Visit(node ast.Node) ast.Visitor {
  1439. if w(node) {
  1440. return w
  1441. }
  1442. return nil
  1443. }
  1444. func isIdent(expr ast.Expr, ident string) bool {
  1445. id, ok := expr.(*ast.Ident)
  1446. return ok && id.Name == ident
  1447. }
  1448. // isBlank returns whether id is the blank identifier "_".
  1449. // If id == nil, the answer is false.
  1450. func isBlank(id *ast.Ident) bool { return id != nil && id.Name == "_" }
  1451. func isPkgDot(expr ast.Expr, pkg, name string) bool {
  1452. sel, ok := expr.(*ast.SelectorExpr)
  1453. return ok && isIdent(sel.X, pkg) && isIdent(sel.Sel, name)
  1454. }
  1455. func isOne(expr ast.Expr) bool {
  1456. lit, ok := expr.(*ast.BasicLit)
  1457. return ok && lit.Kind == token.INT && lit.Value == "1"
  1458. }
  1459. func isCgoExported(f *ast.FuncDecl) bool {
  1460. if f.Recv != nil || f.Doc == nil {
  1461. return false
  1462. }
  1463. cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name)))
  1464. for _, c := range f.Doc.List {
  1465. if cgoExport.MatchString(c.Text) {
  1466. return true
  1467. }
  1468. }
  1469. return false
  1470. }
  1471. var basicTypeKinds = map[types.BasicKind]string{
  1472. types.UntypedBool: "bool",
  1473. types.UntypedInt: "int",
  1474. types.UntypedRune: "rune",
  1475. types.UntypedFloat: "float64",
  1476. types.UntypedComplex: "complex128",
  1477. types.UntypedString: "string",
  1478. }
  1479. // isUntypedConst reports whether expr is an untyped constant,
  1480. // and indicates what its default type is.
  1481. // scope may be nil.
  1482. func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) {
  1483. // Re-evaluate expr outside of its context to see if it's untyped.
  1484. // (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
  1485. exprStr := f.render(expr)
  1486. tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr)
  1487. if err != nil {
  1488. return "", false
  1489. }
  1490. if b, ok := tv.Type.(*types.Basic); ok {
  1491. if dt, ok := basicTypeKinds[b.Kind()]; ok {
  1492. return dt, true
  1493. }
  1494. }
  1495. return "", false
  1496. }
  1497. // firstLineOf renders the given node and returns its first line.
  1498. // It will also match the indentation of another node.
  1499. func (f *file) firstLineOf(node, match ast.Node) string {
  1500. line := f.render(node)
  1501. if i := strings.Index(line, "\n"); i >= 0 {
  1502. line = line[:i]
  1503. }
  1504. return f.indentOf(match) + line
  1505. }
  1506. func (f *file) indentOf(node ast.Node) string {
  1507. line := srcLine(f.src, f.fset.Position(node.Pos()))
  1508. for i, r := range line {
  1509. switch r {
  1510. case ' ', '\t':
  1511. default:
  1512. return line[:i]
  1513. }
  1514. }
  1515. return line // unusual or empty line
  1516. }
  1517. func (f *file) srcLineWithMatch(node ast.Node, pattern string) (m []string) {
  1518. line := srcLine(f.src, f.fset.Position(node.Pos()))
  1519. line = strings.TrimSuffix(line, "\n")
  1520. rx := regexp.MustCompile(pattern)
  1521. return rx.FindStringSubmatch(line)
  1522. }
  1523. // imports returns true if the current file imports the specified package path.
  1524. func (f *file) imports(importPath string) bool {
  1525. all := astutil.Imports(f.fset, f.f)
  1526. for _, p := range all {
  1527. for _, i := range p {
  1528. uq, err := strconv.Unquote(i.Path.Value)
  1529. if err == nil && importPath == uq {
  1530. return true
  1531. }
  1532. }
  1533. }
  1534. return false
  1535. }
  1536. // srcLine returns the complete line at p, including the terminating newline.
  1537. func srcLine(src []byte, p token.Position) string {
  1538. // Run to end of line in both directions if not at line start/end.
  1539. lo, hi := p.Offset, p.Offset+1
  1540. for lo > 0 && src[lo-1] != '\n' {
  1541. lo--
  1542. }
  1543. for hi < len(src) && src[hi-1] != '\n' {
  1544. hi++
  1545. }
  1546. return string(src[lo:hi])
  1547. }