1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package buildir defines an Analyzer that constructs the IR
6 // of an error-free package and returns the set of all
7 // functions within it. It does not report any diagnostics itself but
8 // may be used as an input to other analyzers.
10 // THIS INTERFACE IS EXPERIMENTAL AND MAY BE SUBJECT TO INCOMPATIBLE CHANGE.
18 "golang.org/x/tools/go/analysis"
19 "honnef.co/go/tools/ir"
22 type willExit struct{}
23 type willUnwind struct{}
25 func (*willExit) AFact() {}
26 func (*willUnwind) AFact() {}
28 var Analyzer = &analysis.Analyzer{
30 Doc: "build IR for later passes",
32 ResultType: reflect.TypeOf(new(IR)),
33 FactTypes: []analysis.Fact{new(willExit), new(willUnwind)},
36 // IR provides intermediate representation for all the
37 // non-blank source functions in the current package.
40 SrcFuncs []*ir.Function
43 func run(pass *analysis.Pass) (interface{}, error) {
44 // Plundered from ssautil.BuildPackage.
46 // We must create a new Program for each Package because the
47 // analysis API provides no place to hang a Program shared by
48 // all Packages. Consequently, IR Packages and Functions do not
49 // have a canonical representation across an analysis session of
50 // multiple packages. This is unlikely to be a problem in
51 // practice because the analysis API essentially forces all
52 // packages to be analysed independently, so any given call to
53 // Analysis.Run on a package will see only IR objects belonging
54 // to a single Program.
56 mode := ir.GlobalDebug
58 prog := ir.NewProgram(pass.Fset, mode)
60 // Create IR packages for all imports.
61 // Order is not significant.
62 created := make(map[*types.Package]bool)
63 var createAll func(pkgs []*types.Package)
64 createAll = func(pkgs []*types.Package) {
65 for _, p := range pkgs {
68 irpkg := prog.CreatePackage(p, nil, nil, true)
69 for _, fn := range irpkg.Functions {
70 if ast.IsExported(fn.Name()) {
73 if pass.ImportObjectFact(fn.Object(), &exit) {
76 if pass.ImportObjectFact(fn.Object(), &unwind) {
81 createAll(p.Imports())
85 createAll(pass.Pkg.Imports())
87 // Create and build the primary package.
88 irpkg := prog.CreatePackage(pass.Pkg, pass.Files, pass.TypesInfo, false)
91 // Compute list of source functions, including literals,
93 var addAnons func(f *ir.Function)
94 funcs := make([]*ir.Function, len(irpkg.Functions))
95 copy(funcs, irpkg.Functions)
96 addAnons = func(f *ir.Function) {
97 for _, anon := range f.AnonFuncs {
98 funcs = append(funcs, anon)
102 for _, fn := range irpkg.Functions {
105 pass.ExportObjectFact(fn.Object(), new(willExit))
108 pass.ExportObjectFact(fn.Object(), new(willUnwind))
112 return &IR{Pkg: irpkg, SrcFuncs: funcs}, nil