mirror of
https://github.com/mgechev/revive.git
synced 2024-11-28 08:49:11 +02:00
Add names
This commit is contained in:
parent
0681b5e3d1
commit
e20e8e338a
265
defaultrule/names.go
Normal file
265
defaultrule/names.go
Normal file
@ -0,0 +1,265 @@
|
||||
package defaultrule
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/mgechev/revive/file"
|
||||
"github.com/mgechev/revive/rule"
|
||||
)
|
||||
|
||||
// NamesRule lints given else constructs.
|
||||
type NamesRule struct{}
|
||||
|
||||
// Apply applies the rule to given file.
|
||||
func (r *NamesRule) Apply(file *file.File, arguments rule.Arguments) []rule.Failure {
|
||||
var failures []rule.Failure
|
||||
|
||||
if isTest(file) {
|
||||
return failures
|
||||
}
|
||||
|
||||
fileAst := file.GetAST()
|
||||
walker := lintNames{
|
||||
file: file,
|
||||
fileAst: fileAst,
|
||||
onFailure: func(failure rule.Failure) {
|
||||
failures = append(failures, failure)
|
||||
},
|
||||
}
|
||||
|
||||
ast.Walk(&walker, fileAst)
|
||||
|
||||
return failures
|
||||
}
|
||||
|
||||
// Name returns the rule name.
|
||||
func (r *NamesRule) Name() string {
|
||||
return "imports"
|
||||
}
|
||||
|
||||
type lintNames struct {
|
||||
file *file.File
|
||||
fileAst *ast.File
|
||||
lastGen *ast.GenDecl
|
||||
genDeclMissingComments map[*ast.GenDecl]bool
|
||||
onFailure func(rule.Failure)
|
||||
}
|
||||
|
||||
func (w *lintNames) Visit(n ast.Node) ast.Visitor {
|
||||
|
||||
// Package names need slightly different handling than other names.
|
||||
// if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") {
|
||||
// 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")
|
||||
// }
|
||||
|
||||
switch v := n.(type) {
|
||||
case *ast.AssignStmt:
|
||||
if v.Tok == token.ASSIGN {
|
||||
return w
|
||||
}
|
||||
for _, exp := range v.Lhs {
|
||||
if id, ok := exp.(*ast.Ident); ok {
|
||||
w.check(id, "var")
|
||||
}
|
||||
}
|
||||
case *ast.FuncDecl:
|
||||
if isTest(w.file) && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) {
|
||||
return w
|
||||
}
|
||||
|
||||
thing := "func"
|
||||
if v.Recv != nil {
|
||||
thing = "method"
|
||||
}
|
||||
|
||||
// Exclude naming warnings for functions that are exported to C but
|
||||
// not exported in the Go API.
|
||||
// See https://github.com/golang/lint/issues/144.
|
||||
if ast.IsExported(v.Name.Name) || !isCgoExported(v) {
|
||||
w.check(v.Name, thing)
|
||||
}
|
||||
|
||||
w.checkList(v.Type.Params, thing+" parameter")
|
||||
w.checkList(v.Type.Results, thing+" result")
|
||||
case *ast.GenDecl:
|
||||
if v.Tok == token.IMPORT {
|
||||
return w
|
||||
}
|
||||
var thing string
|
||||
switch v.Tok {
|
||||
case token.CONST:
|
||||
thing = "const"
|
||||
case token.TYPE:
|
||||
thing = "type"
|
||||
case token.VAR:
|
||||
thing = "var"
|
||||
}
|
||||
for _, spec := range v.Specs {
|
||||
switch s := spec.(type) {
|
||||
case *ast.TypeSpec:
|
||||
w.check(s.Name, thing)
|
||||
case *ast.ValueSpec:
|
||||
for _, id := range s.Names {
|
||||
w.check(id, thing)
|
||||
}
|
||||
}
|
||||
}
|
||||
case *ast.InterfaceType:
|
||||
// Do not check interface method names.
|
||||
// They are often constrainted by the method names of concrete types.
|
||||
for _, x := range v.Methods.List {
|
||||
ft, ok := x.Type.(*ast.FuncType)
|
||||
if !ok { // might be an embedded interface name
|
||||
continue
|
||||
}
|
||||
w.checkList(ft.Params, "interface method parameter")
|
||||
w.checkList(ft.Results, "interface method result")
|
||||
}
|
||||
case *ast.RangeStmt:
|
||||
if v.Tok == token.ASSIGN {
|
||||
return w
|
||||
}
|
||||
if id, ok := v.Key.(*ast.Ident); ok {
|
||||
w.check(id, "range var")
|
||||
}
|
||||
if id, ok := v.Value.(*ast.Ident); ok {
|
||||
w.check(id, "range var")
|
||||
}
|
||||
case *ast.StructType:
|
||||
for _, f := range v.Fields.List {
|
||||
for _, id := range f.Names {
|
||||
w.check(id, "struct field")
|
||||
}
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *lintNames) check(id *ast.Ident, thing string) {
|
||||
if id.Name == "_" {
|
||||
return
|
||||
}
|
||||
if knownNameExceptions[id.Name] {
|
||||
return
|
||||
}
|
||||
|
||||
// Handle two common styles from other languages that don't belong in Go.
|
||||
if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") {
|
||||
w.onFailure(rule.Failure{
|
||||
Failure: fmt.Sprintf("don't use ALL_CAPS in Go names; use CamelCase"),
|
||||
Confidence: 0.8,
|
||||
Node: id,
|
||||
})
|
||||
return
|
||||
}
|
||||
if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' {
|
||||
should := string(id.Name[1]+'a'-'A') + id.Name[2:]
|
||||
w.onFailure(rule.Failure{
|
||||
Failure: fmt.Sprintf("don't use leading k in Go names; %s %s should be %s", thing, id.Name, should),
|
||||
Confidence: 0.8,
|
||||
Node: id,
|
||||
})
|
||||
}
|
||||
|
||||
should := lintName(id.Name)
|
||||
if id.Name == should {
|
||||
return
|
||||
}
|
||||
|
||||
if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
|
||||
w.onFailure(rule.Failure{
|
||||
Failure: fmt.Sprintf("don't use underscores in Go names; %s %s should be %s", thing, id.Name, should),
|
||||
Confidence: 0.9,
|
||||
Node: id,
|
||||
})
|
||||
return
|
||||
}
|
||||
w.onFailure(rule.Failure{
|
||||
Failure: fmt.Sprintf("%s %s should be %s", thing, id.Name, should),
|
||||
Confidence: 0.8,
|
||||
Node: id,
|
||||
})
|
||||
}
|
||||
|
||||
func (w *lintNames) checkList(fl *ast.FieldList, thing string) {
|
||||
if fl == nil {
|
||||
return
|
||||
}
|
||||
for _, f := range fl.List {
|
||||
for _, id := range f.Names {
|
||||
w.check(id, thing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lintName returns a different name if it should be different.
|
||||
func lintName(name string) (should string) {
|
||||
// Fast path for simple cases: "_" and all lowercase.
|
||||
if name == "_" {
|
||||
return name
|
||||
}
|
||||
allLower := true
|
||||
for _, r := range name {
|
||||
if !unicode.IsLower(r) {
|
||||
allLower = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allLower {
|
||||
return name
|
||||
}
|
||||
|
||||
// Split camelCase at any lower->upper transition, and split on underscores.
|
||||
// Check each word for common initialisms.
|
||||
runes := []rune(name)
|
||||
w, i := 0, 0 // index of start of word, scan
|
||||
for i+1 <= len(runes) {
|
||||
eow := false // whether we hit the end of a word
|
||||
if i+1 == len(runes) {
|
||||
eow = true
|
||||
} else if runes[i+1] == '_' {
|
||||
// underscore; shift the remainder forward over any run of underscores
|
||||
eow = true
|
||||
n := 1
|
||||
for i+n+1 < len(runes) && runes[i+n+1] == '_' {
|
||||
n++
|
||||
}
|
||||
|
||||
// Leave at most one underscore if the underscore is between two digits
|
||||
if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) {
|
||||
n--
|
||||
}
|
||||
|
||||
copy(runes[i+1:], runes[i+n+1:])
|
||||
runes = runes[:len(runes)-n]
|
||||
} else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) {
|
||||
// lower->non-lower
|
||||
eow = true
|
||||
}
|
||||
i++
|
||||
if !eow {
|
||||
continue
|
||||
}
|
||||
|
||||
// [w,i) is a word.
|
||||
word := string(runes[w:i])
|
||||
if u := strings.ToUpper(word); commonInitialisms[u] {
|
||||
// Keep consistent case, which is lowercase only at the start.
|
||||
if w == 0 && unicode.IsLower(runes[w]) {
|
||||
u = strings.ToLower(u)
|
||||
}
|
||||
// All the common initialisms are ASCII,
|
||||
// so we can replace the bytes exactly.
|
||||
copy(runes[w:], []rune(u))
|
||||
} else if w > 0 && strings.ToLower(word) == word {
|
||||
// already all lowercase, and not the first word, so uppercase the first character.
|
||||
runes[w] = unicode.ToUpper(runes[w])
|
||||
}
|
||||
w = i
|
||||
}
|
||||
return string(runes)
|
||||
}
|
@ -1,7 +1,9 @@
|
||||
package defaultrule
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/mgechev/revive/file"
|
||||
@ -37,3 +39,65 @@ func receiverType(fn *ast.FuncDecl) string {
|
||||
// The parser accepts much more than just the legal forms.
|
||||
return "invalid-type"
|
||||
}
|
||||
|
||||
var knownNameExceptions = map[string]bool{
|
||||
"LastInsertId": true, // must match database/sql
|
||||
"kWh": true,
|
||||
}
|
||||
|
||||
func isCgoExported(f *ast.FuncDecl) bool {
|
||||
if f.Recv != nil || f.Doc == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name)))
|
||||
for _, c := range f.Doc.List {
|
||||
if cgoExport.MatchString(c.Text) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var commonInitialisms = map[string]bool{
|
||||
"ACL": true,
|
||||
"API": true,
|
||||
"ASCII": true,
|
||||
"CPU": true,
|
||||
"CSS": true,
|
||||
"DNS": true,
|
||||
"EOF": true,
|
||||
"GUID": true,
|
||||
"HTML": true,
|
||||
"HTTP": true,
|
||||
"HTTPS": true,
|
||||
"ID": true,
|
||||
"IP": true,
|
||||
"JSON": true,
|
||||
"LHS": true,
|
||||
"QPS": true,
|
||||
"RAM": true,
|
||||
"RHS": true,
|
||||
"RPC": true,
|
||||
"SLA": true,
|
||||
"SMTP": true,
|
||||
"SQL": true,
|
||||
"SSH": true,
|
||||
"TCP": true,
|
||||
"TLS": true,
|
||||
"TTL": true,
|
||||
"UDP": true,
|
||||
"UI": true,
|
||||
"UID": true,
|
||||
"UUID": true,
|
||||
"URI": true,
|
||||
"URL": true,
|
||||
"UTF8": true,
|
||||
"VM": true,
|
||||
"XML": true,
|
||||
"XMPP": true,
|
||||
"XSRF": true,
|
||||
"XSS": true,
|
||||
}
|
||||
|
||||
var allCapsRE = regexp.MustCompile(`^[A-Z0-9_]+$`)
|
||||
|
Loading…
Reference in New Issue
Block a user