Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / honnef.co / go / tools@v0.0.1-2020.1.5 / stylecheck / names.go
1 // Copyright (c) 2013 The Go Authors. All rights reserved.
2 // Copyright (c) 2018 Dominik Honnef. All rights reserved.
3
4 package stylecheck
5
6 import (
7         "fmt"
8         "go/ast"
9         "go/token"
10         "strings"
11         "unicode"
12
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"
17 )
18
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
21 // standard library.
22 var knownNameExceptions = map[string]bool{
23         "LastInsertId": true, // must match database/sql
24         "kWh":          true,
25 }
26
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.
31
32         allCaps := func(s string) bool {
33                 for _, r := range s {
34                         if !((r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_') {
35                                 return false
36                         }
37                 }
38                 return true
39         }
40
41         check := func(id *ast.Ident, thing string, initialisms map[string]bool) {
42                 if id.Name == "_" {
43                         return
44                 }
45                 if knownNameExceptions[id.Name] {
46                         return
47                 }
48
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())
52                         return
53                 }
54
55                 should := lintName(id.Name, initialisms)
56                 if id.Name == should {
57                         return
58                 }
59
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())
62                         return
63                 }
64                 report.Report(pass, id, fmt.Sprintf("%s %s should be %s", thing, id.Name, should), report.FilterGenerated())
65         }
66         checkList := func(fl *ast.FieldList, thing string, initialisms map[string]bool) {
67                 if fl == nil {
68                         return
69                 }
70                 for _, f := range fl.List {
71                         for _, id := range f.Names {
72                                 check(id, thing, initialisms)
73                         }
74                 }
75         }
76
77         il := config.For(pass).Initialisms
78         initialisms := make(map[string]bool, len(il))
79         for _, word := range il {
80                 initialisms[word] = true
81         }
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())
86                 }
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())
89                 }
90         }
91
92         fn := func(node ast.Node) {
93                 switch v := node.(type) {
94                 case *ast.AssignStmt:
95                         if v.Tok != token.DEFINE {
96                                 return
97                         }
98                         for _, exp := range v.Lhs {
99                                 if id, ok := exp.(*ast.Ident); ok {
100                                         check(id, "var", initialisms)
101                                 }
102                         }
103                 case *ast.FuncDecl:
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.
108                         if v.Body == nil {
109                                 return
110                         }
111
112                         if code.IsInTest(pass, v) && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
113                                 return
114                         }
115
116                         thing := "func"
117                         if v.Recv != nil {
118                                 thing = "method"
119                         }
120
121                         if !isTechnicallyExported(v) {
122                                 check(v.Name, thing, initialisms)
123                         }
124
125                         checkList(v.Type.Params, thing+" parameter", initialisms)
126                         checkList(v.Type.Results, thing+" result", initialisms)
127                 case *ast.GenDecl:
128                         if v.Tok == token.IMPORT {
129                                 return
130                         }
131                         var thing string
132                         switch v.Tok {
133                         case token.CONST:
134                                 thing = "const"
135                         case token.TYPE:
136                                 thing = "type"
137                         case token.VAR:
138                                 thing = "var"
139                         }
140                         for _, spec := range v.Specs {
141                                 switch s := spec.(type) {
142                                 case *ast.TypeSpec:
143                                         check(s.Name, thing, initialisms)
144                                 case *ast.ValueSpec:
145                                         for _, id := range s.Names {
146                                                 check(id, thing, initialisms)
147                                         }
148                                 }
149                         }
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
156                                         continue
157                                 }
158                                 checkList(ft.Params, "interface method parameter", initialisms)
159                                 checkList(ft.Results, "interface method result", initialisms)
160                         }
161                 case *ast.RangeStmt:
162                         if v.Tok == token.ASSIGN {
163                                 return
164                         }
165                         if id, ok := v.Key.(*ast.Ident); ok {
166                                 check(id, "range var", initialisms)
167                         }
168                         if id, ok := v.Value.(*ast.Ident); ok {
169                                 check(id, "range var", initialisms)
170                         }
171                 case *ast.StructType:
172                         for _, f := range v.Fields.List {
173                                 for _, id := range f.Names {
174                                         check(id, "struct field", initialisms)
175                                 }
176                         }
177                 }
178         }
179
180         needle := []ast.Node{
181                 (*ast.AssignStmt)(nil),
182                 (*ast.FuncDecl)(nil),
183                 (*ast.GenDecl)(nil),
184                 (*ast.InterfaceType)(nil),
185                 (*ast.RangeStmt)(nil),
186                 (*ast.StructType)(nil),
187         }
188
189         code.Preorder(pass, fn, needle...)
190         return nil, nil
191 }
192
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.
198
199         // Fast path for simple cases: "_" and all lowercase.
200         if name == "_" {
201                 return name
202         }
203         if strings.IndexFunc(name, func(r rune) bool { return !unicode.IsLower(r) }) == -1 {
204                 return name
205         }
206
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) {
214                         eow = true
215                 } else if runes[i+1] == '_' && i+1 != len(runes)-1 {
216                         // underscore; shift the remainder forward over any run of underscores
217                         eow = true
218                         n := 1
219                         for i+n+1 < len(runes) && runes[i+n+1] == '_' {
220                                 n++
221                         }
222
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]) {
225                                 n--
226                         }
227
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]) {
231                         // lower->non-lower
232                         eow = true
233                 }
234                 i++
235                 if !eow {
236                         continue
237                 }
238
239                 // [w,i) is a word.
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)
245                         }
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])
253                 }
254                 w = i
255         }
256         return string(runes)
257 }
258
259 func isTechnicallyExported(f *ast.FuncDecl) bool {
260         if f.Recv != nil || f.Doc == nil {
261                 return false
262         }
263
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 {
268                         return true
269                 }
270
271                 if strings.HasPrefix(c.Text, linkname) {
272                         return true
273                 }
274         }
275         return false
276 }