-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasciicheck.go
102 lines (93 loc) · 2.21 KB
/
asciicheck.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package asciicheck
import (
"fmt"
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
func NewAnalyzer() *analysis.Analyzer {
return &analysis.Analyzer{
Name: "asciicheck",
Doc: "checks that all code identifiers does not have non-ASCII symbols in the name",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
}
func run(pass *analysis.Pass) (any, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.File)(nil),
(*ast.ImportSpec)(nil),
(*ast.TypeSpec)(nil),
(*ast.ValueSpec)(nil),
(*ast.FuncDecl)(nil),
(*ast.StructType)(nil),
(*ast.FuncType)(nil),
(*ast.InterfaceType)(nil),
(*ast.LabeledStmt)(nil),
(*ast.AssignStmt)(nil),
}
inspect.Preorder(nodeFilter, func(n ast.Node) {
switch n := n.(type) {
case *ast.File:
checkIdent(pass, n.Name)
case *ast.ImportSpec:
checkIdent(pass, n.Name)
case *ast.TypeSpec:
checkIdent(pass, n.Name)
checkFieldList(pass, n.TypeParams)
case *ast.ValueSpec:
for _, name := range n.Names {
checkIdent(pass, name)
}
case *ast.FuncDecl:
checkIdent(pass, n.Name)
checkFieldList(pass, n.Recv)
case *ast.StructType:
checkFieldList(pass, n.Fields)
case *ast.FuncType:
checkFieldList(pass, n.TypeParams)
checkFieldList(pass, n.Params)
checkFieldList(pass, n.Results)
case *ast.InterfaceType:
checkFieldList(pass, n.Methods)
case *ast.LabeledStmt:
checkIdent(pass, n.Label)
case *ast.AssignStmt:
if n.Tok == token.DEFINE {
for _, expr := range n.Lhs {
if ident, ok := expr.(*ast.Ident); ok {
checkIdent(pass, ident)
}
}
}
}
})
return nil, nil
}
func checkIdent(pass *analysis.Pass, v *ast.Ident) {
if v == nil {
return
}
ch, ascii := isASCII(v.Name)
if !ascii {
pass.Report(
analysis.Diagnostic{
Pos: v.Pos(),
Message: fmt.Sprintf("identifier \"%s\" contain non-ASCII character: %#U", v.Name, ch),
},
)
}
}
func checkFieldList(pass *analysis.Pass, f *ast.FieldList) {
if f == nil {
return
}
for _, f := range f.List {
for _, name := range f.Names {
checkIdent(pass, name)
}
}
}