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