1 // Copyright (c) 2013 The Go Authors. All rights reserved.
2 // Copyright (c) 2018 Dominik Honnef. All rights reserved.
13 "honnef.co/go/tools/analysis/code"
14 "honnef.co/go/tools/analysis/report"
15 "honnef.co/go/tools/config"
17 "golang.org/x/tools/go/analysis"
20 // knownNameExceptions is a set of names that are known to be exempt from naming checks.
21 // This is usually because they are constrained by having to match names in the
23 var knownNameExceptions = map[string]bool{
24 "LastInsertId": true, // must match database/sql
28 func CheckNames(pass *analysis.Pass) (interface{}, error) {
29 // A large part of this function is copied from
30 // github.com/golang/lint, Copyright (c) 2013 The Go Authors,
31 // licensed under the BSD 3-clause license.
33 allCaps := func(s string) bool {
34 hasUppercaseLetters := false
36 if !hasUppercaseLetters && r >= 'A' && r <= 'Z' {
37 hasUppercaseLetters = true
39 if !((r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
43 return hasUppercaseLetters
46 check := func(id *ast.Ident, thing string, initialisms map[string]bool) {
50 if knownNameExceptions[id.Name] {
54 // Handle two common styles from other languages that don't belong in Go.
55 if len(id.Name) >= 5 && allCaps(id.Name) && strings.Contains(id.Name, "_") {
56 report.Report(pass, id, "should not use ALL_CAPS in Go names; use CamelCase instead", report.FilterGenerated())
60 should := lintName(id.Name, initialisms)
61 if id.Name == should {
65 if len(id.Name) > 2 && strings.Contains(id.Name[1:len(id.Name)-1], "_") {
66 report.Report(pass, id, fmt.Sprintf("should not use underscores in Go names; %s %s should be %s", thing, id.Name, should), report.FilterGenerated())
69 report.Report(pass, id, fmt.Sprintf("%s %s should be %s", thing, id.Name, should), report.FilterGenerated())
71 checkList := func(fl *ast.FieldList, thing string, initialisms map[string]bool) {
75 for _, f := range fl.List {
76 for _, id := range f.Names {
77 check(id, thing, initialisms)
82 il := config.For(pass).Initialisms
83 initialisms := make(map[string]bool, len(il))
84 for _, word := range il {
85 initialisms[word] = true
87 for _, f := range pass.Files {
88 // Package names need slightly different handling than other names.
89 if !strings.HasSuffix(f.Name.Name, "_test") && strings.Contains(f.Name.Name, "_") {
90 report.Report(pass, f, "should not use underscores in package names", report.FilterGenerated())
92 if strings.IndexFunc(f.Name.Name, unicode.IsUpper) != -1 {
93 report.Report(pass, f, fmt.Sprintf("should not use MixedCaps in package name; %s should be %s", f.Name.Name, strings.ToLower(f.Name.Name)), report.FilterGenerated())
97 fn := func(node ast.Node) {
98 switch v := node.(type) {
100 if v.Tok != token.DEFINE {
103 for _, exp := range v.Lhs {
104 if id, ok := exp.(*ast.Ident); ok {
105 check(id, "var", initialisms)
109 // Functions with no body are defined elsewhere (in
110 // assembly, or via go:linkname). These are likely to
111 // be something very low level (such as the runtime),
112 // where our rules don't apply.
117 if code.IsInTest(pass, v) && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
126 if !isTechnicallyExported(v) {
127 check(v.Name, thing, initialisms)
130 checkList(v.Type.Params, thing+" parameter", initialisms)
131 checkList(v.Type.Results, thing+" result", initialisms)
133 if v.Tok == token.IMPORT {
145 for _, spec := range v.Specs {
146 switch s := spec.(type) {
148 check(s.Name, thing, initialisms)
150 for _, id := range s.Names {
151 check(id, thing, initialisms)
155 case *ast.InterfaceType:
156 // Do not check interface method names.
157 // They are often constrained by the method names of concrete types.
158 for _, x := range v.Methods.List {
159 ft, ok := x.Type.(*ast.FuncType)
160 if !ok { // might be an embedded interface name
163 checkList(ft.Params, "interface method parameter", initialisms)
164 checkList(ft.Results, "interface method result", initialisms)
167 if v.Tok == token.ASSIGN {
170 if id, ok := v.Key.(*ast.Ident); ok {
171 check(id, "range var", initialisms)
173 if id, ok := v.Value.(*ast.Ident); ok {
174 check(id, "range var", initialisms)
176 case *ast.StructType:
177 for _, f := range v.Fields.List {
178 for _, id := range f.Names {
179 check(id, "struct field", initialisms)
185 needle := []ast.Node{
186 (*ast.AssignStmt)(nil),
187 (*ast.FuncDecl)(nil),
189 (*ast.InterfaceType)(nil),
190 (*ast.RangeStmt)(nil),
191 (*ast.StructType)(nil),
194 code.Preorder(pass, fn, needle...)
198 // lintName returns a different name if it should be different.
199 func lintName(name string, initialisms map[string]bool) (should string) {
200 // A large part of this function is copied from
201 // github.com/golang/lint, Copyright (c) 2013 The Go Authors,
202 // licensed under the BSD 3-clause license.
204 // Fast path for simple cases: "_" and all lowercase.
208 if strings.IndexFunc(name, func(r rune) bool { return !unicode.IsLower(r) }) == -1 {
212 // Split camelCase at any lower->upper transition, and split on underscores.
213 // Check each word for common initialisms.
214 runes := []rune(name)
215 w, i := 0, 0 // index of start of word, scan
216 for i+1 <= len(runes) {
217 eow := false // whether we hit the end of a word
218 if i+1 == len(runes) {
220 } else if runes[i+1] == '_' && i+1 != len(runes)-1 {
221 // underscore; shift the remainder forward over any run of underscores
224 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
228 // Leave at most one underscore if the underscore is between two digits
229 if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
233 copy(runes[i+1:], runes[i+n+1:])
234 runes = runes[:len(runes)-n]
235 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
245 word := string(runes[w:i])
246 if u := strings.ToUpper(word); initialisms[u] {
247 // Keep consistent case, which is lowercase only at the start.
248 if w == 0 && unicode.IsLower(runes[w]) {
249 u = strings.ToLower(u)
251 // All the common initialisms are ASCII,
252 // so we can replace the bytes exactly.
253 // TODO(dh): this won't be true once we allow custom initialisms
254 copy(runes[w:], []rune(u))
255 } else if w > 0 && strings.ToLower(word) == word {
256 // already all lowercase, and not the first word, so uppercase the first character.
257 runes[w] = unicode.ToUpper(runes[w])
264 func isTechnicallyExported(f *ast.FuncDecl) bool {
265 if f.Recv != nil || f.Doc == nil {
269 const export = "//export "
270 const linkname = "//go:linkname "
271 for _, c := range f.Doc.List {
272 if strings.HasPrefix(c.Text, export) && len(c.Text) == len(export)+len(f.Name.Name) && c.Text[len(export):] == f.Name.Name {
276 if strings.HasPrefix(c.Text, linkname) {