Debian Codegraph @

go/ir/create.go

raw
1 // Copyright 2013 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.
4
5 package ir
6
7 // This file implements the CREATE phase of IR construction.
8 // See builder.go for explanation.
9
10 import (
11 "fmt"
12 "go/ast"
13 "go/token"
14 "go/types"
15 "go/version"
16 "os"
17 "sync"
18
19 "honnef.co/go/tools/go/types/typeutil"
20 )
21
22 // measured on the standard library and rounded up to powers of two,
23 // on average there are 8 blocks and 16 instructions per block in a
24 // function.
25 const avgBlocks = 8
26 const avgInstructionsPerBlock = 16
27
28 // NewProgram returns a new IR Program.
29 //
30 // mode controls diagnostics and checking during IR construction.
31 func NewProgram(fset *token.FileSet, mode BuilderMode) *Program {
32 prog := &Program{
33 Fset: fset,
34 imported: make(map[string]*Package),
35 packages: make(map[*types.Package]*Package),
36 mode: mode,
37 }
38
39 h := typeutil.MakeHasher() // protected by methodsMu, in effect
40 prog.methodSets.SetHasher(h)
41 prog.canon.SetHasher(h)
42
43 return prog
44 }
45
46 // memberFromObject populates package pkg with a member for the
47 // typechecker object obj.
48 //
49 // For objects from Go source code, syntax is the associated syntax tree
50 // (for funcs and vars only) and goversion defines the appropriate
51 // interpretation; they will be used during the build phase.
52 func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node, goversion string) {
53 name := obj.Name()
54 switch obj := obj.(type) {
55 case *types.Builtin:
56 if pkg.Pkg != types.Unsafe {
57 panic("unexpected builtin object: " + obj.String())
58 }
59
60 case *types.TypeName:
61 if name != "_" {
62 pkg.Members[name] = &Type{
63 object: obj,
64 pkg: pkg,
65 }
66 }
67
68 case *types.Const:
69 c := &NamedConst{
70 object: obj,
71 Value: NewConst(obj.Val(), obj.Type(), syntax),
72 pkg: pkg,
73 }
74 pkg.values[obj] = c.Value
75 if name != "_" {
76 pkg.Members[name] = c
77 }
78
79 case *types.Var:
80 g := &Global{
81 Pkg: pkg,
82 name: name,
83 object: obj,
84 typ: types.NewPointer(obj.Type()), // address
85 }
86 pkg.values[obj] = g
87 if name != "_" {
88 pkg.Members[name] = g
89 }
90
91 case *types.Func:
92 sig := obj.Type().(*types.Signature)
93 if sig.Recv() == nil && name == "init" {
94 pkg.ninit++
95 name = fmt.Sprintf("init#%d", pkg.ninit)
96 }
97 fn := &Function{
98 name: name,
99 object: obj,
100 Signature: sig,
101 Pkg: pkg,
102 Prog: pkg.Prog,
103 goversion: goversion,
104 }
105
106 fn.source = syntax
107 fn.initHTML(pkg.printFunc)
108 if syntax == nil {
109 fn.Synthetic = SyntheticLoadedFromExportData
110 } else {
111 // Note: we initialize fn.Blocks in
112 // (*builder).buildFunction and not here because Blocks
113 // being nil is used to indicate that building of the
114 // function hasn't started yet.
115
116 fn.functionBody = &functionBody{
117 scratchInstructions: make([]Instruction, avgBlocks*avgInstructionsPerBlock),
118 }
119 }
120
121 pkg.values[obj] = fn
122 pkg.Functions = append(pkg.Functions, fn)
123 if name != "_" && sig.Recv() == nil {
124 pkg.Members[name] = fn // package-level function
125 }
126
127 default: // (incl. *types.Package)
128 panic("unexpected Object type: " + obj.String())
129 }
130 }
131
132 // membersFromDecl populates package pkg with members for each
133 // typechecker object (var, func, const or type) associated with the
134 // specified decl.
135 func membersFromDecl(pkg *Package, decl ast.Decl, goversion string) {
136 switch decl := decl.(type) {
137 case *ast.GenDecl: // import, const, type or var
138 switch decl.Tok {
139 case token.CONST:
140 for _, spec := range decl.Specs {
141 for _, id := range spec.(*ast.ValueSpec).Names {
142 memberFromObject(pkg, pkg.info.Defs[id], nil, "")
143 }
144 }
145
146 case token.VAR:
147 for _, spec := range decl.Specs {
148 for _, rhs := range spec.(*ast.ValueSpec).Values {
149 pkg.initVersion[rhs] = goversion
150 }
151 for _, id := range spec.(*ast.ValueSpec).Names {
152 memberFromObject(pkg, pkg.info.Defs[id], spec, goversion)
153 }
154 }
155
156 case token.TYPE:
157 for _, spec := range decl.Specs {
158 id := spec.(*ast.TypeSpec).Name
159 memberFromObject(pkg, pkg.info.Defs[id], nil, "")
160 }
161 }
162
163 case *ast.FuncDecl:
164 id := decl.Name
165 obj, ok := pkg.info.Defs[id]
166 if !ok {
167 panic(fmt.Sprintf("couldn't find object for id %q at %s",
168 id.Name, pkg.Prog.Fset.PositionFor(id.Pos(), false)))
169 }
170 if obj == nil {
171 panic(fmt.Sprintf("found nil object for id %q at %s",
172 id.Name, pkg.Prog.Fset.PositionFor(id.Pos(), false)))
173 }
174 memberFromObject(pkg, obj, decl, goversion)
175 }
176 }
177
178 // CreatePackage constructs and returns an IR Package from the
179 // specified type-checked, error-free file ASTs, and populates its
180 // Members mapping.
181 //
182 // importable determines whether this package should be returned by a
183 // subsequent call to ImportedPackage(pkg.Path()).
184 //
185 // The real work of building IR form for each function is not done
186 // until a subsequent call to Package.Build().
187 func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package {
188 p := &Package{
189 Prog: prog,
190 Members: make(map[string]Member),
191 values: make(map[types.Object]Value),
192 Pkg: pkg,
193 // transient values (CREATE and BUILD phases)
194 info: info,
195 files: files,
196 printFunc: prog.PrintFunc,
197 initVersion: make(map[ast.Expr]string),
198 }
199
200 // Add init() function.
201 p.init = &Function{
202 name: "init",
203 Signature: new(types.Signature),
204 Synthetic: SyntheticPackageInitializer,
205 Pkg: p,
206 Prog: prog,
207 functionBody: new(functionBody),
208 goversion: "", // See Package.build for details.
209 }
210 p.init.initHTML(prog.PrintFunc)
211 p.Members[p.init.name] = p.init
212 p.Functions = append(p.Functions, p.init)
213
214 // CREATE phase.
215 // Allocate all package members: vars, funcs, consts and types.
216 if len(files) > 0 {
217 // Go source package.
218 for _, file := range files {
219 goversion := version.Lang(p.info.FileVersions[file])
220 for _, decl := range file.Decls {
221 membersFromDecl(p, decl, goversion)
222 }
223 }
224 } else {
225 // GC-compiled binary package (or "unsafe")
226 // No code.
227 // No position information.
228 scope := p.Pkg.Scope()
229 for _, name := range scope.Names() {
230 obj := scope.Lookup(name)
231 memberFromObject(p, obj, nil, "")
232 if obj, ok := obj.(*types.TypeName); ok {
233 if named, ok := obj.Type().(*types.Named); ok {
234 for i, n := 0, named.NumMethods(); i < n; i++ {
235 memberFromObject(p, named.Method(i), nil, "")
236 }
237 }
238 }
239 }
240 }
241
242 // Add initializer guard variable.
243 initguard := &Global{
244 Pkg: p,
245 name: "init$guard",
246 typ: types.NewPointer(tBool),
247 }
248 p.Members[initguard.Name()] = initguard
249
250 if prog.mode&GlobalDebug != 0 {
251 p.SetDebugMode(true)
252 }
253
254 if prog.mode&PrintPackages != 0 {
255 printMu.Lock()
256 p.WriteTo(os.Stdout)
257 printMu.Unlock()
258 }
259
260 if importable {
261 prog.imported[p.Pkg.Path()] = p
262 }
263 prog.packages[p.Pkg] = p
264
265 return p
266 }
267
268 // printMu serializes printing of Packages/Functions to stdout.
269 var printMu sync.Mutex
270
271 // AllPackages returns a new slice containing all packages in the
272 // program prog in unspecified order.
273 func (prog *Program) AllPackages() []*Package {
274 pkgs := make([]*Package, 0, len(prog.packages))
275 for _, pkg := range prog.packages {
276 pkgs = append(pkgs, pkg)
277 }
278 return pkgs
279 }
280
281 // ImportedPackage returns the importable Package whose PkgPath
282 // is path, or nil if no such Package has been created.
283 //
284 // A parameter to CreatePackage determines whether a package should be
285 // considered importable. For example, no import declaration can resolve
286 // to the ad-hoc main package created by 'go build foo.go'.
287 //
288 // TODO(adonovan): rethink this function and the "importable" concept;
289 // most packages are importable. This function assumes that all
290 // types.Package.Path values are unique within the ir.Program, which is
291 // false---yet this function remains very convenient.
292 // Clients should use (*Program).Package instead where possible.
293 // IR doesn't really need a string-keyed map of packages.
294 func (prog *Program) ImportedPackage(path string) *Package {
295 return prog.imported[path]
296 }
297
298 func (prog *Program) SetNoReturn(fn func(*types.Func) bool) {
299 prog.noReturn = fn
300 }