lint.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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.lintElses()
  172. f.lintRanges()
  173. f.lintErrorf()
  174. f.lintErrors()
  175. f.lintErrorStrings()
  176. f.lintReceiverNames()
  177. f.lintIncDec()
  178. f.lintErrorReturn()
  179. f.lintUnexportedReturn()
  180. f.lintTimeNames()
  181. f.lintContextKeyTypes()
  182. f.lintContextArgs()
  183. }
  184. type link string
  185. type category string
  186. // The variadic arguments may start with link and category types,
  187. // and must end with a format string and any arguments.
  188. // It returns the new Problem.
  189. func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem {
  190. pos := f.fset.Position(n.Pos())
  191. if pos.Filename == "" {
  192. pos.Filename = f.filename
  193. }
  194. return f.pkg.errorfAt(pos, confidence, args...)
  195. }
  196. func (p *pkg) errorfAt(pos token.Position, confidence float64, args ...interface{}) *Problem {
  197. problem := Problem{
  198. Position: pos,
  199. Confidence: confidence,
  200. }
  201. if pos.Filename != "" {
  202. // The file might not exist in our mapping if a //line directive was encountered.
  203. if f, ok := p.files[pos.Filename]; ok {
  204. problem.LineText = srcLine(f.src, pos)
  205. }
  206. }
  207. argLoop:
  208. for len(args) > 1 { // always leave at least the format string in args
  209. switch v := args[0].(type) {
  210. case link:
  211. problem.Link = string(v)
  212. case category:
  213. problem.Category = string(v)
  214. default:
  215. break argLoop
  216. }
  217. args = args[1:]
  218. }
  219. problem.Text = fmt.Sprintf(args[0].(string), args[1:]...)
  220. p.problems = append(p.problems, problem)
  221. return &p.problems[len(p.problems)-1]
  222. }
  223. var newImporter = func(fset *token.FileSet) types.ImporterFrom {
  224. return gcexportdata.NewImporter(fset, make(map[string]*types.Package))
  225. }
  226. func (p *pkg) typeCheck() error {
  227. config := &types.Config{
  228. // By setting a no-op error reporter, the type checker does as much work as possible.
  229. Error: func(error) {},
  230. Importer: newImporter(p.fset),
  231. }
  232. info := &types.Info{
  233. Types: make(map[ast.Expr]types.TypeAndValue),
  234. Defs: make(map[*ast.Ident]types.Object),
  235. Uses: make(map[*ast.Ident]types.Object),
  236. Scopes: make(map[ast.Node]*types.Scope),
  237. }
  238. var anyFile *file
  239. var astFiles []*ast.File
  240. for _, f := range p.files {
  241. anyFile = f
  242. astFiles = append(astFiles, f.f)
  243. }
  244. pkg, err := config.Check(anyFile.f.Name.Name, p.fset, astFiles, info)
  245. // Remember the typechecking info, even if config.Check failed,
  246. // since we will get partial information.
  247. p.typesPkg = pkg
  248. p.typesInfo = info
  249. return err
  250. }
  251. func (p *pkg) typeOf(expr ast.Expr) types.Type {
  252. if p.typesInfo == nil {
  253. return nil
  254. }
  255. return p.typesInfo.TypeOf(expr)
  256. }
  257. func (p *pkg) isNamedType(typ types.Type, importPath, name string) bool {
  258. n, ok := typ.(*types.Named)
  259. if !ok {
  260. return false
  261. }
  262. tn := n.Obj()
  263. return tn != nil && tn.Pkg() != nil && tn.Pkg().Path() == importPath && tn.Name() == name
  264. }
  265. // scopeOf returns the tightest scope encompassing id.
  266. func (p *pkg) scopeOf(id *ast.Ident) *types.Scope {
  267. var scope *types.Scope
  268. if obj := p.typesInfo.ObjectOf(id); obj != nil {
  269. scope = obj.Parent()
  270. }
  271. if scope == p.typesPkg.Scope() {
  272. // We were given a top-level identifier.
  273. // Use the file-level scope instead of the package-level scope.
  274. pos := id.Pos()
  275. for _, f := range p.files {
  276. if f.f.Pos() <= pos && pos < f.f.End() {
  277. scope = p.typesInfo.Scopes[f.f]
  278. break
  279. }
  280. }
  281. }
  282. return scope
  283. }
  284. func (p *pkg) scanSortable() {
  285. p.sortable = make(map[string]bool)
  286. // bitfield for which methods exist on each type.
  287. const (
  288. Len = 1 << iota
  289. Less
  290. Swap
  291. )
  292. nmap := map[string]int{"Len": Len, "Less": Less, "Swap": Swap}
  293. has := make(map[string]int)
  294. for _, f := range p.files {
  295. f.walk(func(n ast.Node) bool {
  296. fn, ok := n.(*ast.FuncDecl)
  297. if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
  298. return true
  299. }
  300. // TODO(dsymonds): We could check the signature to be more precise.
  301. recv := receiverType(fn)
  302. if i, ok := nmap[fn.Name.Name]; ok {
  303. has[recv] |= i
  304. }
  305. return false
  306. })
  307. }
  308. for typ, ms := range has {
  309. if ms == Len|Less|Swap {
  310. p.sortable[typ] = true
  311. }
  312. }
  313. }
  314. func (p *pkg) isMain() bool {
  315. for _, f := range p.files {
  316. if f.isMain() {
  317. return true
  318. }
  319. }
  320. return false
  321. }
  322. func (f *file) isMain() bool {
  323. if f.f.Name.Name == "main" {
  324. return true
  325. }
  326. return false
  327. }
  328. // lintPackageComment checks package comments. It complains if
  329. // there is no package comment, or if it is not of the right form.
  330. // This has a notable false positive in that a package comment
  331. // could rightfully appear in a different file of the same package,
  332. // but that's not easy to fix since this linter is file-oriented.
  333. func (f *file) lintPackageComment() {
  334. if f.isTest() {
  335. return
  336. }
  337. const ref = styleGuideBase + "#package-comments"
  338. prefix := "Package " + f.f.Name.Name + " "
  339. // Look for a detached package comment.
  340. // First, scan for the last comment that occurs before the "package" keyword.
  341. var lastCG *ast.CommentGroup
  342. for _, cg := range f.f.Comments {
  343. if cg.Pos() > f.f.Package {
  344. // Gone past "package" keyword.
  345. break
  346. }
  347. lastCG = cg
  348. }
  349. if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) {
  350. endPos := f.fset.Position(lastCG.End())
  351. pkgPos := f.fset.Position(f.f.Package)
  352. if endPos.Line+1 < pkgPos.Line {
  353. // There isn't a great place to anchor this error;
  354. // the start of the blank lines between the doc and the package statement
  355. // is at least pointing at the location of the problem.
  356. pos := token.Position{
  357. Filename: endPos.Filename,
  358. // Offset not set; it is non-trivial, and doesn't appear to be needed.
  359. Line: endPos.Line + 1,
  360. Column: 1,
  361. }
  362. 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")
  363. return
  364. }
  365. }
  366. if f.f.Doc == nil {
  367. f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package")
  368. return
  369. }
  370. s := f.f.Doc.Text()
  371. if ts := strings.TrimLeft(s, " \t"); ts != s {
  372. f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space")
  373. s = ts
  374. }
  375. // Only non-main packages need to keep to this form.
  376. if !f.pkg.main && !strings.HasPrefix(s, prefix) {
  377. f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix)
  378. }
  379. }
  380. // lintBlankImports complains if a non-main package has blank imports that are
  381. // not documented.
  382. func (f *file) lintBlankImports() {
  383. // In package main and in tests, we don't complain about blank imports.
  384. if f.pkg.main || f.isTest() {
  385. return
  386. }
  387. // The first element of each contiguous group of blank imports should have
  388. // an explanatory comment of some kind.
  389. for i, imp := range f.f.Imports {
  390. pos := f.fset.Position(imp.Pos())
  391. if !isBlank(imp.Name) {
  392. continue // Ignore non-blank imports.
  393. }
  394. if i > 0 {
  395. prev := f.f.Imports[i-1]
  396. prevPos := f.fset.Position(prev.Pos())
  397. if isBlank(prev.Name) && prevPos.Line+1 == pos.Line {
  398. continue // A subsequent blank in a group.
  399. }
  400. }
  401. // This is the first blank import of a group.
  402. if imp.Doc == nil && imp.Comment == nil {
  403. ref := ""
  404. 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")
  405. }
  406. }
  407. }
  408. // lintImports examines import blocks.
  409. func (f *file) lintImports() {
  410. for i, is := range f.f.Imports {
  411. _ = i
  412. if is.Name != nil && is.Name.Name == "." && !f.isTest() {
  413. f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports")
  414. }
  415. }
  416. }
  417. const docCommentsLink = styleGuideBase + "#doc-comments"
  418. // lintExported examines the exported names.
  419. // It complains if any required doc comments are missing,
  420. // or if they are not of the right form. The exact rules are in
  421. // lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function
  422. // also tracks the GenDecl structure being traversed to permit
  423. // doc comments for constants to be on top of the const block.
  424. // It also complains if the names stutter when combined with
  425. // the package name.
  426. func (f *file) lintExported() {
  427. if f.isTest() {
  428. return
  429. }
  430. var lastGen *ast.GenDecl // last GenDecl entered.
  431. // Set of GenDecls that have already had missing comments flagged.
  432. genDeclMissingComments := make(map[*ast.GenDecl]bool)
  433. f.walk(func(node ast.Node) bool {
  434. switch v := node.(type) {
  435. case *ast.GenDecl:
  436. if v.Tok == token.IMPORT {
  437. return false
  438. }
  439. // token.CONST, token.TYPE or token.VAR
  440. lastGen = v
  441. return true
  442. case *ast.FuncDecl:
  443. f.lintFuncDoc(v)
  444. if v.Recv == nil {
  445. // Only check for stutter on functions, not methods.
  446. // Method names are not used package-qualified.
  447. f.checkStutter(v.Name, "func")
  448. }
  449. // Don't proceed inside funcs.
  450. return false
  451. case *ast.TypeSpec:
  452. // inside a GenDecl, which usually has the doc
  453. doc := v.Doc
  454. if doc == nil {
  455. doc = lastGen.Doc
  456. }
  457. f.lintTypeDoc(v, doc)
  458. f.checkStutter(v.Name, "type")
  459. // Don't proceed inside types.
  460. return false
  461. case *ast.ValueSpec:
  462. f.lintValueSpecDoc(v, lastGen, genDeclMissingComments)
  463. return false
  464. }
  465. return true
  466. })
  467. }
  468. var (
  469. allCapsRE = regexp.MustCompile(`^[A-Z0-9_]+$`)
  470. anyCapsRE = regexp.MustCompile(`[A-Z]`)
  471. )
  472. // knownNameExceptions is a set of names that are known to be exempt from naming checks.
  473. // This is usually because they are constrained by having to match names in the
  474. // standard library.
  475. var knownNameExceptions = map[string]bool{
  476. "LastInsertId": true, // must match database/sql
  477. "kWh": true,
  478. }
  479. func isInTopLevel(f *ast.File, ident *ast.Ident) bool {
  480. path, _ := astutil.PathEnclosingInterval(f, ident.Pos(), ident.End())
  481. for _, f := range path {
  482. switch f.(type) {
  483. case *ast.File, *ast.GenDecl, *ast.ValueSpec, *ast.Ident:
  484. continue
  485. }
  486. return false
  487. }
  488. return true
  489. }
  490. // lintNames examines all names in the file.
  491. // It complains if any use underscores or incorrect known initialisms.
  492. func (f *file) lintNames() {
  493. // Package names need slightly different handling than other names.
  494. if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") {
  495. 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")
  496. }
  497. if anyCapsRE.MatchString(f.f.Name.Name) {
  498. 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))
  499. }
  500. check := func(id *ast.Ident, thing string) {
  501. if id.Name == "_" {
  502. return
  503. }
  504. if knownNameExceptions[id.Name] {
  505. return
  506. }
  507. // Handle two common styles from other languages that don't belong in Go.
  508. if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") {
  509. capCount := 0
  510. for _, c := range id.Name {
  511. if 'A' <= c && c <= 'Z' {
  512. capCount++
  513. }
  514. }
  515. if capCount >= 2 {
  516. f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use ALL_CAPS in Go names; use CamelCase")
  517. return
  518. }
  519. }
  520. if thing == "const" || (thing == "var" && isInTopLevel(f.f, id)) {
  521. if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' {
  522. should := string(id.Name[1]+'a'-'A') + id.Name[2:]
  523. 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)
  524. }
  525. }
  526. should := lintName(id.Name)
  527. if id.Name == should {
  528. return
  529. }
  530. if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
  531. 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)
  532. return
  533. }
  534. f.errorf(id, 0.8, link(styleGuideBase+"#initialisms"), category("naming"), "%s %s should be %s", thing, id.Name, should)
  535. }
  536. checkList := func(fl *ast.FieldList, thing string) {
  537. if fl == nil {
  538. return
  539. }
  540. for _, f := range fl.List {
  541. for _, id := range f.Names {
  542. check(id, thing)
  543. }
  544. }
  545. }
  546. f.walk(func(node ast.Node) bool {
  547. switch v := node.(type) {
  548. case *ast.AssignStmt:
  549. if v.Tok == token.ASSIGN {
  550. return true
  551. }
  552. for _, exp := range v.Lhs {
  553. if id, ok := exp.(*ast.Ident); ok {
  554. check(id, "var")
  555. }
  556. }
  557. case *ast.FuncDecl:
  558. if f.isTest() && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
  559. return true
  560. }
  561. thing := "func"
  562. if v.Recv != nil {
  563. thing = "method"
  564. }
  565. // Exclude naming warnings for functions that are exported to C but
  566. // not exported in the Go API.
  567. // See https://github.com/golang/lint/issues/144.
  568. if ast.IsExported(v.Name.Name) || !isCgoExported(v) {
  569. check(v.Name, thing)
  570. }
  571. checkList(v.Type.Params, thing+" parameter")
  572. checkList(v.Type.Results, thing+" result")
  573. case *ast.GenDecl:
  574. if v.Tok == token.IMPORT {
  575. return true
  576. }
  577. var thing string
  578. switch v.Tok {
  579. case token.CONST:
  580. thing = "const"
  581. case token.TYPE:
  582. thing = "type"
  583. case token.VAR:
  584. thing = "var"
  585. }
  586. for _, spec := range v.Specs {
  587. switch s := spec.(type) {
  588. case *ast.TypeSpec:
  589. check(s.Name, thing)
  590. case *ast.ValueSpec:
  591. for _, id := range s.Names {
  592. check(id, thing)
  593. }
  594. }
  595. }
  596. case *ast.InterfaceType:
  597. // Do not check interface method names.
  598. // They are often constrainted by the method names of concrete types.
  599. for _, x := range v.Methods.List {
  600. ft, ok := x.Type.(*ast.FuncType)
  601. if !ok { // might be an embedded interface name
  602. continue
  603. }
  604. checkList(ft.Params, "interface method parameter")
  605. checkList(ft.Results, "interface method result")
  606. }
  607. case *ast.RangeStmt:
  608. if v.Tok == token.ASSIGN {
  609. return true
  610. }
  611. if id, ok := v.Key.(*ast.Ident); ok {
  612. check(id, "range var")
  613. }
  614. if id, ok := v.Value.(*ast.Ident); ok {
  615. check(id, "range var")
  616. }
  617. case *ast.StructType:
  618. for _, f := range v.Fields.List {
  619. for _, id := range f.Names {
  620. check(id, "struct field")
  621. }
  622. }
  623. }
  624. return true
  625. })
  626. }
  627. // lintName returns a different name if it should be different.
  628. func lintName(name string) (should string) {
  629. // Fast path for simple cases: "_" and all lowercase.
  630. if name == "_" {
  631. return name
  632. }
  633. allLower := true
  634. for _, r := range name {
  635. if !unicode.IsLower(r) {
  636. allLower = false
  637. break
  638. }
  639. }
  640. if allLower {
  641. return name
  642. }
  643. // Split camelCase at any lower->upper transition, and split on underscores.
  644. // Check each word for common initialisms.
  645. runes := []rune(name)
  646. w, i := 0, 0 // index of start of word, scan
  647. for i+1 <= len(runes) {
  648. eow := false // whether we hit the end of a word
  649. if i+1 == len(runes) {
  650. eow = true
  651. } else if runes[i+1] == '_' {
  652. // underscore; shift the remainder forward over any run of underscores
  653. eow = true
  654. n := 1
  655. for i+n+1 < len(runes) && runes[i+n+1] == '_' {
  656. n++
  657. }
  658. // Leave at most one underscore if the underscore is between two digits
  659. if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
  660. n--
  661. }
  662. copy(runes[i+1:], runes[i+n+1:])
  663. runes = runes[:len(runes)-n]
  664. } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
  665. // lower->non-lower
  666. eow = true
  667. }
  668. i++
  669. if !eow {
  670. continue
  671. }
  672. // [w,i) is a word.
  673. word := string(runes[w:i])
  674. if u := strings.ToUpper(word); commonInitialisms[u] {
  675. // Keep consistent case, which is lowercase only at the start.
  676. if w == 0 && unicode.IsLower(runes[w]) {
  677. u = strings.ToLower(u)
  678. }
  679. // All the common initialisms are ASCII,
  680. // so we can replace the bytes exactly.
  681. copy(runes[w:], []rune(u))
  682. } else if w > 0 && strings.ToLower(word) == word {
  683. // already all lowercase, and not the first word, so uppercase the first character.
  684. runes[w] = unicode.ToUpper(runes[w])
  685. }
  686. w = i
  687. }
  688. return string(runes)
  689. }
  690. // commonInitialisms is a set of common initialisms.
  691. // Only add entries that are highly unlikely to be non-initialisms.
  692. // For instance, "ID" is fine (Freudian code is rare), but "AND" is not.
  693. var commonInitialisms = map[string]bool{
  694. "ACL": true,
  695. "API": true,
  696. "ASCII": true,
  697. "CPU": true,
  698. "CSS": true,
  699. "DNS": true,
  700. "EOF": true,
  701. "GUID": true,
  702. "HTML": true,
  703. "HTTP": true,
  704. "HTTPS": true,
  705. "ID": true,
  706. "IP": true,
  707. "JSON": true,
  708. "LHS": true,
  709. "QPS": true,
  710. "RAM": true,
  711. "RHS": true,
  712. "RPC": true,
  713. "SLA": true,
  714. "SMTP": true,
  715. "SQL": true,
  716. "SSH": true,
  717. "TCP": true,
  718. "TLS": true,
  719. "TTL": true,
  720. "UDP": true,
  721. "UI": true,
  722. "UID": true,
  723. "UUID": true,
  724. "URI": true,
  725. "URL": true,
  726. "UTF8": true,
  727. "VM": true,
  728. "XML": true,
  729. "XMPP": true,
  730. "XSRF": true,
  731. "XSS": true,
  732. }
  733. // lintTypeDoc examines the doc comment on a type.
  734. // It complains if they are missing from an exported type,
  735. // or if they are not of the standard form.
  736. func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) {
  737. if !ast.IsExported(t.Name.Name) {
  738. return
  739. }
  740. if doc == nil {
  741. f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name)
  742. return
  743. }
  744. s := doc.Text()
  745. articles := [...]string{"A", "An", "The"}
  746. for _, a := range articles {
  747. if strings.HasPrefix(s, a+" ") {
  748. s = s[len(a)+1:]
  749. break
  750. }
  751. }
  752. if !strings.HasPrefix(s, t.Name.Name+" ") {
  753. 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)
  754. }
  755. }
  756. var commonMethods = map[string]bool{
  757. "Error": true,
  758. "Read": true,
  759. "ServeHTTP": true,
  760. "String": true,
  761. "Write": true,
  762. "Unwrap": 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. // lintElses examines else blocks. It complains about any else block whose if block ends in a return.
  893. func (f *file) lintElses() {
  894. // We don't want to flag if { } else if { } else { } constructions.
  895. // They will appear as an IfStmt whose Else field is also an IfStmt.
  896. // Record such a node so we ignore it when we visit it.
  897. ignore := make(map[*ast.IfStmt]bool)
  898. f.walk(func(node ast.Node) bool {
  899. ifStmt, ok := node.(*ast.IfStmt)
  900. if !ok || ifStmt.Else == nil {
  901. return true
  902. }
  903. if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
  904. ignore[elseif] = true
  905. return true
  906. }
  907. if ignore[ifStmt] {
  908. return true
  909. }
  910. if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
  911. // only care about elses without conditions
  912. return true
  913. }
  914. if len(ifStmt.Body.List) == 0 {
  915. return true
  916. }
  917. shortDecl := false // does the if statement have a ":=" initialization statement?
  918. if ifStmt.Init != nil {
  919. if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
  920. shortDecl = true
  921. }
  922. }
  923. lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
  924. if _, ok := lastStmt.(*ast.ReturnStmt); ok {
  925. extra := ""
  926. if shortDecl {
  927. extra = " (move short variable declaration to its own line if necessary)"
  928. }
  929. 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)
  930. }
  931. return true
  932. })
  933. }
  934. // lintRanges examines range clauses. It complains about redundant constructions.
  935. func (f *file) lintRanges() {
  936. f.walk(func(node ast.Node) bool {
  937. rs, ok := node.(*ast.RangeStmt)
  938. if !ok {
  939. return true
  940. }
  941. if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
  942. p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`")
  943. newRS := *rs // shallow copy
  944. newRS.Value = nil
  945. newRS.Key = nil
  946. p.ReplacementLine = f.firstLineOf(&newRS, rs)
  947. return true
  948. }
  949. if isIdent(rs.Value, "_") {
  950. 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)
  951. newRS := *rs // shallow copy
  952. newRS.Value = nil
  953. p.ReplacementLine = f.firstLineOf(&newRS, rs)
  954. }
  955. return true
  956. })
  957. }
  958. // lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
  959. func (f *file) lintErrorf() {
  960. f.walk(func(node ast.Node) bool {
  961. ce, ok := node.(*ast.CallExpr)
  962. if !ok || len(ce.Args) != 1 {
  963. return true
  964. }
  965. isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
  966. var isTestingError bool
  967. se, ok := ce.Fun.(*ast.SelectorExpr)
  968. if ok && se.Sel.Name == "Error" {
  969. if typ := f.pkg.typeOf(se.X); typ != nil {
  970. isTestingError = typ.String() == "*testing.T"
  971. }
  972. }
  973. if !isErrorsNew && !isTestingError {
  974. return true
  975. }
  976. if !f.imports("errors") {
  977. return true
  978. }
  979. arg := ce.Args[0]
  980. ce, ok = arg.(*ast.CallExpr)
  981. if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
  982. return true
  983. }
  984. errorfPrefix := "fmt"
  985. if isTestingError {
  986. errorfPrefix = f.render(se.X)
  987. }
  988. p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix)
  989. m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`)
  990. if m != nil {
  991. p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3]
  992. }
  993. return true
  994. })
  995. }
  996. // lintErrors examines global error vars. It complains if they aren't named in the standard way.
  997. func (f *file) lintErrors() {
  998. for _, decl := range f.f.Decls {
  999. gd, ok := decl.(*ast.GenDecl)
  1000. if !ok || gd.Tok != token.VAR {
  1001. continue
  1002. }
  1003. for _, spec := range gd.Specs {
  1004. spec := spec.(*ast.ValueSpec)
  1005. if len(spec.Names) != 1 || len(spec.Values) != 1 {
  1006. continue
  1007. }
  1008. ce, ok := spec.Values[0].(*ast.CallExpr)
  1009. if !ok {
  1010. continue
  1011. }
  1012. if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
  1013. continue
  1014. }
  1015. id := spec.Names[0]
  1016. prefix := "err"
  1017. if id.IsExported() {
  1018. prefix = "Err"
  1019. }
  1020. if !strings.HasPrefix(id.Name, prefix) {
  1021. f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix)
  1022. }
  1023. }
  1024. }
  1025. }
  1026. func lintErrorString(s string) (isClean bool, conf float64) {
  1027. const basicConfidence = 0.8
  1028. const capConfidence = basicConfidence - 0.2
  1029. first, firstN := utf8.DecodeRuneInString(s)
  1030. last, _ := utf8.DecodeLastRuneInString(s)
  1031. if last == '.' || last == ':' || last == '!' || last == '\n' {
  1032. return false, basicConfidence
  1033. }
  1034. if unicode.IsUpper(first) {
  1035. // People use proper nouns and exported Go identifiers in error strings,
  1036. // so decrease the confidence of warnings for capitalization.
  1037. if len(s) <= firstN {
  1038. return false, capConfidence
  1039. }
  1040. // Flag strings starting with something that doesn't look like an initialism.
  1041. if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) {
  1042. return false, capConfidence
  1043. }
  1044. }
  1045. return true, 0
  1046. }
  1047. // lintErrorStrings examines error strings.
  1048. // It complains if they are capitalized or end in punctuation or a newline.
  1049. func (f *file) lintErrorStrings() {
  1050. f.walk(func(node ast.Node) bool {
  1051. ce, ok := node.(*ast.CallExpr)
  1052. if !ok {
  1053. return true
  1054. }
  1055. if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
  1056. return true
  1057. }
  1058. if len(ce.Args) < 1 {
  1059. return true
  1060. }
  1061. str, ok := ce.Args[0].(*ast.BasicLit)
  1062. if !ok || str.Kind != token.STRING {
  1063. return true
  1064. }
  1065. s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
  1066. if s == "" {
  1067. return true
  1068. }
  1069. clean, conf := lintErrorString(s)
  1070. if clean {
  1071. return true
  1072. }
  1073. f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"),
  1074. "error strings should not be capitalized or end with punctuation or a newline")
  1075. return true
  1076. })
  1077. }
  1078. // lintReceiverNames examines receiver names. It complains about inconsistent
  1079. // names used for the same type and names such as "this".
  1080. func (f *file) lintReceiverNames() {
  1081. typeReceiver := map[string]string{}
  1082. f.walk(func(n ast.Node) bool {
  1083. fn, ok := n.(*ast.FuncDecl)
  1084. if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 {
  1085. return true
  1086. }
  1087. names := fn.Recv.List[0].Names
  1088. if len(names) < 1 {
  1089. return true
  1090. }
  1091. name := names[0].Name
  1092. const ref = styleGuideBase + "#receiver-names"
  1093. if name == "_" {
  1094. f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`)
  1095. return true
  1096. }
  1097. if name == "this" || name == "self" {
  1098. 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"`)
  1099. return true
  1100. }
  1101. recv := receiverType(fn)
  1102. if prev, ok := typeReceiver[recv]; ok && prev != name {
  1103. f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv)
  1104. return true
  1105. }
  1106. typeReceiver[recv] = name
  1107. return true
  1108. })
  1109. }
  1110. // lintIncDec examines statements that increment or decrement a variable.
  1111. // It complains if they don't use x++ or x--.
  1112. func (f *file) lintIncDec() {
  1113. f.walk(func(n ast.Node) bool {
  1114. as, ok := n.(*ast.AssignStmt)
  1115. if !ok {
  1116. return true
  1117. }
  1118. if len(as.Lhs) != 1 {
  1119. return true
  1120. }
  1121. if !isOne(as.Rhs[0]) {
  1122. return true
  1123. }
  1124. var suffix string
  1125. switch as.Tok {
  1126. case token.ADD_ASSIGN:
  1127. suffix = "++"
  1128. case token.SUB_ASSIGN:
  1129. suffix = "--"
  1130. default:
  1131. return true
  1132. }
  1133. f.errorf(as, 0.8, category("unary-op"), "should replace %s with %s%s", f.render(as), f.render(as.Lhs[0]), suffix)
  1134. return true
  1135. })
  1136. }
  1137. // lintErrorReturn examines function declarations that return an error.
  1138. // It complains if the error isn't the last parameter.
  1139. func (f *file) lintErrorReturn() {
  1140. f.walk(func(n ast.Node) bool {
  1141. fn, ok := n.(*ast.FuncDecl)
  1142. if !ok || fn.Type.Results == nil {
  1143. return true
  1144. }
  1145. ret := fn.Type.Results.List
  1146. if len(ret) <= 1 {
  1147. return true
  1148. }
  1149. if isIdent(ret[len(ret)-1].Type, "error") {
  1150. return true
  1151. }
  1152. // An error return parameter should be the last parameter.
  1153. // Flag any error parameters found before the last.
  1154. for _, r := range ret[:len(ret)-1] {
  1155. if isIdent(r.Type, "error") {
  1156. f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items")
  1157. break // only flag one
  1158. }
  1159. }
  1160. return true
  1161. })
  1162. }
  1163. // lintUnexportedReturn examines exported function declarations.
  1164. // It complains if any return an unexported type.
  1165. func (f *file) lintUnexportedReturn() {
  1166. f.walk(func(n ast.Node) bool {
  1167. fn, ok := n.(*ast.FuncDecl)
  1168. if !ok {
  1169. return true
  1170. }
  1171. if fn.Type.Results == nil {
  1172. return false
  1173. }
  1174. if !fn.Name.IsExported() {
  1175. return false
  1176. }
  1177. thing := "func"
  1178. if fn.Recv != nil && len(fn.Recv.List) > 0 {
  1179. thing = "method"
  1180. if !ast.IsExported(receiverType(fn)) {
  1181. // Don't report exported methods of unexported types,
  1182. // such as private implementations of sort.Interface.
  1183. return false
  1184. }
  1185. }
  1186. for _, ret := range fn.Type.Results.List {
  1187. typ := f.pkg.typeOf(ret.Type)
  1188. if exportedType(typ) {
  1189. continue
  1190. }
  1191. f.errorf(ret.Type, 0.8, category("unexported-type-in-api"),
  1192. "exported %s %s returns unexported type %s, which can be annoying to use",
  1193. thing, fn.Name.Name, typ)
  1194. break // only flag one
  1195. }
  1196. return false
  1197. })
  1198. }
  1199. // exportedType reports whether typ is an exported type.
  1200. // It is imprecise, and will err on the side of returning true,
  1201. // such as for composite types.
  1202. func exportedType(typ types.Type) bool {
  1203. switch T := typ.(type) {
  1204. case *types.Named:
  1205. // Builtin types have no package.
  1206. return T.Obj().Pkg() == nil || T.Obj().Exported()
  1207. case *types.Map:
  1208. return exportedType(T.Key()) && exportedType(T.Elem())
  1209. case interface {
  1210. Elem() types.Type
  1211. }: // array, slice, pointer, chan
  1212. return exportedType(T.Elem())
  1213. }
  1214. // Be conservative about other types, such as struct, interface, etc.
  1215. return true
  1216. }
  1217. // timeSuffixes is a list of name suffixes that imply a time unit.
  1218. // This is not an exhaustive list.
  1219. var timeSuffixes = []string{
  1220. "Sec", "Secs", "Seconds",
  1221. "Msec", "Msecs",
  1222. "Milli", "Millis", "Milliseconds",
  1223. "Usec", "Usecs", "Microseconds",
  1224. "MS", "Ms",
  1225. }
  1226. func (f *file) lintTimeNames() {
  1227. f.walk(func(node ast.Node) bool {
  1228. v, ok := node.(*ast.ValueSpec)
  1229. if !ok {
  1230. return true
  1231. }
  1232. for _, name := range v.Names {
  1233. origTyp := f.pkg.typeOf(name)
  1234. // Look for time.Duration or *time.Duration;
  1235. // the latter is common when using flag.Duration.
  1236. typ := origTyp
  1237. if pt, ok := typ.(*types.Pointer); ok {
  1238. typ = pt.Elem()
  1239. }
  1240. if !f.pkg.isNamedType(typ, "time", "Duration") {
  1241. continue
  1242. }
  1243. suffix := ""
  1244. for _, suf := range timeSuffixes {
  1245. if strings.HasSuffix(name.Name, suf) {
  1246. suffix = suf
  1247. break
  1248. }
  1249. }
  1250. if suffix == "" {
  1251. continue
  1252. }
  1253. f.errorf(v, 0.9, category("time"), "var %s is of type %v; don't use unit-specific suffix %q", name.Name, origTyp, suffix)
  1254. }
  1255. return true
  1256. })
  1257. }
  1258. // lintContextKeyTypes checks for call expressions to context.WithValue with
  1259. // basic types used for the key argument.
  1260. // See: https://golang.org/issue/17293
  1261. func (f *file) lintContextKeyTypes() {
  1262. f.walk(func(node ast.Node) bool {
  1263. switch node := node.(type) {
  1264. case *ast.CallExpr:
  1265. f.checkContextKeyType(node)
  1266. }
  1267. return true
  1268. })
  1269. }
  1270. // checkContextKeyType reports an error if the call expression calls
  1271. // context.WithValue with a key argument of basic type.
  1272. func (f *file) checkContextKeyType(x *ast.CallExpr) {
  1273. sel, ok := x.Fun.(*ast.SelectorExpr)
  1274. if !ok {
  1275. return
  1276. }
  1277. pkg, ok := sel.X.(*ast.Ident)
  1278. if !ok || pkg.Name != "context" {
  1279. return
  1280. }
  1281. if sel.Sel.Name != "WithValue" {
  1282. return
  1283. }
  1284. // key is second argument to context.WithValue
  1285. if len(x.Args) != 3 {
  1286. return
  1287. }
  1288. key := f.pkg.typesInfo.Types[x.Args[1]]
  1289. if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid {
  1290. f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type))
  1291. }
  1292. }
  1293. // lintContextArgs examines function declarations that contain an
  1294. // argument with a type of context.Context
  1295. // It complains if that argument isn't the first parameter.
  1296. func (f *file) lintContextArgs() {
  1297. f.walk(func(n ast.Node) bool {
  1298. fn, ok := n.(*ast.FuncDecl)
  1299. if !ok || len(fn.Type.Params.List) <= 1 {
  1300. return true
  1301. }
  1302. // A context.Context should be the first parameter of a function.
  1303. // Flag any that show up after the first.
  1304. for _, arg := range fn.Type.Params.List[1:] {
  1305. if isPkgDot(arg.Type, "context", "Context") {
  1306. f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function")
  1307. break // only flag one
  1308. }
  1309. }
  1310. return true
  1311. })
  1312. }
  1313. // containsComments returns whether the interval [start, end) contains any
  1314. // comments without "// MATCH " prefix.
  1315. func (f *file) containsComments(start, end token.Pos) bool {
  1316. for _, cgroup := range f.f.Comments {
  1317. comments := cgroup.List
  1318. if comments[0].Slash >= end {
  1319. // All comments starting with this group are after end pos.
  1320. return false
  1321. }
  1322. if comments[len(comments)-1].Slash < start {
  1323. // Comments group ends before start pos.
  1324. continue
  1325. }
  1326. for _, c := range comments {
  1327. if start <= c.Slash && c.Slash < end && !strings.HasPrefix(c.Text, "// MATCH ") {
  1328. return true
  1329. }
  1330. }
  1331. }
  1332. return false
  1333. }
  1334. // receiverType returns the named type of the method receiver, sans "*",
  1335. // or "invalid-type" if fn.Recv is ill formed.
  1336. func receiverType(fn *ast.FuncDecl) string {
  1337. switch e := fn.Recv.List[0].Type.(type) {
  1338. case *ast.Ident:
  1339. return e.Name
  1340. case *ast.StarExpr:
  1341. if id, ok := e.X.(*ast.Ident); ok {
  1342. return id.Name
  1343. }
  1344. }
  1345. // The parser accepts much more than just the legal forms.
  1346. return "invalid-type"
  1347. }
  1348. func (f *file) walk(fn func(ast.Node) bool) {
  1349. ast.Walk(walker(fn), f.f)
  1350. }
  1351. func (f *file) render(x interface{}) string {
  1352. var buf bytes.Buffer
  1353. if err := printer.Fprint(&buf, f.fset, x); err != nil {
  1354. panic(err)
  1355. }
  1356. return buf.String()
  1357. }
  1358. func (f *file) debugRender(x interface{}) string {
  1359. var buf bytes.Buffer
  1360. if err := ast.Fprint(&buf, f.fset, x, nil); err != nil {
  1361. panic(err)
  1362. }
  1363. return buf.String()
  1364. }
  1365. // walker adapts a function to satisfy the ast.Visitor interface.
  1366. // The function return whether the walk should proceed into the node's children.
  1367. type walker func(ast.Node) bool
  1368. func (w walker) Visit(node ast.Node) ast.Visitor {
  1369. if w(node) {
  1370. return w
  1371. }
  1372. return nil
  1373. }
  1374. func isIdent(expr ast.Expr, ident string) bool {
  1375. id, ok := expr.(*ast.Ident)
  1376. return ok && id.Name == ident
  1377. }
  1378. // isBlank returns whether id is the blank identifier "_".
  1379. // If id == nil, the answer is false.
  1380. func isBlank(id *ast.Ident) bool { return id != nil && id.Name == "_" }
  1381. func isPkgDot(expr ast.Expr, pkg, name string) bool {
  1382. sel, ok := expr.(*ast.SelectorExpr)
  1383. return ok && isIdent(sel.X, pkg) && isIdent(sel.Sel, name)
  1384. }
  1385. func isOne(expr ast.Expr) bool {
  1386. lit, ok := expr.(*ast.BasicLit)
  1387. return ok && lit.Kind == token.INT && lit.Value == "1"
  1388. }
  1389. func isCgoExported(f *ast.FuncDecl) bool {
  1390. if f.Recv != nil || f.Doc == nil {
  1391. return false
  1392. }
  1393. cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name)))
  1394. for _, c := range f.Doc.List {
  1395. if cgoExport.MatchString(c.Text) {
  1396. return true
  1397. }
  1398. }
  1399. return false
  1400. }
  1401. var basicTypeKinds = map[types.BasicKind]string{
  1402. types.UntypedBool: "bool",
  1403. types.UntypedInt: "int",
  1404. types.UntypedRune: "rune",
  1405. types.UntypedFloat: "float64",
  1406. types.UntypedComplex: "complex128",
  1407. types.UntypedString: "string",
  1408. }
  1409. // isUntypedConst reports whether expr is an untyped constant,
  1410. // and indicates what its default type is.
  1411. // scope may be nil.
  1412. func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) {
  1413. // Re-evaluate expr outside of its context to see if it's untyped.
  1414. // (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
  1415. exprStr := f.render(expr)
  1416. tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr)
  1417. if err != nil {
  1418. return "", false
  1419. }
  1420. if b, ok := tv.Type.(*types.Basic); ok {
  1421. if dt, ok := basicTypeKinds[b.Kind()]; ok {
  1422. return dt, true
  1423. }
  1424. }
  1425. return "", false
  1426. }
  1427. // firstLineOf renders the given node and returns its first line.
  1428. // It will also match the indentation of another node.
  1429. func (f *file) firstLineOf(node, match ast.Node) string {
  1430. line := f.render(node)
  1431. if i := strings.Index(line, "\n"); i >= 0 {
  1432. line = line[:i]
  1433. }
  1434. return f.indentOf(match) + line
  1435. }
  1436. func (f *file) indentOf(node ast.Node) string {
  1437. line := srcLine(f.src, f.fset.Position(node.Pos()))
  1438. for i, r := range line {
  1439. switch r {
  1440. case ' ', '\t':
  1441. default:
  1442. return line[:i]
  1443. }
  1444. }
  1445. return line // unusual or empty line
  1446. }
  1447. func (f *file) srcLineWithMatch(node ast.Node, pattern string) (m []string) {
  1448. line := srcLine(f.src, f.fset.Position(node.Pos()))
  1449. line = strings.TrimSuffix(line, "\n")
  1450. rx := regexp.MustCompile(pattern)
  1451. return rx.FindStringSubmatch(line)
  1452. }
  1453. // imports returns true if the current file imports the specified package path.
  1454. func (f *file) imports(importPath string) bool {
  1455. all := astutil.Imports(f.fset, f.f)
  1456. for _, p := range all {
  1457. for _, i := range p {
  1458. uq, err := strconv.Unquote(i.Path.Value)
  1459. if err == nil && importPath == uq {
  1460. return true
  1461. }
  1462. }
  1463. }
  1464. return false
  1465. }
  1466. // srcLine returns the complete line at p, including the terminating newline.
  1467. func srcLine(src []byte, p token.Position) string {
  1468. // Run to end of line in both directions if not at line start/end.
  1469. lo, hi := p.Offset, p.Offset+1
  1470. for lo > 0 && src[lo-1] != '\n' {
  1471. lo--
  1472. }
  1473. for hi < len(src) && src[hi-1] != '\n' {
  1474. hi++
  1475. }
  1476. return string(src[lo:hi])
  1477. }