-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
334 lines (290 loc) · 7.78 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"errors"
"flag"
"fmt"
"go/ast"
"go/build"
"go/token"
"go/types"
"log"
"os"
"regexp"
"strings"
"github.com/go-toolsmith/astinfo"
"github.com/go-toolsmith/pkgload"
"github.com/kisielk/gotool"
"golang.org/x/tools/go/packages"
)
var generatedFileCommentRE = regexp.MustCompile("Code generated .* DO NOT EDIT.")
func main() {
log.SetFlags(0)
var ctxt context
steps := []struct {
name string
fn func() error
}{
{"parse flags", ctxt.parseFlags},
{"resolve targets", ctxt.resolveTargets},
{"init checkers", ctxt.initCheckers},
{"collect candidates", ctxt.collectAllCandidates},
{"assign suggestions", ctxt.assignSuggestions},
{"print warnings", ctxt.printWarnings},
}
for _, step := range steps {
if err := step.fn(); err != nil {
log.Fatalf("%s: %v", step.name, err)
}
}
}
type context struct {
// flags is an (effectively) immutable struct that holds all command-line
// arguments as they were passed to the program.
//
// For per-argument documentation see context.parseFlags.
flags struct {
pedantic bool
verbose bool
shorterErrLocation bool
noTypes bool
targets []string
exclude string
}
workDir string
paths []string
locs *locationMap
fset *token.FileSet
info *types.Info
astinfo astinfo.Info
checkers []checker
candidates []candidate
}
func (ctxt *context) parseFlags() error {
flag.BoolVar(&ctxt.flags.pedantic, "pedantic", false,
`makes several diagnostics more pedantic and comprehensive`)
flag.BoolVar(&ctxt.flags.verbose, "v", false,
`turn on detailed program execution info printing`)
flag.BoolVar(&ctxt.flags.shorterErrLocation, `shorterErrLocation`, true,
`whether to replace error location prefix with $GOROOT and $GOPATH`)
flag.BoolVar(&ctxt.flags.noTypes, "syntax-only", false,
`disable the typechecking; some checkers can't work without types information`)
flag.StringVar(&ctxt.flags.exclude, "exclude", `^unsafe$|^builtin$`,
`import path excluding regexp`)
flag.Parse()
ctxt.flags.targets = flag.Args()
if len(ctxt.flags.targets) == 0 {
return errors.New("not enough positional args (empty targets list)")
}
if ctxt.flags.shorterErrLocation {
wd, err := os.Getwd()
if err != nil {
log.Printf("getwd: %v", err)
}
ctxt.workDir = wd
}
return nil
}
func (ctxt *context) resolveTargets() error {
ctxt.paths = gotool.ImportPaths(ctxt.flags.targets)
if len(ctxt.paths) == 0 {
return errors.New("targets resolved to an empty import paths list")
}
// Filter-out packages using the exclude pattern.
excludeRE, err := regexp.Compile(ctxt.flags.exclude)
if err != nil {
return fmt.Errorf("compiling -exclude regexp: %w", err)
}
paths := ctxt.paths[:0]
for _, path := range ctxt.paths {
if !excludeRE.MatchString(path) {
paths = append(paths, path)
}
}
ctxt.paths = paths
if len(paths) == 0 {
ctxt.infoPrintf("import paths list is empty after filtering")
}
return nil
}
func (ctxt *context) initCheckers() error {
checkers := []checker{
newUnitImportChecker(ctxt),
newZeroValPtrAllocChecker(ctxt),
newEmptySliceChecker(ctxt),
newEmptyMapChecker(ctxt),
newHexLitChecker(ctxt),
newRangeCheckChecker(ctxt),
newAndNotChecker(ctxt),
newFloatLitChecker(ctxt),
newLabelCaseChecker(ctxt),
newUntypedConstCoerceChecker(ctxt),
newArgListParensChecker(ctxt),
newNonZeroLenTestChecker(ctxt),
newDefaultCaseOrderChecker(ctxt),
}
hasTypes := !ctxt.flags.noTypes
variantID := 0
enabledCheckers := checkers[:0]
for _, c := range checkers {
op := c.Operation()
if op.name == "" {
panic(fmt.Sprintf("%T: empty operation name", c))
}
if !hasTypes && op.needTypes {
ctxt.infoPrintf("checker %q is disabled (types information is required)", op.name)
continue
}
for i, v := range op.variants {
if v.warning == "" {
panic(fmt.Sprintf("%T: empty warning for variant#%d", c, i))
}
v.op = op
v.id = variantID
variantID++
}
enabledCheckers = append(enabledCheckers, c)
}
ctxt.locs = newLocationMap()
ctxt.checkers = enabledCheckers
return nil
}
func (ctxt *context) collectAllCandidates() error {
for _, path := range ctxt.paths {
ctxt.infoPrintf("check %q", path)
if err := ctxt.collectPathCandidates(path); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
}
return nil
}
func (ctxt *context) collectPackageCandidates(pkg *packages.Package) {
ctxt.info = pkg.TypesInfo
for _, f := range pkg.Syntax {
isGenerated := len(f.Comments) != 0 &&
generatedFileCommentRE.MatchString(f.Comments[0].Text())
if isGenerated {
continue
}
ctxt.collectFileCandidates(f)
}
}
func (ctxt *context) collectPathCandidates(path string) error {
ctxt.fset = token.NewFileSet()
loaderFlags := packages.NeedSyntax | packages.NeedName | packages.NeedFiles
if !ctxt.flags.noTypes {
loaderFlags |= packages.NeedTypes
loaderFlags |= packages.NeedTypesInfo
}
conf := &packages.Config{
Mode: loaderFlags,
Fset: ctxt.fset,
Tests: true,
}
// TODO(Quasilyte): current approach is memory-efficient
// and does scale well with huge amounts of targets to check,
// but it's not very fast. Might want to optimize it a little bit.
pkgs, err := packages.Load(conf, path)
if err != nil {
return err
}
if len(pkgs) == 0 {
ctxt.infoPrintf("got 0 packages for %q path", path)
return nil
}
if n := packages.PrintErrors(pkgs); n > 0 {
return fmt.Errorf("%d build errors", n)
}
pkgload.VisitUnits(pkgs, func(u *pkgload.Unit) {
if u.ExternalTest != nil {
ctxt.collectPackageCandidates(u.ExternalTest)
}
if u.Test != nil {
// Prefer tests to the base package, if present.
ctxt.collectPackageCandidates(u.Test)
} else {
ctxt.collectPackageCandidates(u.Base)
}
})
return nil
}
func (ctxt *context) collectFileCandidates(f *ast.File) {
ctxt.astinfo = astinfo.Info{
Parents: make(map[ast.Node]ast.Node),
}
ctxt.astinfo.Origin = f
ctxt.astinfo.Resolve()
for _, c := range ctxt.checkers {
for _, decl := range f.Decls {
ast.Inspect(decl, c.Visit)
}
}
}
func (ctxt *context) assignSuggestions() error {
for _, c := range ctxt.checkers {
op := c.Operation()
op.suggested = op.variants[0]
for _, v := range op.variants[1:] {
if v.count > op.suggested.count {
op.suggested = v
}
}
}
return nil
}
func (ctxt *context) printWarnings() error {
exitCode := 0
visitWarnings(ctxt, func(pos token.Position, v *opVariant) {
exitCode = 1
loc := pos.String()
if ctxt.flags.shorterErrLocation {
loc = ctxt.shortenLocation(loc)
}
fmt.Printf("%s: %s: %s\n", loc, v.op.name, v.op.suggested.warning)
})
os.Exit(exitCode)
return nil
}
func visitWarnings(ctxt *context, visit func(pos token.Position, v *opVariant)) {
// Build variant map which is accessed by variantID.
vcount := 0
for _, c := range ctxt.checkers {
vcount += len(c.Operation().variants)
}
variants := make([]*opVariant, vcount)
for _, c := range ctxt.checkers {
for _, v := range c.Operation().variants {
variants[v.id] = v
}
}
for _, c := range ctxt.candidates {
v := variants[c.variantID]
if v.op.suggested == v {
continue // OK, everything is consistent
}
pos := ctxt.locs.Get(c.locationID)
visit(pos, v)
}
}
func (ctxt *context) shortenLocation(loc string) string {
// If possible, construct relative path.
relLoc := loc
if ctxt.workDir != "" {
relLoc = strings.Replace(loc, ctxt.workDir, ".", 1)
}
switch {
case strings.HasPrefix(loc, build.Default.GOPATH):
loc = strings.Replace(loc, build.Default.GOPATH, "$GOPATH", 1)
case strings.HasPrefix(loc, build.Default.GOROOT):
loc = strings.Replace(loc, build.Default.GOROOT, "$GOROOT", 1)
}
// Return the representation that is shorter.
if len(relLoc) < len(loc) {
return relLoc
}
return loc
}
func (ctxt *context) infoPrintf(format string, args ...interface{}) {
if ctxt.flags.verbose {
log.Printf("\tinfo: "+format, args...)
}
}