1 // Copyright (c) 2013 The Go Authors. All rights reserved.
2 // Copyright (c) 2018 Dominik Honnef. All rights reserved.
13 "golang.org/x/tools/go/analysis"
14 "honnef.co/go/tools/code"
15 "honnef.co/go/tools/config"
16 "honnef.co/go/tools/report"
19 // knownNameExceptions is a set of names that are known to be exempt from naming checks.
20 // This is usually because they are constrained by having to match names in the
22 var knownNameExceptions = map[string]bool{
23 "LastInsertId": true, // must match database/sql
27 func CheckNames(pass *analysis.Pass) (interface{}, error) {
28 // A large part of this function is copied from
29 // github.com/golang/lint, Copyright (c) 2013 The Go Authors,
30 // licensed under the BSD 3-clause license.
32 allCaps := func(s string) bool {
34 if !((r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
41 check := func(id *ast.Ident, thing string, initialisms map[string]bool) {
45 if knownNameExceptions[id.Name] {
49 // Handle two common styles from other languages that don't belong in Go.
50 if len(id.Name) >= 5 && allCaps(id.Name) && strings.Contains(id.Name, "_") {
51 report.Report(pass, id, "should not use ALL_CAPS in Go names; use CamelCase instead", report.FilterGenerated())
55 should := lintName(id.Name, initialisms)
56 if id.Name == should {
60 if len(id.Name) > 2 && strings.Contains(id.Name[1:len(id.Name)-1], "_") {
61 report.Report(pass, id, fmt.Sprintf("should not use underscores in Go names; %s %s should be %s", thing, id.Name, should), report.FilterGenerated())
64 report.Report(pass, id, fmt.Sprintf("%s %s should be %s", thing, id.Name, should), report.FilterGenerated())
66 checkList := func(fl *ast.FieldList, thing string, initialisms map[string]bool) {
70 for _, f := range fl.List {
71 for _, id := range f.Names {
72 check(id, thing, initialisms)
77 il := config.For(pass).Initialisms
78 initialisms := make(map[string]bool, len(il))
79 for _, word := range il {
80 initialisms[word] = true
82 for _, f := range pass.Files {
83 // Package names need slightly different handling than other names.
84 if !strings.HasSuffix(f.Name.Name, "_test") && strings.Contains(f.Name.Name, "_") {
85 report.Report(pass, f, "should not use underscores in package names", report.FilterGenerated())
87 if strings.IndexFunc(f.Name.Name, unicode.IsUpper) != -1 {
88 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())
92 fn := func(node ast.Node) {
93 switch v := node.(type) {
95 if v.Tok != token.DEFINE {
98 for _, exp := range v.Lhs {
99 if id, ok := exp.(*ast.Ident); ok {
100 check(id, "var", initialisms)
104 // Functions with no body are defined elsewhere (in
105 // assembly, or via go:linkname). These are likely to
106 // be something very low level (such as the runtime),
107 // where our rules don't apply.
112 if code.IsInTest(pass, v) && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
121 if !isTechnicallyExported(v) {
122 check(v.Name, thing, initialisms)
125 checkList(v.Type.Params, thing+" parameter", initialisms)
126 checkList(v.Type.Results, thing+" result", initialisms)
128 if v.Tok == token.IMPORT {
140 for _, spec := range v.Specs {
141 switch s := spec.(type) {
143 check(s.Name, thing, initialisms)
145 for _, id := range s.Names {
146 check(id, thing, initialisms)
150 case *ast.InterfaceType:
151 // Do not check interface method names.
152 // They are often constrained by the method names of concrete types.
153 for _, x := range v.Methods.List {
154 ft, ok := x.Type.(*ast.FuncType)
155 if !ok { // might be an embedded interface name
158 checkList(ft.Params, "interface method parameter", initialisms)
159 checkList(ft.Results, "interface method result", initialisms)
162 if v.Tok == token.ASSIGN {
165 if id, ok := v.Key.(*ast.Ident); ok {
166 check(id, "range var", initialisms)
168 if id, ok := v.Value.(*ast.Ident); ok {
169 check(id, "range var", initialisms)
171 case *ast.StructType:
172 for _, f := range v.Fields.List {
173 for _, id := range f.Names {
174 check(id, "struct field", initialisms)
180 needle := []ast.Node{
181 (*ast.AssignStmt)(nil),
182 (*ast.FuncDecl)(nil),
184 (*ast.InterfaceType)(nil),
185 (*ast.RangeStmt)(nil),
186 (*ast.StructType)(nil),
189 code.Preorder(pass, fn, needle...)
193 // lintName returns a different name if it should be different.
194 func lintName(name string, initialisms map[string]bool) (should string) {
195 // A large part of this function is copied from
196 // github.com/golang/lint, Copyright (c) 2013 The Go Authors,
197 // licensed under the BSD 3-clause license.
199 // Fast path for simple cases: "_" and all lowercase.
203 if strings.IndexFunc(name, func(r rune) bool { return !unicode.IsLower(r) }) == -1 {
207 // Split camelCase at any lower->upper transition, and split on underscores.
208 // Check each word for common initialisms.
209 runes := []rune(name)
210 w, i := 0, 0 // index of start of word, scan
211 for i+1 <= len(runes) {
212 eow := false // whether we hit the end of a word
213 if i+1 == len(runes) {
215 } else if runes[i+1] == '_' && i+1 != len(runes)-1 {
216 // underscore; shift the remainder forward over any run of underscores
219 for i+n+1 < len(runes) && runes[i+n+1] == '_' {
223 // Leave at most one underscore if the underscore is between two digits
224 if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
228 copy(runes[i+1:], runes[i+n+1:])
229 runes = runes[:len(runes)-n]
230 } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
240 word := string(runes[w:i])
241 if u := strings.ToUpper(word); initialisms[u] {
242 // Keep consistent case, which is lowercase only at the start.
243 if w == 0 && unicode.IsLower(runes[w]) {
244 u = strings.ToLower(u)
246 // All the common initialisms are ASCII,
247 // so we can replace the bytes exactly.
248 // TODO(dh): this won't be true once we allow custom initialisms
249 copy(runes[w:], []rune(u))
250 } else if w > 0 && strings.ToLower(word) == word {
251 // already all lowercase, and not the first word, so uppercase the first character.
252 runes[w] = unicode.ToUpper(runes[w])
259 func isTechnicallyExported(f *ast.FuncDecl) bool {
260 if f.Recv != nil || f.Doc == nil {
264 const export = "//export "
265 const linkname = "//go:linkname "
266 for _, c := range f.Doc.List {
267 if strings.HasPrefix(c.Text, export) && len(c.Text) == len(export)+len(f.Name.Name) && c.Text[len(export):] == f.Name.Name {
271 if strings.HasPrefix(c.Text, linkname) {