1// Copyright (c) 2013 The Go Authors. All rights reserved.
2// Copyright (c) 2018 Dominik Honnef. All rights reserved.
3
4package stylecheck
5
6import (
7	"fmt"
8	"go/ast"
9	"go/token"
10	"strings"
11	"unicode"
12
13	"honnef.co/go/tools/analysis/code"
14	"honnef.co/go/tools/analysis/report"
15	"honnef.co/go/tools/config"
16
17	"golang.org/x/tools/go/analysis"
18)
19
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
22// standard library.
23var knownNameExceptions = map[string]bool{
24	"LastInsertId": true, // must match database/sql
25	"kWh":          true,
26}
27
28func 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.
32
33	allCaps := func(s string) bool {
34		hasUppercaseLetters := false
35		for _, r := range s {
36			if !hasUppercaseLetters && r >= 'A' && r <= 'Z' {
37				hasUppercaseLetters = true
38			}
39			if !((r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
40				return false
41			}
42		}
43		return hasUppercaseLetters
44	}
45
46	check := func(id *ast.Ident, thing string, initialisms map[string]bool) {
47		if id.Name == "_" {
48			return
49		}
50		if knownNameExceptions[id.Name] {
51			return
52		}
53
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())
57			return
58		}
59
60		should := lintName(id.Name, initialisms)
61		if id.Name == should {
62			return
63		}
64
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())
67			return
68		}
69		report.Report(pass, id, fmt.Sprintf("%s %s should be %s", thing, id.Name, should), report.FilterGenerated())
70	}
71	checkList := func(fl *ast.FieldList, thing string, initialisms map[string]bool) {
72		if fl == nil {
73			return
74		}
75		for _, f := range fl.List {
76			for _, id := range f.Names {
77				check(id, thing, initialisms)
78			}
79		}
80	}
81
82	il := config.For(pass).Initialisms
83	initialisms := make(map[string]bool, len(il))
84	for _, word := range il {
85		initialisms[word] = true
86	}
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())
91		}
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())
94		}
95	}
96
97	fn := func(node ast.Node) {
98		switch v := node.(type) {
99		case *ast.AssignStmt:
100			if v.Tok != token.DEFINE {
101				return
102			}
103			for _, exp := range v.Lhs {
104				if id, ok := exp.(*ast.Ident); ok {
105					check(id, "var", initialisms)
106				}
107			}
108		case *ast.FuncDecl:
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.
113			if v.Body == nil {
114				return
115			}
116
117			if code.IsInTest(pass, v) && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
118				return
119			}
120
121			thing := "func"
122			if v.Recv != nil {
123				thing = "method"
124			}
125
126			if !isTechnicallyExported(v) {
127				check(v.Name, thing, initialisms)
128			}
129
130			checkList(v.Type.Params, thing+" parameter", initialisms)
131			checkList(v.Type.Results, thing+" result", initialisms)
132		case *ast.GenDecl:
133			if v.Tok == token.IMPORT {
134				return
135			}
136			var thing string
137			switch v.Tok {
138			case token.CONST:
139				thing = "const"
140			case token.TYPE:
141				thing = "type"
142			case token.VAR:
143				thing = "var"
144			}
145			for _, spec := range v.Specs {
146				switch s := spec.(type) {
147				case *ast.TypeSpec:
148					check(s.Name, thing, initialisms)
149				case *ast.ValueSpec:
150					for _, id := range s.Names {
151						check(id, thing, initialisms)
152					}
153				}
154			}
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
161					continue
162				}
163				checkList(ft.Params, "interface method parameter", initialisms)
164				checkList(ft.Results, "interface method result", initialisms)
165			}
166		case *ast.RangeStmt:
167			if v.Tok == token.ASSIGN {
168				return
169			}
170			if id, ok := v.Key.(*ast.Ident); ok {
171				check(id, "range var", initialisms)
172			}
173			if id, ok := v.Value.(*ast.Ident); ok {
174				check(id, "range var", initialisms)
175			}
176		case *ast.StructType:
177			for _, f := range v.Fields.List {
178				for _, id := range f.Names {
179					check(id, "struct field", initialisms)
180				}
181			}
182		}
183	}
184
185	needle := []ast.Node{
186		(*ast.AssignStmt)(nil),
187		(*ast.FuncDecl)(nil),
188		(*ast.GenDecl)(nil),
189		(*ast.InterfaceType)(nil),
190		(*ast.RangeStmt)(nil),
191		(*ast.StructType)(nil),
192	}
193
194	code.Preorder(pass, fn, needle...)
195	return nil, nil
196}
197
198// lintName returns a different name if it should be different.
199func 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.
203
204	// Fast path for simple cases: "_" and all lowercase.
205	if name == "_" {
206		return name
207	}
208	if strings.IndexFunc(name, func(r rune) bool { return !unicode.IsLower(r) }) == -1 {
209		return name
210	}
211
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) {
219			eow = true
220		} else if runes[i+1] == '_' && i+1 != len(runes)-1 {
221			// underscore; shift the remainder forward over any run of underscores
222			eow = true
223			n := 1
224			for i+n+1 < len(runes) && runes[i+n+1] == '_' {
225				n++
226			}
227
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]) {
230				n--
231			}
232
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]) {
236			// lower->non-lower
237			eow = true
238		}
239		i++
240		if !eow {
241			continue
242		}
243
244		// [w,i) is a word.
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)
250			}
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])
258		}
259		w = i
260	}
261	return string(runes)
262}
263
264func isTechnicallyExported(f *ast.FuncDecl) bool {
265	if f.Recv != nil || f.Doc == nil {
266		return false
267	}
268
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 {
273			return true
274		}
275
276		if strings.HasPrefix(c.Text, linkname) {
277			return true
278		}
279	}
280	return false
281}
282