Debian Codegraph @

go/ir/print.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 String() methods for all Value and
8 // Instruction types.
9
10 import (
11 "bytes"
12 "fmt"
13 "go/types"
14 "io"
15 "reflect"
16 "sort"
17 "strings"
18
19 "honnef.co/go/tools/go/types/typeutil"
20 )
21
22 // relName returns the name of v relative to i.
23 // In most cases, this is identical to v.Name(), but references to
24 // Functions (including methods) and Globals use RelString and
25 // all types are displayed with relType, so that only cross-package
26 // references are package-qualified.
27 func relName(v Value, i Instruction) string {
28 if v == nil {
29 return "<nil>"
30 }
31 var from *types.Package
32 if i != nil {
33 from = i.Parent().pkg()
34 }
35 switch v := v.(type) {
36 case Member: // *Function or *Global
37 return v.RelString(from)
38 }
39 return v.Name()
40 }
41
42 func relType(t types.Type, from *types.Package) string {
43 return types.TypeString(t, types.RelativeTo(from))
44 }
45
46 func relTerm(term *types.Term, from *types.Package) string {
47 s := relType(term.Type(), from)
48 if term.Tilde() {
49 return "~" + s
50 }
51 return s
52 }
53
54 func relString(m Member, from *types.Package) string {
55 // NB: not all globals have an Object (e.g. init$guard),
56 // so use Package().Object not Object.Package().
57 if pkg := m.Package().Pkg; pkg != nil && pkg != from {
58 return fmt.Sprintf("%s.%s", pkg.Path(), m.Name())
59 }
60 return m.Name()
61 }
62
63 // Value.String()
64 //
65 // This method is provided only for debugging.
66 // It never appears in disassembly, which uses Value.Name().
67
68 func (v *Parameter) String() string {
69 from := v.Parent().pkg()
70 return fmt.Sprintf("Parameter <%s> {%s}", relType(v.Type(), from), v.name)
71 }
72
73 func (v *FreeVar) String() string {
74 from := v.Parent().pkg()
75 return fmt.Sprintf("FreeVar <%s> %s", relType(v.Type(), from), v.Name())
76 }
77
78 func (v *Builtin) String() string {
79 return fmt.Sprintf("Builtin %s", v.Name())
80 }
81
82 // Instruction.String()
83
84 func (v *Alloc) String() string {
85 from := v.Parent().pkg()
86 storage := "Stack"
87 if v.Heap {
88 storage = "Heap"
89 }
90 return fmt.Sprintf("%sAlloc <%s>", storage, relType(v.Type(), from))
91 }
92
93 func (v *Sigma) String() string {
94 from := v.Parent().pkg()
95 s := fmt.Sprintf("Sigma <%s> [b%d] %s", relType(v.Type(), from), v.From.Index, v.X.Name())
96 return s
97 }
98
99 func (v *Phi) String() string {
100 var b bytes.Buffer
101 fmt.Fprintf(&b, "Phi <%s>", v.Type())
102 for i, edge := range v.Edges {
103 b.WriteString(" ")
104 // Be robust against malformed CFG.
105 if v.block == nil {
106 b.WriteString("??")
107 continue
108 }
109 block := -1
110 if i < len(v.block.Preds) {
111 block = v.block.Preds[i].Index
112 }
113 fmt.Fprintf(&b, "%d:", block)
114 edgeVal := "<nil>" // be robust
115 if edge != nil {
116 edgeVal = relName(edge, v)
117 }
118 b.WriteString(edgeVal)
119 }
120 return b.String()
121 }
122
123 func printCall(v *CallCommon, prefix string, instr Instruction) string {
124 var b bytes.Buffer
125 if !v.IsInvoke() {
126 if value, ok := instr.(Value); ok {
127 fmt.Fprintf(&b, "%s <%s> %s", prefix, relType(value.Type(), instr.Parent().pkg()), relName(v.Value, instr))
128 } else {
129 fmt.Fprintf(&b, "%s %s", prefix, relName(v.Value, instr))
130 }
131 } else {
132 if value, ok := instr.(Value); ok {
133 fmt.Fprintf(&b, "%sInvoke <%s> %s.%s", prefix, relType(value.Type(), instr.Parent().pkg()), relName(v.Value, instr), v.Method.Name())
134 } else {
135 fmt.Fprintf(&b, "%sInvoke %s.%s", prefix, relName(v.Value, instr), v.Method.Name())
136 }
137 }
138 for _, arg := range v.TypeArgs {
139 b.WriteString(" ")
140 b.WriteString(relType(arg, instr.Parent().pkg()))
141 }
142 for _, arg := range v.Args {
143 b.WriteString(" ")
144 b.WriteString(relName(arg, instr))
145 }
146 return b.String()
147 }
148
149 func (c *CallCommon) String() string {
150 return printCall(c, "", nil)
151 }
152
153 func (v *Call) String() string {
154 return printCall(&v.Call, "Call", v)
155 }
156
157 func (v *BinOp) String() string {
158 return fmt.Sprintf("BinOp <%s> {%s} %s %s", relType(v.Type(), v.Parent().pkg()), v.Op.String(), relName(v.X, v), relName(v.Y, v))
159 }
160
161 func (v *UnOp) String() string {
162 return fmt.Sprintf("UnOp <%s> {%s} %s", relType(v.Type(), v.Parent().pkg()), v.Op.String(), relName(v.X, v))
163 }
164
165 func (v *Load) String() string {
166 return fmt.Sprintf("Load <%s> %s", relType(v.Type(), v.Parent().pkg()), relName(v.X, v))
167 }
168
169 func (v *Copy) String() string {
170 return fmt.Sprintf("Copy <%s> %s", relType(v.Type(), v.Parent().pkg()), relName(v.X, v))
171 }
172
173 func printConv(prefix string, v, x Value) string {
174 from := v.Parent().pkg()
175 return fmt.Sprintf("%s <%s> %s",
176 prefix,
177 relType(v.Type(), from),
178 relName(x, v.(Instruction)))
179 }
180
181 func (v *ChangeType) String() string { return printConv("ChangeType", v, v.X) }
182 func (v *Convert) String() string { return printConv("Convert", v, v.X) }
183 func (v *ChangeInterface) String() string { return printConv("ChangeInterface", v, v.X) }
184 func (v *SliceToArrayPointer) String() string { return printConv("SliceToArrayPointer", v, v.X) }
185 func (v *SliceToArray) String() string { return printConv("SliceToArray", v, v.X) }
186 func (v *MakeInterface) String() string { return printConv("MakeInterface", v, v.X) }
187
188 func (v *MakeClosure) String() string {
189 from := v.Parent().pkg()
190 var b bytes.Buffer
191 fmt.Fprintf(&b, "MakeClosure <%s> %s", relType(v.Type(), from), relName(v.Fn, v))
192 if v.Bindings != nil {
193 for _, c := range v.Bindings {
194 b.WriteString(" ")
195 b.WriteString(relName(c, v))
196 }
197 }
198 return b.String()
199 }
200
201 func (v *MakeSlice) String() string {
202 from := v.Parent().pkg()
203 return fmt.Sprintf("MakeSlice <%s> %s %s",
204 relType(v.Type(), from),
205 relName(v.Len, v),
206 relName(v.Cap, v))
207 }
208
209 func (v *Slice) String() string {
210 from := v.Parent().pkg()
211 return fmt.Sprintf("Slice <%s> %s %s %s %s",
212 relType(v.Type(), from), relName(v.X, v), relName(v.Low, v), relName(v.High, v), relName(v.Max, v))
213 }
214
215 func (v *MakeMap) String() string {
216 res := ""
217 if v.Reserve != nil {
218 res = relName(v.Reserve, v)
219 }
220 from := v.Parent().pkg()
221 return fmt.Sprintf("MakeMap <%s> %s", relType(v.Type(), from), res)
222 }
223
224 func (v *MakeChan) String() string {
225 from := v.Parent().pkg()
226 return fmt.Sprintf("MakeChan <%s> %s", relType(v.Type(), from), relName(v.Size, v))
227 }
228
229 func (v *FieldAddr) String() string {
230 from := v.Parent().pkg()
231 // v.X.Type() might be a pointer to a type parameter whose core type is a pointer to a struct
232 st := deref(typeutil.CoreType(deref(v.X.Type()))).Underlying().(*types.Struct)
233 // Be robust against a bad index.
234 name := "?"
235 if 0 <= v.Field && v.Field < st.NumFields() {
236 name = st.Field(v.Field).Name()
237 }
238 return fmt.Sprintf("FieldAddr <%s> [%d] (%s) %s", relType(v.Type(), from), v.Field, name, relName(v.X, v))
239 }
240
241 func (v *Field) String() string {
242 st := typeutil.CoreType(v.X.Type()).Underlying().(*types.Struct)
243 // Be robust against a bad index.
244 name := "?"
245 if 0 <= v.Field && v.Field < st.NumFields() {
246 name = st.Field(v.Field).Name()
247 }
248 from := v.Parent().pkg()
249 return fmt.Sprintf("Field <%s> [%d] (%s) %s", relType(v.Type(), from), v.Field, name, relName(v.X, v))
250 }
251
252 func (v *IndexAddr) String() string {
253 from := v.Parent().pkg()
254 return fmt.Sprintf("IndexAddr <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v))
255 }
256
257 func (v *Index) String() string {
258 from := v.Parent().pkg()
259 return fmt.Sprintf("Index <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v))
260 }
261
262 func (v *MapLookup) String() string {
263 from := v.Parent().pkg()
264 return fmt.Sprintf("MapLookup <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v))
265 }
266
267 func (v *StringLookup) String() string {
268 from := v.Parent().pkg()
269 return fmt.Sprintf("StringLookup <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v))
270 }
271
272 func (v *Range) String() string {
273 from := v.Parent().pkg()
274 return fmt.Sprintf("Range <%s> %s", relType(v.Type(), from), relName(v.X, v))
275 }
276
277 func (v *Next) String() string {
278 from := v.Parent().pkg()
279 return fmt.Sprintf("Next <%s> %s", relType(v.Type(), from), relName(v.Iter, v))
280 }
281
282 func (v *TypeAssert) String() string {
283 from := v.Parent().pkg()
284 return fmt.Sprintf("TypeAssert <%s> %s", relType(v.Type(), from), relName(v.X, v))
285 }
286
287 func (v *Extract) String() string {
288 from := v.Parent().pkg()
289 name := v.Tuple.Type().(*types.Tuple).At(v.Index).Name()
290 return fmt.Sprintf("Extract <%s> [%d] (%s) %s", relType(v.Type(), from), v.Index, name, relName(v.Tuple, v))
291 }
292
293 func (s *Jump) String() string {
294 // Be robust against malformed CFG.
295 block := -1
296 if s.block != nil && len(s.block.Succs) == 1 {
297 block = s.block.Succs[0].Index
298 }
299 str := fmt.Sprintf("Jump → b%d", block)
300 if s.Comment() != "" {
301 str = fmt.Sprintf("%s # %s", str, s.Comment())
302 }
303 return str
304 }
305
306 func (s *Unreachable) String() string {
307 // Be robust against malformed CFG.
308 block := -1
309 if s.block != nil && len(s.block.Succs) == 1 {
310 block = s.block.Succs[0].Index
311 }
312 return fmt.Sprintf("Unreachable → b%d", block)
313 }
314
315 func (s *If) String() string {
316 // Be robust against malformed CFG.
317 tblock, fblock := -1, -1
318 if s.block != nil && len(s.block.Succs) == 2 {
319 tblock = s.block.Succs[0].Index
320 fblock = s.block.Succs[1].Index
321 }
322 return fmt.Sprintf("If %s → b%d b%d", relName(s.Cond, s), tblock, fblock)
323 }
324
325 func (s *ConstantSwitch) String() string {
326 var b bytes.Buffer
327 fmt.Fprintf(&b, "ConstantSwitch %s", relName(s.Tag, s))
328 for _, cond := range s.Conds {
329 fmt.Fprintf(&b, " %s", relName(cond, s))
330 }
331 fmt.Fprint(&b, " →")
332 for _, succ := range s.block.Succs {
333 fmt.Fprintf(&b, " b%d", succ.Index)
334 }
335 return b.String()
336 }
337
338 func (v *CompositeValue) String() string {
339 var b bytes.Buffer
340 from := v.Parent().pkg()
341 fmt.Fprintf(&b, "CompositeValue <%s>", relType(v.Type(), from))
342 if v.NumSet >= len(v.Values) {
343 // All values provided
344 fmt.Fprint(&b, " [all]")
345 } else if v.Bitmap.BitLen() == 0 {
346 // No values provided
347 fmt.Fprint(&b, " [none]")
348 } else {
349 // Some values provided
350 bits := fmt.Appendf(nil, "%0*b", len(v.Values), &v.Bitmap)
351 for i := 0; i < len(bits)/2; i++ {
352 o := len(bits) - 1 - i
353 bits[i], bits[o] = bits[o], bits[i]
354 }
355 fmt.Fprintf(&b, " [%s]", bits)
356 }
357 for _, vv := range v.Values {
358 fmt.Fprintf(&b, " %s", relName(vv, v))
359 }
360 return b.String()
361 }
362
363 func (s *TypeSwitch) String() string {
364 from := s.Parent().pkg()
365 var b bytes.Buffer
366 fmt.Fprintf(&b, "TypeSwitch <%s> %s", relType(s.typ, from), relName(s.Tag, s))
367 for _, cond := range s.Conds {
368 fmt.Fprintf(&b, " %q", relType(cond, s.block.parent.pkg()))
369 }
370 return b.String()
371 }
372
373 func (s *Go) String() string {
374 return printCall(&s.Call, "Go", s)
375 }
376
377 func (s *Panic) String() string {
378 // Be robust against malformed CFG.
379 block := -1
380 if s.block != nil && len(s.block.Succs) == 1 {
381 block = s.block.Succs[0].Index
382 }
383 return fmt.Sprintf("Panic %s → b%d", relName(s.X, s), block)
384 }
385
386 func (s *Return) String() string {
387 var b bytes.Buffer
388 b.WriteString("Return")
389 for _, r := range s.Results {
390 b.WriteString(" ")
391 b.WriteString(relName(r, s))
392 }
393 return b.String()
394 }
395
396 func (*RunDefers) String() string {
397 return "RunDefers"
398 }
399
400 func (s *Send) String() string {
401 return fmt.Sprintf("Send %s %s", relName(s.Chan, s), relName(s.X, s))
402 }
403
404 func (recv *Recv) String() string {
405 from := recv.Parent().pkg()
406 return fmt.Sprintf("Recv <%s> %s", relType(recv.Type(), from), relName(recv.Chan, recv))
407 }
408
409 func (s *Defer) String() string {
410 prefix := "Defer "
411 if s._DeferStack != nil {
412 prefix += "[" + relName(s._DeferStack, s) + "] "
413 }
414 c := printCall(&s.Call, prefix, s)
415 return c
416 }
417
418 func (s *Select) String() string {
419 var b bytes.Buffer
420 for i, st := range s.States {
421 if i > 0 {
422 b.WriteString(", ")
423 }
424 if st.Dir == types.RecvOnly {
425 b.WriteString("<-")
426 b.WriteString(relName(st.Chan, s))
427 } else {
428 b.WriteString(relName(st.Chan, s))
429 b.WriteString("<-")
430 b.WriteString(relName(st.Send, s))
431 }
432 }
433 non := ""
434 if !s.Blocking {
435 non = "Non"
436 }
437 from := s.Parent().pkg()
438 return fmt.Sprintf("Select%sBlocking <%s> [%s]", non, relType(s.Type(), from), b.String())
439 }
440
441 func (s *Store) String() string {
442 return fmt.Sprintf("Store {%s} %s %s",
443 s.Val.Type(), relName(s.Addr, s), relName(s.Val, s))
444 }
445
446 func (s *BlankStore) String() string {
447 return fmt.Sprintf("BlankStore %s", relName(s.Val, s))
448 }
449
450 func (s *MapUpdate) String() string {
451 return fmt.Sprintf("MapUpdate %s %s %s", relName(s.Map, s), relName(s.Key, s), relName(s.Value, s))
452 }
453
454 func (s *DebugRef) String() string {
455 p := s.Parent().Prog.Fset.Position(s.Pos())
456 var descr any
457 if s.object != nil {
458 descr = s.object // e.g. "var x int"
459 } else {
460 descr = reflect.TypeOf(s.Expr) // e.g. "*ast.CallExpr"
461 }
462 var addr string
463 if s.IsAddr {
464 addr = "address of "
465 }
466 return fmt.Sprintf("; %s%s @ %d:%d is %s", addr, descr, p.Line, p.Column, s.X.Name())
467 }
468
469 func (p *Package) String() string {
470 return "package " + p.Pkg.Path()
471 }
472
473 var _ io.WriterTo = (*Package)(nil) // *Package implements io.Writer
474
475 func (p *Package) WriteTo(w io.Writer) (int64, error) {
476 var buf bytes.Buffer
477 WritePackage(&buf, p)
478 n, err := w.Write(buf.Bytes())
479 return int64(n), err
480 }
481
482 // WritePackage writes to buf a human-readable summary of p.
483 func WritePackage(buf *bytes.Buffer, p *Package) {
484 fmt.Fprintf(buf, "%s:\n", p)
485
486 var names []string
487 maxname := 0
488 for name := range p.Members {
489 if l := len(name); l > maxname {
490 maxname = l
491 }
492 names = append(names, name)
493 }
494
495 from := p.Pkg
496 sort.Strings(names)
497 for _, name := range names {
498 switch mem := p.Members[name].(type) {
499 case *NamedConst:
500 fmt.Fprintf(buf, " const %-*s %s = %s\n",
501 maxname, name, mem.Name(), mem.Value.RelString(from))
502
503 case *Function:
504 fmt.Fprintf(buf, " func %-*s %s\n",
505 maxname, name, relType(mem.Type(), from))
506
507 case *Type:
508 fmt.Fprintf(buf, " type %-*s %s\n",
509 maxname, name, relType(mem.Type().Underlying(), from))
510 for _, meth := range typeutil.IntuitiveMethodSet(mem.Type(), &p.Prog.MethodSets) {
511 fmt.Fprintf(buf, " %s\n", types.SelectionString(meth, types.RelativeTo(from)))
512 }
513
514 case *Global:
515 fmt.Fprintf(buf, " var %-*s %s\n",
516 maxname, name, relType(mem.Type().(*types.Pointer).Elem(), from))
517 }
518 }
519
520 fmt.Fprintf(buf, "\n")
521 }
522
523 func (v *MultiConvert) String() string {
524 from := v.Parent().Pkg.Pkg
525
526 var b strings.Builder
527 b.WriteString(printConv("MultiConvert", v, v.X))
528 b.WriteString(" [")
529 for i, s := range v.from.Terms {
530 for j, d := range v.to.Terms {
531 if i != 0 || j != 0 {
532 b.WriteString(" | ")
533 }
534 fmt.Fprintf(&b, "%s -> %s", relTerm(s, from), relTerm(d, from))
535 }
536 }
537 b.WriteString("]")
538 return b.String()
539 }