Debian Codegraph @

ast.go

raw
1 // Copyright 2015 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 demangle
6
7 import (
8 "fmt"
9 "strconv"
10 "strings"
11 )
12
13 // AST is an abstract syntax tree representing a C++ declaration.
14 // This is sufficient for the demangler but is by no means a general C++ AST.
15 // This abstract syntax tree is only used for C++ symbols, not Rust symbols.
16 type AST interface {
17 // Internal method to convert to demangled string.
18 print(*printState)
19
20 // Traverse each element of an AST. If the function returns
21 // false, traversal of children of that element is skipped.
22 Traverse(func(AST) bool)
23
24 // Copy an AST with possible transformations.
25 // If the skip function returns true, no copy is required.
26 // If the copy function returns nil, no copy is required.
27 // The Copy method will do the right thing if copy returns nil
28 // for some components of an AST but not others, so a good
29 // copy function will only return non-nil for AST values that
30 // need to change.
31 // Copy itself returns either a copy or nil.
32 Copy(copy func(AST) AST, skip func(AST) bool) AST
33
34 // Implement the fmt.GoStringer interface.
35 GoString() string
36 goString(indent int, field string) string
37 }
38
39 // ASTToString returns the demangled name of the AST.
40 func ASTToString(a AST, options ...Option) string {
41 tparams := true
42 enclosingParams := true
43 llvmStyle := false
44 max := 0
45 for _, o := range options {
46 switch {
47 case o == NoTemplateParams:
48 tparams = false
49 case o == NoEnclosingParams:
50 enclosingParams = false
51 case o == LLVMStyle:
52 llvmStyle = true
53 case isMaxLength(o):
54 max = maxLength(o)
55 }
56 }
57
58 ps := printState{
59 tparams: tparams,
60 enclosingParams: enclosingParams,
61 llvmStyle: llvmStyle,
62 max: max,
63 scopes: 1,
64 }
65 a.print(&ps)
66 s := ps.buf.String()
67 if max > 0 && len(s) > max {
68 s = s[:max]
69 }
70 return s
71 }
72
73 // The printState type holds information needed to print an AST.
74 type printState struct {
75 tparams bool // whether to print template parameters
76 enclosingParams bool // whether to print enclosing parameters
77 llvmStyle bool
78 max int // maximum output length
79
80 // The scopes field is used to avoid unnecessary parentheses
81 // around expressions that use > (or >>). It is incremented if
82 // we output a parenthesis or something else that means that >
83 // or >> won't be treated as ending a template. It starts out
84 // as 1, and is set to 0 when we start writing template
85 // arguments. We add parentheses around expressions using > if
86 // scopes is 0. The effect is that an expression with > gets
87 // parentheses if used as a template argument that is not
88 // inside some other set of parentheses.
89 scopes int
90
91 // lambdaTemplateArgs is true if we are printing the template
92 // arguments to a lambda with explicit template parameters.
93 // In that case template parameters are printed without names.
94 lambdaTemplateArgs bool
95
96 buf strings.Builder
97 last byte // Last byte written to buffer.
98
99 // The inner field is a list of items to print for a type
100 // name. This is used by types to implement the inside-out
101 // C++ declaration syntax.
102 inner []AST
103
104 // The printing field is a list of items we are currently
105 // printing. This avoids endless recursion if a substitution
106 // reference creates a cycle in the graph.
107 printing []AST
108 }
109
110 // writeByte adds a byte to the string being printed.
111 func (ps *printState) writeByte(b byte) {
112 ps.last = b
113 ps.buf.WriteByte(b)
114 }
115
116 // writeString adds a string to the string being printed.
117 func (ps *printState) writeString(s string) {
118 if len(s) > 0 {
119 ps.last = s[len(s)-1]
120 }
121 ps.buf.WriteString(s)
122 }
123
124 // Print an AST.
125 func (ps *printState) print(a AST) {
126 if ps.max > 0 && ps.buf.Len() > ps.max {
127 return
128 }
129
130 c := 0
131 for _, v := range ps.printing {
132 if v == a {
133 // We permit the type to appear once, and
134 // return without printing anything if we see
135 // it twice. This is for a case like
136 // _Z6outer2IsEPFilES1_, where the
137 // substitution is printed differently the
138 // second time because the set of inner types
139 // is different.
140 c++
141 if c > 1 {
142 return
143 }
144 }
145 }
146 ps.printing = append(ps.printing, a)
147
148 a.print(ps)
149
150 ps.printing = ps.printing[:len(ps.printing)-1]
151 }
152
153 // printList prints a list of AST values separated by commas,
154 // optionally skipping some.
155 func (ps *printState) printList(args []AST, skip func(AST) bool) {
156 first := true
157 for _, a := range args {
158 if skip != nil && skip(a) {
159 continue
160 }
161 if !first {
162 ps.writeString(", ")
163 }
164
165 needsParen := false
166 if ps.llvmStyle {
167 if p, ok := a.(hasPrec); ok {
168 if p.prec() >= precComma {
169 needsParen = true
170 }
171 }
172 }
173 if needsParen {
174 ps.startScope('(')
175 }
176
177 ps.print(a)
178
179 if needsParen {
180 ps.endScope(')')
181 }
182
183 first = false
184 }
185 }
186
187 // startScope starts a scope. This is used to decide whether we need
188 // to parenthesize an expression using > or >>.
189 func (ps *printState) startScope(b byte) {
190 ps.scopes++
191 ps.writeByte(b)
192 }
193
194 // endScope closes a scope.
195 func (ps *printState) endScope(b byte) {
196 ps.scopes--
197 ps.writeByte(b)
198 }
199
200 // precedence is used for operator precedence. This is used to avoid
201 // unnecessary parentheses when printing expressions in the LLVM style.
202 type precedence int
203
204 // The precedence values, in order from high to low.
205 const (
206 precPrimary precedence = iota
207 precPostfix
208 precUnary
209 precCast
210 precPtrMem
211 precMul
212 precAdd
213 precShift
214 precSpaceship
215 precRel
216 precEqual
217 precAnd
218 precXor
219 precOr
220 precLogicalAnd
221 precLogicalOr
222 precCond
223 precAssign
224 precComma
225 precDefault
226 )
227
228 // hasPrec matches the AST nodes that have a prec method that returns
229 // the node's precedence.
230 type hasPrec interface {
231 prec() precedence
232 }
233
234 // Name is an unqualified name.
235 type Name struct {
236 Name string
237 }
238
239 func (n *Name) print(ps *printState) {
240 ps.writeString(n.Name)
241 }
242
243 func (n *Name) Traverse(fn func(AST) bool) {
244 fn(n)
245 }
246
247 func (n *Name) Copy(fn func(AST) AST, skip func(AST) bool) AST {
248 if skip(n) {
249 return nil
250 }
251 return fn(n)
252 }
253
254 func (n *Name) GoString() string {
255 return n.goString(0, "Name: ")
256 }
257
258 func (n *Name) goString(indent int, field string) string {
259 return fmt.Sprintf("%*s%s%s", indent, "", field, n.Name)
260 }
261
262 func (n *Name) prec() precedence {
263 return precPrimary
264 }
265
266 // Typed is a typed name.
267 type Typed struct {
268 Name AST
269 Type AST
270 }
271
272 func (t *Typed) print(ps *printState) {
273 // We are printing a typed name, so ignore the current set of
274 // inner names to print. Pass down our name as the one to use.
275 holdInner := ps.inner
276 defer func() { ps.inner = holdInner }()
277
278 ps.inner = []AST{t}
279 ps.print(t.Type)
280 if len(ps.inner) > 0 {
281 // The type did not print the name; print it now in
282 // the default location.
283 ps.writeByte(' ')
284 ps.print(t.Name)
285 }
286 }
287
288 func (t *Typed) printInner(ps *printState) {
289 ps.print(t.Name)
290 }
291
292 func (t *Typed) Traverse(fn func(AST) bool) {
293 if fn(t) {
294 t.Name.Traverse(fn)
295 t.Type.Traverse(fn)
296 }
297 }
298
299 func (t *Typed) Copy(fn func(AST) AST, skip func(AST) bool) AST {
300 if skip(t) {
301 return nil
302 }
303 name := t.Name.Copy(fn, skip)
304 typ := t.Type.Copy(fn, skip)
305 if name == nil && typ == nil {
306 return fn(t)
307 }
308 if name == nil {
309 name = t.Name
310 }
311 if typ == nil {
312 typ = t.Type
313 }
314 t = &Typed{Name: name, Type: typ}
315 if r := fn(t); r != nil {
316 return r
317 }
318 return t
319 }
320
321 func (t *Typed) GoString() string {
322 return t.goString(0, "")
323 }
324
325 func (t *Typed) goString(indent int, field string) string {
326 return fmt.Sprintf("%*s%sTyped:\n%s\n%s", indent, "", field,
327 t.Name.goString(indent+2, "Name: "),
328 t.Type.goString(indent+2, "Type: "))
329 }
330
331 // Qualified is a name in a scope.
332 type Qualified struct {
333 Scope AST
334 Name AST
335
336 // The LocalName field is true if this is parsed as a
337 // <local-name>. We shouldn't really need this, but in some
338 // cases (for the unary sizeof operator) the standard
339 // demangler prints a local name slightly differently. We
340 // keep track of this for compatibility.
341 LocalName bool // A full local name encoding
342 }
343
344 func (q *Qualified) print(ps *printState) {
345 ps.print(q.Scope)
346 ps.writeString("::")
347 ps.print(q.Name)
348 }
349
350 func (q *Qualified) Traverse(fn func(AST) bool) {
351 if fn(q) {
352 q.Scope.Traverse(fn)
353 q.Name.Traverse(fn)
354 }
355 }
356
357 func (q *Qualified) Copy(fn func(AST) AST, skip func(AST) bool) AST {
358 if skip(q) {
359 return nil
360 }
361 scope := q.Scope.Copy(fn, skip)
362 name := q.Name.Copy(fn, skip)
363 if scope == nil && name == nil {
364 return fn(q)
365 }
366 if scope == nil {
367 scope = q.Scope
368 }
369 if name == nil {
370 name = q.Name
371 }
372 q = &Qualified{Scope: scope, Name: name, LocalName: q.LocalName}
373 if r := fn(q); r != nil {
374 return r
375 }
376 return q
377 }
378
379 func (q *Qualified) GoString() string {
380 return q.goString(0, "")
381 }
382
383 func (q *Qualified) goString(indent int, field string) string {
384 s := ""
385 if q.LocalName {
386 s = " LocalName: true"
387 }
388 return fmt.Sprintf("%*s%sQualified:%s\n%s\n%s", indent, "", field,
389 s, q.Scope.goString(indent+2, "Scope: "),
390 q.Name.goString(indent+2, "Name: "))
391 }
392
393 func (q *Qualified) prec() precedence {
394 return precPrimary
395 }
396
397 // Template is a template with arguments.
398 type Template struct {
399 Name AST
400 Args []AST
401 }
402
403 func (t *Template) print(ps *printState) {
404 // Inner types apply to the template as a whole, they don't
405 // cross over into the template.
406 holdInner := ps.inner
407 defer func() { ps.inner = holdInner }()
408
409 ps.inner = nil
410 ps.print(t.Name)
411
412 if !ps.tparams {
413 // Do not print template parameters.
414 return
415 }
416 // We need an extra space after operator<.
417 if ps.last == '<' {
418 ps.writeByte(' ')
419 }
420
421 scopes := ps.scopes
422 ps.scopes = 0
423
424 ps.writeByte('<')
425 ps.printList(t.Args, ps.isEmpty)
426 if ps.last == '>' && !ps.llvmStyle {
427 // Avoid syntactic ambiguity in old versions of C++.
428 ps.writeByte(' ')
429 }
430 ps.writeByte('>')
431
432 ps.scopes = scopes
433 }
434
435 func (t *Template) Traverse(fn func(AST) bool) {
436 if fn(t) {
437 t.Name.Traverse(fn)
438 for _, a := range t.Args {
439 a.Traverse(fn)
440 }
441 }
442 }
443
444 func (t *Template) Copy(fn func(AST) AST, skip func(AST) bool) AST {
445 if skip(t) {
446 return nil
447 }
448 name := t.Name.Copy(fn, skip)
449 changed := name != nil
450 args := make([]AST, len(t.Args))
451 for i, a := range t.Args {
452 ac := a.Copy(fn, skip)
453 if ac == nil {
454 args[i] = a
455 } else {
456 args[i] = ac
457 changed = true
458 }
459 }
460 if !changed {
461 return fn(t)
462 }
463 if name == nil {
464 name = t.Name
465 }
466 t = &Template{Name: name, Args: args}
467 if r := fn(t); r != nil {
468 return r
469 }
470 return t
471 }
472
473 func (t *Template) GoString() string {
474 return t.goString(0, "")
475 }
476
477 func (t *Template) goString(indent int, field string) string {
478 var args string
479 if len(t.Args) == 0 {
480 args = fmt.Sprintf("%*sArgs: nil", indent+2, "")
481 } else {
482 args = fmt.Sprintf("%*sArgs:", indent+2, "")
483 for i, a := range t.Args {
484 args += "\n"
485 args += a.goString(indent+4, fmt.Sprintf("%d: ", i))
486 }
487 }
488 return fmt.Sprintf("%*s%sTemplate (%p):\n%s\n%s", indent, "", field, t,
489 t.Name.goString(indent+2, "Name: "), args)
490 }
491
492 // TemplateParam is a template parameter. The Template field is
493 // filled in while parsing the demangled string. We don't normally
494 // see these while printing--they are replaced by the simplify
495 // function.
496 type TemplateParam struct {
497 Index int
498 Template *Template
499 }
500
501 func (tp *TemplateParam) print(ps *printState) {
502 if tp.Template == nil {
503 panic("TemplateParam Template field is nil")
504 }
505 if tp.Index >= len(tp.Template.Args) {
506 panic("TemplateParam Index out of bounds")
507 }
508 ps.print(tp.Template.Args[tp.Index])
509 }
510
511 func (tp *TemplateParam) Traverse(fn func(AST) bool) {
512 fn(tp)
513 // Don't traverse Template--it points elsewhere in the AST.
514 }
515
516 func (tp *TemplateParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
517 if skip(tp) {
518 return nil
519 }
520 return fn(tp)
521 }
522
523 func (tp *TemplateParam) GoString() string {
524 return tp.goString(0, "")
525 }
526
527 func (tp *TemplateParam) goString(indent int, field string) string {
528 return fmt.Sprintf("%*s%sTemplateParam: Template: %p; Index %d", indent, "", field, tp.Template, tp.Index)
529 }
530
531 // LambdaAuto is a lambda auto parameter.
532 type LambdaAuto struct {
533 Index int
534 }
535
536 func (la *LambdaAuto) print(ps *printState) {
537 // We print the index plus 1 because that is what the standard
538 // demangler does.
539 if ps.llvmStyle {
540 ps.writeString("auto")
541 } else {
542 fmt.Fprintf(&ps.buf, "auto:%d", la.Index+1)
543 }
544 }
545
546 func (la *LambdaAuto) Traverse(fn func(AST) bool) {
547 fn(la)
548 }
549
550 func (la *LambdaAuto) Copy(fn func(AST) AST, skip func(AST) bool) AST {
551 if skip(la) {
552 return nil
553 }
554 return fn(la)
555 }
556
557 func (la *LambdaAuto) GoString() string {
558 return la.goString(0, "")
559 }
560
561 func (la *LambdaAuto) goString(indent int, field string) string {
562 return fmt.Sprintf("%*s%sLambdaAuto: Index %d", indent, "", field, la.Index)
563 }
564
565 // TemplateParamQualifiedArg is used when the mangled name includes
566 // both the template parameter declaration and the template argument.
567 // See https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
568 type TemplateParamQualifiedArg struct {
569 Param AST
570 Arg AST
571 }
572
573 func (tpqa *TemplateParamQualifiedArg) print(ps *printState) {
574 // We only demangle the actual template argument.
575 // That is what the LLVM demangler does.
576 // The parameter disambiguates the argument,
577 // but is hopefully not required by a human reader.
578 ps.print(tpqa.Arg)
579 }
580
581 func (tpqa *TemplateParamQualifiedArg) Traverse(fn func(AST) bool) {
582 if fn(tpqa) {
583 tpqa.Param.Traverse(fn)
584 tpqa.Arg.Traverse(fn)
585 }
586 }
587
588 func (tpqa *TemplateParamQualifiedArg) Copy(fn func(AST) AST, skip func(AST) bool) AST {
589 if skip(tpqa) {
590 return nil
591 }
592 param := tpqa.Param.Copy(fn, skip)
593 arg := tpqa.Arg.Copy(fn, skip)
594 if param == nil && arg == nil {
595 return fn(tpqa)
596 }
597 if param == nil {
598 param = tpqa.Param
599 }
600 if arg == nil {
601 arg = tpqa.Arg
602 }
603 tpqa = &TemplateParamQualifiedArg{Param: param, Arg: arg}
604 if r := fn(tpqa); r != nil {
605 return r
606 }
607 return tpqa
608 }
609
610 func (tpqa *TemplateParamQualifiedArg) GoString() string {
611 return tpqa.goString(0, "")
612 }
613
614 func (tpqa *TemplateParamQualifiedArg) goString(indent int, field string) string {
615 return fmt.Sprintf("%*s%sTemplateParamQualifiedArg:\n%s\n%s", indent, "", field,
616 tpqa.Param.goString(indent+2, "Param: "),
617 tpqa.Arg.goString(indent+2, "Arg: "))
618 }
619
620 // Qualifiers is an ordered list of type qualifiers.
621 type Qualifiers struct {
622 Qualifiers []AST
623 }
624
625 func (qs *Qualifiers) print(ps *printState) {
626 first := true
627 for _, q := range qs.Qualifiers {
628 if !first {
629 ps.writeByte(' ')
630 }
631 q.print(ps)
632 first = false
633 }
634 }
635
636 func (qs *Qualifiers) Traverse(fn func(AST) bool) {
637 if fn(qs) {
638 for _, q := range qs.Qualifiers {
639 q.Traverse(fn)
640 }
641 }
642 }
643
644 func (qs *Qualifiers) Copy(fn func(AST) AST, skip func(AST) bool) AST {
645 if skip(qs) {
646 return nil
647 }
648 changed := false
649 qualifiers := make([]AST, len(qs.Qualifiers))
650 for i, q := range qs.Qualifiers {
651 qc := q.Copy(fn, skip)
652 if qc == nil {
653 qualifiers[i] = q
654 } else {
655 qualifiers[i] = qc
656 changed = true
657 }
658 }
659 if !changed {
660 return fn(qs)
661 }
662 qs = &Qualifiers{Qualifiers: qualifiers}
663 if r := fn(qs); r != nil {
664 return r
665 }
666 return qs
667 }
668
669 func (qs *Qualifiers) GoString() string {
670 return qs.goString(0, "")
671 }
672
673 func (qs *Qualifiers) goString(indent int, field string) string {
674 quals := fmt.Sprintf("%*s%s", indent, "", field)
675 for _, q := range qs.Qualifiers {
676 quals += "\n"
677 quals += q.goString(indent+2, "")
678 }
679 return quals
680 }
681
682 // Qualifier is a single type qualifier.
683 type Qualifier struct {
684 Name string // qualifier name: const, volatile, etc.
685 Exprs []AST // can be non-nil for noexcept and throw
686 }
687
688 func (q *Qualifier) print(ps *printState) {
689 ps.writeString(q.Name)
690 if len(q.Exprs) > 0 {
691 ps.startScope('(')
692 first := true
693 for _, e := range q.Exprs {
694 if el, ok := e.(*ExprList); ok && len(el.Exprs) == 0 {
695 continue
696 }
697 if !first {
698 ps.writeString(", ")
699 }
700 ps.print(e)
701 first = false
702 }
703 ps.endScope(')')
704 }
705 }
706
707 func (q *Qualifier) Traverse(fn func(AST) bool) {
708 if fn(q) {
709 for _, e := range q.Exprs {
710 e.Traverse(fn)
711 }
712 }
713 }
714
715 func (q *Qualifier) Copy(fn func(AST) AST, skip func(AST) bool) AST {
716 if skip(q) {
717 return nil
718 }
719 exprs := make([]AST, len(q.Exprs))
720 changed := false
721 for i, e := range q.Exprs {
722 ec := e.Copy(fn, skip)
723 if ec == nil {
724 exprs[i] = e
725 } else {
726 exprs[i] = ec
727 changed = true
728 }
729 }
730 if !changed {
731 return fn(q)
732 }
733 q = &Qualifier{Name: q.Name, Exprs: exprs}
734 if r := fn(q); r != nil {
735 return r
736 }
737 return q
738 }
739
740 func (q *Qualifier) GoString() string {
741 return q.goString(0, "Qualifier: ")
742 }
743
744 func (q *Qualifier) goString(indent int, field string) string {
745 qs := fmt.Sprintf("%*s%s%s", indent, "", field, q.Name)
746 if len(q.Exprs) > 0 {
747 for i, e := range q.Exprs {
748 qs += "\n"
749 qs += e.goString(indent+2, fmt.Sprintf("%d: ", i))
750 }
751 }
752 return qs
753 }
754
755 // TypeWithQualifiers is a type with standard qualifiers.
756 type TypeWithQualifiers struct {
757 Base AST
758 Qualifiers AST
759 }
760
761 func (twq *TypeWithQualifiers) print(ps *printState) {
762 // Give the base type a chance to print the inner types.
763 ps.inner = append(ps.inner, twq)
764 ps.print(twq.Base)
765 if len(ps.inner) > 0 {
766 // The qualifier wasn't printed by Base.
767 ps.writeByte(' ')
768 ps.print(twq.Qualifiers)
769 // In implausible situations like a throw qualified by a throw,
770 // we may have printed the qualifier already,
771 // so check the length of ps.inner again.
772 if len(ps.inner) > 0 {
773 ps.inner = ps.inner[:len(ps.inner)-1]
774 }
775 }
776 }
777
778 // Print qualifiers as an inner type by just printing the qualifiers.
779 func (twq *TypeWithQualifiers) printInner(ps *printState) {
780 ps.writeByte(' ')
781 ps.print(twq.Qualifiers)
782 }
783
784 func (twq *TypeWithQualifiers) Traverse(fn func(AST) bool) {
785 if fn(twq) {
786 twq.Base.Traverse(fn)
787 }
788 }
789
790 func (twq *TypeWithQualifiers) Copy(fn func(AST) AST, skip func(AST) bool) AST {
791 if skip(twq) {
792 return nil
793 }
794 base := twq.Base.Copy(fn, skip)
795 quals := twq.Qualifiers.Copy(fn, skip)
796 if base == nil && quals == nil {
797 return fn(twq)
798 }
799 if base == nil {
800 base = twq.Base
801 }
802 if quals == nil {
803 quals = twq.Qualifiers
804 }
805 twq = &TypeWithQualifiers{Base: base, Qualifiers: quals}
806 if r := fn(twq); r != nil {
807 return r
808 }
809 return twq
810 }
811
812 func (twq *TypeWithQualifiers) GoString() string {
813 return twq.goString(0, "")
814 }
815
816 func (twq *TypeWithQualifiers) goString(indent int, field string) string {
817 return fmt.Sprintf("%*s%sTypeWithQualifiers:\n%s\n%s", indent, "", field,
818 twq.Qualifiers.goString(indent+2, "Qualifiers: "),
819 twq.Base.goString(indent+2, "Base: "))
820 }
821
822 // MethodWithQualifiers is a method with qualifiers.
823 type MethodWithQualifiers struct {
824 Method AST
825 Qualifiers AST
826 RefQualifier string // "" or "&" or "&&"
827 }
828
829 func (mwq *MethodWithQualifiers) print(ps *printState) {
830 // Give the base type a chance to print the inner types.
831 ps.inner = append(ps.inner, mwq)
832 ps.print(mwq.Method)
833 if len(ps.inner) > 0 {
834 if mwq.Qualifiers != nil {
835 ps.writeByte(' ')
836 ps.print(mwq.Qualifiers)
837 }
838 if mwq.RefQualifier != "" {
839 ps.writeByte(' ')
840 ps.writeString(mwq.RefQualifier)
841 }
842 ps.inner = ps.inner[:len(ps.inner)-1]
843 }
844 }
845
846 func (mwq *MethodWithQualifiers) printInner(ps *printState) {
847 if mwq.Qualifiers != nil {
848 ps.writeByte(' ')
849 ps.print(mwq.Qualifiers)
850 }
851 if mwq.RefQualifier != "" {
852 ps.writeByte(' ')
853 ps.writeString(mwq.RefQualifier)
854 }
855 }
856
857 func (mwq *MethodWithQualifiers) Traverse(fn func(AST) bool) {
858 if fn(mwq) {
859 mwq.Method.Traverse(fn)
860 }
861 }
862
863 func (mwq *MethodWithQualifiers) Copy(fn func(AST) AST, skip func(AST) bool) AST {
864 if skip(mwq) {
865 return nil
866 }
867 method := mwq.Method.Copy(fn, skip)
868 var quals AST
869 if mwq.Qualifiers != nil {
870 quals = mwq.Qualifiers.Copy(fn, skip)
871 }
872 if method == nil && quals == nil {
873 return fn(mwq)
874 }
875 if method == nil {
876 method = mwq.Method
877 }
878 if quals == nil {
879 quals = mwq.Qualifiers
880 }
881 mwq = &MethodWithQualifiers{Method: method, Qualifiers: quals, RefQualifier: mwq.RefQualifier}
882 if r := fn(mwq); r != nil {
883 return r
884 }
885 return mwq
886 }
887
888 func (mwq *MethodWithQualifiers) GoString() string {
889 return mwq.goString(0, "")
890 }
891
892 func (mwq *MethodWithQualifiers) goString(indent int, field string) string {
893 var q string
894 if mwq.Qualifiers != nil {
895 q += "\n" + mwq.Qualifiers.goString(indent+2, "Qualifiers: ")
896 }
897 if mwq.RefQualifier != "" {
898 if q != "" {
899 q += "\n"
900 }
901 q += fmt.Sprintf("%*s%s%s", indent+2, "", "RefQualifier: ", mwq.RefQualifier)
902 }
903 return fmt.Sprintf("%*s%sMethodWithQualifiers:%s\n%s", indent, "", field,
904 q, mwq.Method.goString(indent+2, "Method: "))
905 }
906
907 // BuiltinType is a builtin type, like "int".
908 type BuiltinType struct {
909 Name string
910 }
911
912 func (bt *BuiltinType) print(ps *printState) {
913 name := bt.Name
914 if ps.llvmStyle && name == "decltype(nullptr)" {
915 name = "std::nullptr_t"
916 }
917 ps.writeString(name)
918 }
919
920 func (bt *BuiltinType) Traverse(fn func(AST) bool) {
921 fn(bt)
922 }
923
924 func (bt *BuiltinType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
925 if skip(bt) {
926 return nil
927 }
928 return fn(bt)
929 }
930
931 func (bt *BuiltinType) GoString() string {
932 return bt.goString(0, "")
933 }
934
935 func (bt *BuiltinType) goString(indent int, field string) string {
936 return fmt.Sprintf("%*s%sBuiltinType: %s", indent, "", field, bt.Name)
937 }
938
939 func (bt *BuiltinType) prec() precedence {
940 return precPrimary
941 }
942
943 // printBase is common print code for types that are printed with a
944 // simple suffix.
945 func printBase(ps *printState, qual, base AST) {
946 ps.inner = append(ps.inner, qual)
947 ps.print(base)
948 if len(ps.inner) > 0 {
949 qual.(innerPrinter).printInner(ps)
950 ps.inner = ps.inner[:len(ps.inner)-1]
951 }
952 }
953
954 // PointerType is a pointer type.
955 type PointerType struct {
956 Base AST
957 }
958
959 func (pt *PointerType) print(ps *printState) {
960 printBase(ps, pt, pt.Base)
961 }
962
963 func (pt *PointerType) printInner(ps *printState) {
964 ps.writeString("*")
965 }
966
967 func (pt *PointerType) Traverse(fn func(AST) bool) {
968 if fn(pt) {
969 pt.Base.Traverse(fn)
970 }
971 }
972
973 func (pt *PointerType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
974 if skip(pt) {
975 return nil
976 }
977 base := pt.Base.Copy(fn, skip)
978 if base == nil {
979 return fn(pt)
980 }
981 pt = &PointerType{Base: base}
982 if r := fn(pt); r != nil {
983 return r
984 }
985 return pt
986 }
987
988 func (pt *PointerType) GoString() string {
989 return pt.goString(0, "")
990 }
991
992 func (pt *PointerType) goString(indent int, field string) string {
993 return fmt.Sprintf("%*s%sPointerType:\n%s", indent, "", field,
994 pt.Base.goString(indent+2, ""))
995 }
996
997 // ReferenceType is a reference type.
998 type ReferenceType struct {
999 Base AST
1000 }
1001
1002 func (rt *ReferenceType) print(ps *printState) {
1003 printBase(ps, rt, rt.Base)
1004 }
1005
1006 func (rt *ReferenceType) printInner(ps *printState) {
1007 ps.writeString("&")
1008 }
1009
1010 func (rt *ReferenceType) Traverse(fn func(AST) bool) {
1011 if fn(rt) {
1012 rt.Base.Traverse(fn)
1013 }
1014 }
1015
1016 func (rt *ReferenceType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1017 if skip(rt) {
1018 return nil
1019 }
1020 base := rt.Base.Copy(fn, skip)
1021 if base == nil {
1022 return fn(rt)
1023 }
1024 rt = &ReferenceType{Base: base}
1025 if r := fn(rt); r != nil {
1026 return r
1027 }
1028 return rt
1029 }
1030
1031 func (rt *ReferenceType) GoString() string {
1032 return rt.goString(0, "")
1033 }
1034
1035 func (rt *ReferenceType) goString(indent int, field string) string {
1036 return fmt.Sprintf("%*s%sReferenceType:\n%s", indent, "", field,
1037 rt.Base.goString(indent+2, ""))
1038 }
1039
1040 // RvalueReferenceType is an rvalue reference type.
1041 type RvalueReferenceType struct {
1042 Base AST
1043 }
1044
1045 func (rt *RvalueReferenceType) print(ps *printState) {
1046 printBase(ps, rt, rt.Base)
1047 }
1048
1049 func (rt *RvalueReferenceType) printInner(ps *printState) {
1050 ps.writeString("&&")
1051 }
1052
1053 func (rt *RvalueReferenceType) Traverse(fn func(AST) bool) {
1054 if fn(rt) {
1055 rt.Base.Traverse(fn)
1056 }
1057 }
1058
1059 func (rt *RvalueReferenceType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1060 if skip(rt) {
1061 return nil
1062 }
1063 base := rt.Base.Copy(fn, skip)
1064 if base == nil {
1065 return fn(rt)
1066 }
1067 rt = &RvalueReferenceType{Base: base}
1068 if r := fn(rt); r != nil {
1069 return r
1070 }
1071 return rt
1072 }
1073
1074 func (rt *RvalueReferenceType) GoString() string {
1075 return rt.goString(0, "")
1076 }
1077
1078 func (rt *RvalueReferenceType) goString(indent int, field string) string {
1079 return fmt.Sprintf("%*s%sRvalueReferenceType:\n%s", indent, "", field,
1080 rt.Base.goString(indent+2, ""))
1081 }
1082
1083 // ComplexType is a complex type.
1084 type ComplexType struct {
1085 Base AST
1086 }
1087
1088 func (ct *ComplexType) print(ps *printState) {
1089 printBase(ps, ct, ct.Base)
1090 }
1091
1092 func (ct *ComplexType) printInner(ps *printState) {
1093 ps.writeString(" _Complex")
1094 }
1095
1096 func (ct *ComplexType) Traverse(fn func(AST) bool) {
1097 if fn(ct) {
1098 ct.Base.Traverse(fn)
1099 }
1100 }
1101
1102 func (ct *ComplexType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1103 if skip(ct) {
1104 return nil
1105 }
1106 base := ct.Base.Copy(fn, skip)
1107 if base == nil {
1108 return fn(ct)
1109 }
1110 ct = &ComplexType{Base: base}
1111 if r := fn(ct); r != nil {
1112 return r
1113 }
1114 return ct
1115 }
1116
1117 func (ct *ComplexType) GoString() string {
1118 return ct.goString(0, "")
1119 }
1120
1121 func (ct *ComplexType) goString(indent int, field string) string {
1122 return fmt.Sprintf("%*s%sComplexType:\n%s", indent, "", field,
1123 ct.Base.goString(indent+2, ""))
1124 }
1125
1126 // ImaginaryType is an imaginary type.
1127 type ImaginaryType struct {
1128 Base AST
1129 }
1130
1131 func (it *ImaginaryType) print(ps *printState) {
1132 printBase(ps, it, it.Base)
1133 }
1134
1135 func (it *ImaginaryType) printInner(ps *printState) {
1136 ps.writeString(" _Imaginary")
1137 }
1138
1139 func (it *ImaginaryType) Traverse(fn func(AST) bool) {
1140 if fn(it) {
1141 it.Base.Traverse(fn)
1142 }
1143 }
1144
1145 func (it *ImaginaryType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1146 if skip(it) {
1147 return nil
1148 }
1149 base := it.Base.Copy(fn, skip)
1150 if base == nil {
1151 return fn(it)
1152 }
1153 it = &ImaginaryType{Base: base}
1154 if r := fn(it); r != nil {
1155 return r
1156 }
1157 return it
1158 }
1159
1160 func (it *ImaginaryType) GoString() string {
1161 return it.goString(0, "")
1162 }
1163
1164 func (it *ImaginaryType) goString(indent int, field string) string {
1165 return fmt.Sprintf("%*s%sImaginaryType:\n%s", indent, "", field,
1166 it.Base.goString(indent+2, ""))
1167 }
1168
1169 // SuffixType is an type with an arbitrary suffix.
1170 type SuffixType struct {
1171 Base AST
1172 Suffix string
1173 }
1174
1175 func (st *SuffixType) print(ps *printState) {
1176 printBase(ps, st, st.Base)
1177 }
1178
1179 func (st *SuffixType) printInner(ps *printState) {
1180 ps.writeByte(' ')
1181 ps.writeString(st.Suffix)
1182 }
1183
1184 func (st *SuffixType) Traverse(fn func(AST) bool) {
1185 if fn(st) {
1186 st.Base.Traverse(fn)
1187 }
1188 }
1189
1190 func (st *SuffixType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1191 if skip(st) {
1192 return nil
1193 }
1194 base := st.Base.Copy(fn, skip)
1195 if base == nil {
1196 return fn(st)
1197 }
1198 st = &SuffixType{Base: base, Suffix: st.Suffix}
1199 if r := fn(st); r != nil {
1200 return r
1201 }
1202 return st
1203 }
1204
1205 func (st *SuffixType) GoString() string {
1206 return st.goString(0, "")
1207 }
1208
1209 func (st *SuffixType) goString(indent int, field string) string {
1210 return fmt.Sprintf("%*s%sSuffixType: %s\n%s", indent, "", field,
1211 st.Suffix, st.Base.goString(indent+2, "Base: "))
1212 }
1213
1214 // TransformedType is a builtin type with a template argument.
1215 type TransformedType struct {
1216 Name string
1217 Base AST
1218 }
1219
1220 func (tt *TransformedType) print(ps *printState) {
1221 ps.writeString(tt.Name)
1222 ps.startScope('(')
1223 ps.print(tt.Base)
1224 ps.endScope(')')
1225 }
1226
1227 func (tt *TransformedType) Traverse(fn func(AST) bool) {
1228 if fn(tt) {
1229 tt.Base.Traverse(fn)
1230 }
1231 }
1232
1233 func (tt *TransformedType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1234 if skip(tt) {
1235 return nil
1236 }
1237 base := tt.Base.Copy(fn, skip)
1238 if base == nil {
1239 return fn(tt)
1240 }
1241 tt = &TransformedType{Name: tt.Name, Base: base}
1242 if r := fn(tt); r != nil {
1243 return r
1244 }
1245 return tt
1246 }
1247
1248 func (tt *TransformedType) GoString() string {
1249 return tt.goString(0, "")
1250 }
1251
1252 func (tt *TransformedType) goString(indent int, field string) string {
1253 return fmt.Sprintf("%*s%sTransformedType: %s\n%s", indent, "", field,
1254 tt.Name, tt.Base.goString(indent+2, "Base: "))
1255 }
1256
1257 // VendorQualifier is a type qualified by a vendor-specific qualifier.
1258 type VendorQualifier struct {
1259 Qualifier AST
1260 Type AST
1261 }
1262
1263 func (vq *VendorQualifier) print(ps *printState) {
1264 if ps.llvmStyle {
1265 ps.print(vq.Type)
1266 vq.printInner(ps)
1267 } else {
1268 ps.inner = append(ps.inner, vq)
1269 ps.print(vq.Type)
1270 if len(ps.inner) > 0 {
1271 ps.printOneInner(nil)
1272 }
1273 }
1274 }
1275
1276 func (vq *VendorQualifier) printInner(ps *printState) {
1277 ps.writeByte(' ')
1278 ps.print(vq.Qualifier)
1279 }
1280
1281 func (vq *VendorQualifier) Traverse(fn func(AST) bool) {
1282 if fn(vq) {
1283 vq.Qualifier.Traverse(fn)
1284 vq.Type.Traverse(fn)
1285 }
1286 }
1287
1288 func (vq *VendorQualifier) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1289 if skip(vq) {
1290 return nil
1291 }
1292 qualifier := vq.Qualifier.Copy(fn, skip)
1293 typ := vq.Type.Copy(fn, skip)
1294 if qualifier == nil && typ == nil {
1295 return fn(vq)
1296 }
1297 if qualifier == nil {
1298 qualifier = vq.Qualifier
1299 }
1300 if typ == nil {
1301 typ = vq.Type
1302 }
1303 vq = &VendorQualifier{Qualifier: qualifier, Type: vq.Type}
1304 if r := fn(vq); r != nil {
1305 return r
1306 }
1307 return vq
1308 }
1309
1310 func (vq *VendorQualifier) GoString() string {
1311 return vq.goString(0, "")
1312 }
1313
1314 func (vq *VendorQualifier) goString(indent int, field string) string {
1315 return fmt.Sprintf("%*s%sVendorQualifier:\n%s\n%s", indent, "", field,
1316 vq.Qualifier.goString(indent+2, "Qualifier: "),
1317 vq.Type.goString(indent+2, "Type: "))
1318 }
1319
1320 // ArrayType is an array type.
1321 type ArrayType struct {
1322 Dimension AST
1323 Element AST
1324 }
1325
1326 func (at *ArrayType) print(ps *printState) {
1327 // Pass the array type down as an inner type so that we print
1328 // multi-dimensional arrays correctly.
1329 ps.inner = append(ps.inner, at)
1330 ps.print(at.Element)
1331 if ln := len(ps.inner); ln > 0 {
1332 ps.inner = ps.inner[:ln-1]
1333 at.printDimension(ps)
1334 }
1335 }
1336
1337 func (at *ArrayType) printInner(ps *printState) {
1338 at.printDimension(ps)
1339 }
1340
1341 // Print the array dimension.
1342 func (at *ArrayType) printDimension(ps *printState) {
1343 space := " "
1344 for len(ps.inner) > 0 {
1345 // We haven't gotten to the real type yet. Use
1346 // parentheses around that type, except that if it is
1347 // an array type we print it as a multi-dimensional
1348 // array
1349 in := ps.inner[len(ps.inner)-1]
1350 if twq, ok := in.(*TypeWithQualifiers); ok {
1351 in = twq.Base
1352 }
1353 if _, ok := in.(*ArrayType); ok {
1354 if in == ps.inner[len(ps.inner)-1] {
1355 space = ""
1356 }
1357 ps.printOneInner(nil)
1358 } else {
1359 ps.writeByte(' ')
1360 ps.startScope('(')
1361 ps.printInner(false)
1362 ps.endScope(')')
1363 }
1364 }
1365 ps.writeString(space)
1366 ps.writeByte('[')
1367 ps.print(at.Dimension)
1368 ps.writeByte(']')
1369 }
1370
1371 func (at *ArrayType) Traverse(fn func(AST) bool) {
1372 if fn(at) {
1373 at.Dimension.Traverse(fn)
1374 at.Element.Traverse(fn)
1375 }
1376 }
1377
1378 func (at *ArrayType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1379 if skip(at) {
1380 return nil
1381 }
1382 dimension := at.Dimension.Copy(fn, skip)
1383 element := at.Element.Copy(fn, skip)
1384 if dimension == nil && element == nil {
1385 return fn(at)
1386 }
1387 if dimension == nil {
1388 dimension = at.Dimension
1389 }
1390 if element == nil {
1391 element = at.Element
1392 }
1393 at = &ArrayType{Dimension: dimension, Element: element}
1394 if r := fn(at); r != nil {
1395 return r
1396 }
1397 return at
1398 }
1399
1400 func (at *ArrayType) GoString() string {
1401 return at.goString(0, "")
1402 }
1403
1404 func (at *ArrayType) goString(indent int, field string) string {
1405 return fmt.Sprintf("%*s%sArrayType:\n%s\n%s", indent, "", field,
1406 at.Dimension.goString(indent+2, "Dimension: "),
1407 at.Element.goString(indent+2, "Element: "))
1408 }
1409
1410 // FunctionType is a function type.
1411 type FunctionType struct {
1412 Return AST
1413 Args []AST
1414
1415 // The forLocalName field reports whether this FunctionType
1416 // was created for a local name. With the default GNU demangling
1417 // output we don't print the return type in that case.
1418 ForLocalName bool
1419 }
1420
1421 func (ft *FunctionType) print(ps *printState) {
1422 retType := ft.Return
1423 if ft.ForLocalName && (!ps.enclosingParams || !ps.llvmStyle) {
1424 retType = nil
1425 }
1426 if retType != nil {
1427 // Pass the return type as an inner type in order to
1428 // print the arguments in the right location.
1429 ps.inner = append(ps.inner, ft)
1430 ps.print(retType)
1431 if len(ps.inner) == 0 {
1432 // Everything was printed.
1433 return
1434 }
1435 ps.inner = ps.inner[:len(ps.inner)-1]
1436 ps.writeByte(' ')
1437 }
1438 ft.printArgs(ps)
1439 }
1440
1441 func (ft *FunctionType) printInner(ps *printState) {
1442 ft.printArgs(ps)
1443 }
1444
1445 // printArgs prints the arguments of a function type. It looks at the
1446 // inner types for spacing.
1447 func (ft *FunctionType) printArgs(ps *printState) {
1448 paren := false
1449 space := false
1450 for i := len(ps.inner) - 1; i >= 0; i-- {
1451 switch ps.inner[i].(type) {
1452 case *PointerType, *ReferenceType, *RvalueReferenceType:
1453 paren = true
1454 case *TypeWithQualifiers, *ComplexType, *ImaginaryType, *PtrMem:
1455 space = true
1456 paren = true
1457 }
1458 if paren {
1459 break
1460 }
1461 }
1462
1463 if paren {
1464 if !space && (ps.last != '(' && ps.last != '*') {
1465 space = true
1466 }
1467 if space && ps.last != ' ' {
1468 ps.writeByte(' ')
1469 }
1470 ps.startScope('(')
1471 }
1472
1473 save := ps.printInner(true)
1474
1475 if paren {
1476 ps.endScope(')')
1477 }
1478
1479 ps.startScope('(')
1480 if !ft.ForLocalName || ps.enclosingParams {
1481 first := true
1482 for _, a := range ft.Args {
1483 if ps.isEmpty(a) {
1484 continue
1485 }
1486 if !first {
1487 ps.writeString(", ")
1488 }
1489 ps.print(a)
1490 first = false
1491 }
1492 }
1493 ps.endScope(')')
1494
1495 ps.inner = save
1496 ps.printInner(false)
1497 }
1498
1499 func (ft *FunctionType) Traverse(fn func(AST) bool) {
1500 if fn(ft) {
1501 if ft.Return != nil {
1502 ft.Return.Traverse(fn)
1503 }
1504 for _, a := range ft.Args {
1505 a.Traverse(fn)
1506 }
1507 }
1508 }
1509
1510 func (ft *FunctionType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1511 if skip(ft) {
1512 return nil
1513 }
1514 changed := false
1515 var ret AST
1516 if ft.Return != nil {
1517 ret = ft.Return.Copy(fn, skip)
1518 if ret == nil {
1519 ret = ft.Return
1520 } else {
1521 changed = true
1522 }
1523 }
1524 args := make([]AST, len(ft.Args))
1525 for i, a := range ft.Args {
1526 ac := a.Copy(fn, skip)
1527 if ac == nil {
1528 args[i] = a
1529 } else {
1530 args[i] = ac
1531 changed = true
1532 }
1533 }
1534 if !changed {
1535 return fn(ft)
1536 }
1537 ft = &FunctionType{
1538 Return: ret,
1539 Args: args,
1540 ForLocalName: ft.ForLocalName,
1541 }
1542 if r := fn(ft); r != nil {
1543 return r
1544 }
1545 return ft
1546 }
1547
1548 func (ft *FunctionType) GoString() string {
1549 return ft.goString(0, "")
1550 }
1551
1552 func (ft *FunctionType) goString(indent int, field string) string {
1553 var forLocalName string
1554 if ft.ForLocalName {
1555 forLocalName = " ForLocalName: true"
1556 }
1557 var r string
1558 if ft.Return == nil {
1559 r = fmt.Sprintf("%*sReturn: nil", indent+2, "")
1560 } else {
1561 r = ft.Return.goString(indent+2, "Return: ")
1562 }
1563 var args string
1564 if len(ft.Args) == 0 {
1565 args = fmt.Sprintf("%*sArgs: nil", indent+2, "")
1566 } else {
1567 args = fmt.Sprintf("%*sArgs:", indent+2, "")
1568 for i, a := range ft.Args {
1569 args += "\n"
1570 args += a.goString(indent+4, fmt.Sprintf("%d: ", i))
1571 }
1572 }
1573 return fmt.Sprintf("%*s%sFunctionType:%s\n%s\n%s", indent, "", field,
1574 forLocalName, r, args)
1575 }
1576
1577 // FunctionParam is a parameter of a function, used for last-specified
1578 // return type in a closure.
1579 type FunctionParam struct {
1580 Index int
1581 }
1582
1583 func (fp *FunctionParam) print(ps *printState) {
1584 if fp.Index == 0 {
1585 ps.writeString("this")
1586 } else if ps.llvmStyle {
1587 if fp.Index == 1 {
1588 ps.writeString("fp")
1589 } else {
1590 fmt.Fprintf(&ps.buf, "fp%d", fp.Index-2)
1591 }
1592 } else {
1593 fmt.Fprintf(&ps.buf, "{parm#%d}", fp.Index)
1594 }
1595 }
1596
1597 func (fp *FunctionParam) Traverse(fn func(AST) bool) {
1598 fn(fp)
1599 }
1600
1601 func (fp *FunctionParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1602 if skip(fp) {
1603 return nil
1604 }
1605 return fn(fp)
1606 }
1607
1608 func (fp *FunctionParam) GoString() string {
1609 return fp.goString(0, "")
1610 }
1611
1612 func (fp *FunctionParam) goString(indent int, field string) string {
1613 return fmt.Sprintf("%*s%sFunctionParam: %d", indent, "", field, fp.Index)
1614 }
1615
1616 func (fp *FunctionParam) prec() precedence {
1617 return precPrimary
1618 }
1619
1620 // PtrMem is a pointer-to-member expression.
1621 type PtrMem struct {
1622 Class AST
1623 Member AST
1624 }
1625
1626 func (pm *PtrMem) print(ps *printState) {
1627 ps.inner = append(ps.inner, pm)
1628 ps.print(pm.Member)
1629 if len(ps.inner) > 0 {
1630 ps.printOneInner(nil)
1631 }
1632 }
1633
1634 func (pm *PtrMem) printInner(ps *printState) {
1635 if ps.last != '(' {
1636 ps.writeByte(' ')
1637 }
1638 ps.print(pm.Class)
1639 ps.writeString("::*")
1640 }
1641
1642 func (pm *PtrMem) Traverse(fn func(AST) bool) {
1643 if fn(pm) {
1644 pm.Class.Traverse(fn)
1645 pm.Member.Traverse(fn)
1646 }
1647 }
1648
1649 func (pm *PtrMem) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1650 if skip(pm) {
1651 return nil
1652 }
1653 class := pm.Class.Copy(fn, skip)
1654 member := pm.Member.Copy(fn, skip)
1655 if class == nil && member == nil {
1656 return fn(pm)
1657 }
1658 if class == nil {
1659 class = pm.Class
1660 }
1661 if member == nil {
1662 member = pm.Member
1663 }
1664 pm = &PtrMem{Class: class, Member: member}
1665 if r := fn(pm); r != nil {
1666 return r
1667 }
1668 return pm
1669 }
1670
1671 func (pm *PtrMem) GoString() string {
1672 return pm.goString(0, "")
1673 }
1674
1675 func (pm *PtrMem) goString(indent int, field string) string {
1676 return fmt.Sprintf("%*s%sPtrMem:\n%s\n%s", indent, "", field,
1677 pm.Class.goString(indent+2, "Class: "),
1678 pm.Member.goString(indent+2, "Member: "))
1679 }
1680
1681 // FixedType is a fixed numeric type of unknown size.
1682 type FixedType struct {
1683 Base AST
1684 Accum bool
1685 Sat bool
1686 }
1687
1688 func (ft *FixedType) print(ps *printState) {
1689 if ft.Sat {
1690 ps.writeString("_Sat ")
1691 }
1692 if bt, ok := ft.Base.(*BuiltinType); ok && bt.Name == "int" {
1693 // The standard demangler skips printing "int".
1694 } else {
1695 ps.print(ft.Base)
1696 ps.writeByte(' ')
1697 }
1698 if ft.Accum {
1699 ps.writeString("_Accum")
1700 } else {
1701 ps.writeString("_Fract")
1702 }
1703 }
1704
1705 func (ft *FixedType) Traverse(fn func(AST) bool) {
1706 if fn(ft) {
1707 ft.Base.Traverse(fn)
1708 }
1709 }
1710
1711 func (ft *FixedType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1712 if skip(ft) {
1713 return nil
1714 }
1715 base := ft.Base.Copy(fn, skip)
1716 if base == nil {
1717 return fn(ft)
1718 }
1719 ft = &FixedType{Base: base, Accum: ft.Accum, Sat: ft.Sat}
1720 if r := fn(ft); r != nil {
1721 return r
1722 }
1723 return ft
1724 }
1725
1726 func (ft *FixedType) GoString() string {
1727 return ft.goString(0, "")
1728 }
1729
1730 func (ft *FixedType) goString(indent int, field string) string {
1731 return fmt.Sprintf("%*s%sFixedType: Accum: %t; Sat: %t\n%s", indent, "", field,
1732 ft.Accum, ft.Sat,
1733 ft.Base.goString(indent+2, "Base: "))
1734 }
1735
1736 // BinaryFP is a binary floating-point type.
1737 type BinaryFP struct {
1738 Bits int
1739 Suffix string
1740 }
1741
1742 func (bfp *BinaryFP) print(ps *printState) {
1743 fmt.Fprintf(&ps.buf, "_Float%d%s", bfp.Bits, bfp.Suffix)
1744 }
1745
1746 func (bfp *BinaryFP) Traverse(fn func(AST) bool) {
1747 fn(bfp)
1748 }
1749
1750 func (bfp *BinaryFP) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1751 if skip(bfp) {
1752 return nil
1753 }
1754 return fn(bfp)
1755 }
1756
1757 func (bfp *BinaryFP) GoString() string {
1758 return bfp.goString(0, "")
1759 }
1760
1761 func (bfp *BinaryFP) goString(indent int, field string) string {
1762 return fmt.Sprintf("%*s%sBinaryFP: Bits: %d Suffix: %s", indent, "", field, bfp.Bits, bfp.Suffix)
1763 }
1764
1765 // BitIntType is the C++23 _BitInt(N) type.
1766 type BitIntType struct {
1767 Size AST
1768 Signed bool
1769 }
1770
1771 func (bt *BitIntType) print(ps *printState) {
1772 if !bt.Signed {
1773 ps.writeString("unsigned ")
1774 }
1775 ps.writeString("_BitInt")
1776 ps.startScope('(')
1777 ps.print(bt.Size)
1778 ps.endScope(')')
1779 }
1780
1781 func (bt *BitIntType) Traverse(fn func(AST) bool) {
1782 if fn(bt) {
1783 bt.Size.Traverse(fn)
1784 }
1785 }
1786
1787 func (bt *BitIntType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1788 if skip(bt) {
1789 return nil
1790 }
1791 size := bt.Size.Copy(fn, skip)
1792 if size == nil {
1793 return fn(bt)
1794 }
1795 bt = &BitIntType{Size: size, Signed: bt.Signed}
1796 if r := fn(bt); r != nil {
1797 return r
1798 }
1799 return bt
1800 }
1801
1802 func (bt *BitIntType) GoString() string {
1803 return bt.goString(0, "")
1804 }
1805
1806 func (bt *BitIntType) goString(indent int, field string) string {
1807 return fmt.Sprintf("%*s%sBitIntType: Signed: %t\n%s", indent, "", field,
1808 bt.Signed,
1809 bt.Size.goString(indent+2, "Size: "))
1810 }
1811
1812 // VectorType is a vector type.
1813 type VectorType struct {
1814 Dimension AST
1815 Base AST
1816 }
1817
1818 func (vt *VectorType) print(ps *printState) {
1819 ps.inner = append(ps.inner, vt)
1820 ps.print(vt.Base)
1821 if len(ps.inner) > 0 {
1822 ps.printOneInner(nil)
1823 }
1824 }
1825
1826 func (vt *VectorType) printInner(ps *printState) {
1827 end := byte(')')
1828 if ps.llvmStyle {
1829 ps.writeString(" vector[")
1830 end = ']'
1831 } else {
1832 ps.writeString(" __vector(")
1833 }
1834 ps.print(vt.Dimension)
1835 ps.writeByte(end)
1836 }
1837
1838 func (vt *VectorType) Traverse(fn func(AST) bool) {
1839 if fn(vt) {
1840 vt.Dimension.Traverse(fn)
1841 vt.Base.Traverse(fn)
1842 }
1843 }
1844
1845 func (vt *VectorType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1846 if skip(vt) {
1847 return nil
1848 }
1849 dimension := vt.Dimension.Copy(fn, skip)
1850 base := vt.Base.Copy(fn, skip)
1851 if dimension == nil && base == nil {
1852 return fn(vt)
1853 }
1854 if dimension == nil {
1855 dimension = vt.Dimension
1856 }
1857 if base == nil {
1858 base = vt.Base
1859 }
1860 vt = &VectorType{Dimension: dimension, Base: base}
1861 if r := fn(vt); r != nil {
1862 return r
1863 }
1864 return vt
1865 }
1866
1867 func (vt *VectorType) GoString() string {
1868 return vt.goString(0, "")
1869 }
1870
1871 func (vt *VectorType) goString(indent int, field string) string {
1872 return fmt.Sprintf("%*s%sVectorType:\n%s\n%s", indent, "", field,
1873 vt.Dimension.goString(indent+2, "Dimension: "),
1874 vt.Base.goString(indent+2, "Base: "))
1875 }
1876
1877 // ElaboratedType is an elaborated struct/union/enum type.
1878 type ElaboratedType struct {
1879 Kind string
1880 Type AST
1881 }
1882
1883 func (et *ElaboratedType) print(ps *printState) {
1884 ps.writeString(et.Kind)
1885 ps.writeString(" ")
1886 et.Type.print(ps)
1887 }
1888
1889 func (et *ElaboratedType) Traverse(fn func(AST) bool) {
1890 if fn(et) {
1891 et.Type.Traverse(fn)
1892 }
1893 }
1894
1895 func (et *ElaboratedType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1896 if skip(et) {
1897 return nil
1898 }
1899 typ := et.Type.Copy(fn, skip)
1900 if typ == nil {
1901 return fn(et)
1902 }
1903 et = &ElaboratedType{Kind: et.Kind, Type: typ}
1904 if r := fn(et); r != nil {
1905 return r
1906 }
1907 return et
1908 }
1909
1910 func (et *ElaboratedType) GoString() string {
1911 return et.goString(0, "")
1912 }
1913
1914 func (et *ElaboratedType) goString(indent int, field string) string {
1915 return fmt.Sprintf("%*s%sElaboratedtype: Kind: %s\n%s", indent, "", field,
1916 et.Kind, et.Type.goString(indent+2, "Expr: "))
1917 }
1918
1919 // Decltype is the decltype operator.
1920 type Decltype struct {
1921 Expr AST
1922 }
1923
1924 func (dt *Decltype) print(ps *printState) {
1925 ps.writeString("decltype")
1926 if !ps.llvmStyle {
1927 ps.writeString(" ")
1928 }
1929 ps.startScope('(')
1930 ps.print(dt.Expr)
1931 ps.endScope(')')
1932 }
1933
1934 func (dt *Decltype) Traverse(fn func(AST) bool) {
1935 if fn(dt) {
1936 dt.Expr.Traverse(fn)
1937 }
1938 }
1939
1940 func (dt *Decltype) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1941 if skip(dt) {
1942 return nil
1943 }
1944 expr := dt.Expr.Copy(fn, skip)
1945 if expr == nil {
1946 return fn(dt)
1947 }
1948 dt = &Decltype{Expr: expr}
1949 if r := fn(dt); r != nil {
1950 return r
1951 }
1952 return dt
1953 }
1954
1955 func (dt *Decltype) GoString() string {
1956 return dt.goString(0, "")
1957 }
1958
1959 func (dt *Decltype) goString(indent int, field string) string {
1960 return fmt.Sprintf("%*s%sDecltype:\n%s", indent, "", field,
1961 dt.Expr.goString(indent+2, "Expr: "))
1962 }
1963
1964 // Operator is an operator.
1965 type Operator struct {
1966 Name string
1967 precedence precedence
1968 }
1969
1970 func (op *Operator) print(ps *printState) {
1971 ps.writeString("operator")
1972 if isLower(op.Name[0]) {
1973 ps.writeByte(' ')
1974 }
1975 n := op.Name
1976 n = strings.TrimSuffix(n, " ")
1977 ps.writeString(n)
1978 }
1979
1980 func (op *Operator) Traverse(fn func(AST) bool) {
1981 fn(op)
1982 }
1983
1984 func (op *Operator) Copy(fn func(AST) AST, skip func(AST) bool) AST {
1985 if skip(op) {
1986 return nil
1987 }
1988 return fn(op)
1989 }
1990
1991 func (op *Operator) GoString() string {
1992 return op.goString(0, "")
1993 }
1994
1995 func (op *Operator) goString(indent int, field string) string {
1996 return fmt.Sprintf("%*s%sOperator: %s", indent, "", field, op.Name)
1997 }
1998
1999 func (op *Operator) prec() precedence {
2000 return op.precedence
2001 }
2002
2003 // Constructor is a constructor.
2004 type Constructor struct {
2005 Name AST
2006 Base AST // base class of inheriting constructor
2007 }
2008
2009 func (c *Constructor) print(ps *printState) {
2010 ps.print(c.Name)
2011 // We don't include the base class in the demangled string.
2012 }
2013
2014 func (c *Constructor) Traverse(fn func(AST) bool) {
2015 if fn(c) {
2016 c.Name.Traverse(fn)
2017 if c.Base != nil {
2018 c.Base.Traverse(fn)
2019 }
2020 }
2021 }
2022
2023 func (c *Constructor) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2024 if skip(c) {
2025 return nil
2026 }
2027 name := c.Name.Copy(fn, skip)
2028 var base AST
2029 if c.Base != nil {
2030 base = c.Base.Copy(fn, skip)
2031 }
2032 if name == nil && base == nil {
2033 return fn(c)
2034 }
2035 if name == nil {
2036 name = c.Name
2037 }
2038 if base == nil {
2039 base = c.Base
2040 }
2041 c = &Constructor{Name: name, Base: base}
2042 if r := fn(c); r != nil {
2043 return r
2044 }
2045 return c
2046 }
2047
2048 func (c *Constructor) GoString() string {
2049 return c.goString(0, "")
2050 }
2051
2052 func (c *Constructor) goString(indent int, field string) string {
2053 var sb strings.Builder
2054 fmt.Fprintf(&sb, "%*s%sConstructor:\n", indent, "", field)
2055 if c.Base != nil {
2056 fmt.Fprintf(&sb, "%s\n", c.Base.goString(indent+2, "Base: "))
2057 }
2058 fmt.Fprintf(&sb, "%s", c.Name.goString(indent+2, "Name: "))
2059 return sb.String()
2060 }
2061
2062 // Destructor is a destructor.
2063 type Destructor struct {
2064 Name AST
2065 }
2066
2067 func (d *Destructor) print(ps *printState) {
2068 ps.writeByte('~')
2069 ps.print(d.Name)
2070 }
2071
2072 func (d *Destructor) Traverse(fn func(AST) bool) {
2073 if fn(d) {
2074 d.Name.Traverse(fn)
2075 }
2076 }
2077
2078 func (d *Destructor) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2079 if skip(d) {
2080 return nil
2081 }
2082 name := d.Name.Copy(fn, skip)
2083 if name == nil {
2084 return fn(d)
2085 }
2086 d = &Destructor{Name: name}
2087 if r := fn(d); r != nil {
2088 return r
2089 }
2090 return d
2091 }
2092
2093 func (d *Destructor) GoString() string {
2094 return d.goString(0, "")
2095 }
2096
2097 func (d *Destructor) goString(indent int, field string) string {
2098 return fmt.Sprintf("%*s%sDestructor:\n%s", indent, "", field, d.Name.goString(indent+2, "Name: "))
2099 }
2100
2101 // GlobalCDtor is a global constructor or destructor.
2102 type GlobalCDtor struct {
2103 Ctor bool
2104 Key AST
2105 }
2106
2107 func (gcd *GlobalCDtor) print(ps *printState) {
2108 ps.writeString("global ")
2109 if gcd.Ctor {
2110 ps.writeString("constructors")
2111 } else {
2112 ps.writeString("destructors")
2113 }
2114 ps.writeString(" keyed to ")
2115 ps.print(gcd.Key)
2116 }
2117
2118 func (gcd *GlobalCDtor) Traverse(fn func(AST) bool) {
2119 if fn(gcd) {
2120 gcd.Key.Traverse(fn)
2121 }
2122 }
2123
2124 func (gcd *GlobalCDtor) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2125 if skip(gcd) {
2126 return nil
2127 }
2128 key := gcd.Key.Copy(fn, skip)
2129 if key == nil {
2130 return fn(gcd)
2131 }
2132 gcd = &GlobalCDtor{Ctor: gcd.Ctor, Key: key}
2133 if r := fn(gcd); r != nil {
2134 return r
2135 }
2136 return gcd
2137 }
2138
2139 func (gcd *GlobalCDtor) GoString() string {
2140 return gcd.goString(0, "")
2141 }
2142
2143 func (gcd *GlobalCDtor) goString(indent int, field string) string {
2144 return fmt.Sprintf("%*s%sGlobalCDtor: Ctor: %t\n%s", indent, "", field,
2145 gcd.Ctor, gcd.Key.goString(indent+2, "Key: "))
2146 }
2147
2148 // TaggedName is a name with an ABI tag.
2149 type TaggedName struct {
2150 Name AST
2151 Tag AST
2152 }
2153
2154 func (t *TaggedName) print(ps *printState) {
2155 ps.print(t.Name)
2156 ps.writeString("[abi:")
2157 ps.print(t.Tag)
2158 ps.writeByte(']')
2159 }
2160
2161 func (t *TaggedName) Traverse(fn func(AST) bool) {
2162 if fn(t) {
2163 t.Name.Traverse(fn)
2164 t.Tag.Traverse(fn)
2165 }
2166 }
2167
2168 func (t *TaggedName) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2169 if skip(t) {
2170 return nil
2171 }
2172 name := t.Name.Copy(fn, skip)
2173 tag := t.Tag.Copy(fn, skip)
2174 if name == nil && tag == nil {
2175 return fn(t)
2176 }
2177 if name == nil {
2178 name = t.Name
2179 }
2180 if tag == nil {
2181 tag = t.Tag
2182 }
2183 t = &TaggedName{Name: name, Tag: tag}
2184 if r := fn(t); r != nil {
2185 return r
2186 }
2187 return t
2188 }
2189
2190 func (t *TaggedName) GoString() string {
2191 return t.goString(0, "")
2192 }
2193
2194 func (t *TaggedName) goString(indent int, field string) string {
2195 return fmt.Sprintf("%*s%sTaggedName:\n%s\n%s", indent, "", field,
2196 t.Name.goString(indent+2, "Name: "),
2197 t.Tag.goString(indent+2, "Tag: "))
2198 }
2199
2200 // PackExpansion is a pack expansion. The Pack field may be nil.
2201 type PackExpansion struct {
2202 Base AST
2203 Pack *ArgumentPack
2204 }
2205
2206 func (pe *PackExpansion) print(ps *printState) {
2207 // We normally only get here if the simplify function was
2208 // unable to locate and expand the pack.
2209 if pe.Pack == nil {
2210 if ps.llvmStyle {
2211 ps.print(pe.Base)
2212 } else {
2213 parenthesize(ps, pe.Base)
2214 ps.writeString("...")
2215 }
2216 } else {
2217 ps.print(pe.Base)
2218 }
2219 }
2220
2221 func (pe *PackExpansion) Traverse(fn func(AST) bool) {
2222 if fn(pe) {
2223 pe.Base.Traverse(fn)
2224 // Don't traverse Template--it points elsewhere in the AST.
2225 }
2226 }
2227
2228 func (pe *PackExpansion) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2229 if skip(pe) {
2230 return nil
2231 }
2232 base := pe.Base.Copy(fn, skip)
2233 if base == nil {
2234 return fn(pe)
2235 }
2236 pe = &PackExpansion{Base: base, Pack: pe.Pack}
2237 if r := fn(pe); r != nil {
2238 return r
2239 }
2240 return pe
2241 }
2242
2243 func (pe *PackExpansion) GoString() string {
2244 return pe.goString(0, "")
2245 }
2246
2247 func (pe *PackExpansion) goString(indent int, field string) string {
2248 return fmt.Sprintf("%*s%sPackExpansion: Pack: %p\n%s", indent, "", field,
2249 pe.Pack, pe.Base.goString(indent+2, "Base: "))
2250 }
2251
2252 // ArgumentPack is an argument pack.
2253 type ArgumentPack struct {
2254 Args []AST
2255 }
2256
2257 func (ap *ArgumentPack) print(ps *printState) {
2258 for i, a := range ap.Args {
2259 if i > 0 {
2260 ps.writeString(", ")
2261 }
2262 ps.print(a)
2263 }
2264 }
2265
2266 func (ap *ArgumentPack) Traverse(fn func(AST) bool) {
2267 if fn(ap) {
2268 for _, a := range ap.Args {
2269 a.Traverse(fn)
2270 }
2271 }
2272 }
2273
2274 func (ap *ArgumentPack) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2275 if skip(ap) {
2276 return nil
2277 }
2278 args := make([]AST, len(ap.Args))
2279 changed := false
2280 for i, a := range ap.Args {
2281 ac := a.Copy(fn, skip)
2282 if ac == nil {
2283 args[i] = a
2284 } else {
2285 args[i] = ac
2286 changed = true
2287 }
2288 }
2289 if !changed {
2290 return fn(ap)
2291 }
2292 ap = &ArgumentPack{Args: args}
2293 if r := fn(ap); r != nil {
2294 return r
2295 }
2296 return ap
2297 }
2298
2299 func (ap *ArgumentPack) GoString() string {
2300 return ap.goString(0, "")
2301 }
2302
2303 func (ap *ArgumentPack) goString(indent int, field string) string {
2304 if len(ap.Args) == 0 {
2305 return fmt.Sprintf("%*s%sArgumentPack: nil", indent, "", field)
2306 }
2307 s := fmt.Sprintf("%*s%sArgumentPack:", indent, "", field)
2308 for i, a := range ap.Args {
2309 s += "\n"
2310 s += a.goString(indent+2, fmt.Sprintf("%d: ", i))
2311 }
2312 return s
2313 }
2314
2315 // SizeofPack is the sizeof operator applied to an argument pack.
2316 type SizeofPack struct {
2317 Pack *ArgumentPack
2318 }
2319
2320 func (sp *SizeofPack) print(ps *printState) {
2321 if ps.llvmStyle {
2322 ps.writeString("sizeof...")
2323 ps.startScope('(')
2324 ps.print(sp.Pack)
2325 ps.endScope(')')
2326 } else {
2327 ps.writeString(fmt.Sprintf("%d", len(sp.Pack.Args)))
2328 }
2329 }
2330
2331 func (sp *SizeofPack) Traverse(fn func(AST) bool) {
2332 fn(sp)
2333 // Don't traverse the pack--it points elsewhere in the AST.
2334 }
2335
2336 func (sp *SizeofPack) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2337 if skip(sp) {
2338 return nil
2339 }
2340 sp = &SizeofPack{Pack: sp.Pack}
2341 if r := fn(sp); r != nil {
2342 return r
2343 }
2344 return sp
2345 }
2346
2347 func (sp *SizeofPack) GoString() string {
2348 return sp.goString(0, "")
2349 }
2350
2351 func (sp *SizeofPack) goString(indent int, field string) string {
2352 return fmt.Sprintf("%*s%sSizeofPack: Pack: %p", indent, "", field, sp.Pack)
2353 }
2354
2355 // SizeofArgs is the size of a captured template parameter pack from
2356 // an alias template.
2357 type SizeofArgs struct {
2358 Args []AST
2359 }
2360
2361 func (sa *SizeofArgs) print(ps *printState) {
2362 c := 0
2363 for _, a := range sa.Args {
2364 if ap, ok := a.(*ArgumentPack); ok {
2365 c += len(ap.Args)
2366 } else if el, ok := a.(*ExprList); ok {
2367 c += len(el.Exprs)
2368 } else {
2369 c++
2370 }
2371 }
2372 ps.writeString(fmt.Sprintf("%d", c))
2373 }
2374
2375 func (sa *SizeofArgs) Traverse(fn func(AST) bool) {
2376 if fn(sa) {
2377 for _, a := range sa.Args {
2378 a.Traverse(fn)
2379 }
2380 }
2381 }
2382
2383 func (sa *SizeofArgs) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2384 if skip(sa) {
2385 return nil
2386 }
2387 changed := false
2388 args := make([]AST, len(sa.Args))
2389 for i, a := range sa.Args {
2390 ac := a.Copy(fn, skip)
2391 if ac == nil {
2392 args[i] = a
2393 } else {
2394 args[i] = ac
2395 changed = true
2396 }
2397 }
2398 if !changed {
2399 return fn(sa)
2400 }
2401 sa = &SizeofArgs{Args: args}
2402 if r := fn(sa); r != nil {
2403 return r
2404 }
2405 return sa
2406 }
2407
2408 func (sa *SizeofArgs) GoString() string {
2409 return sa.goString(0, "")
2410 }
2411
2412 func (sa *SizeofArgs) goString(indent int, field string) string {
2413 var args string
2414 if len(sa.Args) == 0 {
2415 args = fmt.Sprintf("%*sArgs: nil", indent+2, "")
2416 } else {
2417 args = fmt.Sprintf("%*sArgs:", indent+2, "")
2418 for i, a := range sa.Args {
2419 args += "\n"
2420 args += a.goString(indent+4, fmt.Sprintf("%d: ", i))
2421 }
2422 }
2423 return fmt.Sprintf("%*s%sSizeofArgs:\n%s", indent, "", field, args)
2424 }
2425
2426 // TemplateParamName is the name of a template parameter that the
2427 // demangler introduced for a lambda that has explicit template
2428 // parameters. This is a prefix with an index.
2429 type TemplateParamName struct {
2430 Prefix string
2431 Index int
2432 }
2433
2434 func (tpn *TemplateParamName) print(ps *printState) {
2435 ps.writeString(tpn.Prefix)
2436 if ps.llvmStyle {
2437 if tpn.Index > 0 {
2438 ps.writeString(fmt.Sprintf("%d", tpn.Index-1))
2439 }
2440 } else {
2441 ps.writeString(fmt.Sprintf("%d", tpn.Index))
2442 }
2443 }
2444
2445 func (tpn *TemplateParamName) Traverse(fn func(AST) bool) {
2446 fn(tpn)
2447 }
2448
2449 func (tpn *TemplateParamName) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2450 if skip(tpn) {
2451 return nil
2452 }
2453 return fn(tpn)
2454 }
2455
2456 func (tpn *TemplateParamName) GoString() string {
2457 return tpn.goString(0, "")
2458 }
2459
2460 func (tpn *TemplateParamName) goString(indent int, field string) string {
2461 return fmt.Sprintf("%*s%sTemplateParamName: %s%d", indent, "", field, tpn.Prefix, tpn.Index)
2462 }
2463
2464 // TypeTemplateParam is a type template parameter that appears in a
2465 // lambda with explicit template parameters.
2466 type TypeTemplateParam struct {
2467 Name AST
2468 }
2469
2470 func (ttp *TypeTemplateParam) print(ps *printState) {
2471 ps.writeString("typename")
2472 if ps.llvmStyle {
2473 ps.writeByte(' ')
2474 }
2475 ps.printInner(false)
2476 if ps.llvmStyle || !ps.lambdaTemplateArgs {
2477 if !ps.llvmStyle {
2478 ps.writeByte(' ')
2479 }
2480 ps.print(ttp.Name)
2481 }
2482 }
2483
2484 func (ttp *TypeTemplateParam) Traverse(fn func(AST) bool) {
2485 if fn(ttp) {
2486 ttp.Name.Traverse(fn)
2487 }
2488 }
2489
2490 func (ttp *TypeTemplateParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2491 if skip(ttp) {
2492 return nil
2493 }
2494 name := ttp.Name.Copy(fn, skip)
2495 if name == nil {
2496 return fn(ttp)
2497 }
2498 ttp = &TypeTemplateParam{Name: name}
2499 if r := fn(ttp); r != nil {
2500 return r
2501 }
2502 return ttp
2503 }
2504
2505 func (ttp *TypeTemplateParam) GoString() string {
2506 return ttp.goString(0, "")
2507 }
2508
2509 func (ttp *TypeTemplateParam) goString(indent int, field string) string {
2510 return fmt.Sprintf("%*s%sTypeTemplateParam:\n%s", indent, "", field,
2511 ttp.Name.goString(indent+2, "Name"))
2512 }
2513
2514 // NonTypeTemplateParam is a non-type template parameter that appears
2515 // in a lambda with explicit template parameters.
2516 type NonTypeTemplateParam struct {
2517 Name AST
2518 Type AST
2519 }
2520
2521 func (nttp *NonTypeTemplateParam) print(ps *printState) {
2522 ps.inner = append(ps.inner, nttp)
2523 ps.print(nttp.Type)
2524 if len(ps.inner) > 0 {
2525 if ps.llvmStyle || !ps.lambdaTemplateArgs {
2526 ps.writeByte(' ')
2527 ps.print(nttp.Name)
2528 }
2529 ps.inner = ps.inner[:len(ps.inner)-1]
2530 }
2531 }
2532
2533 func (nttp *NonTypeTemplateParam) printInner(ps *printState) {
2534 ps.print(nttp.Name)
2535 }
2536
2537 func (nttp *NonTypeTemplateParam) Traverse(fn func(AST) bool) {
2538 if fn(nttp) {
2539 nttp.Name.Traverse(fn)
2540 nttp.Type.Traverse(fn)
2541 }
2542 }
2543
2544 func (nttp *NonTypeTemplateParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2545 if skip(nttp) {
2546 return nil
2547 }
2548 name := nttp.Name.Copy(fn, skip)
2549 typ := nttp.Type.Copy(fn, skip)
2550 if name == nil && typ == nil {
2551 return fn(nttp)
2552 }
2553 if name == nil {
2554 name = nttp.Name
2555 }
2556 if typ == nil {
2557 typ = nttp.Type
2558 }
2559 nttp = &NonTypeTemplateParam{Name: name, Type: typ}
2560 if r := fn(nttp); r != nil {
2561 return r
2562 }
2563 return nttp
2564 }
2565
2566 func (nttp *NonTypeTemplateParam) GoString() string {
2567 return nttp.goString(0, "")
2568 }
2569
2570 func (nttp *NonTypeTemplateParam) goString(indent int, field string) string {
2571 return fmt.Sprintf("%*s%sNonTypeTemplateParam:\n%s\n%s", indent, "", field,
2572 nttp.Name.goString(indent+2, "Name: "),
2573 nttp.Type.goString(indent+2, "Type: "))
2574 }
2575
2576 // TemplateTemplateParam is a template template parameter that appears
2577 // in a lambda with explicit template parameters.
2578 type TemplateTemplateParam struct {
2579 Name AST
2580 Params []AST
2581 Constraint AST
2582 }
2583
2584 func (ttp *TemplateTemplateParam) print(ps *printState) {
2585 scopes := ps.scopes
2586 ps.scopes = 0
2587 lambdaTemplateArgs := ps.lambdaTemplateArgs
2588 ps.lambdaTemplateArgs = true
2589 inner := ps.inner
2590 ps.inner = nil
2591
2592 ps.writeString("template<")
2593 ps.printList(ttp.Params, nil)
2594 ps.writeString("> ")
2595 if ps.llvmStyle {
2596 ps.writeString("typename")
2597 } else {
2598 ps.writeString("class")
2599 }
2600
2601 ps.scopes = scopes
2602 ps.lambdaTemplateArgs = lambdaTemplateArgs
2603 ps.inner = inner
2604
2605 ps.printInner(false)
2606
2607 if ps.llvmStyle || !ps.lambdaTemplateArgs {
2608 ps.writeByte(' ')
2609 ps.print(ttp.Name)
2610 }
2611
2612 if ttp.Constraint != nil {
2613 ps.writeString(" requires ")
2614 ps.print(ttp.Constraint)
2615 }
2616 }
2617
2618 func (ttp *TemplateTemplateParam) Traverse(fn func(AST) bool) {
2619 if fn(ttp) {
2620 ttp.Name.Traverse(fn)
2621 for _, param := range ttp.Params {
2622 param.Traverse(fn)
2623 }
2624 if ttp.Constraint != nil {
2625 ttp.Constraint.Traverse(fn)
2626 }
2627 }
2628 }
2629
2630 func (ttp *TemplateTemplateParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2631 if skip(ttp) {
2632 return nil
2633 }
2634
2635 changed := false
2636
2637 name := ttp.Name.Copy(fn, skip)
2638 if name == nil {
2639 name = ttp.Name
2640 } else {
2641 changed = true
2642 }
2643
2644 params := make([]AST, len(ttp.Params))
2645 for i, p := range ttp.Params {
2646 pc := p.Copy(fn, skip)
2647 if pc == nil {
2648 params[i] = p
2649 } else {
2650 params[i] = pc
2651 changed = true
2652 }
2653 }
2654
2655 var constraint AST
2656 if ttp.Constraint != nil {
2657 constraint = ttp.Constraint.Copy(fn, skip)
2658 if constraint == nil {
2659 constraint = ttp.Constraint
2660 } else {
2661 changed = true
2662 }
2663 }
2664
2665 if !changed {
2666 return fn(ttp)
2667 }
2668
2669 ttp = &TemplateTemplateParam{
2670 Name: name,
2671 Params: params,
2672 Constraint: constraint,
2673 }
2674 if r := fn(ttp); r != nil {
2675 return r
2676 }
2677 return ttp
2678 }
2679
2680 func (ttp *TemplateTemplateParam) GoString() string {
2681 return ttp.goString(0, "")
2682 }
2683
2684 func (ttp *TemplateTemplateParam) goString(indent int, field string) string {
2685 var params strings.Builder
2686 fmt.Fprintf(&params, "%*sParams:", indent+2, "")
2687 for i, p := range ttp.Params {
2688 params.WriteByte('\n')
2689 params.WriteString(p.goString(indent+4, fmt.Sprintf("%d: ", i)))
2690 }
2691 var constraint string
2692 if ttp.Constraint == nil {
2693 constraint = fmt.Sprintf("%*sConstraint: nil", indent+2, "")
2694 } else {
2695 constraint = ttp.Constraint.goString(indent+2, "Constraint: ")
2696 }
2697 return fmt.Sprintf("%*s%sTemplateTemplateParam:\n%s\n%s\n%s", indent, "", field,
2698 ttp.Name.goString(indent+2, "Name: "),
2699 params.String(),
2700 constraint)
2701 }
2702
2703 // ConstrainedTypeTemplateParam is a constrained template type
2704 // parameter declaration.
2705 type ConstrainedTypeTemplateParam struct {
2706 Name AST
2707 Constraint AST
2708 }
2709
2710 func (cttp *ConstrainedTypeTemplateParam) print(ps *printState) {
2711 ps.inner = append(ps.inner, cttp)
2712 ps.print(cttp.Constraint)
2713 if len(ps.inner) > 0 {
2714 ps.writeByte(' ')
2715 ps.print(cttp.Name)
2716 ps.inner = ps.inner[:len(ps.inner)-1]
2717 }
2718 }
2719
2720 func (cttp *ConstrainedTypeTemplateParam) printInner(ps *printState) {
2721 ps.print(cttp.Name)
2722 }
2723
2724 func (cttp *ConstrainedTypeTemplateParam) Traverse(fn func(AST) bool) {
2725 if fn(cttp) {
2726 cttp.Name.Traverse(fn)
2727 cttp.Constraint.Traverse(fn)
2728 }
2729 }
2730
2731 func (cttp *ConstrainedTypeTemplateParam) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2732 if skip(cttp) {
2733 return nil
2734 }
2735 name := cttp.Name.Copy(fn, skip)
2736 constraint := cttp.Constraint.Copy(fn, skip)
2737 if name == nil && constraint == nil {
2738 return fn(cttp)
2739 }
2740 if name == nil {
2741 name = cttp.Name
2742 }
2743 if constraint == nil {
2744 constraint = cttp.Constraint
2745 }
2746 cttp = &ConstrainedTypeTemplateParam{Name: name, Constraint: constraint}
2747 if r := fn(cttp); r != nil {
2748 return r
2749 }
2750 return cttp
2751 }
2752
2753 func (cttp *ConstrainedTypeTemplateParam) GoString() string {
2754 return cttp.goString(0, "")
2755 }
2756
2757 func (cttp *ConstrainedTypeTemplateParam) goString(indent int, field string) string {
2758 return fmt.Sprintf("%*s%sConstrainedTypeTemplateParam\n%s\n%s", indent, "", field,
2759 cttp.Name.goString(indent+2, "Name: "),
2760 cttp.Constraint.goString(indent+2, "Constraint: "))
2761 }
2762
2763 // TemplateParamPack is a template parameter pack that appears in a
2764 // lambda with explicit template parameters.
2765 type TemplateParamPack struct {
2766 Param AST
2767 }
2768
2769 func (tpp *TemplateParamPack) print(ps *printState) {
2770 holdInner := ps.inner
2771 defer func() { ps.inner = holdInner }()
2772
2773 ps.inner = []AST{tpp}
2774 nttp, isNTTP := tpp.Param.(*NonTypeTemplateParam)
2775 if isNTTP {
2776 ps.print(nttp.Type)
2777 } else {
2778 ps.print(tpp.Param)
2779 }
2780 if len(ps.inner) > 0 {
2781 ps.writeString("...")
2782 if isNTTP && (ps.llvmStyle || !ps.lambdaTemplateArgs) {
2783 ps.writeByte(' ')
2784 ps.print(nttp.Name)
2785 }
2786 }
2787 }
2788
2789 func (tpp *TemplateParamPack) printInner(ps *printState) {
2790 ps.writeString("...")
2791 if nttp, ok := tpp.Param.(*NonTypeTemplateParam); ok {
2792 ps.print(nttp.Name)
2793 }
2794 }
2795
2796 func (tpp *TemplateParamPack) Traverse(fn func(AST) bool) {
2797 if fn(tpp) {
2798 tpp.Param.Traverse(fn)
2799 }
2800 }
2801
2802 func (tpp *TemplateParamPack) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2803 if skip(tpp) {
2804 return nil
2805 }
2806 param := tpp.Param.Copy(fn, skip)
2807 if param == nil {
2808 return fn(tpp)
2809 }
2810 tpp = &TemplateParamPack{Param: param}
2811 if r := fn(tpp); r != nil {
2812 return r
2813 }
2814 return tpp
2815 }
2816
2817 func (tpp *TemplateParamPack) GoString() string {
2818 return tpp.goString(0, "")
2819 }
2820
2821 func (tpp *TemplateParamPack) goString(indent int, field string) string {
2822 return fmt.Sprintf("%*s%sTemplateParamPack:\n%s", indent, "", field,
2823 tpp.Param.goString(indent+2, "Param: "))
2824 }
2825
2826 // Cast is a type cast.
2827 type Cast struct {
2828 To AST
2829 }
2830
2831 func (c *Cast) print(ps *printState) {
2832 ps.writeString("operator ")
2833 ps.print(c.To)
2834 }
2835
2836 func (c *Cast) Traverse(fn func(AST) bool) {
2837 if fn(c) {
2838 c.To.Traverse(fn)
2839 }
2840 }
2841
2842 func (c *Cast) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2843 if skip(c) {
2844 return nil
2845 }
2846 to := c.To.Copy(fn, skip)
2847 if to == nil {
2848 return fn(c)
2849 }
2850 c = &Cast{To: to}
2851 if r := fn(c); r != nil {
2852 return r
2853 }
2854 return c
2855 }
2856
2857 func (c *Cast) GoString() string {
2858 return c.goString(0, "")
2859 }
2860
2861 func (c *Cast) goString(indent int, field string) string {
2862 return fmt.Sprintf("%*s%sCast\n%s", indent, "", field,
2863 c.To.goString(indent+2, "To: "))
2864 }
2865
2866 func (c *Cast) prec() precedence {
2867 return precCast
2868 }
2869
2870 // The parenthesize function prints the string for val, wrapped in
2871 // parentheses if necessary.
2872 func parenthesize(ps *printState, val AST) {
2873 paren := false
2874 switch v := val.(type) {
2875 case *Name, *InitializerList:
2876 case *FunctionParam:
2877 if ps.llvmStyle {
2878 paren = true
2879 }
2880 case *Qualified:
2881 if v.LocalName {
2882 paren = true
2883 }
2884 default:
2885 paren = true
2886 }
2887 if paren {
2888 ps.startScope('(')
2889 }
2890 ps.print(val)
2891 if paren {
2892 ps.endScope(')')
2893 }
2894 }
2895
2896 // Nullary is an operator in an expression with no arguments, such as
2897 // throw.
2898 type Nullary struct {
2899 Op AST
2900 }
2901
2902 func (n *Nullary) print(ps *printState) {
2903 if op, ok := n.Op.(*Operator); ok {
2904 ps.writeString(op.Name)
2905 } else {
2906 ps.print(n.Op)
2907 }
2908 }
2909
2910 func (n *Nullary) Traverse(fn func(AST) bool) {
2911 if fn(n) {
2912 n.Op.Traverse(fn)
2913 }
2914 }
2915
2916 func (n *Nullary) Copy(fn func(AST) AST, skip func(AST) bool) AST {
2917 if skip(n) {
2918 return nil
2919 }
2920 op := n.Op.Copy(fn, skip)
2921 if op == nil {
2922 return fn(n)
2923 }
2924 n = &Nullary{Op: op}
2925 if r := fn(n); r != nil {
2926 return r
2927 }
2928 return n
2929 }
2930
2931 func (n *Nullary) GoString() string {
2932 return n.goString(0, "")
2933 }
2934
2935 func (n *Nullary) goString(indent int, field string) string {
2936 return fmt.Sprintf("%*s%sNullary:\n%s", indent, "", field,
2937 n.Op.goString(indent+2, "Op: "))
2938 }
2939
2940 // Unary is a unary operation in an expression.
2941 type Unary struct {
2942 Op AST
2943 Expr AST
2944 Suffix bool // true for ++ -- when used as postfix
2945 SizeofType bool // true for sizeof (type)
2946 }
2947
2948 func (u *Unary) print(ps *printState) {
2949 op, _ := u.Op.(*Operator)
2950 expr := u.Expr
2951
2952 // Don't print the argument list when taking the address of a
2953 // function.
2954 if !ps.llvmStyle {
2955 if op != nil && op.Name == "&" {
2956 if t, ok := expr.(*Typed); ok {
2957 if _, ok := t.Type.(*FunctionType); ok {
2958 expr = t.Name
2959 }
2960 }
2961 }
2962 }
2963
2964 if u.Suffix {
2965 if ps.llvmStyle {
2966 wantParens := true
2967 opPrec := precUnary
2968 if op != nil {
2969 opPrec = op.precedence
2970 }
2971 if p, ok := expr.(hasPrec); ok {
2972 if p.prec() < opPrec {
2973 wantParens = false
2974 }
2975 }
2976 if wantParens {
2977 ps.startScope('(')
2978 }
2979 ps.print(expr)
2980 if wantParens {
2981 ps.endScope(')')
2982 }
2983 } else {
2984 parenthesize(ps, expr)
2985 }
2986 }
2987
2988 if op != nil {
2989 ps.writeString(op.Name)
2990 if ps.llvmStyle && op.Name == "noexcept" {
2991 ps.writeByte(' ')
2992 }
2993 } else if c, ok := u.Op.(*Cast); ok {
2994 ps.startScope('(')
2995 ps.print(c.To)
2996 ps.endScope(')')
2997 } else {
2998 ps.print(u.Op)
2999 }
3000
3001 if !u.Suffix {
3002 alwaysParens := u.SizeofType || (op != nil && (op.Name == "__alignof__" || op.Name == "noexcept"))
3003 if op != nil && op.Name == "::" {
3004 // Don't use parentheses after ::.
3005 ps.print(expr)
3006 } else if alwaysParens {
3007 ps.startScope('(')
3008 ps.print(expr)
3009 ps.endScope(')')
3010 } else if ps.llvmStyle {
3011 var wantParens bool
3012 switch {
3013 case op == nil:
3014 wantParens = true
3015 case op.Name == `operator"" `:
3016 wantParens = false
3017 case op.Name == "&":
3018 wantParens = false
3019 case op.Name == "delete" || op.Name == "delete[]":
3020 wantParens = false
3021 case op.Name == "alignof ":
3022 wantParens = true
3023 case op.Name == "sizeof ":
3024 wantParens = true
3025 case op.Name == "typeid ":
3026 wantParens = true
3027 default:
3028 wantParens = true
3029 if p, ok := expr.(hasPrec); ok {
3030 if p.prec() < op.precedence {
3031 wantParens = false
3032 }
3033 }
3034 }
3035 if wantParens {
3036 ps.startScope('(')
3037 }
3038 ps.print(expr)
3039 if wantParens {
3040 ps.endScope(')')
3041 }
3042 } else {
3043 parenthesize(ps, expr)
3044 }
3045 }
3046 }
3047
3048 func (u *Unary) Traverse(fn func(AST) bool) {
3049 if fn(u) {
3050 u.Op.Traverse(fn)
3051 u.Expr.Traverse(fn)
3052 }
3053 }
3054
3055 func (u *Unary) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3056 if skip(u) {
3057 return nil
3058 }
3059 op := u.Op.Copy(fn, skip)
3060 expr := u.Expr.Copy(fn, skip)
3061 if op == nil && expr == nil {
3062 return fn(u)
3063 }
3064 if op == nil {
3065 op = u.Op
3066 }
3067 if expr == nil {
3068 expr = u.Expr
3069 }
3070 u = &Unary{Op: op, Expr: expr, Suffix: u.Suffix, SizeofType: u.SizeofType}
3071 if r := fn(u); r != nil {
3072 return r
3073 }
3074 return u
3075 }
3076
3077 func (u *Unary) GoString() string {
3078 return u.goString(0, "")
3079 }
3080
3081 func (u *Unary) goString(indent int, field string) string {
3082 var s string
3083 if u.Suffix {
3084 s = " Suffix: true"
3085 }
3086 if u.SizeofType {
3087 s += " SizeofType: true"
3088 }
3089 return fmt.Sprintf("%*s%sUnary:%s\n%s\n%s", indent, "", field,
3090 s, u.Op.goString(indent+2, "Op: "),
3091 u.Expr.goString(indent+2, "Expr: "))
3092 }
3093
3094 func (u *Unary) prec() precedence {
3095 if p, ok := u.Op.(hasPrec); ok {
3096 return p.prec()
3097 }
3098 return precDefault
3099 }
3100
3101 // isDesignatedInitializer reports whether x is a designated
3102 // initializer.
3103 func isDesignatedInitializer(x AST) bool {
3104 switch x := x.(type) {
3105 case *Binary:
3106 if op, ok := x.Op.(*Operator); ok {
3107 if op.Name == "]=" {
3108 return true
3109 }
3110 if op.Name != "=" {
3111 return false
3112 }
3113 if _, ok := x.Left.(*Literal); ok {
3114 return false
3115 }
3116 return true
3117 }
3118 case *Trinary:
3119 if op, ok := x.Op.(*Operator); ok {
3120 return op.Name == "[...]="
3121 }
3122 }
3123 return false
3124 }
3125
3126 // Binary is a binary operation in an expression.
3127 type Binary struct {
3128 Op AST
3129 Left AST
3130 Right AST
3131 }
3132
3133 func (b *Binary) print(ps *printState) {
3134 op, _ := b.Op.(*Operator)
3135
3136 if op != nil && strings.Contains(op.Name, "cast") {
3137 ps.writeString(op.Name)
3138
3139 scopes := ps.scopes
3140 ps.scopes = 0
3141
3142 ps.writeByte('<')
3143 ps.print(b.Left)
3144 ps.writeString(">")
3145
3146 ps.scopes = scopes
3147
3148 ps.startScope('(')
3149 ps.print(b.Right)
3150 ps.endScope(')')
3151 return
3152 }
3153
3154 if isDesignatedInitializer(b) {
3155 if op.Name == "=" {
3156 ps.writeByte('.')
3157 } else {
3158 ps.writeByte('[')
3159 }
3160 ps.print(b.Left)
3161 if op.Name == "]=" {
3162 ps.writeByte(']')
3163 }
3164 if isDesignatedInitializer(b.Right) {
3165 // Don't add anything between designated
3166 // initializer chains.
3167 ps.print(b.Right)
3168 } else {
3169 if ps.llvmStyle {
3170 ps.writeString(" = ")
3171 ps.print(b.Right)
3172 } else {
3173 ps.writeByte('=')
3174 parenthesize(ps, b.Right)
3175 }
3176 }
3177 return
3178 }
3179
3180 // Use an extra set of parentheses around an expression that
3181 // uses the greater-than operator, so that it does not get
3182 // confused with the '>' that ends template parameters.
3183 needsOuterParen := op != nil && (op.Name == ">" || op.Name == ">>")
3184 if ps.llvmStyle && ps.scopes > 0 {
3185 needsOuterParen = false
3186 }
3187 if needsOuterParen {
3188 ps.startScope('(')
3189 }
3190
3191 left := b.Left
3192
3193 skipParens := false
3194 addSpaces := ps.llvmStyle
3195 if ps.llvmStyle && op != nil {
3196 switch op.Name {
3197 case ".", "->", "->*":
3198 addSpaces = false
3199 }
3200 }
3201
3202 // For a function call in an expression, don't print the types
3203 // of the arguments unless there is a return type.
3204 if op != nil && strings.HasPrefix(op.Name, "()") {
3205 if ty, ok := b.Left.(*Typed); ok {
3206 if ft, ok := ty.Type.(*FunctionType); ok {
3207 if ft.Return == nil {
3208 left = ty.Name
3209 } else {
3210 if op.Name != "() " {
3211 skipParens = true
3212 }
3213 }
3214 } else {
3215 left = ty.Name
3216 }
3217 }
3218 if ps.llvmStyle && op.Name != "() " {
3219 skipParens = true
3220 }
3221 }
3222
3223 if skipParens {
3224 ps.print(left)
3225 } else if ps.llvmStyle {
3226 prec := precPrimary
3227 if p, ok := left.(hasPrec); ok {
3228 prec = p.prec()
3229 }
3230 needsParen := op.Name == "() "
3231 if prec > b.prec() {
3232 needsParen = true
3233 }
3234 if needsParen {
3235 ps.startScope('(')
3236 }
3237
3238 ps.print(left)
3239
3240 if needsParen {
3241 ps.endScope(')')
3242 }
3243 } else {
3244 parenthesize(ps, left)
3245 }
3246
3247 if op != nil && op.Name == "[]" {
3248 ps.writeByte('[')
3249 ps.print(b.Right)
3250 ps.writeByte(']')
3251 return
3252 }
3253
3254 if op != nil {
3255 if !strings.HasPrefix(op.Name, "()") {
3256 if addSpaces && op.Name != "," {
3257 ps.writeByte(' ')
3258 }
3259 ps.writeString(op.Name)
3260 if addSpaces {
3261 ps.writeByte(' ')
3262 }
3263 }
3264 } else {
3265 ps.print(b.Op)
3266 }
3267
3268 if ps.llvmStyle {
3269 prec := precPrimary
3270 if p, ok := b.Right.(hasPrec); ok {
3271 prec = p.prec()
3272 }
3273 needsParen := false
3274 if prec >= b.prec() {
3275 needsParen = true
3276 }
3277 if needsParen {
3278 ps.startScope('(')
3279 }
3280
3281 ps.print(b.Right)
3282
3283 if needsParen {
3284 ps.endScope(')')
3285 }
3286 } else {
3287 parenthesize(ps, b.Right)
3288 }
3289
3290 if needsOuterParen {
3291 ps.endScope(')')
3292 }
3293 }
3294
3295 func (b *Binary) Traverse(fn func(AST) bool) {
3296 if fn(b) {
3297 b.Op.Traverse(fn)
3298 b.Left.Traverse(fn)
3299 b.Right.Traverse(fn)
3300 }
3301 }
3302
3303 func (b *Binary) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3304 if skip(b) {
3305 return nil
3306 }
3307 op := b.Op.Copy(fn, skip)
3308 left := b.Left.Copy(fn, skip)
3309 right := b.Right.Copy(fn, skip)
3310 if op == nil && left == nil && right == nil {
3311 return fn(b)
3312 }
3313 if op == nil {
3314 op = b.Op
3315 }
3316 if left == nil {
3317 left = b.Left
3318 }
3319 if right == nil {
3320 right = b.Right
3321 }
3322 b = &Binary{Op: op, Left: left, Right: right}
3323 if r := fn(b); r != nil {
3324 return r
3325 }
3326 return b
3327 }
3328
3329 func (b *Binary) GoString() string {
3330 return b.goString(0, "")
3331 }
3332
3333 func (b *Binary) goString(indent int, field string) string {
3334 return fmt.Sprintf("%*s%sBinary:\n%s\n%s\n%s", indent, "", field,
3335 b.Op.goString(indent+2, "Op: "),
3336 b.Left.goString(indent+2, "Left: "),
3337 b.Right.goString(indent+2, "Right: "))
3338 }
3339
3340 func (b *Binary) prec() precedence {
3341 if p, ok := b.Op.(hasPrec); ok {
3342 return p.prec()
3343 }
3344 return precDefault
3345 }
3346
3347 // Trinary is the ?: trinary operation in an expression.
3348 type Trinary struct {
3349 Op AST
3350 First AST
3351 Second AST
3352 Third AST
3353 }
3354
3355 func (t *Trinary) print(ps *printState) {
3356 if isDesignatedInitializer(t) {
3357 ps.writeByte('[')
3358 ps.print(t.First)
3359 ps.writeString(" ... ")
3360 ps.print(t.Second)
3361 ps.writeByte(']')
3362 if isDesignatedInitializer(t.Third) {
3363 // Don't add anything between designated
3364 // initializer chains.
3365 ps.print(t.Third)
3366 } else {
3367 if ps.llvmStyle {
3368 ps.writeString(" = ")
3369 ps.print(t.Third)
3370 } else {
3371 ps.writeByte('=')
3372 parenthesize(ps, t.Third)
3373 }
3374 }
3375 return
3376 }
3377
3378 if ps.llvmStyle {
3379 wantParens := true
3380 opPrec := precPrimary
3381 if op, ok := t.Op.(*Operator); ok {
3382 opPrec = op.precedence
3383 }
3384 if p, ok := t.First.(hasPrec); ok {
3385 if p.prec() < opPrec {
3386 wantParens = false
3387 }
3388 }
3389 if wantParens {
3390 ps.startScope('(')
3391 }
3392 ps.print(t.First)
3393 if wantParens {
3394 ps.endScope(')')
3395 }
3396 } else {
3397 parenthesize(ps, t.First)
3398 }
3399
3400 if ps.llvmStyle {
3401 ps.writeString(" ? ")
3402 } else {
3403 ps.writeByte('?')
3404 }
3405
3406 if ps.llvmStyle {
3407 wantParens := true
3408 if p, ok := t.Second.(hasPrec); ok {
3409 if p.prec() < precDefault {
3410 wantParens = false
3411 }
3412 }
3413 if wantParens {
3414 ps.startScope('(')
3415 }
3416 ps.print(t.Second)
3417 if wantParens {
3418 ps.endScope(')')
3419 }
3420 } else {
3421 parenthesize(ps, t.Second)
3422 }
3423
3424 ps.writeString(" : ")
3425
3426 if ps.llvmStyle {
3427 wantParens := true
3428 if p, ok := t.Third.(hasPrec); ok {
3429 if p.prec() < precAssign {
3430 wantParens = false
3431 }
3432 }
3433 if wantParens {
3434 ps.startScope('(')
3435 }
3436 ps.print(t.Third)
3437 if wantParens {
3438 ps.endScope(')')
3439 }
3440 } else {
3441 parenthesize(ps, t.Third)
3442 }
3443 }
3444
3445 func (t *Trinary) Traverse(fn func(AST) bool) {
3446 if fn(t) {
3447 t.Op.Traverse(fn)
3448 t.First.Traverse(fn)
3449 t.Second.Traverse(fn)
3450 t.Third.Traverse(fn)
3451 }
3452 }
3453
3454 func (t *Trinary) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3455 if skip(t) {
3456 return nil
3457 }
3458 op := t.Op.Copy(fn, skip)
3459 first := t.First.Copy(fn, skip)
3460 second := t.Second.Copy(fn, skip)
3461 third := t.Third.Copy(fn, skip)
3462 if op == nil && first == nil && second == nil && third == nil {
3463 return fn(t)
3464 }
3465 if op == nil {
3466 op = t.Op
3467 }
3468 if first == nil {
3469 first = t.First
3470 }
3471 if second == nil {
3472 second = t.Second
3473 }
3474 if third == nil {
3475 third = t.Third
3476 }
3477 t = &Trinary{Op: op, First: first, Second: second, Third: third}
3478 if r := fn(t); r != nil {
3479 return r
3480 }
3481 return t
3482 }
3483
3484 func (t *Trinary) GoString() string {
3485 return t.goString(0, "")
3486 }
3487
3488 func (t *Trinary) goString(indent int, field string) string {
3489 return fmt.Sprintf("%*s%sTrinary:\n%s\n%s\n%s\n%s", indent, "", field,
3490 t.Op.goString(indent+2, "Op: "),
3491 t.First.goString(indent+2, "First: "),
3492 t.Second.goString(indent+2, "Second: "),
3493 t.Third.goString(indent+2, "Third: "))
3494 }
3495
3496 // Fold is a C++17 fold-expression. Arg2 is nil for a unary operator.
3497 type Fold struct {
3498 Left bool
3499 Op AST
3500 Arg1 AST
3501 Arg2 AST
3502 }
3503
3504 func (f *Fold) print(ps *printState) {
3505 op, _ := f.Op.(*Operator)
3506 printOp := func() {
3507 if op != nil {
3508 if ps.llvmStyle {
3509 ps.writeByte(' ')
3510 }
3511 ps.writeString(op.Name)
3512 if ps.llvmStyle {
3513 ps.writeByte(' ')
3514 }
3515 } else {
3516 ps.print(f.Op)
3517 }
3518 }
3519 foldParenthesize := func(a AST) {
3520 if ps.llvmStyle {
3521 prec := precDefault
3522 if p, ok := a.(hasPrec); ok {
3523 prec = p.prec()
3524 }
3525 needsParen := false
3526 if prec > precCast {
3527 needsParen = true
3528 }
3529 if needsParen {
3530 ps.startScope('(')
3531 }
3532 ps.print(a)
3533 if needsParen {
3534 ps.endScope(')')
3535 }
3536 } else {
3537 parenthesize(ps, a)
3538 }
3539 }
3540
3541 if f.Arg2 == nil {
3542 if f.Left {
3543 ps.startScope('(')
3544 ps.writeString("...")
3545 printOp()
3546 foldParenthesize(f.Arg1)
3547 ps.endScope(')')
3548 } else {
3549 ps.startScope('(')
3550 foldParenthesize(f.Arg1)
3551 printOp()
3552 ps.writeString("...")
3553 ps.endScope(')')
3554 }
3555 } else {
3556 ps.startScope('(')
3557 foldParenthesize(f.Arg1)
3558 printOp()
3559 ps.writeString("...")
3560 printOp()
3561 foldParenthesize(f.Arg2)
3562 ps.endScope(')')
3563 }
3564 }
3565
3566 func (f *Fold) Traverse(fn func(AST) bool) {
3567 if fn(f) {
3568 f.Op.Traverse(fn)
3569 f.Arg1.Traverse(fn)
3570 if f.Arg2 != nil {
3571 f.Arg2.Traverse(fn)
3572 }
3573 }
3574 }
3575
3576 func (f *Fold) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3577 if skip(f) {
3578 return nil
3579 }
3580 op := f.Op.Copy(fn, skip)
3581 arg1 := f.Arg1.Copy(fn, skip)
3582 var arg2 AST
3583 if f.Arg2 != nil {
3584 arg2 = f.Arg2.Copy(fn, skip)
3585 }
3586 if op == nil && arg1 == nil && arg2 == nil {
3587 return fn(f)
3588 }
3589 if op == nil {
3590 op = f.Op
3591 }
3592 if arg1 == nil {
3593 arg1 = f.Arg1
3594 }
3595 if arg2 == nil {
3596 arg2 = f.Arg2
3597 }
3598 f = &Fold{Left: f.Left, Op: op, Arg1: arg1, Arg2: arg2}
3599 if r := fn(f); r != nil {
3600 return r
3601 }
3602 return f
3603 }
3604
3605 func (f *Fold) GoString() string {
3606 return f.goString(0, "")
3607 }
3608
3609 func (f *Fold) goString(indent int, field string) string {
3610 if f.Arg2 == nil {
3611 return fmt.Sprintf("%*s%sFold: Left: %t\n%s\n%s", indent, "", field,
3612 f.Left, f.Op.goString(indent+2, "Op: "),
3613 f.Arg1.goString(indent+2, "Arg1: "))
3614 } else {
3615 return fmt.Sprintf("%*s%sFold: Left: %t\n%s\n%s\n%s", indent, "", field,
3616 f.Left, f.Op.goString(indent+2, "Op: "),
3617 f.Arg1.goString(indent+2, "Arg1: "),
3618 f.Arg2.goString(indent+2, "Arg2: "))
3619 }
3620 }
3621
3622 // Subobject is a a reference to an offset in an expression. This is
3623 // used for C++20 manglings of class types used as the type of
3624 // non-type template arguments.
3625 //
3626 // See https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
3627 type Subobject struct {
3628 Type AST
3629 SubExpr AST
3630 Offset int
3631 Selectors []int
3632 PastEnd bool
3633 }
3634
3635 func (so *Subobject) print(ps *printState) {
3636 ps.print(so.SubExpr)
3637 ps.writeString(".<")
3638 ps.print(so.Type)
3639 ps.writeString(fmt.Sprintf(" at offset %d>", so.Offset))
3640 }
3641
3642 func (so *Subobject) Traverse(fn func(AST) bool) {
3643 if fn(so) {
3644 so.Type.Traverse(fn)
3645 so.SubExpr.Traverse(fn)
3646 }
3647 }
3648
3649 func (so *Subobject) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3650 if skip(so) {
3651 return nil
3652 }
3653 typ := so.Type.Copy(fn, skip)
3654 subExpr := so.SubExpr.Copy(fn, skip)
3655 if typ == nil && subExpr == nil {
3656 return nil
3657 }
3658 if typ == nil {
3659 typ = so.Type
3660 }
3661 if subExpr == nil {
3662 subExpr = so.SubExpr
3663 }
3664 so = &Subobject{
3665 Type: typ,
3666 SubExpr: subExpr,
3667 Offset: so.Offset,
3668 Selectors: so.Selectors,
3669 PastEnd: so.PastEnd,
3670 }
3671 if r := fn(so); r != nil {
3672 return r
3673 }
3674 return so
3675 }
3676
3677 func (so *Subobject) GoString() string {
3678 return so.goString(0, "")
3679 }
3680
3681 func (so *Subobject) goString(indent int, field string) string {
3682 var selectors string
3683 for _, s := range so.Selectors {
3684 selectors += fmt.Sprintf(" %d", s)
3685 }
3686 return fmt.Sprintf("%*s%sSubobject:\n%s\n%s\n%*sOffset: %d\n%*sSelectors:%s\n%*sPastEnd: %t",
3687 indent, "", field,
3688 so.Type.goString(indent+2, "Type: "),
3689 so.SubExpr.goString(indent+2, "SubExpr: "),
3690 indent+2, "", so.Offset,
3691 indent+2, "", selectors,
3692 indent+2, "", so.PastEnd)
3693 }
3694
3695 // PtrMemCast is a conversion of an expression to a pointer-to-member
3696 // type. This is used for C++20 manglings of class types used as the
3697 // type of non-type template arguments.
3698 //
3699 // See https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
3700 type PtrMemCast struct {
3701 Type AST
3702 Expr AST
3703 Offset int
3704 }
3705
3706 func (pmc *PtrMemCast) print(ps *printState) {
3707 ps.startScope('(')
3708 ps.print(pmc.Type)
3709 ps.writeString(")(")
3710 ps.print(pmc.Expr)
3711 ps.endScope(')')
3712 }
3713
3714 func (pmc *PtrMemCast) Traverse(fn func(AST) bool) {
3715 if fn(pmc) {
3716 pmc.Type.Traverse(fn)
3717 pmc.Expr.Traverse(fn)
3718 }
3719 }
3720
3721 func (pmc *PtrMemCast) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3722 if skip(pmc) {
3723 return nil
3724 }
3725 typ := pmc.Type.Copy(fn, skip)
3726 expr := pmc.Expr.Copy(fn, skip)
3727 if typ == nil && expr == nil {
3728 return nil
3729 }
3730 if typ == nil {
3731 typ = pmc.Type
3732 }
3733 if expr == nil {
3734 expr = pmc.Expr
3735 }
3736 pmc = &PtrMemCast{
3737 Type: typ,
3738 Expr: expr,
3739 Offset: pmc.Offset,
3740 }
3741 if r := fn(pmc); r != nil {
3742 return r
3743 }
3744 return pmc
3745 }
3746
3747 func (pmc *PtrMemCast) GoString() string {
3748 return pmc.goString(0, "")
3749 }
3750
3751 func (pmc *PtrMemCast) goString(indent int, field string) string {
3752 return fmt.Sprintf("%*s%sPtrMemCast:\n%s\n%s\n%*sOffset: %d",
3753 indent, "", field,
3754 pmc.Type.goString(indent+2, "Type: "),
3755 pmc.Expr.goString(indent+2, "Expr: "),
3756 indent+2, "", pmc.Offset)
3757 }
3758
3759 // New is a use of operator new in an expression.
3760 type New struct {
3761 Op AST
3762 Place AST
3763 Type AST
3764 Init AST
3765 }
3766
3767 func (n *New) print(ps *printState) {
3768 if !ps.llvmStyle {
3769 // Op doesn't really matter for printing--we always print "new".
3770 ps.writeString("new ")
3771 } else {
3772 op, _ := n.Op.(*Operator)
3773 if op != nil {
3774 ps.writeString(op.Name)
3775 if n.Place == nil {
3776 ps.writeByte(' ')
3777 }
3778 } else {
3779 ps.print(n.Op)
3780 }
3781 }
3782 if n.Place != nil {
3783 parenthesize(ps, n.Place)
3784 ps.writeByte(' ')
3785 }
3786 ps.print(n.Type)
3787 if n.Init != nil {
3788 parenthesize(ps, n.Init)
3789 }
3790 }
3791
3792 func (n *New) Traverse(fn func(AST) bool) {
3793 if fn(n) {
3794 n.Op.Traverse(fn)
3795 if n.Place != nil {
3796 n.Place.Traverse(fn)
3797 }
3798 n.Type.Traverse(fn)
3799 if n.Init != nil {
3800 n.Init.Traverse(fn)
3801 }
3802 }
3803 }
3804
3805 func (n *New) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3806 if skip(n) {
3807 return nil
3808 }
3809 op := n.Op.Copy(fn, skip)
3810 var place AST
3811 if n.Place != nil {
3812 place = n.Place.Copy(fn, skip)
3813 }
3814 typ := n.Type.Copy(fn, skip)
3815 var ini AST
3816 if n.Init != nil {
3817 ini = n.Init.Copy(fn, skip)
3818 }
3819 if op == nil && place == nil && typ == nil && ini == nil {
3820 return fn(n)
3821 }
3822 if op == nil {
3823 op = n.Op
3824 }
3825 if place == nil {
3826 place = n.Place
3827 }
3828 if typ == nil {
3829 typ = n.Type
3830 }
3831 if ini == nil {
3832 ini = n.Init
3833 }
3834 n = &New{Op: op, Place: place, Type: typ, Init: ini}
3835 if r := fn(n); r != nil {
3836 return r
3837 }
3838 return n
3839 }
3840
3841 func (n *New) GoString() string {
3842 return n.goString(0, "")
3843 }
3844
3845 func (n *New) goString(indent int, field string) string {
3846 var place string
3847 if n.Place == nil {
3848 place = fmt.Sprintf("%*sPlace: nil", indent, "")
3849 } else {
3850 place = n.Place.goString(indent+2, "Place: ")
3851 }
3852 var ini string
3853 if n.Init == nil {
3854 ini = fmt.Sprintf("%*sInit: nil", indent, "")
3855 } else {
3856 ini = n.Init.goString(indent+2, "Init: ")
3857 }
3858 return fmt.Sprintf("%*s%sNew:\n%s\n%s\n%s\n%s", indent, "", field,
3859 n.Op.goString(indent+2, "Op: "), place,
3860 n.Type.goString(indent+2, "Type: "), ini)
3861 }
3862
3863 // Literal is a literal in an expression.
3864 type Literal struct {
3865 Type AST
3866 Val string
3867 Neg bool
3868 }
3869
3870 // Suffixes to use for constants of the given integer type.
3871 var builtinTypeSuffix = map[string]string{
3872 "int": "",
3873 "unsigned int": "u",
3874 "long": "l",
3875 "unsigned long": "ul",
3876 "long long": "ll",
3877 "unsigned long long": "ull",
3878 }
3879
3880 // Builtin float types.
3881 var builtinTypeFloat = map[string]bool{
3882 "double": true,
3883 "long double": true,
3884 "float": true,
3885 "__float128": true,
3886 "half": true,
3887 }
3888
3889 func (l *Literal) print(ps *printState) {
3890 isFloat := false
3891 if b, ok := l.Type.(*BuiltinType); ok {
3892 if suffix, ok := builtinTypeSuffix[b.Name]; ok {
3893 if l.Neg {
3894 ps.writeByte('-')
3895 }
3896 ps.writeString(l.Val)
3897 ps.writeString(suffix)
3898 return
3899 } else if b.Name == "bool" && !l.Neg {
3900 switch l.Val {
3901 case "0":
3902 ps.writeString("false")
3903 return
3904 case "1":
3905 ps.writeString("true")
3906 return
3907 }
3908 } else if b.Name == "decltype(nullptr)" && (l.Val == "" || l.Val == "0") {
3909 if ps.llvmStyle {
3910 ps.writeString("nullptr")
3911 } else {
3912 ps.print(l.Type)
3913 }
3914 return
3915 } else {
3916 isFloat = builtinTypeFloat[b.Name]
3917 }
3918 }
3919
3920 ps.startScope('(')
3921 ps.print(l.Type)
3922 ps.endScope(')')
3923
3924 if isFloat {
3925 ps.writeByte('[')
3926 }
3927 if l.Neg {
3928 ps.writeByte('-')
3929 }
3930 ps.writeString(l.Val)
3931 if isFloat {
3932 ps.writeByte(']')
3933 }
3934 }
3935
3936 func (l *Literal) Traverse(fn func(AST) bool) {
3937 if fn(l) {
3938 l.Type.Traverse(fn)
3939 }
3940 }
3941
3942 func (l *Literal) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3943 if skip(l) {
3944 return nil
3945 }
3946 typ := l.Type.Copy(fn, skip)
3947 if typ == nil {
3948 return fn(l)
3949 }
3950 l = &Literal{Type: typ, Val: l.Val, Neg: l.Neg}
3951 if r := fn(l); r != nil {
3952 return r
3953 }
3954 return l
3955 }
3956
3957 func (l *Literal) GoString() string {
3958 return l.goString(0, "")
3959 }
3960
3961 func (l *Literal) goString(indent int, field string) string {
3962 var neg string
3963 if l.Neg {
3964 neg = " Neg: true"
3965 }
3966 return fmt.Sprintf("%*s%sLiteral:%s\n%s\n%*sVal: %s", indent, "", field,
3967 neg, l.Type.goString(indent+2, "Type: "),
3968 indent+2, "", l.Val)
3969 }
3970
3971 func (l *Literal) prec() precedence {
3972 return precPrimary
3973 }
3974
3975 // StringLiteral is a string literal.
3976 type StringLiteral struct {
3977 Type AST
3978 }
3979
3980 func (sl *StringLiteral) print(ps *printState) {
3981 ps.writeString(`"<`)
3982 sl.Type.print(ps)
3983 ps.writeString(`>"`)
3984 }
3985
3986 func (sl *StringLiteral) Traverse(fn func(AST) bool) {
3987 if fn(sl) {
3988 sl.Type.Traverse(fn)
3989 }
3990 }
3991
3992 func (sl *StringLiteral) Copy(fn func(AST) AST, skip func(AST) bool) AST {
3993 if skip(sl) {
3994 return nil
3995 }
3996 typ := sl.Type.Copy(fn, skip)
3997 if typ == nil {
3998 return fn(sl)
3999 }
4000 sl = &StringLiteral{Type: typ}
4001 if r := fn(sl); r != nil {
4002 return r
4003 }
4004 return sl
4005 }
4006
4007 func (sl *StringLiteral) GoString() string {
4008 return sl.goString(0, "")
4009 }
4010
4011 func (sl *StringLiteral) goString(indent int, field string) string {
4012 return fmt.Sprintf("%*s%sStringLiteral:\n%s", indent, "", field,
4013 sl.Type.goString(indent+2, ""))
4014 }
4015
4016 // LambdaExpr is a literal that is a lambda expression.
4017 type LambdaExpr struct {
4018 Type AST
4019 }
4020
4021 func (le *LambdaExpr) print(ps *printState) {
4022 ps.writeString("[]")
4023 if cl, ok := le.Type.(*Closure); ok {
4024 cl.printTypes(ps)
4025 }
4026 ps.writeString("{...}")
4027 }
4028
4029 func (le *LambdaExpr) Traverse(fn func(AST) bool) {
4030 if fn(le) {
4031 le.Type.Traverse(fn)
4032 }
4033 }
4034
4035 func (le *LambdaExpr) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4036 if skip(le) {
4037 return nil
4038 }
4039 typ := le.Type.Copy(fn, skip)
4040 if typ == nil {
4041 return fn(le)
4042 }
4043 le = &LambdaExpr{Type: typ}
4044 if r := fn(le); r != nil {
4045 return r
4046 }
4047 return le
4048 }
4049
4050 func (le *LambdaExpr) GoString() string {
4051 return le.goString(0, "")
4052 }
4053
4054 func (le *LambdaExpr) goString(indent int, field string) string {
4055 return fmt.Sprintf("%*s%sLambdaExpr:\n%s", indent, "", field,
4056 le.Type.goString(indent+2, ""))
4057 }
4058
4059 // ExprList is a list of expressions, typically arguments to a
4060 // function call in an expression.
4061 type ExprList struct {
4062 Exprs []AST
4063 }
4064
4065 func (el *ExprList) print(ps *printState) {
4066 ps.printList(el.Exprs, nil)
4067 }
4068
4069 func (el *ExprList) Traverse(fn func(AST) bool) {
4070 if fn(el) {
4071 for _, e := range el.Exprs {
4072 e.Traverse(fn)
4073 }
4074 }
4075 }
4076
4077 func (el *ExprList) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4078 if skip(el) {
4079 return nil
4080 }
4081 exprs := make([]AST, len(el.Exprs))
4082 changed := false
4083 for i, e := range el.Exprs {
4084 ec := e.Copy(fn, skip)
4085 if ec == nil {
4086 exprs[i] = e
4087 } else {
4088 exprs[i] = ec
4089 changed = true
4090 }
4091 }
4092 if !changed {
4093 return fn(el)
4094 }
4095 el = &ExprList{Exprs: exprs}
4096 if r := fn(el); r != nil {
4097 return r
4098 }
4099 return el
4100 }
4101
4102 func (el *ExprList) GoString() string {
4103 return el.goString(0, "")
4104 }
4105
4106 func (el *ExprList) goString(indent int, field string) string {
4107 if len(el.Exprs) == 0 {
4108 return fmt.Sprintf("%*s%sExprList: nil", indent, "", field)
4109 }
4110 s := fmt.Sprintf("%*s%sExprList:", indent, "", field)
4111 for i, e := range el.Exprs {
4112 s += "\n"
4113 s += e.goString(indent+2, fmt.Sprintf("%d: ", i))
4114 }
4115 return s
4116 }
4117
4118 func (el *ExprList) prec() precedence {
4119 return precComma
4120 }
4121
4122 // InitializerList is an initializer list: an optional type with a
4123 // list of expressions.
4124 type InitializerList struct {
4125 Type AST
4126 Exprs AST
4127 }
4128
4129 func (il *InitializerList) print(ps *printState) {
4130 if il.Type != nil {
4131 if array, ok := il.Type.(*ArrayType); ok {
4132 if builtin, ok := array.Element.(*BuiltinType); ok && builtin.Name == "char" {
4133 if il.printAsString(ps) {
4134 return
4135 }
4136 }
4137 }
4138 }
4139
4140 if il.Type != nil {
4141 ps.print(il.Type)
4142 }
4143 ps.writeByte('{')
4144 ps.print(il.Exprs)
4145 ps.writeByte('}')
4146 }
4147
4148 // printAsString tries to print a char array initializer as a string.
4149 // It reports whether it succeeded.
4150 func (il *InitializerList) printAsString(ps *printState) bool {
4151 exprList, ok := il.Exprs.(*ExprList)
4152 if !ok {
4153 return false
4154 }
4155
4156 var sb strings.Builder
4157 sb.WriteByte('"')
4158 inNumericEscape := false
4159 for _, e := range exprList.Exprs {
4160 lit, ok := e.(*Literal)
4161 if !ok {
4162 return false
4163 }
4164 if lit.Neg {
4165 return false
4166 }
4167 val, err := strconv.Atoi(lit.Val)
4168 if err != nil || val > 255 {
4169 return false
4170 }
4171
4172 // If we just added a numeric escape,
4173 // make sure it doesn't get accidentally extended
4174 // (numeric escapes here are C++ syntax, not Go syntax).
4175 if inNumericEscape {
4176 if (val >= '0' && val <= '9') ||
4177 (val >= 'a' && val <= 'f') ||
4178 (val >= 'A' && val <= 'F') {
4179 sb.WriteString(`""`)
4180 }
4181 }
4182 inNumericEscape = false
4183
4184 switch val {
4185 case '\a':
4186 sb.WriteString(`\a`)
4187 case '\b':
4188 sb.WriteString(`\b`)
4189 case '\f':
4190 sb.WriteString(`\f`)
4191 case '\n':
4192 sb.WriteString(`\n`)
4193 case '\r':
4194 sb.WriteString(`\r`)
4195 case '\t':
4196 sb.WriteString(`\t`)
4197 case '\v':
4198 sb.WriteString(`\v`)
4199
4200 case '"':
4201 sb.WriteString(`\"`)
4202 case '\\':
4203 sb.WriteString(`\\`)
4204
4205 default:
4206 if val < 32 || val == 127 {
4207 const hex = "0123456789ABCDEF"
4208 sb.WriteByte('\\')
4209 if val > 7 {
4210 sb.WriteByte('x')
4211 }
4212 if val >= 16 {
4213 sb.WriteByte(hex[val>>4])
4214 }
4215 sb.WriteByte(hex[val&0xf])
4216 inNumericEscape = true
4217 break
4218 }
4219
4220 sb.WriteByte(byte(val))
4221 }
4222 }
4223 sb.WriteByte('"')
4224
4225 ps.writeString(sb.String())
4226 return true
4227 }
4228
4229 func (il *InitializerList) Traverse(fn func(AST) bool) {
4230 if fn(il) {
4231 if il.Type != nil {
4232 il.Type.Traverse(fn)
4233 }
4234 il.Exprs.Traverse(fn)
4235 }
4236 }
4237
4238 func (il *InitializerList) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4239 if skip(il) {
4240 return nil
4241 }
4242 var typ AST
4243 if il.Type != nil {
4244 typ = il.Type.Copy(fn, skip)
4245 }
4246 exprs := il.Exprs.Copy(fn, skip)
4247 if typ == nil && exprs == nil {
4248 return fn(il)
4249 }
4250 if typ == nil {
4251 typ = il.Type
4252 }
4253 if exprs == nil {
4254 exprs = il.Exprs
4255 }
4256 il = &InitializerList{Type: typ, Exprs: exprs}
4257 if r := fn(il); r != nil {
4258 return r
4259 }
4260 return il
4261 }
4262
4263 func (il *InitializerList) GoString() string {
4264 return il.goString(0, "")
4265 }
4266
4267 func (il *InitializerList) goString(indent int, field string) string {
4268 var t string
4269 if il.Type == nil {
4270 t = fmt.Sprintf("%*sType: nil", indent+2, "")
4271 } else {
4272 t = il.Type.goString(indent+2, "Type: ")
4273 }
4274 return fmt.Sprintf("%*s%sInitializerList:\n%s\n%s", indent, "", field,
4275 t, il.Exprs.goString(indent+2, "Exprs: "))
4276 }
4277
4278 // DefaultArg holds a default argument for a local name.
4279 type DefaultArg struct {
4280 Num int
4281 Arg AST
4282 }
4283
4284 func (da *DefaultArg) print(ps *printState) {
4285 if !ps.llvmStyle {
4286 fmt.Fprintf(&ps.buf, "{default arg#%d}::", da.Num+1)
4287 }
4288 ps.print(da.Arg)
4289 }
4290
4291 func (da *DefaultArg) Traverse(fn func(AST) bool) {
4292 if fn(da) {
4293 da.Arg.Traverse(fn)
4294 }
4295 }
4296
4297 func (da *DefaultArg) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4298 if skip(da) {
4299 return nil
4300 }
4301 arg := da.Arg.Copy(fn, skip)
4302 if arg == nil {
4303 return fn(da)
4304 }
4305 da = &DefaultArg{Num: da.Num, Arg: arg}
4306 if r := fn(da); r != nil {
4307 return r
4308 }
4309 return da
4310 }
4311
4312 func (da *DefaultArg) GoString() string {
4313 return da.goString(0, "")
4314 }
4315
4316 func (da *DefaultArg) goString(indent int, field string) string {
4317 return fmt.Sprintf("%*s%sDefaultArg: Num: %d\n%s", indent, "", field, da.Num,
4318 da.Arg.goString(indent+2, "Arg: "))
4319 }
4320
4321 // Closure is a closure, or lambda expression.
4322 type Closure struct {
4323 TemplateArgs []AST
4324 TemplateArgsConstraint AST
4325 Types []AST
4326 Num int
4327 CallConstraint AST
4328 }
4329
4330 func (cl *Closure) print(ps *printState) {
4331 if ps.llvmStyle {
4332 if cl.Num == 0 {
4333 ps.writeString("'lambda'")
4334 } else {
4335 ps.writeString(fmt.Sprintf("'lambda%d'", cl.Num-1))
4336 }
4337 } else {
4338 ps.writeString("{lambda")
4339 }
4340 cl.printTypes(ps)
4341 if !ps.llvmStyle {
4342 ps.writeString(fmt.Sprintf("#%d}", cl.Num+1))
4343 }
4344 }
4345
4346 func (cl *Closure) printTypes(ps *printState) {
4347 if len(cl.TemplateArgs) > 0 {
4348 scopes := ps.scopes
4349 ps.scopes = 0
4350
4351 ps.writeString("<")
4352 ps.printList(cl.TemplateArgs, nil)
4353 ps.writeString(">")
4354
4355 ps.scopes = scopes
4356 }
4357
4358 if cl.TemplateArgsConstraint != nil {
4359 ps.writeString(" requires ")
4360 ps.print(cl.TemplateArgsConstraint)
4361 ps.writeByte(' ')
4362 }
4363
4364 ps.startScope('(')
4365 ps.printList(cl.Types, nil)
4366 ps.endScope(')')
4367
4368 if cl.CallConstraint != nil {
4369 ps.writeString(" requires ")
4370 ps.print(cl.CallConstraint)
4371 }
4372 }
4373
4374 func (cl *Closure) Traverse(fn func(AST) bool) {
4375 if fn(cl) {
4376 for _, a := range cl.TemplateArgs {
4377 a.Traverse(fn)
4378 }
4379 if cl.TemplateArgsConstraint != nil {
4380 cl.TemplateArgsConstraint.Traverse(fn)
4381 }
4382 for _, t := range cl.Types {
4383 t.Traverse(fn)
4384 }
4385 if cl.CallConstraint != nil {
4386 cl.CallConstraint.Traverse(fn)
4387 }
4388 }
4389 }
4390
4391 func (cl *Closure) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4392 if skip(cl) {
4393 return nil
4394 }
4395 changed := false
4396
4397 args := make([]AST, len(cl.TemplateArgs))
4398 for i, a := range cl.TemplateArgs {
4399 ac := a.Copy(fn, skip)
4400 if ac == nil {
4401 args[i] = a
4402 } else {
4403 args[i] = ac
4404 changed = true
4405 }
4406 }
4407
4408 var templateArgsConstraint AST
4409 if cl.TemplateArgsConstraint != nil {
4410 templateArgsConstraint = cl.TemplateArgsConstraint.Copy(fn, skip)
4411 if templateArgsConstraint == nil {
4412 templateArgsConstraint = cl.TemplateArgsConstraint
4413 } else {
4414 changed = true
4415 }
4416 }
4417
4418 types := make([]AST, len(cl.Types))
4419 for i, t := range cl.Types {
4420 tc := t.Copy(fn, skip)
4421 if tc == nil {
4422 types[i] = t
4423 } else {
4424 types[i] = tc
4425 changed = true
4426 }
4427 }
4428
4429 var callConstraint AST
4430 if cl.CallConstraint != nil {
4431 callConstraint = cl.CallConstraint.Copy(fn, skip)
4432 if callConstraint == nil {
4433 callConstraint = cl.CallConstraint
4434 } else {
4435 changed = true
4436 }
4437 }
4438
4439 if !changed {
4440 return fn(cl)
4441 }
4442 cl = &Closure{
4443 TemplateArgs: args,
4444 TemplateArgsConstraint: templateArgsConstraint,
4445 Types: types,
4446 Num: cl.Num,
4447 CallConstraint: callConstraint,
4448 }
4449 if r := fn(cl); r != nil {
4450 return r
4451 }
4452 return cl
4453 }
4454
4455 func (cl *Closure) GoString() string {
4456 return cl.goString(0, "")
4457 }
4458
4459 func (cl *Closure) goString(indent int, field string) string {
4460 var args strings.Builder
4461 if len(cl.TemplateArgs) == 0 {
4462 fmt.Fprintf(&args, "%*sTemplateArgs: nil", indent+2, "")
4463 } else {
4464 fmt.Fprintf(&args, "%*sTemplateArgs:", indent+2, "")
4465 for i, a := range cl.TemplateArgs {
4466 args.WriteByte('\n')
4467 args.WriteString(a.goString(indent+4, fmt.Sprintf("%d: ", i)))
4468 }
4469 }
4470
4471 var templateArgsConstraint string
4472 if cl.TemplateArgsConstraint != nil {
4473 templateArgsConstraint = "\n" + cl.TemplateArgsConstraint.goString(indent+2, "TemplateArgsConstraint: ")
4474 }
4475
4476 var types strings.Builder
4477 if len(cl.Types) == 0 {
4478 fmt.Fprintf(&types, "%*sTypes: nil", indent+2, "")
4479 } else {
4480 fmt.Fprintf(&types, "%*sTypes:", indent+2, "")
4481 for i, t := range cl.Types {
4482 types.WriteByte('\n')
4483 types.WriteString(t.goString(indent+4, fmt.Sprintf("%d: ", i)))
4484 }
4485 }
4486
4487 var callConstraint string
4488 if cl.CallConstraint != nil {
4489 callConstraint = "\n" + cl.CallConstraint.goString(indent+2, "CallConstraint: ")
4490 }
4491
4492 return fmt.Sprintf("%*s%sClosure: Num: %d\n%s\n%s%s%s", indent, "", field,
4493 cl.Num, args.String(), templateArgsConstraint, types.String(),
4494 callConstraint)
4495 }
4496
4497 // StructuredBindings is a structured binding declaration.
4498 type StructuredBindings struct {
4499 Bindings []AST
4500 }
4501
4502 func (sb *StructuredBindings) print(ps *printState) {
4503 ps.writeString("[")
4504 ps.printList(sb.Bindings, nil)
4505 ps.writeString("]")
4506 }
4507
4508 func (sb *StructuredBindings) Traverse(fn func(AST) bool) {
4509 if fn(sb) {
4510 for _, b := range sb.Bindings {
4511 b.Traverse(fn)
4512 }
4513 }
4514 }
4515
4516 func (sb *StructuredBindings) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4517 if skip(sb) {
4518 return nil
4519 }
4520 changed := false
4521 bindings := make([]AST, len(sb.Bindings))
4522 for i, b := range sb.Bindings {
4523 bc := b.Copy(fn, skip)
4524 if bc == nil {
4525 bindings[i] = b
4526 } else {
4527 bindings[i] = bc
4528 changed = true
4529 }
4530 }
4531 if !changed {
4532 return fn(sb)
4533 }
4534 sb = &StructuredBindings{Bindings: bindings}
4535 if r := fn(sb); r != nil {
4536 return r
4537 }
4538 return sb
4539 }
4540
4541 func (sb *StructuredBindings) GoString() string {
4542 return sb.goString(0, "")
4543 }
4544
4545 func (sb *StructuredBindings) goString(indent int, field string) string {
4546 var strb strings.Builder
4547 fmt.Fprintf(&strb, "%*s%sStructuredBinding:", indent, "", field)
4548 for _, b := range sb.Bindings {
4549 strb.WriteByte('\n')
4550 strb.WriteString(b.goString(indent+2, ""))
4551 }
4552 return strb.String()
4553 }
4554
4555 // UnnamedType is an unnamed type, that just has an index.
4556 type UnnamedType struct {
4557 Num int
4558 }
4559
4560 func (ut *UnnamedType) print(ps *printState) {
4561 if ps.llvmStyle {
4562 if ut.Num == 0 {
4563 ps.writeString("'unnamed'")
4564 } else {
4565 ps.writeString(fmt.Sprintf("'unnamed%d'", ut.Num-1))
4566 }
4567 } else {
4568 ps.writeString(fmt.Sprintf("{unnamed type#%d}", ut.Num+1))
4569 }
4570 }
4571
4572 func (ut *UnnamedType) Traverse(fn func(AST) bool) {
4573 fn(ut)
4574 }
4575
4576 func (ut *UnnamedType) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4577 if skip(ut) {
4578 return nil
4579 }
4580 return fn(ut)
4581 }
4582
4583 func (ut *UnnamedType) GoString() string {
4584 return ut.goString(0, "")
4585 }
4586
4587 func (ut *UnnamedType) goString(indent int, field string) string {
4588 return fmt.Sprintf("%*s%sUnnamedType: Num: %d", indent, "", field, ut.Num)
4589 }
4590
4591 // UnnamedEnum is an unnamed enum type.
4592 type UnnamedEnum struct {
4593 Underlying AST
4594 Name AST
4595 }
4596
4597 func (ue *UnnamedEnum) print(ps *printState) {
4598 ps.writeString("{enum:")
4599 ps.print(ue.Underlying)
4600 ps.writeByte('{')
4601 ps.print(ue.Name)
4602 ps.writeString("}}")
4603 }
4604
4605 func (ue *UnnamedEnum) Traverse(fn func(AST) bool) {
4606 if fn(ue) {
4607 ue.Underlying.Traverse(fn)
4608 ue.Name.Traverse(fn)
4609 }
4610 }
4611
4612 func (ue *UnnamedEnum) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4613 if skip(ue) {
4614 return nil
4615 }
4616 underlying := ue.Underlying.Copy(fn, skip)
4617 name := ue.Name.Copy(fn, skip)
4618 if underlying == nil && name == nil {
4619 return fn(ue)
4620 }
4621 if underlying == nil {
4622 underlying = ue.Underlying
4623 }
4624 if name == nil {
4625 name = ue.Name
4626 }
4627 ue = &UnnamedEnum{Underlying: underlying, Name: name}
4628 if r := fn(ue); r != nil {
4629 return r
4630 }
4631 return ue
4632 }
4633
4634 func (ue *UnnamedEnum) GoString() string {
4635 return ue.goString(0, "")
4636 }
4637
4638 func (ue *UnnamedEnum) goString(indent int, field string) string {
4639 return fmt.Sprintf("%*s%sUnnamedEnum:\n%s\n%s", indent, "", field,
4640 ue.Underlying.goString(indent+2, "Underlying: "),
4641 ue.Name.goString(indent+2, "Name: "))
4642 }
4643
4644 // Clone is a clone of a function, with a distinguishing suffix.
4645 type Clone struct {
4646 Base AST
4647 Suffix string
4648 }
4649
4650 func (c *Clone) print(ps *printState) {
4651 ps.print(c.Base)
4652 if ps.llvmStyle {
4653 ps.writeByte(' ')
4654 ps.startScope('(')
4655 ps.writeString(c.Suffix)
4656 ps.endScope(')')
4657 } else {
4658 ps.writeString(fmt.Sprintf(" [clone %s]", c.Suffix))
4659 }
4660 }
4661
4662 func (c *Clone) Traverse(fn func(AST) bool) {
4663 if fn(c) {
4664 c.Base.Traverse(fn)
4665 }
4666 }
4667
4668 func (c *Clone) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4669 if skip(c) {
4670 return nil
4671 }
4672 base := c.Base.Copy(fn, skip)
4673 if base == nil {
4674 return fn(c)
4675 }
4676 c = &Clone{Base: base, Suffix: c.Suffix}
4677 if r := fn(c); r != nil {
4678 return r
4679 }
4680 return c
4681 }
4682
4683 func (c *Clone) GoString() string {
4684 return c.goString(0, "")
4685 }
4686
4687 func (c *Clone) goString(indent int, field string) string {
4688 return fmt.Sprintf("%*s%sClone: Suffix: %s\n%s", indent, "", field,
4689 c.Suffix, c.Base.goString(indent+2, "Base: "))
4690 }
4691
4692 // Special is a special symbol, printed as a prefix plus another
4693 // value.
4694 type Special struct {
4695 Prefix string
4696 Val AST
4697 }
4698
4699 func (s *Special) print(ps *printState) {
4700 prefix := s.Prefix
4701 if ps.llvmStyle {
4702 switch prefix {
4703 case "TLS wrapper function for ":
4704 prefix = "thread-local wrapper routine for "
4705 case "TLS init function for ":
4706 prefix = "thread-local initialization routine for "
4707 }
4708 }
4709 ps.writeString(prefix)
4710 ps.print(s.Val)
4711 }
4712
4713 func (s *Special) Traverse(fn func(AST) bool) {
4714 if fn(s) {
4715 s.Val.Traverse(fn)
4716 }
4717 }
4718
4719 func (s *Special) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4720 if skip(s) {
4721 return nil
4722 }
4723 val := s.Val.Copy(fn, skip)
4724 if val == nil {
4725 return fn(s)
4726 }
4727 s = &Special{Prefix: s.Prefix, Val: val}
4728 if r := fn(s); r != nil {
4729 return r
4730 }
4731 return s
4732 }
4733
4734 func (s *Special) GoString() string {
4735 return s.goString(0, "")
4736 }
4737
4738 func (s *Special) goString(indent int, field string) string {
4739 return fmt.Sprintf("%*s%sSpecial: Prefix: %s\n%s", indent, "", field,
4740 s.Prefix, s.Val.goString(indent+2, "Val: "))
4741 }
4742
4743 // Special2 is like special, but uses two values.
4744 type Special2 struct {
4745 Prefix string
4746 Val1 AST
4747 Middle string
4748 Val2 AST
4749 }
4750
4751 func (s *Special2) print(ps *printState) {
4752 ps.writeString(s.Prefix)
4753 ps.print(s.Val1)
4754 ps.writeString(s.Middle)
4755 ps.print(s.Val2)
4756 }
4757
4758 func (s *Special2) Traverse(fn func(AST) bool) {
4759 if fn(s) {
4760 s.Val1.Traverse(fn)
4761 s.Val2.Traverse(fn)
4762 }
4763 }
4764
4765 func (s *Special2) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4766 if skip(s) {
4767 return nil
4768 }
4769 val1 := s.Val1.Copy(fn, skip)
4770 val2 := s.Val2.Copy(fn, skip)
4771 if val1 == nil && val2 == nil {
4772 return fn(s)
4773 }
4774 if val1 == nil {
4775 val1 = s.Val1
4776 }
4777 if val2 == nil {
4778 val2 = s.Val2
4779 }
4780 s = &Special2{Prefix: s.Prefix, Val1: val1, Middle: s.Middle, Val2: val2}
4781 if r := fn(s); r != nil {
4782 return r
4783 }
4784 return s
4785 }
4786
4787 func (s *Special2) GoString() string {
4788 return s.goString(0, "")
4789 }
4790
4791 func (s *Special2) goString(indent int, field string) string {
4792 return fmt.Sprintf("%*s%sSpecial2: Prefix: %s\n%s\n%*sMiddle: %s\n%s", indent, "", field,
4793 s.Prefix, s.Val1.goString(indent+2, "Val1: "),
4794 indent+2, "", s.Middle, s.Val2.goString(indent+2, "Val2: "))
4795 }
4796
4797 // EnableIf is used by clang for an enable_if attribute.
4798 type EnableIf struct {
4799 Type AST
4800 Args []AST
4801 }
4802
4803 func (ei *EnableIf) print(ps *printState) {
4804 ps.print(ei.Type)
4805 ps.writeString(" [enable_if:")
4806 ps.printList(ei.Args, nil)
4807 ps.writeString("]")
4808 }
4809
4810 func (ei *EnableIf) Traverse(fn func(AST) bool) {
4811 if fn(ei) {
4812 ei.Type.Traverse(fn)
4813 for _, a := range ei.Args {
4814 a.Traverse(fn)
4815 }
4816 }
4817 }
4818
4819 func (ei *EnableIf) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4820 if skip(ei) {
4821 return nil
4822 }
4823 typ := ei.Type.Copy(fn, skip)
4824 argsChanged := false
4825 args := make([]AST, len(ei.Args))
4826 for i, a := range ei.Args {
4827 ac := a.Copy(fn, skip)
4828 if ac == nil {
4829 args[i] = a
4830 } else {
4831 args[i] = ac
4832 argsChanged = true
4833 }
4834 }
4835 if typ == nil && !argsChanged {
4836 return fn(ei)
4837 }
4838 if typ == nil {
4839 typ = ei.Type
4840 }
4841 ei = &EnableIf{Type: typ, Args: args}
4842 if r := fn(ei); r != nil {
4843 return r
4844 }
4845 return ei
4846 }
4847
4848 func (ei *EnableIf) GoString() string {
4849 return ei.goString(0, "")
4850 }
4851
4852 func (ei *EnableIf) goString(indent int, field string) string {
4853 var args string
4854 if len(ei.Args) == 0 {
4855 args = fmt.Sprintf("%*sArgs: nil", indent+2, "")
4856 } else {
4857 args = fmt.Sprintf("%*sArgs:", indent+2, "")
4858 for i, a := range ei.Args {
4859 args += "\n"
4860 args += a.goString(indent+4, fmt.Sprintf("%d: ", i))
4861 }
4862 }
4863 return fmt.Sprintf("%*s%sEnableIf:\n%s\n%s", indent, "", field,
4864 ei.Type.goString(indent+2, "Type: "), args)
4865 }
4866
4867 // ModuleName is a C++20 module.
4868 type ModuleName struct {
4869 Parent AST
4870 Name AST
4871 IsPartition bool
4872 }
4873
4874 func (mn *ModuleName) print(ps *printState) {
4875 if mn.Parent != nil {
4876 ps.print(mn.Parent)
4877 }
4878 if mn.IsPartition {
4879 ps.writeByte(':')
4880 } else if mn.Parent != nil {
4881 ps.writeByte('.')
4882 }
4883 ps.print(mn.Name)
4884 }
4885
4886 func (mn *ModuleName) Traverse(fn func(AST) bool) {
4887 if fn(mn) {
4888 if mn.Parent != nil {
4889 mn.Parent.Traverse(fn)
4890 }
4891 mn.Name.Traverse(fn)
4892 }
4893 }
4894
4895 func (mn *ModuleName) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4896 if skip(mn) {
4897 return nil
4898 }
4899 var parent AST
4900 if mn.Parent != nil {
4901 parent = mn.Parent.Copy(fn, skip)
4902 }
4903 name := mn.Name.Copy(fn, skip)
4904 if parent == nil && name == nil {
4905 return fn(mn)
4906 }
4907 if parent == nil {
4908 parent = mn.Parent
4909 }
4910 if name == nil {
4911 name = mn.Name
4912 }
4913 mn = &ModuleName{Parent: parent, Name: name, IsPartition: mn.IsPartition}
4914 if r := fn(mn); r != nil {
4915 return r
4916 }
4917 return mn
4918 }
4919
4920 func (mn *ModuleName) GoString() string {
4921 return mn.goString(0, "")
4922 }
4923
4924 func (mn *ModuleName) goString(indent int, field string) string {
4925 var parent string
4926 if mn.Parent == nil {
4927 parent = fmt.Sprintf("%*sParent: nil", indent+2, "")
4928 } else {
4929 parent = mn.Parent.goString(indent+2, "Parent: ")
4930 }
4931 return fmt.Sprintf("%*s%sModuleName: IsPartition: %t\n%s\n%s", indent, "", field,
4932 mn.IsPartition, parent,
4933 mn.Name.goString(indent+2, "Name: "))
4934 }
4935
4936 // ModuleEntity is a name inside a module.
4937 type ModuleEntity struct {
4938 Module AST
4939 Name AST
4940 }
4941
4942 func (me *ModuleEntity) print(ps *printState) {
4943 ps.print(me.Name)
4944 ps.writeByte('@')
4945 ps.print(me.Module)
4946 }
4947
4948 func (me *ModuleEntity) Traverse(fn func(AST) bool) {
4949 if fn(me) {
4950 me.Module.Traverse(fn)
4951 me.Name.Traverse(fn)
4952 }
4953 }
4954
4955 func (me *ModuleEntity) Copy(fn func(AST) AST, skip func(AST) bool) AST {
4956 if skip(me) {
4957 return nil
4958 }
4959 module := me.Module.Copy(fn, skip)
4960 name := me.Name.Copy(fn, skip)
4961 if module == nil && name == nil {
4962 return fn(me)
4963 }
4964 if module == nil {
4965 module = me.Module
4966 }
4967 if name == nil {
4968 name = me.Name
4969 }
4970 me = &ModuleEntity{Module: module, Name: name}
4971 if r := fn(me); r != nil {
4972 return r
4973 }
4974 return me
4975 }
4976
4977 func (me *ModuleEntity) GoString() string {
4978 return me.goString(0, "")
4979 }
4980
4981 func (me *ModuleEntity) goString(indent int, field string) string {
4982 return fmt.Sprintf("%*s%sModuleEntity:\n%s\n%s", indent, "", field,
4983 me.Module.goString(indent+2, "Module: "),
4984 me.Name.goString(indent+2, "Name: "))
4985 }
4986
4987 // Friend is a member like friend name.
4988 type Friend struct {
4989 Name AST
4990 }
4991
4992 func (f *Friend) print(ps *printState) {
4993 if ps.llvmStyle {
4994 ps.writeString("friend ")
4995 }
4996 ps.print(f.Name)
4997 if !ps.llvmStyle {
4998 ps.writeString("[friend]")
4999 }
5000 }
5001
5002 func (f *Friend) Traverse(fn func(AST) bool) {
5003 if fn(f) {
5004 f.Name.Traverse(fn)
5005 }
5006 }
5007
5008 func (f *Friend) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5009 if skip(f) {
5010 return nil
5011 }
5012 name := f.Name.Copy(fn, skip)
5013 if name == nil {
5014 return fn(f)
5015 }
5016 f = &Friend{Name: name}
5017 if r := fn(f); r != nil {
5018 return r
5019 }
5020 return f
5021 }
5022
5023 func (f *Friend) GoString() string {
5024 return f.goString(0, "")
5025 }
5026
5027 func (f *Friend) goString(indent int, field string) string {
5028 return fmt.Sprintf("%*s%sFriend:\n%s", indent, "", field,
5029 f.Name.goString(indent+2, "Name: "))
5030 }
5031
5032 // Constraint represents an AST with a constraint.
5033 // ForTemplateArgs is true if this constraint was found at the
5034 // end of a list of template arguments. We need that because
5035 // in LLVM style we don't print constraints of that sort.
5036 type Constraint struct {
5037 Name AST
5038 Requires AST
5039 ForTemplateArgs bool
5040 }
5041
5042 func (c *Constraint) print(ps *printState) {
5043 ps.print(c.Name)
5044
5045 // For LLVM style skip the constraint on a template.
5046 if ps.llvmStyle && c.ForTemplateArgs {
5047 return
5048 }
5049
5050 ps.writeString(" requires ")
5051 ps.print(c.Requires)
5052 }
5053
5054 func (c *Constraint) Traverse(fn func(AST) bool) {
5055 if fn(c) {
5056 c.Name.Traverse(fn)
5057 c.Requires.Traverse(fn)
5058 }
5059 }
5060
5061 func (c *Constraint) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5062 if skip(c) {
5063 return nil
5064 }
5065 name := c.Name.Copy(fn, skip)
5066 requires := c.Requires.Copy(fn, skip)
5067 if name == nil && requires == nil {
5068 return fn(c)
5069 }
5070 if name == nil {
5071 name = c.Name
5072 }
5073 if requires == nil {
5074 requires = c.Requires
5075 }
5076 c = &Constraint{
5077 Name: name,
5078 Requires: requires,
5079 ForTemplateArgs: c.ForTemplateArgs,
5080 }
5081 if r := fn(c); r != nil {
5082 return r
5083 }
5084 return c
5085 }
5086
5087 func (c *Constraint) GoString() string {
5088 return c.goString(0, "")
5089 }
5090
5091 func (c *Constraint) goString(indent int, field string) string {
5092 return fmt.Sprintf("%*s%sConstraint: ForTemplateArgs: %t\n%s\n%s", indent, "", field,
5093 c.ForTemplateArgs,
5094 c.Name.goString(indent+2, "Name: "),
5095 c.Requires.goString(indent+2, "Requires: "))
5096 }
5097
5098 // RequiresExpr is a C++20 requires expression.
5099 type RequiresExpr struct {
5100 Params []AST
5101 Requirements []AST
5102 }
5103
5104 func (re *RequiresExpr) print(ps *printState) {
5105 ps.writeString("requires")
5106 if len(re.Params) > 0 {
5107 ps.writeByte(' ')
5108 ps.startScope('(')
5109 ps.printList(re.Params, nil)
5110 ps.endScope(')')
5111 }
5112 ps.writeByte(' ')
5113 ps.startScope('{')
5114 for _, req := range re.Requirements {
5115 ps.print(req)
5116 }
5117 ps.writeByte(' ')
5118 ps.endScope('}')
5119 }
5120
5121 func (re *RequiresExpr) Traverse(fn func(AST) bool) {
5122 if fn(re) {
5123 for _, p := range re.Params {
5124 p.Traverse(fn)
5125 }
5126 for _, r := range re.Requirements {
5127 r.Traverse(fn)
5128 }
5129 }
5130 }
5131
5132 func (re *RequiresExpr) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5133 if skip(re) {
5134 return nil
5135 }
5136
5137 changed := false
5138
5139 var params []AST
5140 if len(re.Params) > 0 {
5141 params = make([]AST, len(re.Params))
5142 for i, p := range re.Params {
5143 pc := p.Copy(fn, skip)
5144 if pc == nil {
5145 params[i] = p
5146 } else {
5147 params[i] = pc
5148 changed = true
5149 }
5150 }
5151 }
5152
5153 requirements := make([]AST, len(re.Requirements))
5154 for i, r := range re.Requirements {
5155 rc := r.Copy(fn, skip)
5156 if rc == nil {
5157 requirements[i] = r
5158 } else {
5159 requirements[i] = rc
5160 changed = true
5161 }
5162 }
5163
5164 if !changed {
5165 return fn(re)
5166 }
5167
5168 re = &RequiresExpr{Params: params, Requirements: requirements}
5169 if r := fn(re); r != nil {
5170 return r
5171 }
5172 return re
5173 }
5174
5175 func (re *RequiresExpr) GoString() string {
5176 return re.goString(0, "")
5177 }
5178
5179 func (re *RequiresExpr) goString(indent int, field string) string {
5180 var params strings.Builder
5181 if len(re.Params) == 0 {
5182 fmt.Fprintf(&params, "%*sParams: nil", indent+2, "")
5183 } else {
5184 fmt.Fprintf(&params, "%*sParams:", indent+2, "")
5185 for i, p := range re.Params {
5186 params.WriteByte('\n')
5187 params.WriteString(p.goString(indent+4, fmt.Sprintf("%d: ", i)))
5188 }
5189 }
5190
5191 var requirements strings.Builder
5192 fmt.Fprintf(&requirements, "%*sRequirements:", indent+2, "")
5193 for i, r := range re.Requirements {
5194 requirements.WriteByte('\n')
5195 requirements.WriteString(r.goString(indent+4, fmt.Sprintf("%d: ", i)))
5196 }
5197
5198 return fmt.Sprintf("%*s%sRequirements:\n%s\n%s", indent, "", field,
5199 params.String(), requirements.String())
5200 }
5201
5202 // ExprRequirement is a simple requirement in a requires expression.
5203 // This is an arbitrary expression.
5204 type ExprRequirement struct {
5205 Expr AST
5206 Noexcept bool
5207 TypeReq AST
5208 }
5209
5210 func (er *ExprRequirement) print(ps *printState) {
5211 ps.writeByte(' ')
5212 if er.Noexcept || er.TypeReq != nil {
5213 ps.startScope('{')
5214 }
5215 ps.print(er.Expr)
5216 if er.Noexcept || er.TypeReq != nil {
5217 ps.endScope('}')
5218 }
5219 if er.Noexcept {
5220 ps.writeString(" noexcept")
5221 }
5222 if er.TypeReq != nil {
5223 ps.writeString(" -> ")
5224 ps.print(er.TypeReq)
5225 }
5226 ps.writeByte(';')
5227 }
5228
5229 func (er *ExprRequirement) Traverse(fn func(AST) bool) {
5230 if fn(er) {
5231 er.Expr.Traverse(fn)
5232 if er.TypeReq != nil {
5233 er.TypeReq.Traverse(fn)
5234 }
5235 }
5236 }
5237
5238 func (er *ExprRequirement) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5239 if skip(er) {
5240 return nil
5241 }
5242 expr := er.Expr.Copy(fn, skip)
5243 var typeReq AST
5244 if er.TypeReq != nil {
5245 typeReq = er.TypeReq.Copy(fn, skip)
5246 }
5247 if expr == nil && typeReq == nil {
5248 return fn(er)
5249 }
5250 if expr == nil {
5251 expr = er.Expr
5252 }
5253 if typeReq == nil {
5254 typeReq = er.TypeReq
5255 }
5256 er = &ExprRequirement{Expr: expr, TypeReq: typeReq}
5257 if r := fn(er); r != nil {
5258 return r
5259 }
5260 return er
5261 }
5262
5263 func (er *ExprRequirement) GoString() string {
5264 return er.goString(0, "")
5265 }
5266
5267 func (er *ExprRequirement) goString(indent int, field string) string {
5268 var typeReq string
5269 if er.TypeReq != nil {
5270 typeReq = "\n" + er.TypeReq.goString(indent+2, "TypeReq: ")
5271 }
5272
5273 return fmt.Sprintf("%*s%sExprRequirement: Noexcept: %t\n%s%s", indent, "", field,
5274 er.Noexcept,
5275 er.Expr.goString(indent+2, "Expr: "),
5276 typeReq)
5277 }
5278
5279 // TypeRequirement is a type requirement in a requires expression.
5280 type TypeRequirement struct {
5281 Type AST
5282 }
5283
5284 func (tr *TypeRequirement) print(ps *printState) {
5285 ps.writeString(" typename ")
5286 ps.print(tr.Type)
5287 ps.writeByte(';')
5288 }
5289
5290 func (tr *TypeRequirement) Traverse(fn func(AST) bool) {
5291 if fn(tr) {
5292 tr.Type.Traverse(fn)
5293 }
5294 }
5295
5296 func (tr *TypeRequirement) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5297 if skip(tr) {
5298 return nil
5299 }
5300 typ := tr.Type.Copy(fn, skip)
5301 if typ == nil {
5302 return fn(tr)
5303 }
5304 tr = &TypeRequirement{Type: typ}
5305 if r := fn(tr); r != nil {
5306 return r
5307 }
5308 return tr
5309 }
5310
5311 func (tr *TypeRequirement) GoString() string {
5312 return tr.goString(0, "")
5313 }
5314
5315 func (tr *TypeRequirement) goString(indent int, field string) string {
5316 return fmt.Sprintf("%*s%sTypeRequirement:\n%s", indent, "", field,
5317 tr.Type.goString(indent+2, ""))
5318 }
5319
5320 // NestedRequirement is a nested requirement in a requires expression.
5321 type NestedRequirement struct {
5322 Constraint AST
5323 }
5324
5325 func (nr *NestedRequirement) print(ps *printState) {
5326 ps.writeString(" requires ")
5327 ps.print(nr.Constraint)
5328 ps.writeByte(';')
5329 }
5330
5331 func (nr *NestedRequirement) Traverse(fn func(AST) bool) {
5332 if fn(nr) {
5333 nr.Constraint.Traverse(fn)
5334 }
5335 }
5336
5337 func (nr *NestedRequirement) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5338 if skip(nr) {
5339 return nil
5340 }
5341 constraint := nr.Constraint.Copy(fn, skip)
5342 if constraint == nil {
5343 return fn(nr)
5344 }
5345 nr = &NestedRequirement{Constraint: constraint}
5346 if r := fn(nr); r != nil {
5347 return r
5348 }
5349 return nr
5350 }
5351
5352 func (nr *NestedRequirement) GoString() string {
5353 return nr.goString(0, "")
5354 }
5355
5356 func (nr *NestedRequirement) goString(indent int, field string) string {
5357 return fmt.Sprintf("%*s%sNestedRequirement:\n%s", indent, "", field,
5358 nr.Constraint.goString(indent+2, ""))
5359 }
5360
5361 // ExplicitObjectParameter represents a C++23 explicit object parameter.
5362 type ExplicitObjectParameter struct {
5363 Base AST
5364 }
5365
5366 func (eop *ExplicitObjectParameter) print(ps *printState) {
5367 ps.writeString("this ")
5368 ps.print(eop.Base)
5369 }
5370
5371 func (eop *ExplicitObjectParameter) Traverse(fn func(AST) bool) {
5372 if fn(eop) {
5373 eop.Base.Traverse(fn)
5374 }
5375 }
5376
5377 func (eop *ExplicitObjectParameter) Copy(fn func(AST) AST, skip func(AST) bool) AST {
5378 if skip(eop) {
5379 return nil
5380 }
5381 base := eop.Base.Copy(fn, skip)
5382 if base == nil {
5383 return fn(eop)
5384 }
5385 eop = &ExplicitObjectParameter{Base: base}
5386 if r := fn(eop); r != nil {
5387 return r
5388 }
5389 return eop
5390 }
5391
5392 func (eop *ExplicitObjectParameter) GoString() string {
5393 return eop.goString(0, "")
5394 }
5395
5396 func (eop *ExplicitObjectParameter) goString(indent int, field string) string {
5397 return fmt.Sprintf("%*s%sExplicitObjectParameter:\n%s", indent, "", field,
5398 eop.Base.goString(indent+2, ""))
5399 }
5400
5401 // Print the inner types.
5402 func (ps *printState) printInner(prefixOnly bool) []AST {
5403 var save []AST
5404 var psave *[]AST
5405 if prefixOnly {
5406 psave = &save
5407 }
5408 for len(ps.inner) > 0 {
5409 ps.printOneInner(psave)
5410 }
5411 return save
5412 }
5413
5414 // innerPrinter is an interface for types that can print themselves as
5415 // inner types.
5416 type innerPrinter interface {
5417 printInner(*printState)
5418 }
5419
5420 // Print the most recent inner type. If save is not nil, only print
5421 // prefixes.
5422 func (ps *printState) printOneInner(save *[]AST) {
5423 if len(ps.inner) == 0 {
5424 panic("printOneInner called with no inner types")
5425 }
5426 ln := len(ps.inner)
5427 a := ps.inner[ln-1]
5428 ps.inner = ps.inner[:ln-1]
5429
5430 if save != nil {
5431 if _, ok := a.(*MethodWithQualifiers); ok {
5432 *save = append(*save, a)
5433 return
5434 }
5435 }
5436
5437 if ip, ok := a.(innerPrinter); ok {
5438 ip.printInner(ps)
5439 } else {
5440 ps.print(a)
5441 }
5442 }
5443
5444 // isEmpty returns whether printing a will not print anything.
5445 func (ps *printState) isEmpty(a AST) bool {
5446 switch a := a.(type) {
5447 case *ArgumentPack:
5448 for _, a := range a.Args {
5449 if !ps.isEmpty(a) {
5450 return false
5451 }
5452 }
5453 return true
5454 case *ExprList:
5455 return len(a.Exprs) == 0
5456 case *PackExpansion:
5457 return a.Pack != nil && ps.isEmpty(a.Base)
5458 default:
5459 return false
5460 }
5461 }