Debian Codegraph @

demangle.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 defines functions that demangle GCC/LLVM
6 // C++ and Rust symbol names.
7 // This package recognizes names that were mangled according to the C++ ABI
8 // defined at http://codesourcery.com/cxx-abi/ and the Rust ABI
9 // defined at
10 // https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html
11 //
12 // Most programs will want to call Filter or ToString.
13 package demangle
14
15 import (
16 "errors"
17 "fmt"
18 "strings"
19 )
20
21 // ErrNotMangledName is returned by CheckedDemangle if the string does
22 // not appear to be a C++ symbol name.
23 var ErrNotMangledName = errors.New("not a C++ or Rust mangled name")
24
25 // Option is the type of demangler options.
26 type Option int
27
28 const (
29 // The NoParams option disables demangling of function parameters.
30 // It only omits the parameters of the function name being demangled,
31 // not the parameter types of other functions that may be mentioned.
32 // Using the option will speed up the demangler and cause it to
33 // use less memory.
34 NoParams Option = iota
35
36 // The NoTemplateParams option disables demangling of template parameters.
37 // This applies to both C++ and Rust.
38 NoTemplateParams
39
40 // The NoEnclosingParams option disables demangling of the function
41 // parameter types of the enclosing function when demangling a
42 // local name defined within a function.
43 NoEnclosingParams
44
45 // The NoClones option disables inclusion of clone suffixes.
46 // NoParams implies NoClones.
47 NoClones
48
49 // The NoRust option disables demangling of old-style Rust
50 // mangled names, which can be confused with C++ style mangled
51 // names. New style Rust mangled names are still recognized.
52 NoRust
53
54 // The Verbose option turns on more verbose demangling.
55 Verbose
56
57 // LLVMStyle tries to translate an AST to a string in the
58 // style of the LLVM demangler. This does not affect
59 // the parsing of the AST, only the conversion of the AST
60 // to a string.
61 LLVMStyle
62 )
63
64 // maxLengthShift is how we shift the MaxLength value.
65 const maxLengthShift = 16
66
67 // maxLengthMask is a mask for the maxLength value.
68 const maxLengthMask = 0x1f << maxLengthShift
69
70 // MaxLength returns an Option that limits the maximum length of a
71 // demangled string. The maximum length is expressed as a power of 2,
72 // so a value of 1 limits the returned string to 2 characters, and
73 // a value of 16 limits the returned string to 65,536 characters.
74 // The value must be between 1 and 30.
75 func MaxLength(pow int) Option {
76 if pow <= 0 || pow > 30 {
77 panic("demangle: invalid MaxLength value")
78 }
79 return Option(pow << maxLengthShift)
80 }
81
82 // isMaxLength reports whether an Option holds a maximum length.
83 func isMaxLength(opt Option) bool {
84 return opt&maxLengthMask != 0
85 }
86
87 // maxLength returns the maximum length stored in an Option.
88 func maxLength(opt Option) int {
89 return 1 << ((opt & maxLengthMask) >> maxLengthShift)
90 }
91
92 // Filter demangles a C++ or Rust symbol name,
93 // returning the human-readable C++ or Rust name.
94 // If any error occurs during demangling, the input string is returned.
95 func Filter(name string, options ...Option) string {
96 ret, err := ToString(name, options...)
97 if err != nil {
98 return name
99 }
100 return ret
101 }
102
103 // ToString demangles a C++ or Rust symbol name,
104 // returning a human-readable C++ or Rust name or an error.
105 // If the name does not appear to be a C++ or Rust symbol name at all,
106 // the error will be ErrNotMangledName.
107 func ToString(name string, options ...Option) (string, error) {
108 if strings.HasPrefix(name, "_R") {
109 return rustToString(name, options)
110 }
111
112 // Check for an old-style Rust mangled name.
113 // It starts with _ZN and ends with "17h" followed by 16 hex digits
114 // followed by "E" followed by an optional suffix starting with "."
115 // (which we ignore).
116 if strings.HasPrefix(name, "_ZN") {
117 rname := name
118 if pos := strings.LastIndex(rname, "E."); pos > 0 {
119 rname = rname[:pos+1]
120 }
121 if strings.HasSuffix(rname, "E") && len(rname) > 23 && rname[len(rname)-20:len(rname)-17] == "17h" {
122 noRust := false
123 for _, o := range options {
124 if o == NoRust {
125 noRust = true
126 break
127 }
128 }
129 if !noRust {
130 s, ok := oldRustToString(rname, options)
131 if ok {
132 return s, nil
133 }
134 }
135 }
136 }
137
138 a, err := ToAST(name, options...)
139 if err != nil {
140 return "", err
141 }
142 return ASTToString(a, options...), nil
143 }
144
145 // ToAST demangles a C++ symbol name into an abstract syntax tree
146 // representing the symbol.
147 // If the NoParams option is passed, and the name has a function type,
148 // the parameter types are not demangled.
149 // If the name does not appear to be a C++ symbol name at all, the
150 // error will be ErrNotMangledName.
151 // This function does not currently support Rust symbol names.
152 func ToAST(name string, options ...Option) (AST, error) {
153 if strings.HasPrefix(name, "_Z") {
154 a, err := doDemangle(name[2:], options...)
155 return a, adjustErr(err, 2)
156 }
157
158 if strings.HasPrefix(name, "___Z") {
159 // clang extensions
160 block := strings.LastIndex(name, "_block_invoke")
161 if block == -1 {
162 return nil, ErrNotMangledName
163 }
164 a, err := doDemangle(name[4:block], options...)
165 if err != nil {
166 return a, adjustErr(err, 4)
167 }
168 name = strings.TrimPrefix(name[block:], "_block_invoke")
169 if len(name) > 0 && name[0] == '_' {
170 name = name[1:]
171 }
172 for len(name) > 0 && isDigit(name[0]) {
173 name = name[1:]
174 }
175 if len(name) > 0 && name[0] != '.' {
176 return nil, errors.New("unparsed characters at end of mangled name")
177 }
178 a = &Special{Prefix: "invocation function for block in ", Val: a}
179 return a, nil
180 }
181
182 const prefix = "_GLOBAL_"
183 if strings.HasPrefix(name, prefix) {
184 // The standard demangler ignores NoParams for global
185 // constructors. We are compatible.
186 i := 0
187 for i < len(options) {
188 if options[i] == NoParams {
189 options = append(options[:i:i], options[i+1:]...)
190 } else {
191 i++
192 }
193 }
194 a, err := globalCDtorName(name[len(prefix):], options...)
195 return a, adjustErr(err, len(prefix))
196 }
197
198 return nil, ErrNotMangledName
199 }
200
201 // globalCDtorName demangles a global constructor/destructor symbol name.
202 // The parameter is the string following the "_GLOBAL_" prefix.
203 func globalCDtorName(name string, options ...Option) (AST, error) {
204 if len(name) < 4 {
205 return nil, ErrNotMangledName
206 }
207 switch name[0] {
208 case '.', '_', '$':
209 default:
210 return nil, ErrNotMangledName
211 }
212
213 var ctor bool
214 switch name[1] {
215 case 'I':
216 ctor = true
217 case 'D':
218 ctor = false
219 default:
220 return nil, ErrNotMangledName
221 }
222
223 if name[2] != '_' {
224 return nil, ErrNotMangledName
225 }
226
227 if !strings.HasPrefix(name[3:], "_Z") {
228 return &GlobalCDtor{Ctor: ctor, Key: &Name{Name: name}}, nil
229 } else {
230 a, err := doDemangle(name[5:], options...)
231 if err != nil {
232 return nil, adjustErr(err, 5)
233 }
234 return &GlobalCDtor{Ctor: ctor, Key: a}, nil
235 }
236 }
237
238 // The doDemangle function is the entry point into the demangler proper.
239 func doDemangle(name string, options ...Option) (ret AST, err error) {
240 // When the demangling routines encounter an error, they panic
241 // with a value of type demangleErr.
242 defer func() {
243 if r := recover(); r != nil {
244 if de, ok := r.(demangleErr); ok {
245 ret = nil
246 err = de
247 return
248 }
249 panic(r)
250 }
251 }()
252
253 params := true
254 clones := true
255 verbose := false
256 for _, o := range options {
257 switch {
258 case o == NoParams:
259 params = false
260 clones = false
261 case o == NoClones:
262 clones = false
263 case o == Verbose:
264 verbose = true
265 case o == NoTemplateParams || o == NoEnclosingParams || o == LLVMStyle || isMaxLength(o):
266 // These are valid options but only affect
267 // printing of the AST.
268 case o == NoRust:
269 // Unimportant here.
270 default:
271 return nil, fmt.Errorf("unrecognized demangler option %v", o)
272 }
273 }
274
275 st := &state{str: name, verbose: verbose}
276 a := st.encoding(params, notForLocalName)
277
278 // Accept a clone suffix.
279 if clones {
280 for len(st.str) > 1 && st.str[0] == '.' && (isLower(st.str[1]) || st.str[1] == '_' || isDigit(st.str[1])) {
281 a = st.cloneSuffix(a)
282 }
283 }
284
285 if clones && len(st.str) > 0 {
286 st.fail("unparsed characters at end of mangled name")
287 }
288
289 return a, nil
290 }
291
292 // A state holds the current state of demangling a string.
293 type state struct {
294 str string // remainder of string to demangle
295 verbose bool // whether to use verbose demangling
296 off int // offset of str within original string
297 subs substitutions // substitutions
298 templates []*Template // templates being processed
299
300 // The number of entries in templates when we started parsing
301 // a lambda, plus 1 so that 0 means not parsing a lambda.
302 lambdaTemplateLevel int
303
304 parsingConstraint bool // whether parsing a constraint expression
305
306 // Counts of template parameters without template arguments,
307 // for lambdas.
308 typeTemplateParamCount int
309 nonTypeTemplateParamCount int
310 templateTemplateParamCount int
311 }
312
313 // copy returns a copy of the current state.
314 func (st *state) copy() *state {
315 n := new(state)
316 *n = *st
317 return n
318 }
319
320 // fail panics with demangleErr, to be caught in doDemangle.
321 func (st *state) fail(err string) {
322 panic(demangleErr{err: err, off: st.off})
323 }
324
325 // failEarlier is like fail, but decrements the offset to indicate
326 // that the point of failure occurred earlier in the string.
327 func (st *state) failEarlier(err string, dec int) {
328 if st.off < dec {
329 panic("internal error")
330 }
331 panic(demangleErr{err: err, off: st.off - dec})
332 }
333
334 // advance advances the current string offset.
335 func (st *state) advance(add int) {
336 if len(st.str) < add {
337 panic("internal error")
338 }
339 st.str = st.str[add:]
340 st.off += add
341 }
342
343 // checkChar requires that the next character in the string be c, and
344 // advances past it.
345 func (st *state) checkChar(c byte) {
346 if len(st.str) == 0 || st.str[0] != c {
347 panic("internal error")
348 }
349 st.advance(1)
350 }
351
352 // A demangleErr is an error at a specific offset in the mangled
353 // string.
354 type demangleErr struct {
355 err string
356 off int
357 }
358
359 // Error implements the builtin error interface for demangleErr.
360 func (de demangleErr) Error() string {
361 return fmt.Sprintf("%s at %d", de.err, de.off)
362 }
363
364 // adjustErr adjusts the position of err, if it is a demangleErr,
365 // and returns err.
366 func adjustErr(err error, adj int) error {
367 if err == nil {
368 return nil
369 }
370 if de, ok := err.(demangleErr); ok {
371 de.off += adj
372 return de
373 }
374 return err
375 }
376
377 type forLocalNameType int
378
379 const (
380 forLocalName forLocalNameType = iota
381 notForLocalName
382 )
383
384 // encoding parses:
385 //
386 // encoding ::= <(function) name> <bare-function-type>
387 // <(data) name>
388 // <special-name>
389 func (st *state) encoding(params bool, local forLocalNameType) AST {
390 if len(st.str) < 1 {
391 st.fail("expected encoding")
392 }
393
394 if st.str[0] == 'G' || st.str[0] == 'T' {
395 return st.specialName()
396 }
397
398 a, explicitObjectParameter := st.name()
399 a = simplify(a)
400
401 if !params {
402 // Don't demangle the parameters.
403
404 // Strip CV-qualifiers, as they apply to the 'this'
405 // parameter, and are not output by the standard
406 // demangler without parameters.
407 if mwq, ok := a.(*MethodWithQualifiers); ok {
408 a = mwq.Method
409 }
410
411 // If this is a local name, there may be CV-qualifiers
412 // on the name that really apply to the top level, and
413 // therefore must be discarded when discarding
414 // parameters. This can happen when parsing a class
415 // that is local to a function.
416 if q, ok := a.(*Qualified); ok && q.LocalName {
417 p := &q.Name
418 if da, ok := (*p).(*DefaultArg); ok {
419 p = &da.Arg
420 }
421 if mwq, ok := (*p).(*MethodWithQualifiers); ok {
422 *p = mwq.Method
423 }
424 }
425
426 return a
427 }
428
429 if len(st.str) == 0 || st.str[0] == 'E' {
430 // There are no parameters--this is a data symbol, not
431 // a function symbol.
432 return a
433 }
434
435 mwq, _ := a.(*MethodWithQualifiers)
436
437 var findTemplate func(AST) *Template
438 findTemplate = func(check AST) *Template {
439 switch check := check.(type) {
440 case *Template:
441 return check
442 case *Qualified:
443 if check.LocalName {
444 return findTemplate(check.Name)
445 } else if _, ok := check.Name.(*Constructor); ok {
446 return findTemplate(check.Name)
447 }
448 case *MethodWithQualifiers:
449 return findTemplate(check.Method)
450 case *Constructor:
451 if check.Base != nil {
452 return findTemplate(check.Base)
453 }
454 case *Constraint:
455 return findTemplate(check.Name)
456 }
457 return nil
458 }
459
460 template := findTemplate(a)
461 var oldLambdaTemplateLevel int
462 if template != nil {
463 st.templates = append(st.templates, template)
464 oldLambdaTemplateLevel = st.lambdaTemplateLevel
465 st.lambdaTemplateLevel = 0
466 }
467
468 // Checking for the enable_if attribute here is what the LLVM
469 // demangler does. This is not very general but perhaps it is
470 // sufficient.
471 const enableIfPrefix = "Ua9enable_ifI"
472 var (
473 enableIfArgs []AST
474 enableIfConstraint AST
475 )
476 if strings.HasPrefix(st.str, enableIfPrefix) {
477 st.advance(len(enableIfPrefix) - 1)
478 enableIfArgs, enableIfConstraint = st.templateArgs()
479 }
480
481 ft := st.bareFunctionType(hasReturnType(a), explicitObjectParameter)
482
483 var constraint AST
484 if len(st.str) > 0 && st.str[0] == 'Q' {
485 constraint = st.constraintExpr()
486 }
487
488 if template != nil {
489 st.templates = st.templates[:len(st.templates)-1]
490 st.lambdaTemplateLevel = oldLambdaTemplateLevel
491 }
492
493 ft = simplify(ft)
494
495 // For a local name, discard the return type, so that it
496 // doesn't get confused with the top level return type.
497 if local == forLocalName {
498 if functype, ok := ft.(*FunctionType); ok {
499 functype.ForLocalName = true
500 }
501 }
502
503 // Any top-level qualifiers belong to the function type.
504 if mwq != nil {
505 a = mwq.Method
506 mwq.Method = ft
507 ft = mwq
508 }
509 if q, ok := a.(*Qualified); ok && q.LocalName {
510 p := &q.Name
511 if da, ok := (*p).(*DefaultArg); ok {
512 p = &da.Arg
513 }
514 if mwq, ok := (*p).(*MethodWithQualifiers); ok {
515 *p = mwq.Method
516 mwq.Method = ft
517 ft = mwq
518 }
519 }
520
521 // Any top-level constraint belongs on the function type.
522 var forTemplateArgs bool
523 if c, ok := a.(*Constraint); ok && constraint == nil {
524 a = c.Name
525 constraint = c.Requires
526 forTemplateArgs = c.ForTemplateArgs
527 }
528
529 r := AST(&Typed{Name: a, Type: ft})
530
531 if len(enableIfArgs) > 0 {
532 r = &EnableIf{Type: r, Args: enableIfArgs}
533 r = st.maybeAddConstraint(r, enableIfConstraint)
534 }
535
536 if constraint != nil {
537 r = &Constraint{
538 Name: r,
539 Requires: constraint,
540 ForTemplateArgs: forTemplateArgs,
541 }
542 }
543
544 return r
545 }
546
547 // hasReturnType returns whether the mangled form of a will have a
548 // return type.
549 func hasReturnType(a AST) bool {
550 switch a := a.(type) {
551 case *Qualified:
552 if a.LocalName {
553 return hasReturnType(a.Name)
554 }
555 return false
556 case *Template:
557 return !isCDtorConversion(a.Name)
558 case *TypeWithQualifiers:
559 return hasReturnType(a.Base)
560 case *MethodWithQualifiers:
561 return hasReturnType(a.Method)
562 case *Constraint:
563 return hasReturnType(a.Name)
564 default:
565 return false
566 }
567 }
568
569 // isCDtorConversion returns when an AST is a constructor, a
570 // destructor, or a conversion operator.
571 func isCDtorConversion(a AST) bool {
572 switch a := a.(type) {
573 case *Qualified:
574 return isCDtorConversion(a.Name)
575 case *Constructor, *Destructor, *Cast:
576 return true
577 default:
578 return false
579 }
580 }
581
582 // taggedName parses:
583 //
584 // <tagged-name> ::= <name> B <source-name>
585 func (st *state) taggedName(a AST) AST {
586 for len(st.str) > 0 && st.str[0] == 'B' {
587 st.advance(1)
588 tag := st.sourceName()
589 a = &TaggedName{Name: a, Tag: tag}
590 }
591 return a
592 }
593
594 // name parses:
595 //
596 // <name> ::= <nested-name>
597 // ::= <unscoped-name>
598 // ::= <unscoped-template-name> <template-args>
599 // ::= <local-name>
600 //
601 // <unscoped-name> ::= <unqualified-name>
602 // ::= St <unqualified-name>
603 //
604 // <unscoped-template-name> ::= <unscoped-name>
605 // ::= <substitution>
606 //
607 // Besides the name, this returns whether it saw the code indicating
608 // a C++23 explicit object parameter.
609 func (st *state) name() (AST, bool) {
610 if len(st.str) < 1 {
611 st.fail("expected name")
612 }
613
614 var module AST
615 switch st.str[0] {
616 case 'N':
617 return st.nestedName()
618 case 'Z':
619 return st.localName()
620 case 'U':
621 a, isCast := st.unqualifiedName(nil)
622 if isCast {
623 st.setTemplate(a, nil)
624 }
625 return a, false
626 case 'S':
627 if len(st.str) < 2 {
628 st.advance(1)
629 st.fail("expected substitution index")
630 }
631 var a AST
632 isCast := false
633 subst := false
634 if st.str[1] == 't' {
635 st.advance(2)
636 a, isCast = st.unqualifiedName(nil)
637 a = &Qualified{Scope: &Name{Name: "std"}, Name: a, LocalName: false}
638 } else {
639 a = st.substitution(false)
640 if mn, ok := a.(*ModuleName); ok {
641 module = mn
642 break
643 }
644 subst = true
645 }
646 var constraint AST
647 if len(st.str) > 0 && st.str[0] == 'I' {
648 // This can only happen if we saw
649 // <unscoped-template-name> and are about to see
650 // <template-args>. <unscoped-template-name> is a
651 // substitution candidate if it did not come from a
652 // substitution.
653 if !subst {
654 st.subs.add(a)
655 }
656 var args []AST
657 args, constraint = st.templateArgs()
658 tmpl := &Template{Name: a, Args: args}
659 if isCast {
660 st.setTemplate(a, tmpl)
661 st.clearTemplateArgs(args)
662 isCast = false
663 }
664 a = tmpl
665 }
666 if isCast {
667 st.setTemplate(a, nil)
668 }
669 a = st.maybeAddConstraint(a, constraint)
670 return a, false
671 }
672
673 a, isCast := st.unqualifiedName(module)
674 var constraint AST
675 if len(st.str) > 0 && st.str[0] == 'I' {
676 st.subs.add(a)
677 var args []AST
678 args, constraint = st.templateArgs()
679 tmpl := &Template{Name: a, Args: args}
680 if isCast {
681 st.setTemplate(a, tmpl)
682 st.clearTemplateArgs(args)
683 isCast = false
684 }
685 a = tmpl
686 }
687 if isCast {
688 st.setTemplate(a, nil)
689 }
690 a = st.maybeAddConstraint(a, constraint)
691 return a, false
692 }
693
694 // nestedName parses:
695 //
696 // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
697 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
698 //
699 // Besides the name, this returns whether it saw the code indicating
700 // a C++23 explicit object parameter.
701 func (st *state) nestedName() (AST, bool) {
702 st.checkChar('N')
703
704 var q AST
705 var r string
706
707 explicitObjectParameter := false
708 if len(st.str) > 0 && st.str[0] == 'H' {
709 st.advance(1)
710 explicitObjectParameter = true
711 } else {
712 q = st.cvQualifiers()
713 r = st.refQualifier()
714 }
715
716 a := st.prefix()
717
718 if q != nil || r != "" {
719 a = &MethodWithQualifiers{Method: a, Qualifiers: q, RefQualifier: r}
720 }
721 if len(st.str) == 0 || st.str[0] != 'E' {
722 st.fail("expected E after nested name")
723 }
724 st.advance(1)
725 return a, explicitObjectParameter
726 }
727
728 // prefix parses:
729 //
730 // <prefix> ::= <prefix> <unqualified-name>
731 // ::= <template-prefix> <template-args>
732 // ::= <template-param>
733 // ::= <decltype>
734 // ::=
735 // ::= <substitution>
736 //
737 // <template-prefix> ::= <prefix> <(template) unqualified-name>
738 // ::= <template-param>
739 // ::= <substitution>
740 //
741 // <decltype> ::= Dt <expression> E
742 // ::= DT <expression> E
743 func (st *state) prefix() AST {
744 var a AST
745
746 // The last name seen, for a constructor/destructor.
747 var last AST
748
749 var module AST
750
751 getLast := func(a AST) AST {
752 for {
753 if t, ok := a.(*Template); ok {
754 a = t.Name
755 } else if q, ok := a.(*Qualified); ok {
756 a = q.Name
757 } else if t, ok := a.(*TaggedName); ok {
758 a = t.Name
759 } else {
760 return a
761 }
762 }
763 }
764
765 var cast *Cast
766 for {
767 if len(st.str) == 0 {
768 st.fail("expected prefix")
769 }
770 var next AST
771
772 c := st.str[0]
773 if isDigit(c) || isLower(c) || c == 'U' || c == 'L' || c == 'F' || c == 'W' || (c == 'D' && len(st.str) > 1 && st.str[1] == 'C') {
774 un, isUnCast := st.unqualifiedName(module)
775 next = un
776 module = nil
777 if isUnCast {
778 if cast != nil {
779 st.fail("cast in scope of cast")
780 }
781 if m, ok := un.(*ModuleEntity); ok {
782 un = m.Name
783 }
784 for {
785 tn, ok := un.(*TaggedName)
786 if !ok {
787 break
788 }
789 un = tn.Name
790 }
791 if f, ok := un.(*Friend); ok {
792 un = f.Name
793 }
794 cast = un.(*Cast)
795 }
796 } else {
797 switch st.str[0] {
798 case 'C':
799 inheriting := false
800 st.advance(1)
801 if len(st.str) > 0 && st.str[0] == 'I' {
802 inheriting = true
803 st.advance(1)
804 }
805 if len(st.str) < 1 {
806 st.fail("expected constructor type")
807 }
808 if last == nil {
809 st.fail("constructor before name is seen")
810 }
811 switch st.str[0] {
812 // 0 is not used.
813 case '1', '2', '3', '4', '5':
814 default:
815 st.fail("unknown constructor type")
816 }
817 st.advance(1)
818 var base AST
819 if inheriting {
820 base = st.demangleType(false)
821 }
822 next = &Constructor{
823 Name: getLast(last),
824 Base: base,
825 }
826 if len(st.str) > 0 && st.str[0] == 'B' {
827 next = st.taggedName(next)
828 }
829 case 'D':
830 if len(st.str) > 1 && (st.str[1] == 'T' || st.str[1] == 't') {
831 next = st.demangleType(false)
832 } else {
833 if len(st.str) < 2 {
834 st.fail("expected destructor type")
835 }
836 if last == nil {
837 st.fail("destructor before name is seen")
838 }
839 switch st.str[1] {
840 // 3 is not used.
841 case '0', '1', '2', '4', '5':
842 default:
843 st.fail("unknown destructor type")
844 }
845 st.advance(2)
846 next = &Destructor{Name: getLast(last)}
847 if len(st.str) > 0 && st.str[0] == 'B' {
848 next = st.taggedName(next)
849 }
850 }
851 case 'S':
852 next = st.substitution(true)
853 if mn, ok := next.(*ModuleName); ok {
854 module = mn
855 next = nil
856 }
857 case 'I':
858 if a == nil {
859 st.fail("unexpected template arguments")
860 }
861 args, constraint := st.templateArgs()
862 tmpl := &Template{Name: a, Args: args}
863 if cast != nil {
864 st.setTemplate(cast, tmpl)
865 st.clearTemplateArgs(args)
866 cast = nil
867 }
868 a = nil
869 next = st.maybeAddConstraint(tmpl, constraint)
870 case 'T':
871 next = st.templateParam()
872 case 'E':
873 if a == nil {
874 st.fail("expected prefix")
875 }
876 if cast != nil {
877 var toTmpl *Template
878 if castTempl, ok := cast.To.(*Template); ok {
879 toTmpl = castTempl
880 }
881 st.setTemplate(cast, toTmpl)
882 }
883 return a
884 case 'M':
885 if a == nil {
886 st.fail("unexpected lambda initializer")
887 }
888 // This is the initializer scope for a
889 // lambda. We don't need to record
890 // it. The normal code will treat the
891 // variable has a type scope, which
892 // gives appropriate output.
893 st.advance(1)
894 continue
895 case 'J':
896 // It appears that in some cases clang
897 // can emit a J for a template arg
898 // without the expected I. I don't
899 // know when this happens, but I've
900 // seen it in some large C++ programs.
901 if a == nil {
902 st.fail("unexpected template arguments")
903 }
904 var args []AST
905 for len(st.str) == 0 || st.str[0] != 'E' {
906 arg := st.templateArg(nil)
907 args = append(args, arg)
908 }
909 st.advance(1)
910 tmpl := &Template{Name: a, Args: args}
911 if cast != nil {
912 st.setTemplate(cast, tmpl)
913 st.clearTemplateArgs(args)
914 cast = nil
915 }
916 a = nil
917 next = tmpl
918 default:
919 st.fail("unrecognized letter in prefix")
920 }
921 }
922
923 if next == nil {
924 continue
925 }
926
927 last = next
928 if a == nil {
929 a = next
930 } else {
931 a = &Qualified{Scope: a, Name: next, LocalName: false}
932 }
933
934 if c != 'S' && (len(st.str) == 0 || st.str[0] != 'E') {
935 st.subs.add(a)
936 }
937 }
938 }
939
940 // unqualifiedName parses:
941 //
942 // <unqualified-name> ::= <operator-name>
943 // ::= <ctor-dtor-name>
944 // ::= <source-name>
945 // ::= <local-source-name>
946 //
947 // <local-source-name> ::= L <source-name> <discriminator>
948 func (st *state) unqualifiedName(module AST) (r AST, isCast bool) {
949 module = st.moduleName(module)
950
951 if len(st.str) < 1 {
952 st.fail("expected unqualified name")
953 }
954
955 friend := false
956 if len(st.str) > 0 && st.str[0] == 'F' {
957 st.advance(1)
958 friend = true
959 if len(st.str) < 1 {
960 st.fail("expected unqualified name")
961 }
962 }
963
964 var a AST
965 isCast = false
966 c := st.str[0]
967 if isDigit(c) {
968 a = st.sourceName()
969 } else if isLower(c) {
970 a, _ = st.operatorName(false)
971 if _, ok := a.(*Cast); ok {
972 isCast = true
973 }
974 if op, ok := a.(*Operator); ok && op.Name == `operator"" ` {
975 n := st.sourceName()
976 a = &Unary{Op: op, Expr: n, Suffix: false, SizeofType: false}
977 }
978 } else if c == 'D' && len(st.str) > 1 && st.str[1] == 'C' {
979 var bindings []AST
980 st.advance(2)
981 for {
982 binding := st.sourceName()
983 bindings = append(bindings, binding)
984 if len(st.str) > 0 && st.str[0] == 'E' {
985 st.advance(1)
986 break
987 }
988 }
989 a = &StructuredBindings{Bindings: bindings}
990 } else {
991 switch c {
992 case 'C', 'D':
993 st.fail("constructor/destructor not in nested name")
994 case 'L':
995 st.advance(1)
996 a = st.sourceName()
997 a = st.discriminator(a)
998 case 'U':
999 if len(st.str) < 2 {
1000 st.advance(1)
1001 st.fail("expected closure or unnamed type")
1002 }
1003 c := st.str[1]
1004 switch c {
1005 case 'b':
1006 st.advance(2)
1007 st.compactNumber()
1008 a = &Name{Name: "'block-literal'"}
1009 case 'e':
1010 a = st.unnamedEnum()
1011 case 'l':
1012 a = st.closureTypeName()
1013 case 't':
1014 a = st.unnamedTypeName()
1015 default:
1016 st.advance(1)
1017 st.fail("expected closure or unnamed type")
1018 }
1019 default:
1020 st.fail("expected unqualified name")
1021 }
1022 }
1023
1024 if module != nil {
1025 a = &ModuleEntity{Module: module, Name: a}
1026 }
1027
1028 if len(st.str) > 0 && st.str[0] == 'B' {
1029 a = st.taggedName(a)
1030 }
1031
1032 if friend {
1033 a = &Friend{Name: a}
1034 }
1035
1036 return a, isCast
1037 }
1038
1039 // sourceName parses:
1040 //
1041 // <source-name> ::= <(positive length) number> <identifier>
1042 // identifier ::= <(unqualified source code identifier)>
1043 func (st *state) sourceName() AST {
1044 val := st.number()
1045 if val <= 0 {
1046 st.fail("expected positive number")
1047 }
1048 if len(st.str) < val {
1049 st.fail("not enough characters for identifier")
1050 }
1051 id := st.str[:val]
1052 st.advance(val)
1053
1054 // Look for GCC encoding of anonymous namespace, and make it
1055 // more friendly.
1056 const anonPrefix = "_GLOBAL_"
1057 if strings.HasPrefix(id, anonPrefix) && len(id) > len(anonPrefix)+2 {
1058 c1 := id[len(anonPrefix)]
1059 c2 := id[len(anonPrefix)+1]
1060 if (c1 == '.' || c1 == '_' || c1 == '$') && c2 == 'N' {
1061 id = "(anonymous namespace)"
1062 }
1063 }
1064
1065 n := &Name{Name: id}
1066 return n
1067 }
1068
1069 // moduleName parses:
1070 //
1071 // <module-name> ::= <module-subname>
1072 // ::= <module-name> <module-subname>
1073 // ::= <substitution> # passed in by caller
1074 // <module-subname> ::= W <source-name>
1075 // ::= W P <source-name>
1076 //
1077 // The module name is optional. If it is not present, this returns the parent.
1078 func (st *state) moduleName(parent AST) AST {
1079 ret := parent
1080 for len(st.str) > 0 && st.str[0] == 'W' {
1081 st.advance(1)
1082 isPartition := false
1083 if len(st.str) > 0 && st.str[0] == 'P' {
1084 st.advance(1)
1085 isPartition = true
1086 }
1087 name := st.sourceName()
1088 ret = &ModuleName{
1089 Parent: ret,
1090 Name: name,
1091 IsPartition: isPartition,
1092 }
1093 st.subs.add(ret)
1094 }
1095 return ret
1096 }
1097
1098 // number parses:
1099 //
1100 // number ::= [n] <(non-negative decimal integer)>
1101 func (st *state) number() int {
1102 neg := false
1103 if len(st.str) > 0 && st.str[0] == 'n' {
1104 neg = true
1105 st.advance(1)
1106 }
1107 if len(st.str) == 0 || !isDigit(st.str[0]) {
1108 st.fail("missing number")
1109 }
1110 val := 0
1111 for len(st.str) > 0 && isDigit(st.str[0]) {
1112 // Number picked to ensure we can't overflow with 32-bit int.
1113 // Any very large number here is bogus.
1114 if val >= 0x80000000/10-10 {
1115 st.fail("numeric overflow")
1116 }
1117 val = val*10 + int(st.str[0]-'0')
1118 st.advance(1)
1119 }
1120 if neg {
1121 val = -val
1122 }
1123 return val
1124 }
1125
1126 // seqID parses:
1127 //
1128 // <seq-id> ::= <0-9A-Z>+
1129 //
1130 // We expect this to be followed by an underscore.
1131 func (st *state) seqID(eofOK bool) int {
1132 if len(st.str) > 0 && st.str[0] == '_' {
1133 st.advance(1)
1134 return 0
1135 }
1136 id := 0
1137 for {
1138 if len(st.str) == 0 {
1139 if eofOK {
1140 return id + 1
1141 }
1142 st.fail("missing end to sequence ID")
1143 }
1144 // Don't overflow a 32-bit int.
1145 if id >= 0x80000000/36-36 {
1146 st.fail("sequence ID overflow")
1147 }
1148 c := st.str[0]
1149 if c == '_' {
1150 st.advance(1)
1151 return id + 1
1152 }
1153 if isDigit(c) {
1154 id = id*36 + int(c-'0')
1155 } else if isUpper(c) {
1156 id = id*36 + int(c-'A') + 10
1157 } else {
1158 st.fail("invalid character in sequence ID")
1159 }
1160 st.advance(1)
1161 }
1162 }
1163
1164 // An operator is the demangled name, and the number of arguments it
1165 // takes in an expression.
1166 type operator struct {
1167 name string
1168 args int
1169 prec precedence
1170 }
1171
1172 // The operators map maps the mangled operator names to information
1173 // about them.
1174 var operators = map[string]operator{
1175 "aN": {"&=", 2, precAssign},
1176 "aS": {"=", 2, precAssign},
1177 "aa": {"&&", 2, precLogicalAnd},
1178 "ad": {"&", 1, precUnary},
1179 "an": {"&", 2, precAnd},
1180 "at": {"alignof ", 1, precUnary},
1181 "aw": {"co_await ", 1, precPrimary},
1182 "az": {"alignof ", 1, precUnary},
1183 "cc": {"const_cast", 2, precPostfix},
1184 "cl": {"()", 2, precPostfix},
1185 // cp is not in the ABI but is used by clang "when the call
1186 // would use ADL except for being parenthesized."
1187 // The trailing space indicates this to the printer.
1188 "cp": {"() ", 2, precPostfix},
1189 "cm": {",", 2, precComma},
1190 "co": {"~", 1, precUnary},
1191 "dV": {"/=", 2, precAssign},
1192 "dX": {"[...]=", 3, precAssign},
1193 "da": {"delete[] ", 1, precUnary},
1194 "dc": {"dynamic_cast", 2, precPostfix},
1195 "de": {"*", 1, precUnary},
1196 "di": {"=", 2, precAssign},
1197 "dl": {"delete ", 1, precUnary},
1198 "ds": {".*", 2, precPtrMem},
1199 "dt": {".", 2, precPostfix},
1200 "dv": {"/", 2, precAssign},
1201 "dx": {"]=", 2, precAssign},
1202 "eO": {"^=", 2, precAssign},
1203 "eo": {"^", 2, precXor},
1204 "eq": {"==", 2, precEqual},
1205 "fl": {"...", 2, precPrimary},
1206 "fr": {"...", 2, precPrimary},
1207 "fL": {"...", 3, precPrimary},
1208 "fR": {"...", 3, precPrimary},
1209 "ge": {">=", 2, precRel},
1210 "gs": {"::", 1, precUnary},
1211 "gt": {">", 2, precRel},
1212 "ix": {"[]", 2, precPostfix},
1213 "lS": {"<<=", 2, precAssign},
1214 "le": {"<=", 2, precRel},
1215 "li": {`operator"" `, 1, precUnary},
1216 "ls": {"<<", 2, precShift},
1217 "lt": {"<", 2, precRel},
1218 "mI": {"-=", 2, precAssign},
1219 "mL": {"*=", 2, precAssign},
1220 "mi": {"-", 2, precAdd},
1221 "ml": {"*", 2, precMul},
1222 "mm": {"--", 1, precPostfix},
1223 "na": {"new[]", 3, precUnary},
1224 "ne": {"!=", 2, precEqual},
1225 "ng": {"-", 1, precUnary},
1226 "nt": {"!", 1, precUnary},
1227 "nw": {"new", 3, precUnary},
1228 "nx": {"noexcept", 1, precUnary},
1229 "oR": {"|=", 2, precAssign},
1230 "oo": {"||", 2, precLogicalOr},
1231 "or": {"|", 2, precOr},
1232 "pL": {"+=", 2, precAssign},
1233 "pl": {"+", 2, precAdd},
1234 "pm": {"->*", 2, precPtrMem},
1235 "pp": {"++", 1, precPostfix},
1236 "ps": {"+", 1, precUnary},
1237 "pt": {"->", 2, precPostfix},
1238 "qu": {"?", 3, precCond},
1239 "rM": {"%=", 2, precAssign},
1240 "rS": {">>=", 2, precAssign},
1241 "rc": {"reinterpret_cast", 2, precPostfix},
1242 "rm": {"%", 2, precMul},
1243 "rs": {">>", 2, precShift},
1244 "sP": {"sizeof...", 1, precUnary},
1245 "sZ": {"sizeof...", 1, precUnary},
1246 "sc": {"static_cast", 2, precPostfix},
1247 "ss": {"<=>", 2, precSpaceship},
1248 "st": {"sizeof ", 1, precUnary},
1249 "sz": {"sizeof ", 1, precUnary},
1250 "te": {"typeid ", 1, precPostfix},
1251 "ti": {"typeid ", 1, precPostfix},
1252 "tr": {"throw", 0, precPrimary},
1253 "tw": {"throw ", 1, precUnary},
1254 }
1255
1256 // operatorName parses:
1257 //
1258 // operator_name ::= many different two character encodings.
1259 // ::= cv <type>
1260 // ::= v <digit> <source-name>
1261 //
1262 // We need to know whether we are in an expression because it affects
1263 // how we handle template parameters in the type of a cast operator.
1264 func (st *state) operatorName(inExpression bool) (AST, int) {
1265 if len(st.str) < 2 {
1266 st.fail("missing operator code")
1267 }
1268 code := st.str[:2]
1269 st.advance(2)
1270 if code[0] == 'v' && isDigit(code[1]) {
1271 name := st.sourceName()
1272 return &Operator{Name: name.(*Name).Name}, int(code[1] - '0')
1273 } else if code == "cv" {
1274 // Push a nil on templates to indicate that template
1275 // parameters will have their template filled in
1276 // later.
1277 if !inExpression {
1278 st.templates = append(st.templates, nil)
1279 }
1280
1281 t := st.demangleType(!inExpression)
1282
1283 if !inExpression {
1284 st.templates = st.templates[:len(st.templates)-1]
1285 }
1286
1287 return &Cast{To: t}, 1
1288 } else if op, ok := operators[code]; ok {
1289 return &Operator{Name: op.name, precedence: op.prec}, op.args
1290 } else {
1291 st.failEarlier("unrecognized operator code", 2)
1292 panic("not reached")
1293 }
1294 }
1295
1296 // localName parses:
1297 //
1298 // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
1299 // ::= Z <(function) encoding> E s [<discriminator>]
1300 // ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
1301 //
1302 // Besides the name, this returns whether it saw the code indicating
1303 // a C++23 explicit object parameter.
1304 func (st *state) localName() (AST, bool) {
1305 st.checkChar('Z')
1306 fn := st.encoding(true, forLocalName)
1307 if len(st.str) == 0 || st.str[0] != 'E' {
1308 st.fail("expected E after local name")
1309 }
1310 st.advance(1)
1311 if len(st.str) > 0 && st.str[0] == 's' {
1312 st.advance(1)
1313 var n AST = &Name{Name: "string literal"}
1314 n = st.discriminator(n)
1315 return &Qualified{Scope: fn, Name: n, LocalName: true}, false
1316 } else {
1317 num := -1
1318 if len(st.str) > 0 && st.str[0] == 'd' {
1319 // Default argument scope.
1320 st.advance(1)
1321 num = st.compactNumber()
1322 }
1323 n, explicitObjectParameter := st.name()
1324 n = st.discriminator(n)
1325 if num >= 0 {
1326 n = &DefaultArg{Num: num, Arg: n}
1327 }
1328 return &Qualified{Scope: fn, Name: n, LocalName: true}, explicitObjectParameter
1329 }
1330 }
1331
1332 // Parse a Java resource special-name.
1333 func (st *state) javaResource() AST {
1334 off := st.off
1335 ln := st.number()
1336 if ln <= 1 {
1337 st.failEarlier("java resource length less than 1", st.off-off)
1338 }
1339 if len(st.str) == 0 || st.str[0] != '_' {
1340 st.fail("expected _ after number")
1341 }
1342 st.advance(1)
1343 ln--
1344 if len(st.str) < ln {
1345 st.fail("not enough characters for java resource length")
1346 }
1347 str := st.str[:ln]
1348 final := ""
1349 st.advance(ln)
1350 for i := 0; i < len(str); i++ {
1351 if str[i] != '$' {
1352 final += string(str[i])
1353 } else {
1354 if len(str) <= i+1 {
1355 st.failEarlier("java resource escape at end of string", 1)
1356 }
1357 i++
1358 r, ok := map[byte]string{
1359 'S': "/",
1360 '_': ".",
1361 '$': "$",
1362 }[str[i]]
1363 if !ok {
1364 st.failEarlier("unrecognized java resource escape", ln-i-1)
1365 }
1366 final += r
1367 }
1368 }
1369 return &Special{Prefix: "java resource ", Val: &Name{Name: final}}
1370 }
1371
1372 // specialName parses:
1373 //
1374 // <special-name> ::= TV <type>
1375 // ::= TT <type>
1376 // ::= TI <type>
1377 // ::= TS <type>
1378 // ::= TA <template-arg>
1379 // ::= GV <(object) name>
1380 // ::= T <call-offset> <(base) encoding>
1381 // ::= Tc <call-offset> <call-offset> <(base) encoding>
1382 // g++ extensions:
1383 // ::= TC <type> <(offset) number> _ <(base) type>
1384 // ::= TF <type>
1385 // ::= TJ <type>
1386 // ::= GR <name>
1387 // ::= GA <encoding>
1388 // ::= Gr <resource name>
1389 // ::= GTt <encoding>
1390 // ::= GTn <encoding>
1391 // ::= GI <module name>
1392 func (st *state) specialName() AST {
1393 if st.str[0] == 'T' {
1394 st.advance(1)
1395 if len(st.str) == 0 {
1396 st.fail("expected special name code")
1397 }
1398 c := st.str[0]
1399 st.advance(1)
1400 switch c {
1401 case 'V':
1402 t := st.demangleType(false)
1403 return &Special{Prefix: "vtable for ", Val: t}
1404 case 'T':
1405 t := st.demangleType(false)
1406 return &Special{Prefix: "VTT for ", Val: t}
1407 case 'I':
1408 t := st.demangleType(false)
1409 return &Special{Prefix: "typeinfo for ", Val: t}
1410 case 'S':
1411 t := st.demangleType(false)
1412 return &Special{Prefix: "typeinfo name for ", Val: t}
1413 case 'A':
1414 t := st.templateArg(nil)
1415 return &Special{Prefix: "template parameter object for ", Val: t}
1416 case 'h':
1417 st.callOffset('h')
1418 v := st.encoding(true, notForLocalName)
1419 return &Special{Prefix: "non-virtual thunk to ", Val: v}
1420 case 'v':
1421 st.callOffset('v')
1422 v := st.encoding(true, notForLocalName)
1423 return &Special{Prefix: "virtual thunk to ", Val: v}
1424 case 'c':
1425 st.callOffset(0)
1426 st.callOffset(0)
1427 v := st.encoding(true, notForLocalName)
1428 return &Special{Prefix: "covariant return thunk to ", Val: v}
1429 case 'C':
1430 derived := st.demangleType(false)
1431 off := st.off
1432 offset := st.number()
1433 if offset < 0 {
1434 st.failEarlier("expected positive offset", st.off-off)
1435 }
1436 if len(st.str) == 0 || st.str[0] != '_' {
1437 st.fail("expected _ after number")
1438 }
1439 st.advance(1)
1440 base := st.demangleType(false)
1441 return &Special2{Prefix: "construction vtable for ", Val1: base, Middle: "-in-", Val2: derived}
1442 case 'F':
1443 t := st.demangleType(false)
1444 return &Special{Prefix: "typeinfo fn for ", Val: t}
1445 case 'J':
1446 t := st.demangleType(false)
1447 return &Special{Prefix: "java Class for ", Val: t}
1448 case 'H':
1449 n, _ := st.name()
1450 return &Special{Prefix: "TLS init function for ", Val: n}
1451 case 'W':
1452 n, _ := st.name()
1453 return &Special{Prefix: "TLS wrapper function for ", Val: n}
1454 default:
1455 st.fail("unrecognized special T name code")
1456 panic("not reached")
1457 }
1458 } else {
1459 st.checkChar('G')
1460 if len(st.str) == 0 {
1461 st.fail("expected special name code")
1462 }
1463 c := st.str[0]
1464 st.advance(1)
1465 switch c {
1466 case 'V':
1467 n, _ := st.name()
1468 return &Special{Prefix: "guard variable for ", Val: n}
1469 case 'R':
1470 n, _ := st.name()
1471 st.seqID(true)
1472 return &Special{Prefix: "reference temporary for ", Val: n}
1473 case 'A':
1474 v := st.encoding(true, notForLocalName)
1475 return &Special{Prefix: "hidden alias for ", Val: v}
1476 case 'T':
1477 if len(st.str) == 0 {
1478 st.fail("expected special GT name code")
1479 }
1480 c := st.str[0]
1481 st.advance(1)
1482 v := st.encoding(true, notForLocalName)
1483 switch c {
1484 case 'n':
1485 return &Special{Prefix: "non-transaction clone for ", Val: v}
1486 default:
1487 // The proposal is that different
1488 // letters stand for different types
1489 // of transactional cloning. Treat
1490 // them all the same for now.
1491 fallthrough
1492 case 't':
1493 return &Special{Prefix: "transaction clone for ", Val: v}
1494 }
1495 case 'r':
1496 return st.javaResource()
1497 case 'I':
1498 module := st.moduleName(nil)
1499 if module == nil {
1500 st.fail("expected module after GI")
1501 }
1502 return &Special{Prefix: "initializer for module ", Val: module}
1503 default:
1504 st.fail("unrecognized special G name code")
1505 panic("not reached")
1506 }
1507 }
1508 }
1509
1510 // callOffset parses:
1511 //
1512 // <call-offset> ::= h <nv-offset> _
1513 // ::= v <v-offset> _
1514 //
1515 // <nv-offset> ::= <(offset) number>
1516 //
1517 // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
1518 //
1519 // The c parameter, if not 0, is a character we just read which is the
1520 // start of the <call-offset>.
1521 //
1522 // We don't display the offset information anywhere.
1523 func (st *state) callOffset(c byte) {
1524 if c == 0 {
1525 if len(st.str) == 0 {
1526 st.fail("missing call offset")
1527 }
1528 c = st.str[0]
1529 st.advance(1)
1530 }
1531 switch c {
1532 case 'h':
1533 st.number()
1534 case 'v':
1535 st.number()
1536 if len(st.str) == 0 || st.str[0] != '_' {
1537 st.fail("expected _ after number")
1538 }
1539 st.advance(1)
1540 st.number()
1541 default:
1542 st.failEarlier("unrecognized call offset code", 1)
1543 }
1544 if len(st.str) == 0 || st.str[0] != '_' {
1545 st.fail("expected _ after call offset")
1546 }
1547 st.advance(1)
1548 }
1549
1550 // builtinTypes maps the type letter to the type name.
1551 var builtinTypes = map[byte]string{
1552 'a': "signed char",
1553 'b': "bool",
1554 'c': "char",
1555 'd': "double",
1556 'e': "long double",
1557 'f': "float",
1558 'g': "__float128",
1559 'h': "unsigned char",
1560 'i': "int",
1561 'j': "unsigned int",
1562 'l': "long",
1563 'm': "unsigned long",
1564 'n': "__int128",
1565 'o': "unsigned __int128",
1566 's': "short",
1567 't': "unsigned short",
1568 'v': "void",
1569 'w': "wchar_t",
1570 'x': "long long",
1571 'y': "unsigned long long",
1572 'z': "...",
1573 }
1574
1575 // demangleType parses:
1576 //
1577 // <type> ::= <builtin-type>
1578 // ::= <function-type>
1579 // ::= <class-enum-type>
1580 // ::= <array-type>
1581 // ::= <pointer-to-member-type>
1582 // ::= <template-param>
1583 // ::= <template-template-param> <template-args>
1584 // ::= <substitution>
1585 // ::= <CV-qualifiers> <type>
1586 // ::= P <type>
1587 // ::= R <type>
1588 // ::= O <type> (C++0x)
1589 // ::= C <type>
1590 // ::= G <type>
1591 // ::= U <source-name> <type>
1592 //
1593 // <builtin-type> ::= various one letter codes
1594 // ::= u <source-name>
1595 func (st *state) demangleType(isCast bool) AST {
1596 if len(st.str) == 0 {
1597 st.fail("expected type")
1598 }
1599
1600 addSubst := true
1601
1602 q := st.cvQualifiers()
1603 if q != nil {
1604 if len(st.str) == 0 {
1605 st.fail("expected type")
1606 }
1607
1608 // CV-qualifiers before a function type apply to
1609 // 'this', so avoid adding the unqualified function
1610 // type to the substitution list.
1611 if st.str[0] == 'F' {
1612 addSubst = false
1613 }
1614 }
1615
1616 var ret AST
1617
1618 // Use correct substitution for a template parameter.
1619 var sub AST
1620
1621 if btype, ok := builtinTypes[st.str[0]]; ok {
1622 ret = &BuiltinType{Name: btype}
1623 st.advance(1)
1624 if q != nil {
1625 ret = &TypeWithQualifiers{Base: ret, Qualifiers: q}
1626 st.subs.add(ret)
1627 }
1628 return ret
1629 }
1630 c := st.str[0]
1631 switch c {
1632 case 'u':
1633 st.advance(1)
1634 ret = st.sourceName()
1635 if len(st.str) > 0 && st.str[0] == 'I' {
1636 st.advance(1)
1637 base := st.demangleType(false)
1638 if len(st.str) == 0 || st.str[0] != 'E' {
1639 st.fail("expected E after transformed type")
1640 }
1641 st.advance(1)
1642 ret = &TransformedType{Name: ret.(*Name).Name, Base: base}
1643 }
1644 case 'F':
1645 ret = st.functionType()
1646 case 'N', 'W', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
1647 ret, _ = st.name()
1648 case 'A':
1649 ret = st.arrayType(isCast)
1650 case 'M':
1651 ret = st.pointerToMemberType(isCast)
1652 case 'T':
1653 if len(st.str) > 1 && (st.str[1] == 's' || st.str[1] == 'u' || st.str[1] == 'e') {
1654 c = st.str[1]
1655 st.advance(2)
1656 ret, _ = st.name()
1657 var kind string
1658 switch c {
1659 case 's':
1660 kind = "struct"
1661 case 'u':
1662 kind = "union"
1663 case 'e':
1664 kind = "enum"
1665 }
1666 ret = &ElaboratedType{Kind: kind, Type: ret}
1667 break
1668 }
1669
1670 ret = st.templateParam()
1671 if len(st.str) > 0 && st.str[0] == 'I' {
1672 // See the function comment to explain this.
1673 if !isCast {
1674 st.subs.add(ret)
1675 ret = st.template(ret)
1676 } else {
1677 ret = st.demangleCastTemplateArgs(ret, true)
1678 }
1679 }
1680 case 'S':
1681 // If this is a special substitution, then it
1682 // is the start of <class-enum-type>.
1683 var c2 byte
1684 if len(st.str) > 1 {
1685 c2 = st.str[1]
1686 }
1687 if isDigit(c2) || c2 == '_' || isUpper(c2) {
1688 ret = st.substitution(false)
1689 if _, ok := ret.(*ModuleName); ok {
1690 var isCast bool
1691 ret, isCast = st.unqualifiedName(ret)
1692 if isCast {
1693 st.setTemplate(ret, nil)
1694 }
1695 st.subs.add(ret)
1696 }
1697 if len(st.str) == 0 || st.str[0] != 'I' {
1698 addSubst = false
1699 } else {
1700 // See the function comment to explain this.
1701 if _, ok := ret.(*TemplateParam); !ok || !isCast {
1702 ret = st.template(ret)
1703 } else {
1704 next := st.demangleCastTemplateArgs(ret, false)
1705 if next == ret {
1706 addSubst = false
1707 }
1708 ret = next
1709 }
1710 }
1711 } else {
1712 ret, _ = st.name()
1713 // This substitution is not itself a
1714 // substitution candidate, unless template
1715 // arguments were added.
1716 if ret == subAST[c2] || ret == verboseAST[c2] {
1717 addSubst = false
1718 }
1719 }
1720 case 'O', 'P', 'R', 'C', 'G':
1721 st.advance(1)
1722 t := st.demangleType(isCast)
1723 switch c {
1724 case 'O':
1725 ret = &RvalueReferenceType{Base: t}
1726 case 'P':
1727 ret = &PointerType{Base: t}
1728 case 'R':
1729 ret = &ReferenceType{Base: t}
1730 case 'C':
1731 ret = &ComplexType{Base: t}
1732 case 'G':
1733 ret = &ImaginaryType{Base: t}
1734 }
1735 case 'U':
1736 if len(st.str) < 2 {
1737 st.fail("expected source name or unnamed type")
1738 }
1739 switch st.str[1] {
1740 case 'e':
1741 ret = st.unnamedEnum()
1742 addSubst = false
1743 case 'l':
1744 ret = st.closureTypeName()
1745 addSubst = false
1746 case 't':
1747 ret = st.unnamedTypeName()
1748 addSubst = false
1749 default:
1750 st.advance(1)
1751 n := st.sourceName()
1752 if len(st.str) > 0 && st.str[0] == 'I' {
1753 n = st.template(n)
1754 }
1755 t := st.demangleType(isCast)
1756 ret = &VendorQualifier{Qualifier: n, Type: t}
1757 }
1758 case 'D':
1759 st.advance(1)
1760 if len(st.str) == 0 {
1761 st.fail("expected D code for type")
1762 }
1763 addSubst = false
1764 c2 := st.str[0]
1765 st.advance(1)
1766
1767 fixedPrefix := func(c byte) (string, bool) {
1768 switch c {
1769 case 's':
1770 return "short ", true
1771 case 't':
1772 return "unsigned short ", true
1773 case 'i':
1774 return "", true
1775 case 'j':
1776 return "unsigned ", true
1777 case 'l':
1778 return "long ", true
1779 case 'm':
1780 return "unsigned long ", true
1781 default:
1782 return "", false
1783 }
1784 }
1785
1786 switch c2 {
1787 case 'T', 't':
1788 // decltype(expression)
1789 ret = st.expression()
1790 if len(st.str) == 0 || st.str[0] != 'E' {
1791 st.fail("expected E after expression in type")
1792 }
1793 st.advance(1)
1794 ret = &Decltype{Expr: ret}
1795 addSubst = true
1796
1797 case 'p':
1798 t := st.demangleType(isCast)
1799 pack := st.findArgumentPack(t)
1800 ret = &PackExpansion{Base: t, Pack: pack}
1801 addSubst = true
1802
1803 case 'a':
1804 ret = &Name{Name: "auto"}
1805 case 'c':
1806 ret = &Name{Name: "decltype(auto)"}
1807
1808 case 'f':
1809 ret = &BuiltinType{Name: "decimal32"}
1810 case 'd':
1811 ret = &BuiltinType{Name: "decimal64"}
1812 case 'e':
1813 ret = &BuiltinType{Name: "decimal128"}
1814 case 'h':
1815 ret = &BuiltinType{Name: "half"}
1816 case 'u':
1817 ret = &BuiltinType{Name: "char8_t"}
1818 case 's':
1819 ret = &BuiltinType{Name: "char16_t"}
1820 case 'i':
1821 ret = &BuiltinType{Name: "char32_t"}
1822 case 'n':
1823 ret = &BuiltinType{Name: "decltype(nullptr)"}
1824
1825 case 'F':
1826 accum := false
1827 bits := 0
1828 if len(st.str) > 0 && isDigit(st.str[0]) {
1829 accum = true
1830 bits = st.number()
1831 }
1832 if len(st.str) > 0 && st.str[0] == '_' {
1833 if bits == 0 {
1834 st.fail("expected non-zero number of bits")
1835 }
1836 st.advance(1)
1837 ret = &BinaryFP{Bits: bits, Suffix: ""}
1838 } else if len(st.str) > 0 && st.str[0] == 'x' {
1839 if bits == 0 {
1840 st.fail("expected non-zero number of bits")
1841 }
1842 st.advance(1)
1843 ret = &BinaryFP{Bits: bits, Suffix: "x"}
1844 } else if len(st.str) > 0 && st.str[0] == 'b' {
1845 if bits != 16 {
1846 st.fail("expected bits to be 16 for std::bfloat16_t")
1847 }
1848 st.advance(1)
1849 ret = &BuiltinType{Name: "std::bfloat16_t"}
1850 } else {
1851 base := st.demangleType(isCast)
1852 if len(st.str) > 0 && isDigit(st.str[0]) {
1853 // We don't care about the bits.
1854 st.number()
1855 }
1856 sat := false
1857 if len(st.str) > 0 {
1858 if st.str[0] == 's' {
1859 sat = true
1860 }
1861 st.advance(1)
1862 }
1863 ret = &FixedType{Base: base, Accum: accum, Sat: sat}
1864 }
1865
1866 case 'v':
1867 ret = st.vectorType(isCast)
1868 addSubst = true
1869
1870 case 'B', 'U':
1871 signed := c2 == 'B'
1872 var size AST
1873 if len(st.str) > 0 && isDigit(st.str[0]) {
1874 bits := st.number()
1875 size = &Name{Name: fmt.Sprintf("%d", bits)}
1876 } else {
1877 size = st.expression()
1878 }
1879 if len(st.str) == 0 || st.str[0] != '_' {
1880 st.fail("expected _ after _BitInt size")
1881 }
1882 st.advance(1)
1883 ret = &BitIntType{Size: size, Signed: signed}
1884 addSubst = true
1885
1886 case 'k':
1887 constraint, _ := st.name()
1888 ret = &SuffixType{
1889 Base: constraint,
1890 Suffix: "auto",
1891 }
1892
1893 case 'K':
1894 constraint, _ := st.name()
1895 ret = &SuffixType{
1896 Base: constraint,
1897 Suffix: "decltype(auto)",
1898 }
1899
1900 case 'A', 'R':
1901 if len(st.str) == 0 {
1902 st.fail("missing D{A,R} code in type")
1903 }
1904 prefix, ok := fixedPrefix(st.str[0])
1905 if !ok {
1906 st.fail("unrecognized D{A,R} code in type")
1907 }
1908 st.advance(1)
1909
1910 switch c2 {
1911 case 'A':
1912 ret = &BuiltinType{Name: prefix + "_Accum"}
1913 case 'R':
1914 ret = &BuiltinType{Name: prefix + "_Fract"}
1915 default:
1916 panic("internal error")
1917 }
1918
1919 case 'S':
1920 if len(st.str) < 3 {
1921 st.fail("missing DS code in type")
1922 }
1923 if st.str[0] != 'D' {
1924 st.fail("unrecognized DS code in type")
1925 }
1926
1927 var suffix string
1928 switch st.str[1] {
1929 case 'A':
1930 suffix = "_Accum"
1931 case 'R':
1932 suffix = "_Fract"
1933 default:
1934 st.fail("unrecognized DSD code in type")
1935 }
1936
1937 prefix, ok := fixedPrefix(st.str[2])
1938 if !ok {
1939 st.fail("unrecognized DSD{A,R} code in type")
1940 }
1941
1942 st.advance(3)
1943
1944 ret = &BuiltinType{Name: "_Sat " + prefix + suffix}
1945
1946 default:
1947 st.fail("unrecognized D code in type")
1948 }
1949
1950 default:
1951 st.fail("unrecognized type code")
1952 }
1953
1954 if addSubst {
1955 if sub != nil {
1956 st.subs.add(sub)
1957 } else {
1958 st.subs.add(ret)
1959 }
1960 }
1961
1962 if q != nil {
1963 if _, ok := ret.(*FunctionType); ok {
1964 ret = &MethodWithQualifiers{Method: ret, Qualifiers: q, RefQualifier: ""}
1965 } else if mwq, ok := ret.(*MethodWithQualifiers); ok {
1966 // Merge adjacent qualifiers. This case
1967 // happens with a function with a trailing
1968 // ref-qualifier.
1969 mwq.Qualifiers = mergeQualifiers(q, mwq.Qualifiers)
1970 } else {
1971 // Merge adjacent qualifiers. This case
1972 // happens with multi-dimensional array types.
1973 if qsub, ok := ret.(*TypeWithQualifiers); ok {
1974 q = mergeQualifiers(q, qsub.Qualifiers)
1975 ret = qsub.Base
1976 }
1977 ret = &TypeWithQualifiers{Base: ret, Qualifiers: q}
1978 }
1979 st.subs.add(ret)
1980 }
1981
1982 return ret
1983 }
1984
1985 // demangleCastTemplateArgs is for a rather hideous parse. When we
1986 // see a template-param followed by a template-args, we need to decide
1987 // whether we have a template-param or a template-template-param.
1988 // Normally it is template-template-param, meaning that we pick up the
1989 // template arguments here. But, if we are parsing the type for a
1990 // cast operator, then the only way this can be template-template-param
1991 // is if there is another set of template-args immediately after this
1992 // set. That would look like this:
1993 //
1994 // <nested-name>
1995 // -> <template-prefix> <template-args>
1996 // -> <prefix> <template-unqualified-name> <template-args>
1997 // -> <unqualified-name> <template-unqualified-name> <template-args>
1998 // -> <source-name> <template-unqualified-name> <template-args>
1999 // -> <source-name> <operator-name> <template-args>
2000 // -> <source-name> cv <type> <template-args>
2001 // -> <source-name> cv <template-template-param> <template-args> <template-args>
2002 //
2003 // Otherwise, we have this derivation:
2004 //
2005 // <nested-name>
2006 // -> <template-prefix> <template-args>
2007 // -> <prefix> <template-unqualified-name> <template-args>
2008 // -> <unqualified-name> <template-unqualified-name> <template-args>
2009 // -> <source-name> <template-unqualified-name> <template-args>
2010 // -> <source-name> <operator-name> <template-args>
2011 // -> <source-name> cv <type> <template-args>
2012 // -> <source-name> cv <template-param> <template-args>
2013 //
2014 // in which the template-args are actually part of the prefix. For
2015 // the special case where this arises, demangleType is called with
2016 // isCast as true. This function is then responsible for checking
2017 // whether we see <template-param> <template-args> but there is not
2018 // another following <template-args>. In that case, we reset the
2019 // parse and just return the <template-param>.
2020 func (st *state) demangleCastTemplateArgs(tp AST, addSubst bool) AST {
2021 save := st.copy()
2022
2023 var (
2024 args []AST
2025 constraint AST
2026 )
2027 failed := false
2028 func() {
2029 defer func() {
2030 if r := recover(); r != nil {
2031 if _, ok := r.(demangleErr); ok {
2032 failed = true
2033 } else {
2034 panic(r)
2035 }
2036 }
2037 }()
2038
2039 args, constraint = st.templateArgs()
2040 }()
2041
2042 if !failed && len(st.str) > 0 && st.str[0] == 'I' {
2043 if addSubst {
2044 st.subs.add(tp)
2045 }
2046 ret := &Template{Name: tp, Args: args}
2047 return st.maybeAddConstraint(ret, constraint)
2048 }
2049 // Reset back to before we started reading the template arguments.
2050 // They will be read again by st.prefix.
2051 *st = *save
2052 return tp
2053 }
2054
2055 // mergeQualifiers merges two qualifier lists into one.
2056 func mergeQualifiers(q1AST, q2AST AST) AST {
2057 if q1AST == nil {
2058 return q2AST
2059 }
2060 if q2AST == nil {
2061 return q1AST
2062 }
2063 q1 := q1AST.(*Qualifiers)
2064 m := make(map[string]bool)
2065 for _, qualAST := range q1.Qualifiers {
2066 qual := qualAST.(*Qualifier)
2067 if len(qual.Exprs) == 0 {
2068 m[qual.Name] = true
2069 }
2070 }
2071 rq := q1.Qualifiers
2072 for _, qualAST := range q2AST.(*Qualifiers).Qualifiers {
2073 qual := qualAST.(*Qualifier)
2074 if len(qual.Exprs) > 0 {
2075 rq = append(rq, qualAST)
2076 } else if !m[qual.Name] {
2077 rq = append(rq, qualAST)
2078 m[qual.Name] = true
2079 }
2080 }
2081 q1.Qualifiers = rq
2082 return q1
2083 }
2084
2085 // qualifiers maps from the character used in the mangled name to the
2086 // string to print.
2087 var qualifiers = map[byte]string{
2088 'r': "restrict",
2089 'V': "volatile",
2090 'K': "const",
2091 }
2092
2093 // cvQualifiers parses:
2094 //
2095 // <CV-qualifiers> ::= [r] [V] [K]
2096 func (st *state) cvQualifiers() AST {
2097 var q []AST
2098 qualLoop:
2099 for len(st.str) > 0 {
2100 if qv, ok := qualifiers[st.str[0]]; ok {
2101 qual := &Qualifier{Name: qv}
2102 q = append([]AST{qual}, q...)
2103 st.advance(1)
2104 } else if len(st.str) > 1 && st.str[0] == 'D' {
2105 var qual AST
2106 switch st.str[1] {
2107 case 'x':
2108 qual = &Qualifier{Name: "transaction_safe"}
2109 st.advance(2)
2110 case 'o':
2111 qual = &Qualifier{Name: "noexcept"}
2112 st.advance(2)
2113 case 'O':
2114 st.advance(2)
2115 expr := st.expression()
2116 if len(st.str) == 0 || st.str[0] != 'E' {
2117 st.fail("expected E after computed noexcept expression")
2118 }
2119 st.advance(1)
2120 qual = &Qualifier{Name: "noexcept", Exprs: []AST{expr}}
2121 case 'w':
2122 st.advance(2)
2123 parmlist := st.parmlist(false)
2124 if len(st.str) == 0 || st.str[0] != 'E' {
2125 st.fail("expected E after throw parameter list")
2126 }
2127 st.advance(1)
2128 qual = &Qualifier{Name: "throw", Exprs: parmlist}
2129 default:
2130 break qualLoop
2131 }
2132 q = append([]AST{qual}, q...)
2133 } else {
2134 break
2135 }
2136 }
2137 if len(q) == 0 {
2138 return nil
2139 }
2140 return &Qualifiers{Qualifiers: q}
2141 }
2142
2143 // refQualifier parses:
2144 //
2145 // <ref-qualifier> ::= R
2146 // ::= O
2147 func (st *state) refQualifier() string {
2148 if len(st.str) > 0 {
2149 switch st.str[0] {
2150 case 'R':
2151 st.advance(1)
2152 return "&"
2153 case 'O':
2154 st.advance(1)
2155 return "&&"
2156 }
2157 }
2158 return ""
2159 }
2160
2161 // parmlist parses:
2162 //
2163 // <type>+
2164 func (st *state) parmlist(explicitObjectParameter bool) []AST {
2165 var ret []AST
2166 for {
2167 if len(st.str) < 1 {
2168 break
2169 }
2170 if st.str[0] == 'E' || st.str[0] == '.' {
2171 break
2172 }
2173 if (st.str[0] == 'R' || st.str[0] == 'O') && len(st.str) > 1 && st.str[1] == 'E' {
2174 // This is a function ref-qualifier.
2175 break
2176 }
2177 if st.str[0] == 'Q' {
2178 // This is a requires clause.
2179 break
2180 }
2181 ptype := st.demangleType(false)
2182
2183 if len(ret) == 0 && explicitObjectParameter {
2184 ptype = &ExplicitObjectParameter{Base: ptype}
2185 }
2186
2187 ret = append(ret, ptype)
2188 }
2189
2190 // There should always be at least one type. A function that
2191 // takes no arguments will have a single parameter type
2192 // "void".
2193 if len(ret) == 0 {
2194 st.fail("expected at least one type in type list")
2195 }
2196
2197 // Omit a single parameter type void.
2198 if len(ret) == 1 {
2199 if bt, ok := ret[0].(*BuiltinType); ok && bt.Name == "void" {
2200 ret = nil
2201 }
2202 }
2203
2204 return ret
2205 }
2206
2207 // functionType parses:
2208 //
2209 // <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] E
2210 func (st *state) functionType() AST {
2211 st.checkChar('F')
2212 if len(st.str) > 0 && st.str[0] == 'Y' {
2213 // Function has C linkage. We don't print this.
2214 st.advance(1)
2215 }
2216 ret := st.bareFunctionType(true, false)
2217 r := st.refQualifier()
2218 if r != "" {
2219 ret = &MethodWithQualifiers{Method: ret, Qualifiers: nil, RefQualifier: r}
2220 }
2221 if len(st.str) == 0 || st.str[0] != 'E' {
2222 st.fail("expected E after function type")
2223 }
2224 st.advance(1)
2225 return ret
2226 }
2227
2228 // bareFunctionType parses:
2229 //
2230 // <bare-function-type> ::= [J]<type>+
2231 func (st *state) bareFunctionType(hasReturnType, explicitObjectParameter bool) AST {
2232 if len(st.str) > 0 && st.str[0] == 'J' {
2233 hasReturnType = true
2234 st.advance(1)
2235 }
2236 var returnType AST
2237 if hasReturnType {
2238 returnType = st.demangleType(false)
2239 }
2240 types := st.parmlist(explicitObjectParameter)
2241 return &FunctionType{
2242 Return: returnType,
2243 Args: types,
2244 ForLocalName: false, // may be set later in encoding
2245 }
2246 }
2247
2248 // arrayType parses:
2249 //
2250 // <array-type> ::= A <(positive dimension) number> _ <(element) type>
2251 // ::= A [<(dimension) expression>] _ <(element) type>
2252 func (st *state) arrayType(isCast bool) AST {
2253 st.checkChar('A')
2254
2255 if len(st.str) == 0 {
2256 st.fail("missing array dimension")
2257 }
2258
2259 var dim AST
2260 if st.str[0] == '_' {
2261 dim = &Name{Name: ""}
2262 } else if isDigit(st.str[0]) {
2263 i := 1
2264 for len(st.str) > i && isDigit(st.str[i]) {
2265 i++
2266 }
2267 dim = &Name{Name: st.str[:i]}
2268 st.advance(i)
2269 } else {
2270 dim = st.expression()
2271 }
2272
2273 if len(st.str) == 0 || st.str[0] != '_' {
2274 st.fail("expected _ after dimension")
2275 }
2276 st.advance(1)
2277
2278 t := st.demangleType(isCast)
2279
2280 arr := &ArrayType{Dimension: dim, Element: t}
2281
2282 // Qualifiers on the element of an array type go on the whole
2283 // array type.
2284 if q, ok := arr.Element.(*TypeWithQualifiers); ok {
2285 return &TypeWithQualifiers{Base: &ArrayType{Dimension: dim, Element: q.Base}, Qualifiers: q.Qualifiers}
2286 }
2287
2288 return arr
2289 }
2290
2291 // vectorType parses:
2292 //
2293 // <vector-type> ::= Dv <number> _ <type>
2294 // ::= Dv _ <expression> _ <type>
2295 func (st *state) vectorType(isCast bool) AST {
2296 if len(st.str) == 0 {
2297 st.fail("expected vector dimension")
2298 }
2299
2300 var dim AST
2301 if st.str[0] == '_' {
2302 st.advance(1)
2303 dim = st.expression()
2304 } else {
2305 num := st.number()
2306 dim = &Name{Name: fmt.Sprintf("%d", num)}
2307 }
2308
2309 if len(st.str) == 0 || st.str[0] != '_' {
2310 st.fail("expected _ after vector dimension")
2311 }
2312 st.advance(1)
2313
2314 t := st.demangleType(isCast)
2315
2316 return &VectorType{Dimension: dim, Base: t}
2317 }
2318
2319 // pointerToMemberType parses:
2320 //
2321 // <pointer-to-member-type> ::= M <(class) type> <(member) type>
2322 func (st *state) pointerToMemberType(isCast bool) AST {
2323 st.checkChar('M')
2324 cl := st.demangleType(false)
2325
2326 // The ABI says, "The type of a non-static member function is
2327 // considered to be different, for the purposes of
2328 // substitution, from the type of a namespace-scope or static
2329 // member function whose type appears similar. The types of
2330 // two non-static member functions are considered to be
2331 // different, for the purposes of substitution, if the
2332 // functions are members of different classes. In other words,
2333 // for the purposes of substitution, the class of which the
2334 // function is a member is considered part of the type of
2335 // function."
2336 //
2337 // For a pointer to member function, this call to demangleType
2338 // will end up adding a (possibly qualified) non-member
2339 // function type to the substitution table, which is not
2340 // correct; however, the member function type will never be
2341 // used in a substitution, so putting the wrong type in the
2342 // substitution table is harmless.
2343 mem := st.demangleType(isCast)
2344 return &PtrMem{Class: cl, Member: mem}
2345 }
2346
2347 // compactNumber parses:
2348 //
2349 // <non-negative number> _
2350 func (st *state) compactNumber() int {
2351 if len(st.str) == 0 {
2352 st.fail("missing index")
2353 }
2354 if st.str[0] == '_' {
2355 st.advance(1)
2356 return 0
2357 } else if st.str[0] == 'n' {
2358 st.fail("unexpected negative number")
2359 }
2360 n := st.number()
2361 if len(st.str) == 0 || st.str[0] != '_' {
2362 st.fail("missing underscore after number")
2363 }
2364 st.advance(1)
2365 return n + 1
2366 }
2367
2368 // templateParam parses:
2369 //
2370 // <template-param> ::= T_
2371 // ::= T <(parameter-2 non-negative) number> _
2372 // ::= TL <level-1> __
2373 // ::= TL <level-1> _ <parameter-2 non-negative number> _
2374 //
2375 // When a template parameter is a substitution candidate, any
2376 // reference to that substitution refers to the template parameter
2377 // with the same index in the currently active template, not to
2378 // whatever the template parameter would be expanded to here. We sort
2379 // this out in substitution and simplify.
2380 func (st *state) templateParam() AST {
2381 off := st.off
2382 str := st.str
2383 st.checkChar('T')
2384
2385 level := 0
2386 if len(st.str) > 0 && st.str[0] == 'L' {
2387 st.advance(1)
2388 level = st.compactNumber()
2389 }
2390
2391 n := st.compactNumber()
2392
2393 // We don't try to substitute template parameters in a
2394 // constraint expression.
2395 if st.parsingConstraint {
2396 return &Name{Name: str[:st.off-1-off]}
2397 }
2398
2399 if level >= len(st.templates) {
2400 if st.lambdaTemplateLevel > 0 && level == st.lambdaTemplateLevel-1 {
2401 // Lambda auto params are mangled as template params.
2402 // See https://gcc.gnu.org/PR78252.
2403 return &LambdaAuto{Index: n}
2404 }
2405 st.failEarlier(fmt.Sprintf("template parameter is not in scope of template (level %d >= %d)", level, len(st.templates)), st.off-off)
2406 }
2407
2408 template := st.templates[level]
2409
2410 if template == nil {
2411 // We are parsing a cast operator. If the cast is
2412 // itself a template, then this is a forward
2413 // reference. Fill it in later.
2414 return &TemplateParam{Index: n, Template: nil}
2415 }
2416
2417 if n >= len(template.Args) {
2418 if st.lambdaTemplateLevel > 0 && level == st.lambdaTemplateLevel-1 {
2419 // Lambda auto params are mangled as template params.
2420 // See https://gcc.gnu.org/PR78252.
2421 return &LambdaAuto{Index: n}
2422 }
2423 st.failEarlier(fmt.Sprintf("template index out of range (%d >= %d)", n, len(template.Args)), st.off-off)
2424 }
2425
2426 return &TemplateParam{Index: n, Template: template}
2427 }
2428
2429 // setTemplate sets the Template field of any TemplateParam's in a.
2430 // This handles the forward referencing template parameters found in
2431 // cast operators.
2432 func (st *state) setTemplate(a AST, tmpl *Template) {
2433 seen := make(map[AST]bool)
2434 a.Traverse(func(a AST) bool {
2435 switch a := a.(type) {
2436 case *TemplateParam:
2437 if a.Template != nil {
2438 if tmpl != nil {
2439 st.fail("duplicate template parameters")
2440 }
2441 return false
2442 }
2443 if tmpl == nil {
2444 st.fail("cast template parameter not in scope of template")
2445 }
2446 if a.Index >= len(tmpl.Args) {
2447 st.fail(fmt.Sprintf("cast template index out of range (%d >= %d)", a.Index, len(tmpl.Args)))
2448 }
2449 a.Template = tmpl
2450 return false
2451 case *Closure:
2452 // There are no template params in closure types.
2453 // https://gcc.gnu.org/PR78252.
2454 return false
2455 default:
2456 if seen[a] {
2457 return false
2458 }
2459 seen[a] = true
2460 return true
2461 }
2462 })
2463 }
2464
2465 // clearTemplateArgs gives an error for any unset Template field in
2466 // args. This handles erroneous cases where a cast operator with a
2467 // forward referenced template is in the scope of another cast
2468 // operator.
2469 func (st *state) clearTemplateArgs(args []AST) {
2470 for _, a := range args {
2471 st.setTemplate(a, nil)
2472 }
2473 }
2474
2475 // templateArgs parses:
2476 //
2477 // <template-args> ::= I <template-arg>+ E
2478 //
2479 // This returns the template arguments and an optional constraint.
2480 func (st *state) templateArgs() ([]AST, AST) {
2481 if len(st.str) == 0 || (st.str[0] != 'I' && st.str[0] != 'J') {
2482 panic("internal error")
2483 }
2484 st.advance(1)
2485
2486 var (
2487 ret []AST
2488 constraint AST
2489 )
2490 for len(st.str) == 0 || st.str[0] != 'E' {
2491 arg := st.templateArg(ret)
2492 ret = append(ret, arg)
2493
2494 if len(st.str) > 0 && st.str[0] == 'Q' {
2495 constraint = st.constraintExpr()
2496 if len(st.str) == 0 || st.str[0] != 'E' {
2497 st.fail("expected end of template arguments after constraint")
2498 }
2499 }
2500 }
2501 st.advance(1)
2502 return ret, constraint
2503 }
2504
2505 // templateArg parses:
2506 //
2507 // <template-arg> ::= <type>
2508 // ::= X <expression> E
2509 // ::= <expr-primary>
2510 // ::= J <template-arg>* E
2511 // ::= LZ <encoding> E
2512 // ::= <template-param-decl> <template-arg>
2513 func (st *state) templateArg(prev []AST) AST {
2514 if len(st.str) == 0 {
2515 st.fail("missing template argument")
2516 }
2517 switch st.str[0] {
2518 case 'X':
2519 st.advance(1)
2520 expr := st.expression()
2521 if len(st.str) == 0 || st.str[0] != 'E' {
2522 st.fail("missing end of expression")
2523 }
2524 st.advance(1)
2525 return expr
2526
2527 case 'L':
2528 return st.exprPrimary()
2529
2530 case 'I', 'J':
2531 args, constraint := st.templateArgs()
2532 ret := &ArgumentPack{Args: args}
2533 return st.maybeAddConstraint(ret, constraint)
2534
2535 case 'T':
2536 var arg byte
2537 if len(st.str) > 1 {
2538 arg = st.str[1]
2539 }
2540 switch arg {
2541 case 'y', 'n', 't', 'p', 'k':
2542 off := st.off
2543
2544 // Apparently template references in the
2545 // template parameter refer to previous
2546 // arguments in the same template.
2547 template := &Template{Args: prev}
2548 st.templates = append(st.templates, template)
2549
2550 param, _ := st.templateParamDecl()
2551
2552 st.templates = st.templates[:len(st.templates)-1]
2553
2554 if param == nil {
2555 st.failEarlier("expected template parameter as template argument", st.off-off)
2556 }
2557 arg := st.templateArg(nil)
2558 return &TemplateParamQualifiedArg{Param: param, Arg: arg}
2559 }
2560 return st.demangleType(false)
2561
2562 default:
2563 return st.demangleType(false)
2564 }
2565 }
2566
2567 // maybeAddConstraint adds a constraint to an AST, if constraint is not nil.
2568 // This is only called with a constraint found at the end of
2569 // template arguments.
2570 func (st *state) maybeAddConstraint(a, constraint AST) AST {
2571 if constraint == nil {
2572 return a
2573 }
2574 return &Constraint{
2575 Name: a,
2576 Requires: constraint,
2577 ForTemplateArgs: true,
2578 }
2579 }
2580
2581 // template parses template arguments into a Template with a given name.
2582 func (st *state) template(name AST) AST {
2583 args, constraint := st.templateArgs()
2584 ret := &Template{Name: name, Args: args}
2585 return st.maybeAddConstraint(ret, constraint)
2586 }
2587
2588 // exprList parses a sequence of expressions up to a terminating character.
2589 func (st *state) exprList(stop byte) AST {
2590 if len(st.str) > 0 && st.str[0] == stop {
2591 st.advance(1)
2592 return &ExprList{Exprs: nil}
2593 }
2594
2595 var exprs []AST
2596 for {
2597 e := st.expression()
2598 exprs = append(exprs, e)
2599 if len(st.str) > 0 && st.str[0] == stop {
2600 st.advance(1)
2601 break
2602 }
2603 }
2604 return &ExprList{Exprs: exprs}
2605 }
2606
2607 // expression parses:
2608 //
2609 // <expression> ::= <(unary) operator-name> <expression>
2610 // ::= <(binary) operator-name> <expression> <expression>
2611 // ::= <(trinary) operator-name> <expression> <expression> <expression>
2612 // ::= pp_ <expression>
2613 // ::= mm_ <expression>
2614 // ::= cl <expression>+ E
2615 // ::= cl <expression>+ E
2616 // ::= cv <type> <expression>
2617 // ::= cv <type> _ <expression>* E
2618 // ::= tl <type> <braced-expression>* E
2619 // ::= il <braced-expression>* E
2620 // ::= [gs] nw <expression>* _ <type> E
2621 // ::= [gs] nw <expression>* _ <type> <initializer>
2622 // ::= [gs] na <expression>* _ <type> E
2623 // ::= [gs] na <expression>* _ <type> <initializer>
2624 // ::= [gs] dl <expression>
2625 // ::= [gs] da <expression>
2626 // ::= dc <type> <expression>
2627 // ::= sc <type> <expression>
2628 // ::= cc <type> <expression>
2629 // ::= mc <parameter type> <expr> [<offset number>] E
2630 // ::= rc <type> <expression>
2631 // ::= ti <type>
2632 // ::= te <expression>
2633 // ::= so <referent type> <expr> [<offset number>] <union-selector>* [p] E
2634 // ::= st <type>
2635 // ::= sz <expression>
2636 // ::= at <type>
2637 // ::= az <expression>
2638 // ::= nx <expression>
2639 // ::= <template-param>
2640 // ::= <function-param>
2641 // ::= dt <expression> <unresolved-name>
2642 // ::= pt <expression> <unresolved-name>
2643 // ::= ds <expression> <expression>
2644 // ::= sZ <template-param>
2645 // ::= sZ <function-param>
2646 // ::= sP <template-arg>* E
2647 // ::= sp <expression>
2648 // ::= fl <binary operator-name> <expression>
2649 // ::= fr <binary operator-name> <expression>
2650 // ::= fL <binary operator-name> <expression> <expression>
2651 // ::= fR <binary operator-name> <expression> <expression>
2652 // ::= tw <expression>
2653 // ::= tr
2654 // ::= u <source-name> <template-arg>* E
2655 // ::= <unresolved-name>
2656 // ::= <expr-primary>
2657 //
2658 // <function-param> ::= fp <CV-qualifiers> _
2659 // ::= fp <CV-qualifiers> <number>
2660 // ::= fL <number> p <CV-qualifiers> _
2661 // ::= fL <number> p <CV-qualifiers> <number>
2662 // ::= fpT
2663 //
2664 // <braced-expression> ::= <expression>
2665 // ::= di <field source-name> <braced-expression>
2666 // ::= dx <index expression> <braced-expression>
2667 // ::= dX <range begin expression> <range end expression> <braced-expression>
2668 func (st *state) expression() AST {
2669 if len(st.str) == 0 {
2670 st.fail("expected expression")
2671 }
2672 if st.str[0] == 'L' {
2673 return st.exprPrimary()
2674 } else if st.str[0] == 'T' {
2675 return st.templateParam()
2676 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'o' {
2677 st.advance(2)
2678 return st.subobject()
2679 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'r' {
2680 return st.unresolvedName()
2681 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'p' {
2682 st.advance(2)
2683 e := st.expression()
2684 pack := st.findArgumentPack(e)
2685 return &PackExpansion{Base: e, Pack: pack}
2686 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'Z' {
2687 st.advance(2)
2688 off := st.off
2689 e := st.expression()
2690 ap := st.findArgumentPack(e)
2691 if ap == nil {
2692 st.failEarlier("missing argument pack", st.off-off)
2693 }
2694 return &SizeofPack{Pack: ap}
2695 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'P' {
2696 st.advance(2)
2697 var args []AST
2698 for len(st.str) == 0 || st.str[0] != 'E' {
2699 arg := st.templateArg(nil)
2700 args = append(args, arg)
2701 }
2702 st.advance(1)
2703 return &SizeofArgs{Args: args}
2704 } else if st.str[0] == 'f' && len(st.str) > 1 && st.str[1] == 'p' {
2705 st.advance(2)
2706 if len(st.str) > 0 && st.str[0] == 'T' {
2707 st.advance(1)
2708 return &FunctionParam{Index: 0}
2709 } else {
2710 // We can see qualifiers here, but we don't
2711 // include them in the demangled string.
2712 st.cvQualifiers()
2713 index := st.compactNumber()
2714 return &FunctionParam{Index: index + 1}
2715 }
2716 } else if st.str[0] == 'f' && len(st.str) > 2 && st.str[1] == 'L' && isDigit(st.str[2]) {
2717 st.advance(2)
2718 // We don't include the scope count in the demangled string.
2719 st.number()
2720 if len(st.str) == 0 || st.str[0] != 'p' {
2721 st.fail("expected p after function parameter scope count")
2722 }
2723 st.advance(1)
2724 // We can see qualifiers here, but we don't include them
2725 // in the demangled string.
2726 st.cvQualifiers()
2727 index := st.compactNumber()
2728 return &FunctionParam{Index: index + 1}
2729 } else if st.str[0] == 'm' && len(st.str) > 1 && st.str[1] == 'c' {
2730 st.advance(2)
2731 typ := st.demangleType(false)
2732 expr := st.expression()
2733 offset := 0
2734 if len(st.str) > 0 && (st.str[0] == 'n' || isDigit(st.str[0])) {
2735 offset = st.number()
2736 }
2737 if len(st.str) == 0 || st.str[0] != 'E' {
2738 st.fail("expected E after pointer-to-member conversion")
2739 }
2740 st.advance(1)
2741 return &PtrMemCast{
2742 Type: typ,
2743 Expr: expr,
2744 Offset: offset,
2745 }
2746 } else if isDigit(st.str[0]) || (st.str[0] == 'o' && len(st.str) > 1 && st.str[1] == 'n') {
2747 if st.str[0] == 'o' {
2748 // Skip operator function ID.
2749 st.advance(2)
2750 }
2751 n, isCast := st.unqualifiedName(nil)
2752 if isCast {
2753 st.setTemplate(n, nil)
2754 }
2755 if len(st.str) > 0 && st.str[0] == 'I' {
2756 n = st.template(n)
2757 }
2758 return n
2759 } else if (st.str[0] == 'i' || st.str[0] == 't') && len(st.str) > 1 && st.str[1] == 'l' {
2760 // Brace-enclosed initializer list.
2761 c := st.str[0]
2762 st.advance(2)
2763 var t AST
2764 if c == 't' {
2765 t = st.demangleType(false)
2766 }
2767 exprs := st.exprList('E')
2768 return &InitializerList{Type: t, Exprs: exprs}
2769 } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 't' {
2770 o, _ := st.operatorName(true)
2771 t := st.demangleType(false)
2772 return &Unary{Op: o, Expr: t, Suffix: false, SizeofType: true}
2773 } else if st.str[0] == 'u' {
2774 st.advance(1)
2775 name := st.sourceName()
2776 // Special case __uuidof followed by type or
2777 // expression, as used by LLVM.
2778 if n, ok := name.(*Name); ok && n.Name == "__uuidof" {
2779 if len(st.str) < 2 {
2780 st.fail("missing uuidof argument")
2781 }
2782 var operand AST
2783 if st.str[0] == 't' {
2784 st.advance(1)
2785 operand = st.demangleType(false)
2786 } else if st.str[0] == 'z' {
2787 st.advance(1)
2788 operand = st.expression()
2789 }
2790 if operand != nil {
2791 return &Binary{
2792 Op: &Operator{Name: "()"},
2793 Left: name,
2794 Right: &ExprList{
2795 Exprs: []AST{operand},
2796 },
2797 }
2798 }
2799 }
2800 var args []AST
2801 for {
2802 if len(st.str) == 0 {
2803 st.fail("missing argument in vendor extended expressoin")
2804 }
2805 if st.str[0] == 'E' {
2806 st.advance(1)
2807 break
2808 }
2809 arg := st.templateArg(nil)
2810 args = append(args, arg)
2811 }
2812 return &Binary{
2813 Op: &Operator{Name: "()"},
2814 Left: name,
2815 Right: &ExprList{Exprs: args},
2816 }
2817 } else if st.str[0] == 'r' && len(st.str) > 1 && (st.str[1] == 'q' || st.str[1] == 'Q') {
2818 return st.requiresExpr()
2819 } else {
2820 if len(st.str) < 2 {
2821 st.fail("missing operator code")
2822 }
2823 code := st.str[:2]
2824 o, args := st.operatorName(true)
2825 switch args {
2826 case 0:
2827 return &Nullary{Op: o}
2828
2829 case 1:
2830 suffix := false
2831 if code == "pp" || code == "mm" {
2832 if len(st.str) > 0 && st.str[0] == '_' {
2833 st.advance(1)
2834 } else {
2835 suffix = true
2836 }
2837 }
2838 var operand AST
2839 if _, ok := o.(*Cast); ok && len(st.str) > 0 && st.str[0] == '_' {
2840 st.advance(1)
2841 operand = st.exprList('E')
2842 } else {
2843 operand = st.expression()
2844 }
2845 return &Unary{Op: o, Expr: operand, Suffix: suffix, SizeofType: false}
2846
2847 case 2:
2848 var left, right AST
2849 if code == "sc" || code == "dc" || code == "cc" || code == "rc" {
2850 left = st.demangleType(false)
2851 } else if code[0] == 'f' {
2852 left, _ = st.operatorName(true)
2853 right = st.expression()
2854 return &Fold{Left: code[1] == 'l', Op: left, Arg1: right, Arg2: nil}
2855 } else if code == "di" {
2856 var isCast bool
2857 left, isCast = st.unqualifiedName(nil)
2858 if isCast {
2859 st.setTemplate(left, nil)
2860 }
2861 } else {
2862 left = st.expression()
2863 }
2864 if code == "cl" || code == "cp" {
2865 right = st.exprList('E')
2866 } else if code == "dt" || code == "pt" {
2867 if len(st.str) > 0 && st.str[0] == 'L' {
2868 right = st.exprPrimary()
2869 } else {
2870 right = st.unresolvedName()
2871 if len(st.str) > 0 && st.str[0] == 'I' {
2872 right = st.template(right)
2873 }
2874 }
2875 } else {
2876 right = st.expression()
2877 }
2878 return &Binary{Op: o, Left: left, Right: right}
2879
2880 case 3:
2881 if code[0] == 'n' {
2882 if code[1] != 'w' && code[1] != 'a' {
2883 panic("internal error")
2884 }
2885 place := st.exprList('_')
2886 if place.(*ExprList).Exprs == nil {
2887 place = nil
2888 }
2889 t := st.demangleType(false)
2890 var ini AST
2891 if len(st.str) > 0 && st.str[0] == 'E' {
2892 st.advance(1)
2893 } else if len(st.str) > 1 && st.str[0] == 'p' && st.str[1] == 'i' {
2894 // Parenthesized initializer.
2895 st.advance(2)
2896 ini = st.exprList('E')
2897 } else if len(st.str) > 1 && st.str[0] == 'i' && st.str[1] == 'l' {
2898 // Initializer list.
2899 ini = st.expression()
2900 } else {
2901 st.fail("unrecognized new initializer")
2902 }
2903 return &New{Op: o, Place: place, Type: t, Init: ini}
2904 } else if code[0] == 'f' {
2905 first, _ := st.operatorName(true)
2906 second := st.expression()
2907 third := st.expression()
2908 return &Fold{Left: code[1] == 'L', Op: first, Arg1: second, Arg2: third}
2909 } else {
2910 first := st.expression()
2911 second := st.expression()
2912 third := st.expression()
2913 return &Trinary{Op: o, First: first, Second: second, Third: third}
2914 }
2915
2916 default:
2917 st.fail(fmt.Sprintf("unsupported number of operator arguments: %d", args))
2918 panic("not reached")
2919 }
2920 }
2921 }
2922
2923 // subobject parses:
2924 //
2925 // <expression> ::= so <referent type> <expr> [<offset number>] <union-selector>* [p] E
2926 // <union-selector> ::= _ [<number>]
2927 func (st *state) subobject() AST {
2928 typ := st.demangleType(false)
2929 expr := st.expression()
2930 offset := 0
2931 if len(st.str) > 0 && (st.str[0] == 'n' || isDigit(st.str[0])) {
2932 offset = st.number()
2933 }
2934 var selectors []int
2935 for len(st.str) > 0 && st.str[0] == '_' {
2936 st.advance(1)
2937 selector := 0
2938 if len(st.str) > 0 && (st.str[0] == 'n' || isDigit(st.str[0])) {
2939 selector = st.number()
2940 }
2941 selectors = append(selectors, selector)
2942 }
2943 pastEnd := false
2944 if len(st.str) > 0 && st.str[0] == 'p' {
2945 st.advance(1)
2946 pastEnd = true
2947 }
2948 if len(st.str) == 0 || st.str[0] != 'E' {
2949 st.fail("expected E after subobject")
2950 }
2951 st.advance(1)
2952 return &Subobject{
2953 Type: typ,
2954 SubExpr: expr,
2955 Offset: offset,
2956 Selectors: selectors,
2957 PastEnd: pastEnd,
2958 }
2959 }
2960
2961 // unresolvedName parses:
2962 //
2963 // <unresolved-name> ::= [gs] <base-unresolved-name>
2964 // ::= sr <unresolved-type> <base-unresolved-name>
2965 // ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2966 // ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2967 func (st *state) unresolvedName() AST {
2968 if len(st.str) >= 2 && st.str[:2] == "gs" {
2969 st.advance(2)
2970 n := st.unresolvedName()
2971 return &Unary{
2972 Op: &Operator{Name: "::"},
2973 Expr: n,
2974 Suffix: false,
2975 SizeofType: false,
2976 }
2977 } else if len(st.str) >= 2 && st.str[:2] == "sr" {
2978 st.advance(2)
2979 if len(st.str) == 0 {
2980 st.fail("expected unresolved type")
2981 }
2982 switch st.str[0] {
2983 case 'T', 'D', 'S':
2984 t := st.demangleType(false)
2985 n := st.baseUnresolvedName()
2986 n = &Qualified{Scope: t, Name: n, LocalName: false}
2987 if len(st.str) > 0 && st.str[0] == 'I' {
2988 n = st.template(n)
2989 st.subs.add(n)
2990 }
2991 return n
2992 default:
2993 var s AST
2994 if st.str[0] == 'N' {
2995 st.advance(1)
2996 s = st.demangleType(false)
2997 }
2998 for len(st.str) == 0 || st.str[0] != 'E' {
2999 // GCC does not seem to follow the ABI here.
3000 // It can emit type/name without an 'E'.
3001 if s != nil && len(st.str) > 0 && !isDigit(st.str[0]) {
3002 if q, ok := s.(*Qualified); ok {
3003 a := q.Scope
3004 if t, ok := a.(*Template); ok {
3005 st.subs.add(t.Name)
3006 st.subs.add(t)
3007 } else {
3008 st.subs.add(a)
3009 }
3010 return s
3011 }
3012 }
3013 n := st.sourceName()
3014 if len(st.str) > 0 && st.str[0] == 'I' {
3015 st.subs.add(n)
3016 n = st.template(n)
3017 }
3018 if s == nil {
3019 s = n
3020 } else {
3021 s = &Qualified{Scope: s, Name: n, LocalName: false}
3022 }
3023 }
3024 if s == nil {
3025 st.fail("missing scope in unresolved name")
3026 }
3027 st.advance(1)
3028 n := st.baseUnresolvedName()
3029 return &Qualified{Scope: s, Name: n, LocalName: false}
3030 }
3031 } else {
3032 return st.baseUnresolvedName()
3033 }
3034 }
3035
3036 // baseUnresolvedName parses:
3037 //
3038 // <base-unresolved-name> ::= <simple-id>
3039 // ::= on <operator-name>
3040 // ::= on <operator-name> <template-args>
3041 // ::= dn <destructor-name>
3042 //
3043 // <simple-id> ::= <source-name> [ <template-args> ]
3044 func (st *state) baseUnresolvedName() AST {
3045 var n AST
3046 if len(st.str) >= 2 && st.str[:2] == "on" {
3047 st.advance(2)
3048 n, _ = st.operatorName(true)
3049 } else if len(st.str) >= 2 && st.str[:2] == "dn" {
3050 st.advance(2)
3051 if len(st.str) > 0 && isDigit(st.str[0]) {
3052 n = st.sourceName()
3053 } else {
3054 n = st.demangleType(false)
3055 }
3056 n = &Destructor{Name: n}
3057 } else if len(st.str) > 0 && isDigit(st.str[0]) {
3058 n = st.sourceName()
3059 } else {
3060 // GCC seems to not follow the ABI here: it can have
3061 // an operator name without on.
3062 // See https://gcc.gnu.org/PR70182.
3063 n, _ = st.operatorName(true)
3064 }
3065 if len(st.str) > 0 && st.str[0] == 'I' {
3066 n = st.template(n)
3067 }
3068 return n
3069 }
3070
3071 // requiresExpr parses:
3072 //
3073 // <expression> ::= rQ <bare-function-type> _ <requirement>+ E
3074 // ::= rq <requirement>+ E
3075 // <requirement> ::= X <expression> [N] [R <type-constraint>]
3076 // ::= T <type>
3077 // ::= Q <constraint-expression>
3078 func (st *state) requiresExpr() AST {
3079 st.checkChar('r')
3080 if len(st.str) == 0 || (st.str[0] != 'q' && st.str[0] != 'Q') {
3081 st.fail("expected q or Q in requires clause in expression")
3082 }
3083 kind := st.str[0]
3084 st.advance(1)
3085
3086 var params []AST
3087 if kind == 'Q' {
3088 for len(st.str) > 0 && st.str[0] != '_' {
3089 typ := st.demangleType(false)
3090 params = append(params, typ)
3091 }
3092 if len(st.str) == 0 {
3093 st.fail("expected requirement parameter")
3094 }
3095 st.advance(1)
3096 }
3097
3098 var requirements []AST
3099 for len(st.str) > 0 && st.str[0] != 'E' {
3100 var req AST
3101 switch st.str[0] {
3102 case 'X':
3103 st.advance(1)
3104 expr := st.expression()
3105 var noexcept bool
3106 if len(st.str) > 0 && st.str[0] == 'N' {
3107 st.advance(1)
3108 noexcept = true
3109 }
3110 var typeReq AST
3111 if len(st.str) > 0 && st.str[0] == 'R' {
3112 st.advance(1)
3113 typeReq, _ = st.name()
3114 }
3115 req = &ExprRequirement{
3116 Expr: expr,
3117 Noexcept: noexcept,
3118 TypeReq: typeReq,
3119 }
3120
3121 case 'T':
3122 st.advance(1)
3123 typ := st.demangleType(false)
3124 req = &TypeRequirement{Type: typ}
3125
3126 case 'Q':
3127 st.advance(1)
3128 // We parse a regular expression rather than a
3129 // constraint expression.
3130 expr := st.expression()
3131 req = &NestedRequirement{Constraint: expr}
3132
3133 default:
3134 st.fail("unrecognized requirement code")
3135 }
3136
3137 requirements = append(requirements, req)
3138 }
3139
3140 if len(st.str) == 0 || st.str[0] != 'E' {
3141 st.fail("expected E after requirements")
3142 }
3143 st.advance(1)
3144
3145 return &RequiresExpr{
3146 Params: params,
3147 Requirements: requirements,
3148 }
3149 }
3150
3151 // exprPrimary parses:
3152 //
3153 // <expr-primary> ::= L <type> <(value) number> E
3154 // ::= L <type> <(value) float> E
3155 // ::= L <mangled-name> E
3156 func (st *state) exprPrimary() AST {
3157 st.checkChar('L')
3158 if len(st.str) == 0 {
3159 st.fail("expected primary expression")
3160
3161 }
3162
3163 // Check for 'Z' here because g++ incorrectly omitted the
3164 // underscore until -fabi-version=3.
3165 var ret AST
3166 if st.str[0] == '_' || st.str[0] == 'Z' {
3167 if st.str[0] == '_' {
3168 st.advance(1)
3169 }
3170 if len(st.str) == 0 || st.str[0] != 'Z' {
3171 st.fail("expected mangled name")
3172 }
3173 st.advance(1)
3174 ret = st.encoding(true, notForLocalName)
3175 } else {
3176 t := st.demangleType(false)
3177
3178 isArrayType := func(typ AST) bool {
3179 if twq, ok := typ.(*TypeWithQualifiers); ok {
3180 typ = twq.Base
3181 }
3182 _, ok := typ.(*ArrayType)
3183 return ok
3184 }
3185
3186 neg := false
3187 if len(st.str) > 0 && st.str[0] == 'n' {
3188 neg = true
3189 st.advance(1)
3190 }
3191 if len(st.str) > 0 && st.str[0] == 'E' {
3192 if bt, ok := t.(*BuiltinType); ok && bt.Name == "decltype(nullptr)" {
3193 // A nullptr should not have a value.
3194 // We accept one if present because GCC
3195 // used to generate one.
3196 // https://gcc.gnu.org/PR91979.
3197 } else if cl, ok := t.(*Closure); ok {
3198 // A closure doesn't have a value.
3199 st.advance(1)
3200 return &LambdaExpr{Type: cl}
3201 } else if isArrayType(t) {
3202 st.advance(1)
3203 return &StringLiteral{Type: t}
3204 } else {
3205 st.fail("missing literal value")
3206 }
3207 }
3208 i := 0
3209 for len(st.str) > i && st.str[i] != 'E' {
3210 i++
3211 }
3212 val := st.str[:i]
3213 st.advance(i)
3214 ret = &Literal{Type: t, Val: val, Neg: neg}
3215 }
3216 if len(st.str) == 0 || st.str[0] != 'E' {
3217 st.fail("expected E after literal")
3218 }
3219 st.advance(1)
3220 return ret
3221 }
3222
3223 // discriminator parses:
3224 //
3225 // <discriminator> ::= _ <(non-negative) number> (when number < 10)
3226 // __ <(non-negative) number> _ (when number >= 10)
3227 func (st *state) discriminator(a AST) AST {
3228 if len(st.str) == 0 || st.str[0] != '_' {
3229 // clang can generate a discriminator at the end of
3230 // the string with no underscore.
3231 for i := 0; i < len(st.str); i++ {
3232 if !isDigit(st.str[i]) {
3233 return a
3234 }
3235 }
3236 // Skip the trailing digits.
3237 st.advance(len(st.str))
3238 return a
3239 }
3240 off := st.off
3241 st.advance(1)
3242 trailingUnderscore := false
3243 if len(st.str) > 0 && st.str[0] == '_' {
3244 st.advance(1)
3245 trailingUnderscore = true
3246 }
3247 d := st.number()
3248 if d < 0 {
3249 st.failEarlier("invalid negative discriminator", st.off-off)
3250 }
3251 if trailingUnderscore && d >= 10 {
3252 if len(st.str) == 0 || st.str[0] != '_' {
3253 st.fail("expected _ after discriminator >= 10")
3254 }
3255 st.advance(1)
3256 }
3257 // We don't currently print out the discriminator, so we don't
3258 // save it.
3259 return a
3260 }
3261
3262 // closureTypeName parses:
3263 //
3264 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
3265 // <lambda-sig> ::= <parameter type>+
3266 func (st *state) closureTypeName() AST {
3267 st.checkChar('U')
3268 st.checkChar('l')
3269
3270 oldLambdaTemplateLevel := st.lambdaTemplateLevel
3271 st.lambdaTemplateLevel = len(st.templates) + 1
3272
3273 var templateArgs []AST
3274 var template *Template
3275 for len(st.str) > 1 && st.str[0] == 'T' {
3276 arg, templateVal := st.templateParamDecl()
3277 if arg == nil {
3278 break
3279 }
3280 templateArgs = append(templateArgs, arg)
3281 if template == nil {
3282 template = &Template{
3283 Name: &Name{Name: "lambda"},
3284 }
3285 st.templates = append(st.templates, template)
3286 }
3287 template.Args = append(template.Args, templateVal)
3288 }
3289
3290 var templateArgsConstraint AST
3291 if len(st.str) > 0 && st.str[0] == 'Q' {
3292 templateArgsConstraint = st.constraintExpr()
3293 }
3294
3295 types := st.parmlist(false)
3296
3297 st.lambdaTemplateLevel = oldLambdaTemplateLevel
3298
3299 if template != nil {
3300 st.templates = st.templates[:len(st.templates)-1]
3301 }
3302
3303 var callConstraint AST
3304 if len(st.str) > 0 && st.str[0] == 'Q' {
3305 callConstraint = st.constraintExpr()
3306 }
3307
3308 if len(st.str) == 0 || st.str[0] != 'E' {
3309 st.fail("expected E after closure type name")
3310 }
3311 st.advance(1)
3312 num := st.compactNumber()
3313 return &Closure{
3314 TemplateArgs: templateArgs,
3315 TemplateArgsConstraint: templateArgsConstraint,
3316 Types: types,
3317 Num: num,
3318 CallConstraint: callConstraint,
3319 }
3320 }
3321
3322 // templateParamDecl parses:
3323 //
3324 // <template-param-decl> ::= Ty # type parameter
3325 // ::= Tk <concept name> [<template-args>] # constrained type parameter
3326 // ::= Tn <type> # non-type parameter
3327 // ::= Tt <template-param-decl>* E # template parameter
3328 // ::= Tp <template-param-decl> # parameter pack
3329 //
3330 // Returns the new AST to include in the AST we are building and the
3331 // new AST to add to the list of template parameters.
3332 //
3333 // Returns nil, nil if not looking at a template-param-decl.
3334 func (st *state) templateParamDecl() (AST, AST) {
3335 if len(st.str) < 2 || st.str[0] != 'T' {
3336 return nil, nil
3337 }
3338 mk := func(prefix string, p *int) AST {
3339 idx := *p
3340 (*p)++
3341 return &TemplateParamName{
3342 Prefix: prefix,
3343 Index: idx,
3344 }
3345 }
3346 switch st.str[1] {
3347 case 'y':
3348 st.advance(2)
3349 name := mk("$T", &st.typeTemplateParamCount)
3350 tp := &TypeTemplateParam{
3351 Name: name,
3352 }
3353 return tp, name
3354 case 'k':
3355 // We don't track enclosing template parameter levels.
3356 // Don't try to demangle template parameter substitutions
3357 // in constraints.
3358 hold := st.parsingConstraint
3359 st.parsingConstraint = true
3360 defer func() { st.parsingConstraint = hold }()
3361
3362 st.advance(2)
3363 constraint, _ := st.name()
3364 name := mk("$T", &st.typeTemplateParamCount)
3365 tp := &ConstrainedTypeTemplateParam{
3366 Name: name,
3367 Constraint: constraint,
3368 }
3369 return tp, name
3370 case 'n':
3371 st.advance(2)
3372 name := mk("$N", &st.nonTypeTemplateParamCount)
3373 typ := st.demangleType(false)
3374 tp := &NonTypeTemplateParam{
3375 Name: name,
3376 Type: typ,
3377 }
3378 return tp, name
3379 case 't':
3380 st.advance(2)
3381 name := mk("$TT", &st.templateTemplateParamCount)
3382 var params []AST
3383 var template *Template
3384 var constraint AST
3385 for {
3386 if len(st.str) == 0 {
3387 st.fail("expected closure template parameter")
3388 }
3389 if st.str[0] == 'E' {
3390 st.advance(1)
3391 break
3392 }
3393 off := st.off
3394 param, templateVal := st.templateParamDecl()
3395 if param == nil {
3396 st.failEarlier("expected closure template parameter", st.off-off)
3397 }
3398 params = append(params, param)
3399 if template == nil {
3400 template = &Template{
3401 Name: &Name{Name: "template_template"},
3402 }
3403 st.templates = append(st.templates, template)
3404 }
3405 template.Args = append(template.Args, templateVal)
3406
3407 if len(st.str) > 0 && st.str[0] == 'Q' {
3408 // A list of template template
3409 // parameters can have a constraint.
3410 constraint = st.constraintExpr()
3411 if len(st.str) == 0 || st.str[0] != 'E' {
3412 st.fail("expected end of template template parameters after constraint")
3413 }
3414 }
3415 }
3416 if template != nil {
3417 st.templates = st.templates[:len(st.templates)-1]
3418 }
3419 tp := &TemplateTemplateParam{
3420 Name: name,
3421 Params: params,
3422 Constraint: constraint,
3423 }
3424 return tp, name
3425 case 'p':
3426 st.advance(2)
3427 off := st.off
3428 param, templateVal := st.templateParamDecl()
3429 if param == nil {
3430 st.failEarlier("expected lambda template parameter", st.off-off)
3431 }
3432 return &TemplateParamPack{Param: param}, templateVal
3433 default:
3434 return nil, nil
3435 }
3436 }
3437
3438 // unnamedTypeName parses:
3439 //
3440 // <unnamed-type-name> ::= Ut [ <nonnegative number> ] _
3441 func (st *state) unnamedTypeName() AST {
3442 st.checkChar('U')
3443 st.checkChar('t')
3444 num := st.compactNumber()
3445 ret := &UnnamedType{Num: num}
3446 st.subs.add(ret)
3447 return ret
3448 }
3449
3450 // unnamedEnum parses an unnamed enum type.
3451 // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2115r0.html
3452 func (st *state) unnamedEnum() AST {
3453 st.checkChar('U')
3454 st.checkChar('e')
3455 typ := st.demangleType(false)
3456 name := st.sourceName()
3457 ret := &UnnamedEnum{
3458 Underlying: typ,
3459 Name: name,
3460 }
3461 st.subs.add(ret)
3462 return ret
3463 }
3464
3465 // constraintExpr parses a constraint expression. This is just a
3466 // regular expression, but template parameters are handled specially.
3467 func (st *state) constraintExpr() AST {
3468 st.checkChar('Q')
3469
3470 hold := st.parsingConstraint
3471 st.parsingConstraint = true
3472 defer func() { st.parsingConstraint = hold }()
3473
3474 return st.expression()
3475 }
3476
3477 // Recognize a clone suffix. These are not part of the mangling API,
3478 // but are added by GCC when cloning functions.
3479 func (st *state) cloneSuffix(a AST) AST {
3480 i := 0
3481 if len(st.str) > 1 && st.str[0] == '.' && (isLower(st.str[1]) || isDigit(st.str[1]) || st.str[1] == '_') {
3482 i += 2
3483 for len(st.str) > i && (isLower(st.str[i]) || isDigit(st.str[i]) || st.str[i] == '_') {
3484 i++
3485 }
3486 }
3487 for len(st.str) > i+1 && st.str[i] == '.' && isDigit(st.str[i+1]) {
3488 i += 2
3489 for len(st.str) > i && isDigit(st.str[i]) {
3490 i++
3491 }
3492 }
3493 suffix := st.str[:i]
3494 st.advance(i)
3495 return &Clone{Base: a, Suffix: suffix}
3496 }
3497
3498 // substitutions is the list of substitution candidates that may
3499 // appear later in the string.
3500 type substitutions []AST
3501
3502 // add adds a new substitution candidate.
3503 func (subs *substitutions) add(a AST) {
3504 *subs = append(*subs, a)
3505 }
3506
3507 // subAST maps standard substitution codes to the corresponding AST.
3508 var subAST = map[byte]AST{
3509 't': &Name{Name: "std"},
3510 'a': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
3511 'b': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
3512 's': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "string"}},
3513 'i': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "istream"}},
3514 'o': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "ostream"}},
3515 'd': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "iostream"}},
3516 }
3517
3518 // verboseAST maps standard substitution codes to the long form of the
3519 // corresponding AST. We use this when the Verbose option is used, to
3520 // match the standard demangler.
3521 var verboseAST = map[byte]AST{
3522 't': &Name{Name: "std"},
3523 'a': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
3524 'b': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
3525
3526 // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
3527 's': &Template{
3528 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
3529 Args: []AST{
3530 &BuiltinType{Name: "char"},
3531 &Template{
3532 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
3533 Args: []AST{&BuiltinType{Name: "char"}}},
3534 &Template{
3535 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
3536 Args: []AST{&BuiltinType{Name: "char"}}}}},
3537 // std::basic_istream<char, std::char_traits<char> >
3538 'i': &Template{
3539 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_istream"}},
3540 Args: []AST{
3541 &BuiltinType{Name: "char"},
3542 &Template{
3543 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
3544 Args: []AST{&BuiltinType{Name: "char"}}}}},
3545 // std::basic_ostream<char, std::char_traits<char> >
3546 'o': &Template{
3547 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_ostream"}},
3548 Args: []AST{
3549 &BuiltinType{Name: "char"},
3550 &Template{
3551 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
3552 Args: []AST{&BuiltinType{Name: "char"}}}}},
3553 // std::basic_iostream<char, std::char_traits<char> >
3554 'd': &Template{
3555 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_iostream"}},
3556 Args: []AST{
3557 &BuiltinType{Name: "char"},
3558 &Template{
3559 Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
3560 Args: []AST{&BuiltinType{Name: "char"}}}}},
3561 }
3562
3563 // substitution parses:
3564 //
3565 // <substitution> ::= S <seq-id> _
3566 // ::= S_
3567 // ::= St
3568 // ::= Sa
3569 // ::= Sb
3570 // ::= Ss
3571 // ::= Si
3572 // ::= So
3573 // ::= Sd
3574 func (st *state) substitution(forPrefix bool) AST {
3575 st.checkChar('S')
3576 if len(st.str) == 0 {
3577 st.fail("missing substitution index")
3578 }
3579 c := st.str[0]
3580 off := st.off
3581 if c == '_' || isDigit(c) || isUpper(c) {
3582 id := st.seqID(false)
3583 if id >= len(st.subs) {
3584 st.failEarlier(fmt.Sprintf("substitution index out of range (%d >= %d)", id, len(st.subs)), st.off-off)
3585 }
3586
3587 ret := st.subs[id]
3588
3589 // We need to update any references to template
3590 // parameters to refer to the currently active
3591 // template.
3592
3593 // When copying a Typed we may need to adjust
3594 // the templates.
3595 copyTemplates := st.templates
3596 var oldLambdaTemplateLevel []int
3597
3598 // pushTemplate is called from skip, popTemplate from copy.
3599 pushTemplate := func(template *Template) {
3600 copyTemplates = append(copyTemplates, template)
3601 oldLambdaTemplateLevel = append(oldLambdaTemplateLevel, st.lambdaTemplateLevel)
3602 st.lambdaTemplateLevel = 0
3603 }
3604 popTemplate := func() {
3605 copyTemplates = copyTemplates[:len(copyTemplates)-1]
3606 st.lambdaTemplateLevel = oldLambdaTemplateLevel[len(oldLambdaTemplateLevel)-1]
3607 oldLambdaTemplateLevel = oldLambdaTemplateLevel[:len(oldLambdaTemplateLevel)-1]
3608 }
3609
3610 copy := func(a AST) AST {
3611 var index int
3612 switch a := a.(type) {
3613 case *Typed:
3614 // Remove the template added in skip.
3615 if _, ok := a.Name.(*Template); ok {
3616 popTemplate()
3617 }
3618 return nil
3619 case *Closure:
3620 // Undo the save in skip.
3621 st.lambdaTemplateLevel = oldLambdaTemplateLevel[len(oldLambdaTemplateLevel)-1]
3622 oldLambdaTemplateLevel = oldLambdaTemplateLevel[:len(oldLambdaTemplateLevel)-1]
3623 return nil
3624 case *TemplateParam:
3625 index = a.Index
3626 case *LambdaAuto:
3627 // A lambda auto parameter is represented
3628 // as a template parameter, so we may have
3629 // to change back when substituting.
3630 index = a.Index
3631 case *PackExpansion:
3632 // Find the possibly-new argument pack.
3633 pack := st.findArgumentPack(a.Base)
3634 if pack != a.Pack {
3635 return &PackExpansion{
3636 Base: a.Base,
3637 Pack: pack,
3638 }
3639 }
3640 return nil
3641 default:
3642 return nil
3643 }
3644 if st.parsingConstraint {
3645 // We don't try to substitute template
3646 // parameters in a constraint expression.
3647 return &Name{Name: fmt.Sprintf("T%d", index)}
3648 }
3649 if st.lambdaTemplateLevel > 0 {
3650 if _, ok := a.(*LambdaAuto); ok {
3651 return nil
3652 }
3653 return &LambdaAuto{Index: index}
3654 }
3655 var template *Template
3656 if len(copyTemplates) > 0 {
3657 template = copyTemplates[len(copyTemplates)-1]
3658 } else if rt, ok := ret.(*Template); ok {
3659 // At least with clang we can see a template
3660 // to start, and sometimes we need to refer
3661 // to it. There is probably something wrong
3662 // here.
3663 template = rt
3664 } else {
3665 st.failEarlier("substituted template parameter not in scope of template", st.off-off)
3666 }
3667 if template == nil {
3668 // This template parameter is within
3669 // the scope of a cast operator.
3670 return &TemplateParam{Index: index, Template: nil}
3671 }
3672
3673 if index >= len(template.Args) {
3674 st.failEarlier(fmt.Sprintf("substituted template index out of range (%d >= %d)", index, len(template.Args)), st.off-off)
3675 }
3676
3677 return &TemplateParam{Index: index, Template: template}
3678 }
3679 seen := make(map[AST]bool)
3680 skip := func(a AST) bool {
3681 switch a := a.(type) {
3682 case *Typed:
3683 if template, ok := a.Name.(*Template); ok {
3684 // This template is removed in copy.
3685 pushTemplate(template)
3686 }
3687 return false
3688 case *Closure:
3689 // This is undone in copy.
3690 oldLambdaTemplateLevel = append(oldLambdaTemplateLevel, st.lambdaTemplateLevel)
3691 st.lambdaTemplateLevel = len(copyTemplates) + 1
3692 return false
3693 case *TemplateParam, *LambdaAuto:
3694 return false
3695 }
3696 if seen[a] {
3697 return true
3698 }
3699 seen[a] = true
3700 return false
3701 }
3702
3703 if c := ret.Copy(copy, skip); c != nil {
3704 return c
3705 }
3706
3707 return ret
3708 } else {
3709 st.advance(1)
3710 m := subAST
3711 if st.verbose {
3712 m = verboseAST
3713 }
3714 // For compatibility with the standard demangler, use
3715 // a longer name for a constructor or destructor.
3716 if forPrefix && len(st.str) > 0 && (st.str[0] == 'C' || st.str[0] == 'D') {
3717 m = verboseAST
3718 }
3719 a, ok := m[c]
3720 if !ok {
3721 st.failEarlier("unrecognized substitution code", 1)
3722 }
3723
3724 if len(st.str) > 0 && st.str[0] == 'B' {
3725 a = st.taggedName(a)
3726 st.subs.add(a)
3727 }
3728
3729 return a
3730 }
3731 }
3732
3733 // isDigit returns whetner c is a digit for demangling purposes.
3734 func isDigit(c byte) bool {
3735 return c >= '0' && c <= '9'
3736 }
3737
3738 // isUpper returns whether c is an upper case letter for demangling purposes.
3739 func isUpper(c byte) bool {
3740 return c >= 'A' && c <= 'Z'
3741 }
3742
3743 // isLower returns whether c is a lower case letter for demangling purposes.
3744 func isLower(c byte) bool {
3745 return c >= 'a' && c <= 'z'
3746 }
3747
3748 // simplify replaces template parameters with their expansions, and
3749 // merges qualifiers.
3750 func simplify(a AST) AST {
3751 seen := make(map[AST]bool)
3752 skip := func(a AST) bool {
3753 if seen[a] {
3754 return true
3755 }
3756 seen[a] = true
3757 return false
3758 }
3759 if r := a.Copy(simplifyOne, skip); r != nil {
3760 return r
3761 }
3762 return a
3763 }
3764
3765 // simplifyOne simplifies a single AST. It returns nil if there is
3766 // nothing to do.
3767 func simplifyOne(a AST) AST {
3768 switch a := a.(type) {
3769 case *TemplateParam:
3770 if a.Template != nil && a.Index < len(a.Template.Args) {
3771 return a.Template.Args[a.Index]
3772 }
3773 case *MethodWithQualifiers:
3774 if m, ok := a.Method.(*MethodWithQualifiers); ok {
3775 ref := a.RefQualifier
3776 if ref == "" {
3777 ref = m.RefQualifier
3778 } else if m.RefQualifier != "" {
3779 if ref == "&" || m.RefQualifier == "&" {
3780 ref = "&"
3781 }
3782 }
3783 return &MethodWithQualifiers{Method: m.Method, Qualifiers: mergeQualifiers(a.Qualifiers, m.Qualifiers), RefQualifier: ref}
3784 }
3785 if t, ok := a.Method.(*TypeWithQualifiers); ok {
3786 return &MethodWithQualifiers{Method: t.Base, Qualifiers: mergeQualifiers(a.Qualifiers, t.Qualifiers), RefQualifier: a.RefQualifier}
3787 }
3788 case *TypeWithQualifiers:
3789 if ft, ok := a.Base.(*FunctionType); ok {
3790 return &MethodWithQualifiers{Method: ft, Qualifiers: a.Qualifiers, RefQualifier: ""}
3791 }
3792 if t, ok := a.Base.(*TypeWithQualifiers); ok {
3793 return &TypeWithQualifiers{Base: t.Base, Qualifiers: mergeQualifiers(a.Qualifiers, t.Qualifiers)}
3794 }
3795 if m, ok := a.Base.(*MethodWithQualifiers); ok {
3796 return &MethodWithQualifiers{Method: m.Method, Qualifiers: mergeQualifiers(a.Qualifiers, m.Qualifiers), RefQualifier: m.RefQualifier}
3797 }
3798 case *ReferenceType:
3799 if rt, ok := a.Base.(*ReferenceType); ok {
3800 return rt
3801 }
3802 if rrt, ok := a.Base.(*RvalueReferenceType); ok {
3803 return &ReferenceType{Base: rrt.Base}
3804 }
3805 case *RvalueReferenceType:
3806 if rrt, ok := a.Base.(*RvalueReferenceType); ok {
3807 return rrt
3808 }
3809 if rt, ok := a.Base.(*ReferenceType); ok {
3810 return rt
3811 }
3812 case *ArrayType:
3813 // Qualifiers on the element of an array type
3814 // go on the whole array type.
3815 if q, ok := a.Element.(*TypeWithQualifiers); ok {
3816 return &TypeWithQualifiers{
3817 Base: &ArrayType{Dimension: a.Dimension, Element: q.Base},
3818 Qualifiers: q.Qualifiers,
3819 }
3820 }
3821 case *PackExpansion:
3822 // Expand the pack and replace it with a list of
3823 // expressions.
3824 if a.Pack != nil {
3825 exprs := make([]AST, len(a.Pack.Args))
3826 for i, arg := range a.Pack.Args {
3827 copy := func(sub AST) AST {
3828 // Replace the ArgumentPack
3829 // with a specific argument.
3830 if sub == a.Pack {
3831 return arg
3832 }
3833 // Copy everything else.
3834 return nil
3835 }
3836
3837 seen := make(map[AST]bool)
3838 skip := func(sub AST) bool {
3839 // Don't traverse into another
3840 // pack expansion.
3841 if _, ok := sub.(*PackExpansion); ok {
3842 return true
3843 }
3844 if seen[sub] {
3845 return true
3846 }
3847 seen[sub] = true
3848 return false
3849 }
3850
3851 b := a.Base.Copy(copy, skip)
3852 if b == nil {
3853 b = a.Base
3854 }
3855 exprs[i] = simplify(b)
3856 }
3857 return &ExprList{Exprs: exprs}
3858 }
3859 }
3860 return nil
3861 }
3862
3863 // findArgumentPack walks the AST looking for the argument pack for a
3864 // pack expansion. We find it via a template parameter.
3865 func (st *state) findArgumentPack(a AST) *ArgumentPack {
3866 seen := make(map[AST]bool)
3867 var ret *ArgumentPack
3868 a.Traverse(func(a AST) bool {
3869 if ret != nil {
3870 return false
3871 }
3872 switch a := a.(type) {
3873 case *TemplateParam:
3874 if a.Template == nil || a.Index >= len(a.Template.Args) {
3875 return true
3876 }
3877 if pack, ok := a.Template.Args[a.Index].(*ArgumentPack); ok {
3878 ret = pack
3879 return false
3880 }
3881 case *PackExpansion, *Closure, *Name:
3882 return false
3883 case *TaggedName, *Operator, *BuiltinType, *FunctionParam:
3884 return false
3885 case *UnnamedType, *FixedType, *DefaultArg:
3886 return false
3887 }
3888 if seen[a] {
3889 return false
3890 }
3891 seen[a] = true
3892 return true
3893 })
3894 return ret
3895 }