1
0
mirror of https://github.com/mgechev/revive.git synced 2024-12-04 10:24:49 +02:00
revive/rule/var_naming.go

274 lines
7.0 KiB
Go
Raw Normal View History

2018-01-22 04:04:41 +02:00
package rule
2017-11-27 05:28:18 +02:00
import (
"fmt"
"go/ast"
"go/token"
"regexp"
2017-11-27 05:28:18 +02:00
"strings"
2022-04-10 09:06:59 +02:00
"sync"
2017-11-27 05:28:18 +02:00
2018-01-25 01:44:03 +02:00
"github.com/mgechev/revive/lint"
2017-11-27 05:28:18 +02:00
)
var anyCapsRE = regexp.MustCompile(`[A-Z]`)
// regexp for constant names like `SOME_CONST`, `SOME_CONST_2`, `X123_3`, `_SOME_PRIVATE_CONST` (#851, #865)
var upperCaseConstRE = regexp.MustCompile(`^_?[A-Z][A-Z\d]*(_[A-Z\d]+)*$`)
2018-05-27 06:28:31 +02:00
// VarNamingRule lints given else constructs.
2021-10-17 20:34:48 +02:00
type VarNamingRule struct {
2024-10-01 12:14:02 +02:00
allowList []string
blockList []string
allowUpperCaseConst bool // if true - allows to use UPPER_SOME_NAMES for constants
skipPackageNameChecks bool
configureOnce sync.Once
2021-10-17 20:34:48 +02:00
}
2017-11-27 05:28:18 +02:00
2022-04-10 09:06:59 +02:00
func (r *VarNamingRule) configure(arguments lint.Arguments) {
if len(arguments) >= 1 {
2024-10-01 12:14:02 +02:00
r.allowList = getList(arguments[0], "allowlist")
}
if len(arguments) >= 2 {
2024-10-01 12:14:02 +02:00
r.blockList = getList(arguments[1], "blocklist")
}
if len(arguments) >= 3 {
// not pretty code because should keep compatibility with TOML (no mixed array types) and new map parameters
thirdArgument := arguments[2]
asSlice, ok := thirdArgument.([]any)
if !ok {
panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, got %T", "options", arguments[2]))
}
if len(asSlice) != 1 {
panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, of len==1, but %d", "options", len(asSlice)))
}
args, ok := asSlice[0].(map[string]any)
if !ok {
panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, of len==1, with map, but %T", "options", asSlice[0]))
}
2024-10-01 12:14:02 +02:00
r.allowUpperCaseConst = fmt.Sprint(args["upperCaseConst"]) == "true"
r.skipPackageNameChecks = fmt.Sprint(args["skipPackageNameChecks"]) == "true"
}
2022-04-10 09:06:59 +02:00
}
func (r *VarNamingRule) applyPackageCheckRules(walker *lintNames) {
// Package names need slightly different handling than other names.
if strings.Contains(walker.fileAst.Name.Name, "_") && !strings.HasSuffix(walker.fileAst.Name.Name, "_test") {
walker.onFailure(lint.Failure{
Failure: "don't use an underscore in package name",
Confidence: 1,
Node: walker.fileAst.Name,
Category: "naming",
})
}
if anyCapsRE.MatchString(walker.fileAst.Name.Name) {
walker.onFailure(lint.Failure{
Failure: fmt.Sprintf("don't use MixedCaps in package name; %s should be %s", walker.fileAst.Name.Name, strings.ToLower(walker.fileAst.Name.Name)),
Confidence: 1,
Node: walker.fileAst.Name,
Category: "naming",
})
}
}
2022-04-10 09:06:59 +02:00
// Apply applies the rule to given file.
func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
r.configureOnce.Do(func() { r.configure(arguments) })
2022-04-10 09:06:59 +02:00
var failures []lint.Failure
2018-01-22 04:48:51 +02:00
fileAst := file.AST
2022-04-10 09:06:59 +02:00
2017-11-27 05:28:18 +02:00
walker := lintNames{
file: file,
fileAst: fileAst,
2024-10-01 12:14:02 +02:00
allowList: r.allowList,
blockList: r.blockList,
2018-01-25 01:44:03 +02:00
onFailure: func(failure lint.Failure) {
2017-11-27 05:28:18 +02:00
failures = append(failures, failure)
},
2024-10-01 12:14:02 +02:00
upperCaseConst: r.allowUpperCaseConst,
2017-11-27 05:28:18 +02:00
}
if !r.skipPackageNameChecks {
r.applyPackageCheckRules(&walker)
}
2018-01-25 01:17:19 +02:00
2017-11-27 05:28:18 +02:00
ast.Walk(&walker, fileAst)
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*VarNamingRule) Name() string {
2018-05-27 06:28:31 +02:00
return "var-naming"
2017-11-27 05:28:18 +02:00
}
func (w *lintNames) checkList(fl *ast.FieldList, thing string) {
2018-01-25 01:17:19 +02:00
if fl == nil {
return
}
for _, f := range fl.List {
for _, id := range f.Names {
w.check(id, thing)
2018-01-25 01:17:19 +02:00
}
}
}
func (w *lintNames) check(id *ast.Ident, thing string) {
2018-01-25 01:17:19 +02:00
if id.Name == "_" {
return
}
if knownNameExceptions[id.Name] {
return
}
// #851 upperCaseConst support
// if it's const
if thing == token.CONST.String() && w.upperCaseConst && upperCaseConstRE.MatchString(id.Name) {
return
}
2018-01-25 01:17:19 +02:00
// 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, "_") {
2018-01-25 01:44:03 +02:00
w.onFailure(lint.Failure{
2018-01-25 01:17:19 +02:00
Failure: "don't use ALL_CAPS in Go names; use CamelCase",
Confidence: 0.8,
Node: id,
Category: "naming",
})
return
}
2024-10-01 12:14:02 +02:00
should := lint.Name(id.Name, w.allowList, w.blockList)
2018-01-25 01:17:19 +02:00
if id.Name == should {
return
}
if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") {
2018-01-25 01:44:03 +02:00
w.onFailure(lint.Failure{
2018-01-25 01:17:19 +02:00
Failure: fmt.Sprintf("don't use underscores in Go names; %s %s should be %s", thing, id.Name, should),
Confidence: 0.9,
Node: id,
Category: "naming",
})
return
}
2018-01-25 01:44:03 +02:00
w.onFailure(lint.Failure{
2018-01-25 01:17:19 +02:00
Failure: fmt.Sprintf("%s %s should be %s", thing, id.Name, should),
Confidence: 0.8,
Node: id,
Category: "naming",
})
}
2017-11-27 05:28:18 +02:00
type lintNames struct {
file *lint.File
fileAst *ast.File
onFailure func(lint.Failure)
2024-10-01 12:14:02 +02:00
allowList []string
blockList []string
upperCaseConst bool
2017-11-27 05:28:18 +02:00
}
func (w *lintNames) Visit(n ast.Node) ast.Visitor {
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")
2017-11-27 05:28:18 +02:00
}
}
case *ast.FuncDecl:
funcName := v.Name.Name
if w.file.IsTest() &&
(strings.HasPrefix(funcName, "Example") ||
strings.HasPrefix(funcName, "Test") ||
strings.HasPrefix(funcName, "Benchmark") ||
strings.HasPrefix(funcName, "Fuzz")) {
2017-11-27 05:28:18 +02:00
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)
2017-11-27 05:28:18 +02:00
}
w.checkList(v.Type.Params, thing+" parameter")
w.checkList(v.Type.Results, thing+" result")
2017-11-27 05:28:18 +02:00
case *ast.GenDecl:
if v.Tok == token.IMPORT {
return w
}
thing := v.Tok.String()
2017-11-27 05:28:18 +02:00
for _, spec := range v.Specs {
switch s := spec.(type) {
case *ast.TypeSpec:
w.check(s.Name, thing)
2017-11-27 05:28:18 +02:00
case *ast.ValueSpec:
for _, id := range s.Names {
w.check(id, thing)
2017-11-27 05:28:18 +02:00
}
}
}
case *ast.InterfaceType:
// Do not check interface method names.
// They are often constrained by the method names of concrete types.
2017-11-27 05:28:18 +02:00
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")
2017-11-27 05:28:18 +02:00
}
case *ast.RangeStmt:
if v.Tok == token.ASSIGN {
return w
}
if id, ok := v.Key.(*ast.Ident); ok {
w.check(id, "range var")
2017-11-27 05:28:18 +02:00
}
if id, ok := v.Value.(*ast.Ident); ok {
w.check(id, "range var")
2017-11-27 05:28:18 +02:00
}
case *ast.StructType:
for _, f := range v.Fields.List {
for _, id := range f.Names {
w.check(id, "struct field")
2017-11-27 05:28:18 +02:00
}
}
}
return w
}
func getList(arg any, argName string) []string {
args, ok := arg.([]any)
if !ok {
panic(fmt.Sprintf("Invalid argument to the var-naming rule. Expecting a %s of type slice with initialisms, got %T", argName, arg))
}
var list []string
for _, v := range args {
val, ok := v.(string)
if !ok {
panic(fmt.Sprintf("Invalid %s values of the var-naming rule. Expecting slice of strings but got element of type %T", val, arg))
}
list = append(list, val)
}
return list
}