aboutsummaryrefslogtreecommitdiff
path: root/go/tools/builders/nogo_main.go
blob: 631cf0e5daee63bfeb7cf1fd1d27d3e6522bc362 (plain)
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/* Copyright 2018 The Bazel Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Loads and runs registered analyses on a well-typed Go package.
// The code in this file is combined with the code generated by
// generate_nogo_main.go.

package main

import (
	"bytes"
	"encoding/gob"
	"errors"
	"flag"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"go/types"
	"io/ioutil"
	"log"
	"os"
	"reflect"
	"regexp"
	"sort"
	"strings"
	"sync"

	"golang.org/x/tools/go/analysis"
	"golang.org/x/tools/go/analysis/internal/facts"
	"golang.org/x/tools/go/gcexportdata"
)

func init() {
	if err := analysis.Validate(analyzers); err != nil {
		log.Fatal(err)
	}
}

var typesSizes = types.SizesFor("gc", os.Getenv("GOARCH"))

func main() {
	log.SetFlags(0) // no timestamp
	log.SetPrefix("nogo: ")
	if err := run(os.Args[1:]); err != nil {
		log.Fatal(err)
	}
}

// run returns an error if there is a problem loading the package or if any
// analysis fails.
func run(args []string) error {
	args, err := expandParamsFiles(args)
	if err != nil {
		return fmt.Errorf("error reading paramfiles: %v", err)
	}

	factMap := factMultiFlag{}
	flags := flag.NewFlagSet("nogo", flag.ExitOnError)
	flags.Var(&factMap, "fact", "Import path and file containing facts for that library, separated by '=' (may be repeated)'")
	importcfg := flags.String("importcfg", "", "The import configuration file")
	packagePath := flags.String("p", "", "The package path (importmap) of the package being compiled")
	xPath := flags.String("x", "", "The archive file where serialized facts should be written")
	flags.Parse(args)
	srcs := flags.Args()

	packageFile, importMap, err := readImportCfg(*importcfg)
	if err != nil {
		return fmt.Errorf("error parsing importcfg: %v", err)
	}

	diagnostics, facts, err := checkPackage(analyzers, *packagePath, packageFile, importMap, factMap, srcs)
	if err != nil {
		return fmt.Errorf("error running analyzers: %v", err)
	}
	if diagnostics != "" {
		return fmt.Errorf("errors found by nogo during build-time code analysis:\n%s\n", diagnostics)
	}
	if *xPath != "" {
		if err := ioutil.WriteFile(abs(*xPath), facts, 0666); err != nil {
			return fmt.Errorf("error writing facts: %v", err)
		}
	}

	return nil
}

// Adapted from go/src/cmd/compile/internal/gc/main.go. Keep in sync.
func readImportCfg(file string) (packageFile map[string]string, importMap map[string]string, err error) {
	packageFile, importMap = make(map[string]string), make(map[string]string)
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, nil, fmt.Errorf("-importcfg: %v", err)
	}

	for lineNum, line := range strings.Split(string(data), "\n") {
		lineNum++ // 1-based
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		var verb, args string
		if i := strings.Index(line, " "); i < 0 {
			verb = line
		} else {
			verb, args = line[:i], strings.TrimSpace(line[i+1:])
		}
		var before, after string
		if i := strings.Index(args, "="); i >= 0 {
			before, after = args[:i], args[i+1:]
		}
		switch verb {
		default:
			return nil, nil, fmt.Errorf("%s:%d: unknown directive %q", file, lineNum, verb)
		case "importmap":
			if before == "" || after == "" {
				return nil, nil, fmt.Errorf(`%s:%d: invalid importmap: syntax is "importmap old=new"`, file, lineNum)
			}
			importMap[before] = after
		case "packagefile":
			if before == "" || after == "" {
				return nil, nil, fmt.Errorf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
			}
			packageFile[before] = after
		}
	}
	return packageFile, importMap, nil
}

// checkPackage runs all the given analyzers on the specified package and
// returns the source code diagnostics that the must be printed in the build log.
// It returns an empty string if no source code diagnostics need to be printed.
//
// This implementation was adapted from that of golang.org/x/tools/go/checker/internal/checker.
func checkPackage(analyzers []*analysis.Analyzer, packagePath string, packageFile, importMap map[string]string, factMap map[string]string, filenames []string) (string, []byte, error) {
	// Register fact types and establish dependencies between analyzers.
	actions := make(map[*analysis.Analyzer]*action)
	var visit func(a *analysis.Analyzer) *action
	visit = func(a *analysis.Analyzer) *action {
		act, ok := actions[a]
		if !ok {
			act = &action{a: a}
			actions[a] = act
			for _, f := range a.FactTypes {
				act.usesFacts = true
				gob.Register(f)
			}
			act.deps = make([]*action, len(a.Requires))
			for i, req := range a.Requires {
				dep := visit(req)
				if dep.usesFacts {
					act.usesFacts = true
				}
				act.deps[i] = dep
			}
		}
		return act
	}

	roots := make([]*action, 0, len(analyzers))
	for _, a := range analyzers {
		roots = append(roots, visit(a))
	}

	// Load the package, including AST, types, and facts.
	imp := newImporter(importMap, packageFile, factMap)
	pkg, err := load(packagePath, imp, filenames)
	if err != nil {
		return "", nil, fmt.Errorf("error loading package: %v", err)
	}
	for _, act := range actions {
		act.pkg = pkg
	}

	// Execute the analyzers.
	execAll(roots)

	// Process diagnostics and encode facts for importers of this package.
	diagnostics := checkAnalysisResults(roots, pkg)
	facts := pkg.facts.Encode()
	return diagnostics, facts, nil
}

// An action represents one unit of analysis work: the application of
// one analysis to one package. Actions form a DAG within a
// package (as different analyzers are applied, either in sequence or
// parallel).
type action struct {
	once        sync.Once
	a           *analysis.Analyzer
	pass        *analysis.Pass
	pkg         *goPackage
	deps        []*action
	inputs      map[*analysis.Analyzer]interface{}
	result      interface{}
	diagnostics []analysis.Diagnostic
	usesFacts   bool
	err         error
}

func (act *action) String() string {
	return fmt.Sprintf("%s@%s", act.a, act.pkg)
}

func execAll(actions []*action) {
	var wg sync.WaitGroup
	wg.Add(len(actions))
	for _, act := range actions {
		go func(act *action) {
			defer wg.Done()
			act.exec()
		}(act)
	}
	wg.Wait()
}

func (act *action) exec() { act.once.Do(act.execOnce) }

func (act *action) execOnce() {
	// Analyze dependencies.
	execAll(act.deps)

	// Report an error if any dependency failed.
	var failed []string
	for _, dep := range act.deps {
		if dep.err != nil {
			failed = append(failed, dep.String())
		}
	}
	if failed != nil {
		sort.Strings(failed)
		act.err = fmt.Errorf("failed prerequisites: %s", strings.Join(failed, ", "))
		return
	}

	// Plumb the output values of the dependencies
	// into the inputs of this action.
	inputs := make(map[*analysis.Analyzer]interface{})
	for _, dep := range act.deps {
		// Same package, different analysis (horizontal edge):
		// in-memory outputs of prerequisite analyzers
		// become inputs to this analysis pass.
		inputs[dep.a] = dep.result
	}

	// Run the analysis.
	factFilter := make(map[reflect.Type]bool)
	for _, f := range act.a.FactTypes {
		factFilter[reflect.TypeOf(f)] = true
	}
	pass := &analysis.Pass{
		Analyzer:          act.a,
		Fset:              act.pkg.fset,
		Files:             act.pkg.syntax,
		Pkg:               act.pkg.types,
		TypesInfo:         act.pkg.typesInfo,
		ResultOf:          inputs,
		Report:            func(d analysis.Diagnostic) { act.diagnostics = append(act.diagnostics, d) },
		ImportPackageFact: act.pkg.facts.ImportPackageFact,
		ExportPackageFact: act.pkg.facts.ExportPackageFact,
		ImportObjectFact:  act.pkg.facts.ImportObjectFact,
		ExportObjectFact:  act.pkg.facts.ExportObjectFact,
		AllPackageFacts:   func() []analysis.PackageFact { return act.pkg.facts.AllPackageFacts(factFilter) },
		AllObjectFacts:    func() []analysis.ObjectFact { return act.pkg.facts.AllObjectFacts(factFilter) },
		TypesSizes:        typesSizes,
	}
	act.pass = pass

	var err error
	if act.pkg.illTyped && !pass.Analyzer.RunDespiteErrors {
		err = fmt.Errorf("analysis skipped due to type-checking error: %v", act.pkg.typeCheckError)
	} else {
		act.result, err = pass.Analyzer.Run(pass)
		if err == nil {
			if got, want := reflect.TypeOf(act.result), pass.Analyzer.ResultType; got != want {
				err = fmt.Errorf(
					"internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v",
					pass.Pkg.Path(), pass.Analyzer, got, want)
			}
		}
	}
	act.err = err
}

// load parses and type checks the source code in each file in filenames.
// load also deserializes facts stored for imported packages.
func load(packagePath string, imp *importer, filenames []string) (*goPackage, error) {
	if len(filenames) == 0 {
		return nil, errors.New("no filenames")
	}
	var syntax []*ast.File
	for _, file := range filenames {
		s, err := parser.ParseFile(imp.fset, file, nil, parser.ParseComments)
		if err != nil {
			return nil, err
		}
		syntax = append(syntax, s)
	}
	pkg := &goPackage{fset: imp.fset, syntax: syntax}

	config := types.Config{Importer: imp}
	info := &types.Info{
		Types:      make(map[ast.Expr]types.TypeAndValue),
		Uses:       make(map[*ast.Ident]types.Object),
		Defs:       make(map[*ast.Ident]types.Object),
		Implicits:  make(map[ast.Node]types.Object),
		Scopes:     make(map[ast.Node]*types.Scope),
		Selections: make(map[*ast.SelectorExpr]*types.Selection),
	}
	types, err := config.Check(packagePath, pkg.fset, syntax, info)
	if err != nil {
		pkg.illTyped, pkg.typeCheckError = true, err
	}
	pkg.types, pkg.typesInfo = types, info

	pkg.facts, err = facts.Decode(pkg.types, imp.readFacts)
	if err != nil {
		return nil, fmt.Errorf("internal error decoding facts: %v", err)
	}

	return pkg, nil
}

// A goPackage describes a loaded Go package.
type goPackage struct {
	// fset provides position information for types, typesInfo, and syntax.
	// It is set only when types is set.
	fset *token.FileSet
	// syntax is the package's syntax trees.
	syntax []*ast.File
	// types provides type information for the package.
	types *types.Package
	// facts contains information saved by the analysis framework. Passes may
	// import facts for imported packages and may also export facts for this
	// package to be consumed by analyses in downstream packages.
	facts *facts.Set
	// illTyped indicates whether the package or any dependency contains errors.
	// It is set only when types is set.
	illTyped bool
	// typeCheckError contains any error encountered during type-checking. It is
	// only set when illTyped is true.
	typeCheckError error
	// typesInfo provides type information about the package's syntax trees.
	// It is set only when syntax is set.
	typesInfo *types.Info
}

func (g *goPackage) String() string {
	return g.types.Path()
}

// checkAnalysisResults checks the analysis diagnostics in the given actions
// and returns a string containing all the diagnostics that should be printed
// to the build log.
func checkAnalysisResults(actions []*action, pkg *goPackage) string {
	type entry struct {
		analysis.Diagnostic
		*analysis.Analyzer
	}
	var diagnostics []entry
	var errs []error
	for _, act := range actions {
		if act.err != nil {
			// Analyzer failed.
			errs = append(errs, fmt.Errorf("analyzer %q failed: %v", act.a.Name, act.err))
			continue
		}
		if len(act.diagnostics) == 0 {
			continue
		}
		config, ok := configs[act.a.Name]
		if !ok {
			// If the analyzer is not explicitly configured, it emits diagnostics for
			// all files.
			for _, diag := range act.diagnostics {
				diagnostics = append(diagnostics, entry{Diagnostic: diag, Analyzer: act.a})
			}
			continue
		}
		// Discard diagnostics based on the analyzer configuration.
		for _, d := range act.diagnostics {
			// NOTE(golang.org/issue/31008): nilness does not set positions,
			// so don't assume the position is valid.
			p := pkg.fset.Position(d.Pos)
			filename := "-"
			if p.IsValid() {
				filename = p.Filename
			}
			include := true
			if len(config.onlyFiles) > 0 {
				// This analyzer emits diagnostics for only a set of files.
				include = false
				for _, pattern := range config.onlyFiles {
					if pattern.MatchString(filename) {
						include = true
						break
					}
				}
			}
			if include {
				for _, pattern := range config.excludeFiles {
					if pattern.MatchString(filename) {
						include = false
						break
					}
				}
			}
			if include {
				diagnostics = append(diagnostics, entry{Diagnostic: d, Analyzer: act.a})
			}
		}
	}
	if len(diagnostics) == 0 && len(errs) == 0 {
		return ""
	}

	sort.Slice(diagnostics, func(i, j int) bool {
		return diagnostics[i].Pos < diagnostics[j].Pos
	})
	errMsg := &bytes.Buffer{}
	sep := ""
	for _, err := range errs {
		errMsg.WriteString(sep)
		sep = "\n"
		errMsg.WriteString(err.Error())
	}
	for _, d := range diagnostics {
		errMsg.WriteString(sep)
		sep = "\n"
		fmt.Fprintf(errMsg, "%s: %s (%s)", pkg.fset.Position(d.Pos), d.Message, d.Name)
	}
	return errMsg.String()
}

// config determines which source files an analyzer will emit diagnostics for.
// config values are generated in another file that is compiled with
// nogo_main.go by the nogo rule.
type config struct {
	// onlyFiles is a list of regular expressions that match files an analyzer
	// will emit diagnostics for. When empty, the analyzer will emit diagnostics
	// for all files.
	onlyFiles []*regexp.Regexp

	// excludeFiles is a list of regular expressions that match files that an
	// analyzer will not emit diagnostics for.
	excludeFiles []*regexp.Regexp
}

// importer is an implementation of go/types.Importer that imports type
// information from the export data in compiled .a files.
type importer struct {
	fset         *token.FileSet
	importMap    map[string]string         // map import path in source code to package path
	packageCache map[string]*types.Package // cache of previously imported packages
	packageFile  map[string]string         // map package path to .a file with export data
	factMap      map[string]string         // map import path in source code to file containing serialized facts
}

func newImporter(importMap, packageFile map[string]string, factMap map[string]string) *importer {
	return &importer{
		fset:         token.NewFileSet(),
		importMap:    importMap,
		packageCache: make(map[string]*types.Package),
		packageFile:  packageFile,
		factMap:      factMap,
	}
}

func (i *importer) Import(path string) (*types.Package, error) {
	if imp, ok := i.importMap[path]; ok {
		// Translate import path if necessary.
		path = imp
	}
	if path == "unsafe" {
		// Special case: go/types has pre-defined type information for unsafe.
		// See https://github.com/golang/go/issues/13882.
		return types.Unsafe, nil
	}
	if pkg, ok := i.packageCache[path]; ok && pkg.Complete() {
		return pkg, nil // cache hit
	}

	archive, ok := i.packageFile[path]
	if !ok {
		return nil, fmt.Errorf("could not import %q", path)
	}
	// open file
	f, err := os.Open(archive)
	if err != nil {
		return nil, err
	}
	defer func() {
		f.Close()
		if err != nil {
			// add file name to error
			err = fmt.Errorf("reading export data: %s: %v", archive, err)
		}
	}()

	r, err := gcexportdata.NewReader(f)
	if err != nil {
		return nil, err
	}

	return gcexportdata.Read(r, i.fset, i.packageCache, path)
}

func (i *importer) readFacts(path string) ([]byte, error) {
	archive := i.factMap[path]
	if archive == "" {
		// Packages that were not built with the nogo toolchain will not be
		// analyzed, so there's no opportunity to store facts. This includes
		// packages in the standard library and packages built with go_tool_library,
		// such as coverdata. Analyzers are expected to hard code information
		// about standard library definitions and must gracefully handle packages
		// that don't have facts. For example, the "printf" analyzer must know
		// fmt.Printf accepts a format string.
		return nil, nil
	}
	factReader, err := readFileInArchive(nogoFact, archive)
	if os.IsNotExist(err) {
		// Packages that were not built with the nogo toolchain will not be
		// analyzed, so there's no opportunity to store facts. This includes
		// packages in the standard library and packages built with go_tool_library,
		// such as coverdata.
		return nil, nil
	} else if err != nil {
		return nil, err
	}
	defer factReader.Close()
	return ioutil.ReadAll(factReader)
}

type factMultiFlag map[string]string

func (m *factMultiFlag) String() string {
	if m == nil || len(*m) == 0 {
		return ""
	}
	return fmt.Sprintf("%v", *m)
}

func (m *factMultiFlag) Set(v string) error {
	parts := strings.Split(v, "=")
	if len(parts) != 2 {
		return fmt.Errorf("badly formatted -fact flag: %s", v)
	}
	(*m)[parts[0]] = parts[1]
	return nil
}