• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===------------------------- ItaniumDemangle.h ----------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Generic itanium demangler library. This file has two byte-per-byte identical
10 // copies in the source tree, one in libcxxabi, and the other in llvm.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef DEMANGLE_ITANIUMDEMANGLE_H
15 #define DEMANGLE_ITANIUMDEMANGLE_H
16 
17 // FIXME: (possibly) incomplete list of features that clang mangles that this
18 // file does not yet support:
19 //   - C++ modules TS
20 
21 #include "DemangleConfig.h"
22 #include "StringView.h"
23 #include "Utility.h"
24 #include <cassert>
25 #include <cctype>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <cstring>
29 #include <exception>
30 #include <numeric>
31 #include <type_traits>
32 #include <utility>
33 
34 #define FOR_EACH_NODE_KIND(X) \
35     X(NodeArrayNode) \
36     X(DotSuffix) \
37     X(VendorExtQualType) \
38     X(QualType) \
39     X(ConversionOperatorType) \
40     X(PostfixQualifiedType) \
41     X(ElaboratedTypeSpefType) \
42     X(NameType) \
43     X(AbiTagAttr) \
44     X(EnableIfAttr) \
45     X(ObjCProtoName) \
46     X(PointerType) \
47     X(ReferenceType) \
48     X(PointerToMemberType) \
49     X(ArrayType) \
50     X(FunctionType) \
51     X(NoexceptSpec) \
52     X(DynamicExceptionSpec) \
53     X(FunctionEncoding) \
54     X(LiteralOperator) \
55     X(SpecialName) \
56     X(CtorVtableSpecialName) \
57     X(QualifiedName) \
58     X(NestedName) \
59     X(LocalName) \
60     X(VectorType) \
61     X(PixelVectorType) \
62     X(SyntheticTemplateParamName) \
63     X(TypeTemplateParamDecl) \
64     X(NonTypeTemplateParamDecl) \
65     X(TemplateTemplateParamDecl) \
66     X(TemplateParamPackDecl) \
67     X(ParameterPack) \
68     X(TemplateArgumentPack) \
69     X(ParameterPackExpansion) \
70     X(TemplateArgs) \
71     X(ForwardTemplateReference) \
72     X(NameWithTemplateArgs) \
73     X(GlobalQualifiedName) \
74     X(StdQualifiedName) \
75     X(ExpandedSpecialSubstitution) \
76     X(SpecialSubstitution) \
77     X(CtorDtorName) \
78     X(DtorName) \
79     X(UnnamedTypeName) \
80     X(ClosureTypeName) \
81     X(StructuredBindingName) \
82     X(BinaryExpr) \
83     X(ArraySubscriptExpr) \
84     X(PostfixExpr) \
85     X(ConditionalExpr) \
86     X(MemberExpr) \
87     X(EnclosingExpr) \
88     X(CastExpr) \
89     X(SizeofParamPackExpr) \
90     X(CallExpr) \
91     X(NewExpr) \
92     X(DeleteExpr) \
93     X(PrefixExpr) \
94     X(FunctionParam) \
95     X(ConversionExpr) \
96     X(InitListExpr) \
97     X(FoldExpr) \
98     X(ThrowExpr) \
99     X(UUIDOfExpr) \
100     X(BoolExpr) \
101     X(StringLiteral) \
102     X(LambdaExpr) \
103     X(IntegerCastExpr) \
104     X(IntegerLiteral) \
105     X(FloatLiteral) \
106     X(DoubleLiteral) \
107     X(LongDoubleLiteral) \
108     X(BracedExpr) \
109     X(BracedRangeExpr)
110 
111 DEMANGLE_NAMESPACE_BEGIN
112 
113 // Base class of all AST nodes. The AST is built by the parser, then is
114 // traversed by the printLeft/Right functions to produce a demangled string.
115 class Node {
116 public:
117   enum Kind : unsigned char {
118 #define ENUMERATOR(NodeKind) K ## NodeKind,
119     FOR_EACH_NODE_KIND(ENUMERATOR)
120 #undef ENUMERATOR
121   };
122 
123   /// Three-way bool to track a cached value. Unknown is possible if this node
124   /// has an unexpanded parameter pack below it that may affect this cache.
125   enum class Cache : unsigned char { Yes, No, Unknown, };
126 
127 private:
128   Kind K;
129 
130   // FIXME: Make these protected.
131 public:
132   /// Tracks if this node has a component on its right side, in which case we
133   /// need to call printRight.
134   Cache RHSComponentCache;
135 
136   /// Track if this node is a (possibly qualified) array type. This can affect
137   /// how we format the output string.
138   Cache ArrayCache;
139 
140   /// Track if this node is a (possibly qualified) function type. This can
141   /// affect how we format the output string.
142   Cache FunctionCache;
143 
144 public:
145   Node(Kind K_, Cache RHSComponentCache_ = Cache::No,
146        Cache ArrayCache_ = Cache::No, Cache FunctionCache_ = Cache::No)
K(K_)147       : K(K_), RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
148         FunctionCache(FunctionCache_) {}
149 
150   /// Visit the most-derived object corresponding to this object.
151   template<typename Fn> void visit(Fn F) const;
152 
153   // The following function is provided by all derived classes:
154   //
155   // Call F with arguments that, when passed to the constructor of this node,
156   // would construct an equivalent node.
157   //template<typename Fn> void match(Fn F) const;
158 
hasRHSComponent(OutputStream & S)159   bool hasRHSComponent(OutputStream &S) const {
160     if (RHSComponentCache != Cache::Unknown)
161       return RHSComponentCache == Cache::Yes;
162     return hasRHSComponentSlow(S);
163   }
164 
hasArray(OutputStream & S)165   bool hasArray(OutputStream &S) const {
166     if (ArrayCache != Cache::Unknown)
167       return ArrayCache == Cache::Yes;
168     return hasArraySlow(S);
169   }
170 
hasFunction(OutputStream & S)171   bool hasFunction(OutputStream &S) const {
172     if (FunctionCache != Cache::Unknown)
173       return FunctionCache == Cache::Yes;
174     return hasFunctionSlow(S);
175   }
176 
getKind()177   Kind getKind() const { return K; }
178 
hasRHSComponentSlow(OutputStream &)179   virtual bool hasRHSComponentSlow(OutputStream &) const { return false; }
hasArraySlow(OutputStream &)180   virtual bool hasArraySlow(OutputStream &) const { return false; }
hasFunctionSlow(OutputStream &)181   virtual bool hasFunctionSlow(OutputStream &) const { return false; }
182 
183   // Dig through "glue" nodes like ParameterPack and ForwardTemplateReference to
184   // get at a node that actually represents some concrete syntax.
getSyntaxNode(OutputStream &)185   virtual const Node *getSyntaxNode(OutputStream &) const {
186     return this;
187   }
188 
print(OutputStream & S)189   void print(OutputStream &S) const {
190     printLeft(S);
191     if (RHSComponentCache != Cache::No)
192       printRight(S);
193   }
194 
195   // Print the "left" side of this Node into OutputStream.
196   virtual void printLeft(OutputStream &) const = 0;
197 
198   // Print the "right". This distinction is necessary to represent C++ types
199   // that appear on the RHS of their subtype, such as arrays or functions.
200   // Since most types don't have such a component, provide a default
201   // implementation.
printRight(OutputStream &)202   virtual void printRight(OutputStream &) const {}
203 
getBaseName()204   virtual StringView getBaseName() const { return StringView(); }
205 
206   // Silence compiler warnings, this dtor will never be called.
207   virtual ~Node() = default;
208 
209 #ifndef NDEBUG
210   DEMANGLE_DUMP_METHOD void dump() const;
211 #endif
212 };
213 
214 class NodeArray {
215   Node **Elements;
216   size_t NumElements;
217 
218 public:
NodeArray()219   NodeArray() : Elements(nullptr), NumElements(0) {}
NodeArray(Node ** Elements_,size_t NumElements_)220   NodeArray(Node **Elements_, size_t NumElements_)
221       : Elements(Elements_), NumElements(NumElements_) {}
222 
empty()223   bool empty() const { return NumElements == 0; }
size()224   size_t size() const { return NumElements; }
225 
begin()226   Node **begin() const { return Elements; }
end()227   Node **end() const { return Elements + NumElements; }
228 
229   Node *operator[](size_t Idx) const { return Elements[Idx]; }
230 
printWithComma(OutputStream & S)231   void printWithComma(OutputStream &S) const {
232     bool FirstElement = true;
233     for (size_t Idx = 0; Idx != NumElements; ++Idx) {
234       size_t BeforeComma = S.getCurrentPosition();
235       if (!FirstElement)
236         S += ", ";
237       size_t AfterComma = S.getCurrentPosition();
238       Elements[Idx]->print(S);
239 
240       // Elements[Idx] is an empty parameter pack expansion, we should erase the
241       // comma we just printed.
242       if (AfterComma == S.getCurrentPosition()) {
243         S.setCurrentPosition(BeforeComma);
244         continue;
245       }
246 
247       FirstElement = false;
248     }
249   }
250 };
251 
252 struct NodeArrayNode : Node {
253   NodeArray Array;
NodeArrayNodeNodeArrayNode254   NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
255 
matchNodeArrayNode256   template<typename Fn> void match(Fn F) const { F(Array); }
257 
printLeftNodeArrayNode258   void printLeft(OutputStream &S) const override {
259     Array.printWithComma(S);
260   }
261 };
262 
263 class DotSuffix final : public Node {
264   const Node *Prefix;
265   const StringView Suffix;
266 
267 public:
DotSuffix(const Node * Prefix_,StringView Suffix_)268   DotSuffix(const Node *Prefix_, StringView Suffix_)
269       : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
270 
match(Fn F)271   template<typename Fn> void match(Fn F) const { F(Prefix, Suffix); }
272 
printLeft(OutputStream & s)273   void printLeft(OutputStream &s) const override {
274     Prefix->print(s);
275     s += " (";
276     s += Suffix;
277     s += ")";
278   }
279 };
280 
281 class VendorExtQualType final : public Node {
282   const Node *Ty;
283   StringView Ext;
284 
285 public:
VendorExtQualType(const Node * Ty_,StringView Ext_)286   VendorExtQualType(const Node *Ty_, StringView Ext_)
287       : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_) {}
288 
match(Fn F)289   template<typename Fn> void match(Fn F) const { F(Ty, Ext); }
290 
printLeft(OutputStream & S)291   void printLeft(OutputStream &S) const override {
292     Ty->print(S);
293     S += " ";
294     S += Ext;
295   }
296 };
297 
298 enum FunctionRefQual : unsigned char {
299   FrefQualNone,
300   FrefQualLValue,
301   FrefQualRValue,
302 };
303 
304 enum Qualifiers {
305   QualNone = 0,
306   QualConst = 0x1,
307   QualVolatile = 0x2,
308   QualRestrict = 0x4,
309 };
310 
311 inline Qualifiers operator|=(Qualifiers &Q1, Qualifiers Q2) {
312   return Q1 = static_cast<Qualifiers>(Q1 | Q2);
313 }
314 
315 class QualType final : public Node {
316 protected:
317   const Qualifiers Quals;
318   const Node *Child;
319 
printQuals(OutputStream & S)320   void printQuals(OutputStream &S) const {
321     if (Quals & QualConst)
322       S += " const";
323     if (Quals & QualVolatile)
324       S += " volatile";
325     if (Quals & QualRestrict)
326       S += " restrict";
327   }
328 
329 public:
QualType(const Node * Child_,Qualifiers Quals_)330   QualType(const Node *Child_, Qualifiers Quals_)
331       : Node(KQualType, Child_->RHSComponentCache,
332              Child_->ArrayCache, Child_->FunctionCache),
333         Quals(Quals_), Child(Child_) {}
334 
match(Fn F)335   template<typename Fn> void match(Fn F) const { F(Child, Quals); }
336 
hasRHSComponentSlow(OutputStream & S)337   bool hasRHSComponentSlow(OutputStream &S) const override {
338     return Child->hasRHSComponent(S);
339   }
hasArraySlow(OutputStream & S)340   bool hasArraySlow(OutputStream &S) const override {
341     return Child->hasArray(S);
342   }
hasFunctionSlow(OutputStream & S)343   bool hasFunctionSlow(OutputStream &S) const override {
344     return Child->hasFunction(S);
345   }
346 
printLeft(OutputStream & S)347   void printLeft(OutputStream &S) const override {
348     Child->printLeft(S);
349     printQuals(S);
350   }
351 
printRight(OutputStream & S)352   void printRight(OutputStream &S) const override { Child->printRight(S); }
353 };
354 
355 class ConversionOperatorType final : public Node {
356   const Node *Ty;
357 
358 public:
ConversionOperatorType(const Node * Ty_)359   ConversionOperatorType(const Node *Ty_)
360       : Node(KConversionOperatorType), Ty(Ty_) {}
361 
match(Fn F)362   template<typename Fn> void match(Fn F) const { F(Ty); }
363 
printLeft(OutputStream & S)364   void printLeft(OutputStream &S) const override {
365     S += "operator ";
366     Ty->print(S);
367   }
368 };
369 
370 class PostfixQualifiedType final : public Node {
371   const Node *Ty;
372   const StringView Postfix;
373 
374 public:
PostfixQualifiedType(Node * Ty_,StringView Postfix_)375   PostfixQualifiedType(Node *Ty_, StringView Postfix_)
376       : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
377 
match(Fn F)378   template<typename Fn> void match(Fn F) const { F(Ty, Postfix); }
379 
printLeft(OutputStream & s)380   void printLeft(OutputStream &s) const override {
381     Ty->printLeft(s);
382     s += Postfix;
383   }
384 };
385 
386 class NameType final : public Node {
387   const StringView Name;
388 
389 public:
NameType(StringView Name_)390   NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
391 
match(Fn F)392   template<typename Fn> void match(Fn F) const { F(Name); }
393 
getName()394   StringView getName() const { return Name; }
getBaseName()395   StringView getBaseName() const override { return Name; }
396 
printLeft(OutputStream & s)397   void printLeft(OutputStream &s) const override { s += Name; }
398 };
399 
400 class ElaboratedTypeSpefType : public Node {
401   StringView Kind;
402   Node *Child;
403 public:
ElaboratedTypeSpefType(StringView Kind_,Node * Child_)404   ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
405       : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
406 
match(Fn F)407   template<typename Fn> void match(Fn F) const { F(Kind, Child); }
408 
printLeft(OutputStream & S)409   void printLeft(OutputStream &S) const override {
410     S += Kind;
411     S += ' ';
412     Child->print(S);
413   }
414 };
415 
416 struct AbiTagAttr : Node {
417   Node *Base;
418   StringView Tag;
419 
AbiTagAttrAbiTagAttr420   AbiTagAttr(Node* Base_, StringView Tag_)
421       : Node(KAbiTagAttr, Base_->RHSComponentCache,
422              Base_->ArrayCache, Base_->FunctionCache),
423         Base(Base_), Tag(Tag_) {}
424 
matchAbiTagAttr425   template<typename Fn> void match(Fn F) const { F(Base, Tag); }
426 
printLeftAbiTagAttr427   void printLeft(OutputStream &S) const override {
428     Base->printLeft(S);
429     S += "[abi:";
430     S += Tag;
431     S += "]";
432   }
433 };
434 
435 class EnableIfAttr : public Node {
436   NodeArray Conditions;
437 public:
EnableIfAttr(NodeArray Conditions_)438   EnableIfAttr(NodeArray Conditions_)
439       : Node(KEnableIfAttr), Conditions(Conditions_) {}
440 
match(Fn F)441   template<typename Fn> void match(Fn F) const { F(Conditions); }
442 
printLeft(OutputStream & S)443   void printLeft(OutputStream &S) const override {
444     S += " [enable_if:";
445     Conditions.printWithComma(S);
446     S += ']';
447   }
448 };
449 
450 class ObjCProtoName : public Node {
451   const Node *Ty;
452   StringView Protocol;
453 
454   friend class PointerType;
455 
456 public:
ObjCProtoName(const Node * Ty_,StringView Protocol_)457   ObjCProtoName(const Node *Ty_, StringView Protocol_)
458       : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
459 
match(Fn F)460   template<typename Fn> void match(Fn F) const { F(Ty, Protocol); }
461 
isObjCObject()462   bool isObjCObject() const {
463     return Ty->getKind() == KNameType &&
464            static_cast<const NameType *>(Ty)->getName() == "objc_object";
465   }
466 
printLeft(OutputStream & S)467   void printLeft(OutputStream &S) const override {
468     Ty->print(S);
469     S += "<";
470     S += Protocol;
471     S += ">";
472   }
473 };
474 
475 class PointerType final : public Node {
476   const Node *Pointee;
477 
478 public:
PointerType(const Node * Pointee_)479   PointerType(const Node *Pointee_)
480       : Node(KPointerType, Pointee_->RHSComponentCache),
481         Pointee(Pointee_) {}
482 
match(Fn F)483   template<typename Fn> void match(Fn F) const { F(Pointee); }
484 
hasRHSComponentSlow(OutputStream & S)485   bool hasRHSComponentSlow(OutputStream &S) const override {
486     return Pointee->hasRHSComponent(S);
487   }
488 
printLeft(OutputStream & s)489   void printLeft(OutputStream &s) const override {
490     // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
491     if (Pointee->getKind() != KObjCProtoName ||
492         !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
493       Pointee->printLeft(s);
494       if (Pointee->hasArray(s))
495         s += " ";
496       if (Pointee->hasArray(s) || Pointee->hasFunction(s))
497         s += "(";
498       s += "*";
499     } else {
500       const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
501       s += "id<";
502       s += objcProto->Protocol;
503       s += ">";
504     }
505   }
506 
printRight(OutputStream & s)507   void printRight(OutputStream &s) const override {
508     if (Pointee->getKind() != KObjCProtoName ||
509         !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
510       if (Pointee->hasArray(s) || Pointee->hasFunction(s))
511         s += ")";
512       Pointee->printRight(s);
513     }
514   }
515 };
516 
517 enum class ReferenceKind {
518   LValue,
519   RValue,
520 };
521 
522 // Represents either a LValue or an RValue reference type.
523 class ReferenceType : public Node {
524   const Node *Pointee;
525   ReferenceKind RK;
526 
527   mutable bool Printing = false;
528 
529   // Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
530   // rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
531   // other combination collapses to a lvalue ref.
collapse(OutputStream & S)532   std::pair<ReferenceKind, const Node *> collapse(OutputStream &S) const {
533     auto SoFar = std::make_pair(RK, Pointee);
534     for (;;) {
535       const Node *SN = SoFar.second->getSyntaxNode(S);
536       if (SN->getKind() != KReferenceType)
537         break;
538       auto *RT = static_cast<const ReferenceType *>(SN);
539       SoFar.second = RT->Pointee;
540       SoFar.first = std::min(SoFar.first, RT->RK);
541     }
542     return SoFar;
543   }
544 
545 public:
ReferenceType(const Node * Pointee_,ReferenceKind RK_)546   ReferenceType(const Node *Pointee_, ReferenceKind RK_)
547       : Node(KReferenceType, Pointee_->RHSComponentCache),
548         Pointee(Pointee_), RK(RK_) {}
549 
match(Fn F)550   template<typename Fn> void match(Fn F) const { F(Pointee, RK); }
551 
hasRHSComponentSlow(OutputStream & S)552   bool hasRHSComponentSlow(OutputStream &S) const override {
553     return Pointee->hasRHSComponent(S);
554   }
555 
printLeft(OutputStream & s)556   void printLeft(OutputStream &s) const override {
557     if (Printing)
558       return;
559     SwapAndRestore<bool> SavePrinting(Printing, true);
560     std::pair<ReferenceKind, const Node *> Collapsed = collapse(s);
561     Collapsed.second->printLeft(s);
562     if (Collapsed.second->hasArray(s))
563       s += " ";
564     if (Collapsed.second->hasArray(s) || Collapsed.second->hasFunction(s))
565       s += "(";
566 
567     s += (Collapsed.first == ReferenceKind::LValue ? "&" : "&&");
568   }
printRight(OutputStream & s)569   void printRight(OutputStream &s) const override {
570     if (Printing)
571       return;
572     SwapAndRestore<bool> SavePrinting(Printing, true);
573     std::pair<ReferenceKind, const Node *> Collapsed = collapse(s);
574     if (Collapsed.second->hasArray(s) || Collapsed.second->hasFunction(s))
575       s += ")";
576     Collapsed.second->printRight(s);
577   }
578 };
579 
580 class PointerToMemberType final : public Node {
581   const Node *ClassType;
582   const Node *MemberType;
583 
584 public:
PointerToMemberType(const Node * ClassType_,const Node * MemberType_)585   PointerToMemberType(const Node *ClassType_, const Node *MemberType_)
586       : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
587         ClassType(ClassType_), MemberType(MemberType_) {}
588 
match(Fn F)589   template<typename Fn> void match(Fn F) const { F(ClassType, MemberType); }
590 
hasRHSComponentSlow(OutputStream & S)591   bool hasRHSComponentSlow(OutputStream &S) const override {
592     return MemberType->hasRHSComponent(S);
593   }
594 
printLeft(OutputStream & s)595   void printLeft(OutputStream &s) const override {
596     MemberType->printLeft(s);
597     if (MemberType->hasArray(s) || MemberType->hasFunction(s))
598       s += "(";
599     else
600       s += " ";
601     ClassType->print(s);
602     s += "::*";
603   }
604 
printRight(OutputStream & s)605   void printRight(OutputStream &s) const override {
606     if (MemberType->hasArray(s) || MemberType->hasFunction(s))
607       s += ")";
608     MemberType->printRight(s);
609   }
610 };
611 
612 class ArrayType final : public Node {
613   const Node *Base;
614   Node *Dimension;
615 
616 public:
ArrayType(const Node * Base_,Node * Dimension_)617   ArrayType(const Node *Base_, Node *Dimension_)
618       : Node(KArrayType,
619              /*RHSComponentCache=*/Cache::Yes,
620              /*ArrayCache=*/Cache::Yes),
621         Base(Base_), Dimension(Dimension_) {}
622 
match(Fn F)623   template<typename Fn> void match(Fn F) const { F(Base, Dimension); }
624 
hasRHSComponentSlow(OutputStream &)625   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
hasArraySlow(OutputStream &)626   bool hasArraySlow(OutputStream &) const override { return true; }
627 
printLeft(OutputStream & S)628   void printLeft(OutputStream &S) const override { Base->printLeft(S); }
629 
printRight(OutputStream & S)630   void printRight(OutputStream &S) const override {
631     if (S.back() != ']')
632       S += " ";
633     S += "[";
634     if (Dimension)
635       Dimension->print(S);
636     S += "]";
637     Base->printRight(S);
638   }
639 };
640 
641 class FunctionType final : public Node {
642   const Node *Ret;
643   NodeArray Params;
644   Qualifiers CVQuals;
645   FunctionRefQual RefQual;
646   const Node *ExceptionSpec;
647 
648 public:
FunctionType(const Node * Ret_,NodeArray Params_,Qualifiers CVQuals_,FunctionRefQual RefQual_,const Node * ExceptionSpec_)649   FunctionType(const Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
650                FunctionRefQual RefQual_, const Node *ExceptionSpec_)
651       : Node(KFunctionType,
652              /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
653              /*FunctionCache=*/Cache::Yes),
654         Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
655         ExceptionSpec(ExceptionSpec_) {}
656 
match(Fn F)657   template<typename Fn> void match(Fn F) const {
658     F(Ret, Params, CVQuals, RefQual, ExceptionSpec);
659   }
660 
hasRHSComponentSlow(OutputStream &)661   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
hasFunctionSlow(OutputStream &)662   bool hasFunctionSlow(OutputStream &) const override { return true; }
663 
664   // Handle C++'s ... quirky decl grammar by using the left & right
665   // distinction. Consider:
666   //   int (*f(float))(char) {}
667   // f is a function that takes a float and returns a pointer to a function
668   // that takes a char and returns an int. If we're trying to print f, start
669   // by printing out the return types's left, then print our parameters, then
670   // finally print right of the return type.
printLeft(OutputStream & S)671   void printLeft(OutputStream &S) const override {
672     Ret->printLeft(S);
673     S += " ";
674   }
675 
printRight(OutputStream & S)676   void printRight(OutputStream &S) const override {
677     S += "(";
678     Params.printWithComma(S);
679     S += ")";
680     Ret->printRight(S);
681 
682     if (CVQuals & QualConst)
683       S += " const";
684     if (CVQuals & QualVolatile)
685       S += " volatile";
686     if (CVQuals & QualRestrict)
687       S += " restrict";
688 
689     if (RefQual == FrefQualLValue)
690       S += " &";
691     else if (RefQual == FrefQualRValue)
692       S += " &&";
693 
694     if (ExceptionSpec != nullptr) {
695       S += ' ';
696       ExceptionSpec->print(S);
697     }
698   }
699 };
700 
701 class NoexceptSpec : public Node {
702   const Node *E;
703 public:
NoexceptSpec(const Node * E_)704   NoexceptSpec(const Node *E_) : Node(KNoexceptSpec), E(E_) {}
705 
match(Fn F)706   template<typename Fn> void match(Fn F) const { F(E); }
707 
printLeft(OutputStream & S)708   void printLeft(OutputStream &S) const override {
709     S += "noexcept(";
710     E->print(S);
711     S += ")";
712   }
713 };
714 
715 class DynamicExceptionSpec : public Node {
716   NodeArray Types;
717 public:
DynamicExceptionSpec(NodeArray Types_)718   DynamicExceptionSpec(NodeArray Types_)
719       : Node(KDynamicExceptionSpec), Types(Types_) {}
720 
match(Fn F)721   template<typename Fn> void match(Fn F) const { F(Types); }
722 
printLeft(OutputStream & S)723   void printLeft(OutputStream &S) const override {
724     S += "throw(";
725     Types.printWithComma(S);
726     S += ')';
727   }
728 };
729 
730 class FunctionEncoding final : public Node {
731   const Node *Ret;
732   const Node *Name;
733   NodeArray Params;
734   const Node *Attrs;
735   Qualifiers CVQuals;
736   FunctionRefQual RefQual;
737 
738 public:
FunctionEncoding(const Node * Ret_,const Node * Name_,NodeArray Params_,const Node * Attrs_,Qualifiers CVQuals_,FunctionRefQual RefQual_)739   FunctionEncoding(const Node *Ret_, const Node *Name_, NodeArray Params_,
740                    const Node *Attrs_, Qualifiers CVQuals_,
741                    FunctionRefQual RefQual_)
742       : Node(KFunctionEncoding,
743              /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
744              /*FunctionCache=*/Cache::Yes),
745         Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
746         CVQuals(CVQuals_), RefQual(RefQual_) {}
747 
match(Fn F)748   template<typename Fn> void match(Fn F) const {
749     F(Ret, Name, Params, Attrs, CVQuals, RefQual);
750   }
751 
getCVQuals()752   Qualifiers getCVQuals() const { return CVQuals; }
getRefQual()753   FunctionRefQual getRefQual() const { return RefQual; }
getParams()754   NodeArray getParams() const { return Params; }
getReturnType()755   const Node *getReturnType() const { return Ret; }
756 
hasRHSComponentSlow(OutputStream &)757   bool hasRHSComponentSlow(OutputStream &) const override { return true; }
hasFunctionSlow(OutputStream &)758   bool hasFunctionSlow(OutputStream &) const override { return true; }
759 
getName()760   const Node *getName() const { return Name; }
761 
printLeft(OutputStream & S)762   void printLeft(OutputStream &S) const override {
763     if (Ret) {
764       Ret->printLeft(S);
765       if (!Ret->hasRHSComponent(S))
766         S += " ";
767     }
768     Name->print(S);
769   }
770 
printRight(OutputStream & S)771   void printRight(OutputStream &S) const override {
772     S += "(";
773     Params.printWithComma(S);
774     S += ")";
775     if (Ret)
776       Ret->printRight(S);
777 
778     if (CVQuals & QualConst)
779       S += " const";
780     if (CVQuals & QualVolatile)
781       S += " volatile";
782     if (CVQuals & QualRestrict)
783       S += " restrict";
784 
785     if (RefQual == FrefQualLValue)
786       S += " &";
787     else if (RefQual == FrefQualRValue)
788       S += " &&";
789 
790     if (Attrs != nullptr)
791       Attrs->print(S);
792   }
793 };
794 
795 class LiteralOperator : public Node {
796   const Node *OpName;
797 
798 public:
LiteralOperator(const Node * OpName_)799   LiteralOperator(const Node *OpName_)
800       : Node(KLiteralOperator), OpName(OpName_) {}
801 
match(Fn F)802   template<typename Fn> void match(Fn F) const { F(OpName); }
803 
printLeft(OutputStream & S)804   void printLeft(OutputStream &S) const override {
805     S += "operator\"\" ";
806     OpName->print(S);
807   }
808 };
809 
810 class SpecialName final : public Node {
811   const StringView Special;
812   const Node *Child;
813 
814 public:
SpecialName(StringView Special_,const Node * Child_)815   SpecialName(StringView Special_, const Node *Child_)
816       : Node(KSpecialName), Special(Special_), Child(Child_) {}
817 
match(Fn F)818   template<typename Fn> void match(Fn F) const { F(Special, Child); }
819 
printLeft(OutputStream & S)820   void printLeft(OutputStream &S) const override {
821     S += Special;
822     Child->print(S);
823   }
824 };
825 
826 class CtorVtableSpecialName final : public Node {
827   const Node *FirstType;
828   const Node *SecondType;
829 
830 public:
CtorVtableSpecialName(const Node * FirstType_,const Node * SecondType_)831   CtorVtableSpecialName(const Node *FirstType_, const Node *SecondType_)
832       : Node(KCtorVtableSpecialName),
833         FirstType(FirstType_), SecondType(SecondType_) {}
834 
match(Fn F)835   template<typename Fn> void match(Fn F) const { F(FirstType, SecondType); }
836 
printLeft(OutputStream & S)837   void printLeft(OutputStream &S) const override {
838     S += "construction vtable for ";
839     FirstType->print(S);
840     S += "-in-";
841     SecondType->print(S);
842   }
843 };
844 
845 struct NestedName : Node {
846   Node *Qual;
847   Node *Name;
848 
NestedNameNestedName849   NestedName(Node *Qual_, Node *Name_)
850       : Node(KNestedName), Qual(Qual_), Name(Name_) {}
851 
matchNestedName852   template<typename Fn> void match(Fn F) const { F(Qual, Name); }
853 
getBaseNameNestedName854   StringView getBaseName() const override { return Name->getBaseName(); }
855 
printLeftNestedName856   void printLeft(OutputStream &S) const override {
857     Qual->print(S);
858     S += "::";
859     Name->print(S);
860   }
861 };
862 
863 struct LocalName : Node {
864   Node *Encoding;
865   Node *Entity;
866 
LocalNameLocalName867   LocalName(Node *Encoding_, Node *Entity_)
868       : Node(KLocalName), Encoding(Encoding_), Entity(Entity_) {}
869 
matchLocalName870   template<typename Fn> void match(Fn F) const { F(Encoding, Entity); }
871 
printLeftLocalName872   void printLeft(OutputStream &S) const override {
873     Encoding->print(S);
874     S += "::";
875     Entity->print(S);
876   }
877 };
878 
879 class QualifiedName final : public Node {
880   // qualifier::name
881   const Node *Qualifier;
882   const Node *Name;
883 
884 public:
QualifiedName(const Node * Qualifier_,const Node * Name_)885   QualifiedName(const Node *Qualifier_, const Node *Name_)
886       : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
887 
match(Fn F)888   template<typename Fn> void match(Fn F) const { F(Qualifier, Name); }
889 
getBaseName()890   StringView getBaseName() const override { return Name->getBaseName(); }
891 
printLeft(OutputStream & S)892   void printLeft(OutputStream &S) const override {
893     Qualifier->print(S);
894     S += "::";
895     Name->print(S);
896   }
897 };
898 
899 class VectorType final : public Node {
900   const Node *BaseType;
901   const Node *Dimension;
902 
903 public:
VectorType(const Node * BaseType_,Node * Dimension_)904   VectorType(const Node *BaseType_, Node *Dimension_)
905       : Node(KVectorType), BaseType(BaseType_),
906         Dimension(Dimension_) {}
907 
match(Fn F)908   template<typename Fn> void match(Fn F) const { F(BaseType, Dimension); }
909 
printLeft(OutputStream & S)910   void printLeft(OutputStream &S) const override {
911     BaseType->print(S);
912     S += " vector[";
913     if (Dimension)
914       Dimension->print(S);
915     S += "]";
916   }
917 };
918 
919 class PixelVectorType final : public Node {
920   const Node *Dimension;
921 
922 public:
PixelVectorType(const Node * Dimension_)923   PixelVectorType(const Node *Dimension_)
924       : Node(KPixelVectorType), Dimension(Dimension_) {}
925 
match(Fn F)926   template<typename Fn> void match(Fn F) const { F(Dimension); }
927 
printLeft(OutputStream & S)928   void printLeft(OutputStream &S) const override {
929     // FIXME: This should demangle as "vector pixel".
930     S += "pixel vector[";
931     Dimension->print(S);
932     S += "]";
933   }
934 };
935 
936 enum class TemplateParamKind { Type, NonType, Template };
937 
938 /// An invented name for a template parameter for which we don't have a
939 /// corresponding template argument.
940 ///
941 /// This node is created when parsing the <lambda-sig> for a lambda with
942 /// explicit template arguments, which might be referenced in the parameter
943 /// types appearing later in the <lambda-sig>.
944 class SyntheticTemplateParamName final : public Node {
945   TemplateParamKind Kind;
946   unsigned Index;
947 
948 public:
SyntheticTemplateParamName(TemplateParamKind Kind_,unsigned Index_)949   SyntheticTemplateParamName(TemplateParamKind Kind_, unsigned Index_)
950       : Node(KSyntheticTemplateParamName), Kind(Kind_), Index(Index_) {}
951 
match(Fn F)952   template<typename Fn> void match(Fn F) const { F(Kind, Index); }
953 
printLeft(OutputStream & S)954   void printLeft(OutputStream &S) const override {
955     switch (Kind) {
956     case TemplateParamKind::Type:
957       S += "$T";
958       break;
959     case TemplateParamKind::NonType:
960       S += "$N";
961       break;
962     case TemplateParamKind::Template:
963       S += "$TT";
964       break;
965     }
966     if (Index > 0)
967       S << Index - 1;
968   }
969 };
970 
971 /// A template type parameter declaration, 'typename T'.
972 class TypeTemplateParamDecl final : public Node {
973   Node *Name;
974 
975 public:
TypeTemplateParamDecl(Node * Name_)976   TypeTemplateParamDecl(Node *Name_)
977       : Node(KTypeTemplateParamDecl, Cache::Yes), Name(Name_) {}
978 
match(Fn F)979   template<typename Fn> void match(Fn F) const { F(Name); }
980 
printLeft(OutputStream & S)981   void printLeft(OutputStream &S) const override {
982     S += "typename ";
983   }
984 
printRight(OutputStream & S)985   void printRight(OutputStream &S) const override {
986     Name->print(S);
987   }
988 };
989 
990 /// A non-type template parameter declaration, 'int N'.
991 class NonTypeTemplateParamDecl final : public Node {
992   Node *Name;
993   Node *Type;
994 
995 public:
NonTypeTemplateParamDecl(Node * Name_,Node * Type_)996   NonTypeTemplateParamDecl(Node *Name_, Node *Type_)
997       : Node(KNonTypeTemplateParamDecl, Cache::Yes), Name(Name_), Type(Type_) {}
998 
match(Fn F)999   template<typename Fn> void match(Fn F) const { F(Name, Type); }
1000 
printLeft(OutputStream & S)1001   void printLeft(OutputStream &S) const override {
1002     Type->printLeft(S);
1003     if (!Type->hasRHSComponent(S))
1004       S += " ";
1005   }
1006 
printRight(OutputStream & S)1007   void printRight(OutputStream &S) const override {
1008     Name->print(S);
1009     Type->printRight(S);
1010   }
1011 };
1012 
1013 /// A template template parameter declaration,
1014 /// 'template<typename T> typename N'.
1015 class TemplateTemplateParamDecl final : public Node {
1016   Node *Name;
1017   NodeArray Params;
1018 
1019 public:
TemplateTemplateParamDecl(Node * Name_,NodeArray Params_)1020   TemplateTemplateParamDecl(Node *Name_, NodeArray Params_)
1021       : Node(KTemplateTemplateParamDecl, Cache::Yes), Name(Name_),
1022         Params(Params_) {}
1023 
match(Fn F)1024   template<typename Fn> void match(Fn F) const { F(Name, Params); }
1025 
printLeft(OutputStream & S)1026   void printLeft(OutputStream &S) const override {
1027     S += "template<";
1028     Params.printWithComma(S);
1029     S += "> typename ";
1030   }
1031 
printRight(OutputStream & S)1032   void printRight(OutputStream &S) const override {
1033     Name->print(S);
1034   }
1035 };
1036 
1037 /// A template parameter pack declaration, 'typename ...T'.
1038 class TemplateParamPackDecl final : public Node {
1039   Node *Param;
1040 
1041 public:
TemplateParamPackDecl(Node * Param_)1042   TemplateParamPackDecl(Node *Param_)
1043       : Node(KTemplateParamPackDecl, Cache::Yes), Param(Param_) {}
1044 
match(Fn F)1045   template<typename Fn> void match(Fn F) const { F(Param); }
1046 
printLeft(OutputStream & S)1047   void printLeft(OutputStream &S) const override {
1048     Param->printLeft(S);
1049     S += "...";
1050   }
1051 
printRight(OutputStream & S)1052   void printRight(OutputStream &S) const override {
1053     Param->printRight(S);
1054   }
1055 };
1056 
1057 /// An unexpanded parameter pack (either in the expression or type context). If
1058 /// this AST is correct, this node will have a ParameterPackExpansion node above
1059 /// it.
1060 ///
1061 /// This node is created when some <template-args> are found that apply to an
1062 /// <encoding>, and is stored in the TemplateParams table. In order for this to
1063 /// appear in the final AST, it has to referenced via a <template-param> (ie,
1064 /// T_).
1065 class ParameterPack final : public Node {
1066   NodeArray Data;
1067 
1068   // Setup OutputStream for a pack expansion unless we're already expanding one.
initializePackExpansion(OutputStream & S)1069   void initializePackExpansion(OutputStream &S) const {
1070     if (S.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
1071       S.CurrentPackMax = static_cast<unsigned>(Data.size());
1072       S.CurrentPackIndex = 0;
1073     }
1074   }
1075 
1076 public:
ParameterPack(NodeArray Data_)1077   ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
1078     ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
1079     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1080           return P->ArrayCache == Cache::No;
1081         }))
1082       ArrayCache = Cache::No;
1083     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1084           return P->FunctionCache == Cache::No;
1085         }))
1086       FunctionCache = Cache::No;
1087     if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1088           return P->RHSComponentCache == Cache::No;
1089         }))
1090       RHSComponentCache = Cache::No;
1091   }
1092 
match(Fn F)1093   template<typename Fn> void match(Fn F) const { F(Data); }
1094 
hasRHSComponentSlow(OutputStream & S)1095   bool hasRHSComponentSlow(OutputStream &S) const override {
1096     initializePackExpansion(S);
1097     size_t Idx = S.CurrentPackIndex;
1098     return Idx < Data.size() && Data[Idx]->hasRHSComponent(S);
1099   }
hasArraySlow(OutputStream & S)1100   bool hasArraySlow(OutputStream &S) const override {
1101     initializePackExpansion(S);
1102     size_t Idx = S.CurrentPackIndex;
1103     return Idx < Data.size() && Data[Idx]->hasArray(S);
1104   }
hasFunctionSlow(OutputStream & S)1105   bool hasFunctionSlow(OutputStream &S) const override {
1106     initializePackExpansion(S);
1107     size_t Idx = S.CurrentPackIndex;
1108     return Idx < Data.size() && Data[Idx]->hasFunction(S);
1109   }
getSyntaxNode(OutputStream & S)1110   const Node *getSyntaxNode(OutputStream &S) const override {
1111     initializePackExpansion(S);
1112     size_t Idx = S.CurrentPackIndex;
1113     return Idx < Data.size() ? Data[Idx]->getSyntaxNode(S) : this;
1114   }
1115 
printLeft(OutputStream & S)1116   void printLeft(OutputStream &S) const override {
1117     initializePackExpansion(S);
1118     size_t Idx = S.CurrentPackIndex;
1119     if (Idx < Data.size())
1120       Data[Idx]->printLeft(S);
1121   }
printRight(OutputStream & S)1122   void printRight(OutputStream &S) const override {
1123     initializePackExpansion(S);
1124     size_t Idx = S.CurrentPackIndex;
1125     if (Idx < Data.size())
1126       Data[Idx]->printRight(S);
1127   }
1128 };
1129 
1130 /// A variadic template argument. This node represents an occurrence of
1131 /// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1132 /// one of it's Elements is. The parser inserts a ParameterPack into the
1133 /// TemplateParams table if the <template-args> this pack belongs to apply to an
1134 /// <encoding>.
1135 class TemplateArgumentPack final : public Node {
1136   NodeArray Elements;
1137 public:
TemplateArgumentPack(NodeArray Elements_)1138   TemplateArgumentPack(NodeArray Elements_)
1139       : Node(KTemplateArgumentPack), Elements(Elements_) {}
1140 
match(Fn F)1141   template<typename Fn> void match(Fn F) const { F(Elements); }
1142 
getElements()1143   NodeArray getElements() const { return Elements; }
1144 
printLeft(OutputStream & S)1145   void printLeft(OutputStream &S) const override {
1146     Elements.printWithComma(S);
1147   }
1148 };
1149 
1150 /// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1151 /// which each have Child->ParameterPackSize elements.
1152 class ParameterPackExpansion final : public Node {
1153   const Node *Child;
1154 
1155 public:
ParameterPackExpansion(const Node * Child_)1156   ParameterPackExpansion(const Node *Child_)
1157       : Node(KParameterPackExpansion), Child(Child_) {}
1158 
match(Fn F)1159   template<typename Fn> void match(Fn F) const { F(Child); }
1160 
getChild()1161   const Node *getChild() const { return Child; }
1162 
printLeft(OutputStream & S)1163   void printLeft(OutputStream &S) const override {
1164     constexpr unsigned Max = std::numeric_limits<unsigned>::max();
1165     SwapAndRestore<unsigned> SavePackIdx(S.CurrentPackIndex, Max);
1166     SwapAndRestore<unsigned> SavePackMax(S.CurrentPackMax, Max);
1167     size_t StreamPos = S.getCurrentPosition();
1168 
1169     // Print the first element in the pack. If Child contains a ParameterPack,
1170     // it will set up S.CurrentPackMax and print the first element.
1171     Child->print(S);
1172 
1173     // No ParameterPack was found in Child. This can occur if we've found a pack
1174     // expansion on a <function-param>.
1175     if (S.CurrentPackMax == Max) {
1176       S += "...";
1177       return;
1178     }
1179 
1180     // We found a ParameterPack, but it has no elements. Erase whatever we may
1181     // of printed.
1182     if (S.CurrentPackMax == 0) {
1183       S.setCurrentPosition(StreamPos);
1184       return;
1185     }
1186 
1187     // Else, iterate through the rest of the elements in the pack.
1188     for (unsigned I = 1, E = S.CurrentPackMax; I < E; ++I) {
1189       S += ", ";
1190       S.CurrentPackIndex = I;
1191       Child->print(S);
1192     }
1193   }
1194 };
1195 
1196 class TemplateArgs final : public Node {
1197   NodeArray Params;
1198 
1199 public:
TemplateArgs(NodeArray Params_)1200   TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
1201 
match(Fn F)1202   template<typename Fn> void match(Fn F) const { F(Params); }
1203 
getParams()1204   NodeArray getParams() { return Params; }
1205 
printLeft(OutputStream & S)1206   void printLeft(OutputStream &S) const override {
1207     S += "<";
1208     Params.printWithComma(S);
1209     if (S.back() == '>')
1210       S += " ";
1211     S += ">";
1212   }
1213 };
1214 
1215 /// A forward-reference to a template argument that was not known at the point
1216 /// where the template parameter name was parsed in a mangling.
1217 ///
1218 /// This is created when demangling the name of a specialization of a
1219 /// conversion function template:
1220 ///
1221 /// \code
1222 /// struct A {
1223 ///   template<typename T> operator T*();
1224 /// };
1225 /// \endcode
1226 ///
1227 /// When demangling a specialization of the conversion function template, we
1228 /// encounter the name of the template (including the \c T) before we reach
1229 /// the template argument list, so we cannot substitute the parameter name
1230 /// for the corresponding argument while parsing. Instead, we create a
1231 /// \c ForwardTemplateReference node that is resolved after we parse the
1232 /// template arguments.
1233 struct ForwardTemplateReference : Node {
1234   size_t Index;
1235   Node *Ref = nullptr;
1236 
1237   // If we're currently printing this node. It is possible (though invalid) for
1238   // a forward template reference to refer to itself via a substitution. This
1239   // creates a cyclic AST, which will stack overflow printing. To fix this, bail
1240   // out if more than one print* function is active.
1241   mutable bool Printing = false;
1242 
ForwardTemplateReferenceForwardTemplateReference1243   ForwardTemplateReference(size_t Index_)
1244       : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
1245              Cache::Unknown),
1246         Index(Index_) {}
1247 
1248   // We don't provide a matcher for these, because the value of the node is
1249   // not determined by its construction parameters, and it generally needs
1250   // special handling.
1251   template<typename Fn> void match(Fn F) const = delete;
1252 
hasRHSComponentSlowForwardTemplateReference1253   bool hasRHSComponentSlow(OutputStream &S) const override {
1254     if (Printing)
1255       return false;
1256     SwapAndRestore<bool> SavePrinting(Printing, true);
1257     return Ref->hasRHSComponent(S);
1258   }
hasArraySlowForwardTemplateReference1259   bool hasArraySlow(OutputStream &S) const override {
1260     if (Printing)
1261       return false;
1262     SwapAndRestore<bool> SavePrinting(Printing, true);
1263     return Ref->hasArray(S);
1264   }
hasFunctionSlowForwardTemplateReference1265   bool hasFunctionSlow(OutputStream &S) const override {
1266     if (Printing)
1267       return false;
1268     SwapAndRestore<bool> SavePrinting(Printing, true);
1269     return Ref->hasFunction(S);
1270   }
getSyntaxNodeForwardTemplateReference1271   const Node *getSyntaxNode(OutputStream &S) const override {
1272     if (Printing)
1273       return this;
1274     SwapAndRestore<bool> SavePrinting(Printing, true);
1275     return Ref->getSyntaxNode(S);
1276   }
1277 
printLeftForwardTemplateReference1278   void printLeft(OutputStream &S) const override {
1279     if (Printing)
1280       return;
1281     SwapAndRestore<bool> SavePrinting(Printing, true);
1282     Ref->printLeft(S);
1283   }
printRightForwardTemplateReference1284   void printRight(OutputStream &S) const override {
1285     if (Printing)
1286       return;
1287     SwapAndRestore<bool> SavePrinting(Printing, true);
1288     Ref->printRight(S);
1289   }
1290 };
1291 
1292 struct NameWithTemplateArgs : Node {
1293   // name<template_args>
1294   Node *Name;
1295   Node *TemplateArgs;
1296 
NameWithTemplateArgsNameWithTemplateArgs1297   NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
1298       : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
1299 
matchNameWithTemplateArgs1300   template<typename Fn> void match(Fn F) const { F(Name, TemplateArgs); }
1301 
getBaseNameNameWithTemplateArgs1302   StringView getBaseName() const override { return Name->getBaseName(); }
1303 
printLeftNameWithTemplateArgs1304   void printLeft(OutputStream &S) const override {
1305     Name->print(S);
1306     TemplateArgs->print(S);
1307   }
1308 };
1309 
1310 class GlobalQualifiedName final : public Node {
1311   Node *Child;
1312 
1313 public:
GlobalQualifiedName(Node * Child_)1314   GlobalQualifiedName(Node* Child_)
1315       : Node(KGlobalQualifiedName), Child(Child_) {}
1316 
match(Fn F)1317   template<typename Fn> void match(Fn F) const { F(Child); }
1318 
getBaseName()1319   StringView getBaseName() const override { return Child->getBaseName(); }
1320 
printLeft(OutputStream & S)1321   void printLeft(OutputStream &S) const override {
1322     S += "::";
1323     Child->print(S);
1324   }
1325 };
1326 
1327 struct StdQualifiedName : Node {
1328   Node *Child;
1329 
StdQualifiedNameStdQualifiedName1330   StdQualifiedName(Node *Child_) : Node(KStdQualifiedName), Child(Child_) {}
1331 
matchStdQualifiedName1332   template<typename Fn> void match(Fn F) const { F(Child); }
1333 
getBaseNameStdQualifiedName1334   StringView getBaseName() const override { return Child->getBaseName(); }
1335 
printLeftStdQualifiedName1336   void printLeft(OutputStream &S) const override {
1337     S += "std::";
1338     Child->print(S);
1339   }
1340 };
1341 
1342 enum class SpecialSubKind {
1343   allocator,
1344   basic_string,
1345   string,
1346   istream,
1347   ostream,
1348   iostream,
1349 };
1350 
1351 class ExpandedSpecialSubstitution final : public Node {
1352   SpecialSubKind SSK;
1353 
1354 public:
ExpandedSpecialSubstitution(SpecialSubKind SSK_)1355   ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1356       : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
1357 
match(Fn F)1358   template<typename Fn> void match(Fn F) const { F(SSK); }
1359 
getBaseName()1360   StringView getBaseName() const override {
1361     switch (SSK) {
1362     case SpecialSubKind::allocator:
1363       return StringView("allocator");
1364     case SpecialSubKind::basic_string:
1365       return StringView("basic_string");
1366     case SpecialSubKind::string:
1367       return StringView("basic_string");
1368     case SpecialSubKind::istream:
1369       return StringView("basic_istream");
1370     case SpecialSubKind::ostream:
1371       return StringView("basic_ostream");
1372     case SpecialSubKind::iostream:
1373       return StringView("basic_iostream");
1374     }
1375     DEMANGLE_UNREACHABLE;
1376   }
1377 
printLeft(OutputStream & S)1378   void printLeft(OutputStream &S) const override {
1379     switch (SSK) {
1380     case SpecialSubKind::allocator:
1381       S += "std::allocator";
1382       break;
1383     case SpecialSubKind::basic_string:
1384       S += "std::basic_string";
1385       break;
1386     case SpecialSubKind::string:
1387       S += "std::basic_string<char, std::char_traits<char>, "
1388            "std::allocator<char> >";
1389       break;
1390     case SpecialSubKind::istream:
1391       S += "std::basic_istream<char, std::char_traits<char> >";
1392       break;
1393     case SpecialSubKind::ostream:
1394       S += "std::basic_ostream<char, std::char_traits<char> >";
1395       break;
1396     case SpecialSubKind::iostream:
1397       S += "std::basic_iostream<char, std::char_traits<char> >";
1398       break;
1399     }
1400   }
1401 };
1402 
1403 class SpecialSubstitution final : public Node {
1404 public:
1405   SpecialSubKind SSK;
1406 
SpecialSubstitution(SpecialSubKind SSK_)1407   SpecialSubstitution(SpecialSubKind SSK_)
1408       : Node(KSpecialSubstitution), SSK(SSK_) {}
1409 
match(Fn F)1410   template<typename Fn> void match(Fn F) const { F(SSK); }
1411 
getBaseName()1412   StringView getBaseName() const override {
1413     switch (SSK) {
1414     case SpecialSubKind::allocator:
1415       return StringView("allocator");
1416     case SpecialSubKind::basic_string:
1417       return StringView("basic_string");
1418     case SpecialSubKind::string:
1419       return StringView("string");
1420     case SpecialSubKind::istream:
1421       return StringView("istream");
1422     case SpecialSubKind::ostream:
1423       return StringView("ostream");
1424     case SpecialSubKind::iostream:
1425       return StringView("iostream");
1426     }
1427     DEMANGLE_UNREACHABLE;
1428   }
1429 
printLeft(OutputStream & S)1430   void printLeft(OutputStream &S) const override {
1431     switch (SSK) {
1432     case SpecialSubKind::allocator:
1433       S += "std::allocator";
1434       break;
1435     case SpecialSubKind::basic_string:
1436       S += "std::basic_string";
1437       break;
1438     case SpecialSubKind::string:
1439       S += "std::string";
1440       break;
1441     case SpecialSubKind::istream:
1442       S += "std::istream";
1443       break;
1444     case SpecialSubKind::ostream:
1445       S += "std::ostream";
1446       break;
1447     case SpecialSubKind::iostream:
1448       S += "std::iostream";
1449       break;
1450     }
1451   }
1452 };
1453 
1454 class CtorDtorName final : public Node {
1455   const Node *Basename;
1456   const bool IsDtor;
1457   const int Variant;
1458 
1459 public:
CtorDtorName(const Node * Basename_,bool IsDtor_,int Variant_)1460   CtorDtorName(const Node *Basename_, bool IsDtor_, int Variant_)
1461       : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_),
1462         Variant(Variant_) {}
1463 
match(Fn F)1464   template<typename Fn> void match(Fn F) const { F(Basename, IsDtor, Variant); }
1465 
printLeft(OutputStream & S)1466   void printLeft(OutputStream &S) const override {
1467     if (IsDtor)
1468       S += "~";
1469     S += Basename->getBaseName();
1470   }
1471 };
1472 
1473 class DtorName : public Node {
1474   const Node *Base;
1475 
1476 public:
DtorName(const Node * Base_)1477   DtorName(const Node *Base_) : Node(KDtorName), Base(Base_) {}
1478 
match(Fn F)1479   template<typename Fn> void match(Fn F) const { F(Base); }
1480 
printLeft(OutputStream & S)1481   void printLeft(OutputStream &S) const override {
1482     S += "~";
1483     Base->printLeft(S);
1484   }
1485 };
1486 
1487 class UnnamedTypeName : public Node {
1488   const StringView Count;
1489 
1490 public:
UnnamedTypeName(StringView Count_)1491   UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
1492 
match(Fn F)1493   template<typename Fn> void match(Fn F) const { F(Count); }
1494 
printLeft(OutputStream & S)1495   void printLeft(OutputStream &S) const override {
1496     S += "'unnamed";
1497     S += Count;
1498     S += "\'";
1499   }
1500 };
1501 
1502 class ClosureTypeName : public Node {
1503   NodeArray TemplateParams;
1504   NodeArray Params;
1505   StringView Count;
1506 
1507 public:
ClosureTypeName(NodeArray TemplateParams_,NodeArray Params_,StringView Count_)1508   ClosureTypeName(NodeArray TemplateParams_, NodeArray Params_,
1509                   StringView Count_)
1510       : Node(KClosureTypeName), TemplateParams(TemplateParams_),
1511         Params(Params_), Count(Count_) {}
1512 
match(Fn F)1513   template<typename Fn> void match(Fn F) const {
1514     F(TemplateParams, Params, Count);
1515   }
1516 
printDeclarator(OutputStream & S)1517   void printDeclarator(OutputStream &S) const {
1518     if (!TemplateParams.empty()) {
1519       S += "<";
1520       TemplateParams.printWithComma(S);
1521       S += ">";
1522     }
1523     S += "(";
1524     Params.printWithComma(S);
1525     S += ")";
1526   }
1527 
printLeft(OutputStream & S)1528   void printLeft(OutputStream &S) const override {
1529     S += "\'lambda";
1530     S += Count;
1531     S += "\'";
1532     printDeclarator(S);
1533   }
1534 };
1535 
1536 class StructuredBindingName : public Node {
1537   NodeArray Bindings;
1538 public:
StructuredBindingName(NodeArray Bindings_)1539   StructuredBindingName(NodeArray Bindings_)
1540       : Node(KStructuredBindingName), Bindings(Bindings_) {}
1541 
match(Fn F)1542   template<typename Fn> void match(Fn F) const { F(Bindings); }
1543 
printLeft(OutputStream & S)1544   void printLeft(OutputStream &S) const override {
1545     S += '[';
1546     Bindings.printWithComma(S);
1547     S += ']';
1548   }
1549 };
1550 
1551 // -- Expression Nodes --
1552 
1553 class BinaryExpr : public Node {
1554   const Node *LHS;
1555   const StringView InfixOperator;
1556   const Node *RHS;
1557 
1558 public:
BinaryExpr(const Node * LHS_,StringView InfixOperator_,const Node * RHS_)1559   BinaryExpr(const Node *LHS_, StringView InfixOperator_, const Node *RHS_)
1560       : Node(KBinaryExpr), LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {
1561   }
1562 
match(Fn F)1563   template<typename Fn> void match(Fn F) const { F(LHS, InfixOperator, RHS); }
1564 
printLeft(OutputStream & S)1565   void printLeft(OutputStream &S) const override {
1566     // might be a template argument expression, then we need to disambiguate
1567     // with parens.
1568     if (InfixOperator == ">")
1569       S += "(";
1570 
1571     S += "(";
1572     LHS->print(S);
1573     S += ") ";
1574     S += InfixOperator;
1575     S += " (";
1576     RHS->print(S);
1577     S += ")";
1578 
1579     if (InfixOperator == ">")
1580       S += ")";
1581   }
1582 };
1583 
1584 class ArraySubscriptExpr : public Node {
1585   const Node *Op1;
1586   const Node *Op2;
1587 
1588 public:
ArraySubscriptExpr(const Node * Op1_,const Node * Op2_)1589   ArraySubscriptExpr(const Node *Op1_, const Node *Op2_)
1590       : Node(KArraySubscriptExpr), Op1(Op1_), Op2(Op2_) {}
1591 
match(Fn F)1592   template<typename Fn> void match(Fn F) const { F(Op1, Op2); }
1593 
printLeft(OutputStream & S)1594   void printLeft(OutputStream &S) const override {
1595     S += "(";
1596     Op1->print(S);
1597     S += ")[";
1598     Op2->print(S);
1599     S += "]";
1600   }
1601 };
1602 
1603 class PostfixExpr : public Node {
1604   const Node *Child;
1605   const StringView Operator;
1606 
1607 public:
PostfixExpr(const Node * Child_,StringView Operator_)1608   PostfixExpr(const Node *Child_, StringView Operator_)
1609       : Node(KPostfixExpr), Child(Child_), Operator(Operator_) {}
1610 
match(Fn F)1611   template<typename Fn> void match(Fn F) const { F(Child, Operator); }
1612 
printLeft(OutputStream & S)1613   void printLeft(OutputStream &S) const override {
1614     S += "(";
1615     Child->print(S);
1616     S += ")";
1617     S += Operator;
1618   }
1619 };
1620 
1621 class ConditionalExpr : public Node {
1622   const Node *Cond;
1623   const Node *Then;
1624   const Node *Else;
1625 
1626 public:
ConditionalExpr(const Node * Cond_,const Node * Then_,const Node * Else_)1627   ConditionalExpr(const Node *Cond_, const Node *Then_, const Node *Else_)
1628       : Node(KConditionalExpr), Cond(Cond_), Then(Then_), Else(Else_) {}
1629 
match(Fn F)1630   template<typename Fn> void match(Fn F) const { F(Cond, Then, Else); }
1631 
printLeft(OutputStream & S)1632   void printLeft(OutputStream &S) const override {
1633     S += "(";
1634     Cond->print(S);
1635     S += ") ? (";
1636     Then->print(S);
1637     S += ") : (";
1638     Else->print(S);
1639     S += ")";
1640   }
1641 };
1642 
1643 class MemberExpr : public Node {
1644   const Node *LHS;
1645   const StringView Kind;
1646   const Node *RHS;
1647 
1648 public:
MemberExpr(const Node * LHS_,StringView Kind_,const Node * RHS_)1649   MemberExpr(const Node *LHS_, StringView Kind_, const Node *RHS_)
1650       : Node(KMemberExpr), LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
1651 
match(Fn F)1652   template<typename Fn> void match(Fn F) const { F(LHS, Kind, RHS); }
1653 
printLeft(OutputStream & S)1654   void printLeft(OutputStream &S) const override {
1655     LHS->print(S);
1656     S += Kind;
1657     RHS->print(S);
1658   }
1659 };
1660 
1661 class EnclosingExpr : public Node {
1662   const StringView Prefix;
1663   const Node *Infix;
1664   const StringView Postfix;
1665 
1666 public:
EnclosingExpr(StringView Prefix_,Node * Infix_,StringView Postfix_)1667   EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
1668       : Node(KEnclosingExpr), Prefix(Prefix_), Infix(Infix_),
1669         Postfix(Postfix_) {}
1670 
match(Fn F)1671   template<typename Fn> void match(Fn F) const { F(Prefix, Infix, Postfix); }
1672 
printLeft(OutputStream & S)1673   void printLeft(OutputStream &S) const override {
1674     S += Prefix;
1675     Infix->print(S);
1676     S += Postfix;
1677   }
1678 };
1679 
1680 class CastExpr : public Node {
1681   // cast_kind<to>(from)
1682   const StringView CastKind;
1683   const Node *To;
1684   const Node *From;
1685 
1686 public:
CastExpr(StringView CastKind_,const Node * To_,const Node * From_)1687   CastExpr(StringView CastKind_, const Node *To_, const Node *From_)
1688       : Node(KCastExpr), CastKind(CastKind_), To(To_), From(From_) {}
1689 
match(Fn F)1690   template<typename Fn> void match(Fn F) const { F(CastKind, To, From); }
1691 
printLeft(OutputStream & S)1692   void printLeft(OutputStream &S) const override {
1693     S += CastKind;
1694     S += "<";
1695     To->printLeft(S);
1696     S += ">(";
1697     From->printLeft(S);
1698     S += ")";
1699   }
1700 };
1701 
1702 class SizeofParamPackExpr : public Node {
1703   const Node *Pack;
1704 
1705 public:
SizeofParamPackExpr(const Node * Pack_)1706   SizeofParamPackExpr(const Node *Pack_)
1707       : Node(KSizeofParamPackExpr), Pack(Pack_) {}
1708 
match(Fn F)1709   template<typename Fn> void match(Fn F) const { F(Pack); }
1710 
printLeft(OutputStream & S)1711   void printLeft(OutputStream &S) const override {
1712     S += "sizeof...(";
1713     ParameterPackExpansion PPE(Pack);
1714     PPE.printLeft(S);
1715     S += ")";
1716   }
1717 };
1718 
1719 class CallExpr : public Node {
1720   const Node *Callee;
1721   NodeArray Args;
1722 
1723 public:
CallExpr(const Node * Callee_,NodeArray Args_)1724   CallExpr(const Node *Callee_, NodeArray Args_)
1725       : Node(KCallExpr), Callee(Callee_), Args(Args_) {}
1726 
match(Fn F)1727   template<typename Fn> void match(Fn F) const { F(Callee, Args); }
1728 
printLeft(OutputStream & S)1729   void printLeft(OutputStream &S) const override {
1730     Callee->print(S);
1731     S += "(";
1732     Args.printWithComma(S);
1733     S += ")";
1734   }
1735 };
1736 
1737 class NewExpr : public Node {
1738   // new (expr_list) type(init_list)
1739   NodeArray ExprList;
1740   Node *Type;
1741   NodeArray InitList;
1742   bool IsGlobal; // ::operator new ?
1743   bool IsArray;  // new[] ?
1744 public:
NewExpr(NodeArray ExprList_,Node * Type_,NodeArray InitList_,bool IsGlobal_,bool IsArray_)1745   NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1746           bool IsArray_)
1747       : Node(KNewExpr), ExprList(ExprList_), Type(Type_), InitList(InitList_),
1748         IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1749 
match(Fn F)1750   template<typename Fn> void match(Fn F) const {
1751     F(ExprList, Type, InitList, IsGlobal, IsArray);
1752   }
1753 
printLeft(OutputStream & S)1754   void printLeft(OutputStream &S) const override {
1755     if (IsGlobal)
1756       S += "::operator ";
1757     S += "new";
1758     if (IsArray)
1759       S += "[]";
1760     S += ' ';
1761     if (!ExprList.empty()) {
1762       S += "(";
1763       ExprList.printWithComma(S);
1764       S += ")";
1765     }
1766     Type->print(S);
1767     if (!InitList.empty()) {
1768       S += "(";
1769       InitList.printWithComma(S);
1770       S += ")";
1771     }
1772 
1773   }
1774 };
1775 
1776 class DeleteExpr : public Node {
1777   Node *Op;
1778   bool IsGlobal;
1779   bool IsArray;
1780 
1781 public:
DeleteExpr(Node * Op_,bool IsGlobal_,bool IsArray_)1782   DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
1783       : Node(KDeleteExpr), Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1784 
match(Fn F)1785   template<typename Fn> void match(Fn F) const { F(Op, IsGlobal, IsArray); }
1786 
printLeft(OutputStream & S)1787   void printLeft(OutputStream &S) const override {
1788     if (IsGlobal)
1789       S += "::";
1790     S += "delete";
1791     if (IsArray)
1792       S += "[] ";
1793     Op->print(S);
1794   }
1795 };
1796 
1797 class PrefixExpr : public Node {
1798   StringView Prefix;
1799   Node *Child;
1800 
1801 public:
PrefixExpr(StringView Prefix_,Node * Child_)1802   PrefixExpr(StringView Prefix_, Node *Child_)
1803       : Node(KPrefixExpr), Prefix(Prefix_), Child(Child_) {}
1804 
match(Fn F)1805   template<typename Fn> void match(Fn F) const { F(Prefix, Child); }
1806 
printLeft(OutputStream & S)1807   void printLeft(OutputStream &S) const override {
1808     S += Prefix;
1809     S += "(";
1810     Child->print(S);
1811     S += ")";
1812   }
1813 };
1814 
1815 class FunctionParam : public Node {
1816   StringView Number;
1817 
1818 public:
FunctionParam(StringView Number_)1819   FunctionParam(StringView Number_) : Node(KFunctionParam), Number(Number_) {}
1820 
match(Fn F)1821   template<typename Fn> void match(Fn F) const { F(Number); }
1822 
printLeft(OutputStream & S)1823   void printLeft(OutputStream &S) const override {
1824     S += "fp";
1825     S += Number;
1826   }
1827 };
1828 
1829 class ConversionExpr : public Node {
1830   const Node *Type;
1831   NodeArray Expressions;
1832 
1833 public:
ConversionExpr(const Node * Type_,NodeArray Expressions_)1834   ConversionExpr(const Node *Type_, NodeArray Expressions_)
1835       : Node(KConversionExpr), Type(Type_), Expressions(Expressions_) {}
1836 
match(Fn F)1837   template<typename Fn> void match(Fn F) const { F(Type, Expressions); }
1838 
printLeft(OutputStream & S)1839   void printLeft(OutputStream &S) const override {
1840     S += "(";
1841     Type->print(S);
1842     S += ")(";
1843     Expressions.printWithComma(S);
1844     S += ")";
1845   }
1846 };
1847 
1848 class InitListExpr : public Node {
1849   const Node *Ty;
1850   NodeArray Inits;
1851 public:
InitListExpr(const Node * Ty_,NodeArray Inits_)1852   InitListExpr(const Node *Ty_, NodeArray Inits_)
1853       : Node(KInitListExpr), Ty(Ty_), Inits(Inits_) {}
1854 
match(Fn F)1855   template<typename Fn> void match(Fn F) const { F(Ty, Inits); }
1856 
printLeft(OutputStream & S)1857   void printLeft(OutputStream &S) const override {
1858     if (Ty)
1859       Ty->print(S);
1860     S += '{';
1861     Inits.printWithComma(S);
1862     S += '}';
1863   }
1864 };
1865 
1866 class BracedExpr : public Node {
1867   const Node *Elem;
1868   const Node *Init;
1869   bool IsArray;
1870 public:
BracedExpr(const Node * Elem_,const Node * Init_,bool IsArray_)1871   BracedExpr(const Node *Elem_, const Node *Init_, bool IsArray_)
1872       : Node(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
1873 
match(Fn F)1874   template<typename Fn> void match(Fn F) const { F(Elem, Init, IsArray); }
1875 
printLeft(OutputStream & S)1876   void printLeft(OutputStream &S) const override {
1877     if (IsArray) {
1878       S += '[';
1879       Elem->print(S);
1880       S += ']';
1881     } else {
1882       S += '.';
1883       Elem->print(S);
1884     }
1885     if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1886       S += " = ";
1887     Init->print(S);
1888   }
1889 };
1890 
1891 class BracedRangeExpr : public Node {
1892   const Node *First;
1893   const Node *Last;
1894   const Node *Init;
1895 public:
BracedRangeExpr(const Node * First_,const Node * Last_,const Node * Init_)1896   BracedRangeExpr(const Node *First_, const Node *Last_, const Node *Init_)
1897       : Node(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
1898 
match(Fn F)1899   template<typename Fn> void match(Fn F) const { F(First, Last, Init); }
1900 
printLeft(OutputStream & S)1901   void printLeft(OutputStream &S) const override {
1902     S += '[';
1903     First->print(S);
1904     S += " ... ";
1905     Last->print(S);
1906     S += ']';
1907     if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1908       S += " = ";
1909     Init->print(S);
1910   }
1911 };
1912 
1913 class FoldExpr : public Node {
1914   const Node *Pack, *Init;
1915   StringView OperatorName;
1916   bool IsLeftFold;
1917 
1918 public:
FoldExpr(bool IsLeftFold_,StringView OperatorName_,const Node * Pack_,const Node * Init_)1919   FoldExpr(bool IsLeftFold_, StringView OperatorName_, const Node *Pack_,
1920            const Node *Init_)
1921       : Node(KFoldExpr), Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
1922         IsLeftFold(IsLeftFold_) {}
1923 
match(Fn F)1924   template<typename Fn> void match(Fn F) const {
1925     F(IsLeftFold, OperatorName, Pack, Init);
1926   }
1927 
printLeft(OutputStream & S)1928   void printLeft(OutputStream &S) const override {
1929     auto PrintPack = [&] {
1930       S += '(';
1931       ParameterPackExpansion(Pack).print(S);
1932       S += ')';
1933     };
1934 
1935     S += '(';
1936 
1937     if (IsLeftFold) {
1938       // init op ... op pack
1939       if (Init != nullptr) {
1940         Init->print(S);
1941         S += ' ';
1942         S += OperatorName;
1943         S += ' ';
1944       }
1945       // ... op pack
1946       S += "... ";
1947       S += OperatorName;
1948       S += ' ';
1949       PrintPack();
1950     } else { // !IsLeftFold
1951       // pack op ...
1952       PrintPack();
1953       S += ' ';
1954       S += OperatorName;
1955       S += " ...";
1956       // pack op ... op init
1957       if (Init != nullptr) {
1958         S += ' ';
1959         S += OperatorName;
1960         S += ' ';
1961         Init->print(S);
1962       }
1963     }
1964     S += ')';
1965   }
1966 };
1967 
1968 class ThrowExpr : public Node {
1969   const Node *Op;
1970 
1971 public:
ThrowExpr(const Node * Op_)1972   ThrowExpr(const Node *Op_) : Node(KThrowExpr), Op(Op_) {}
1973 
match(Fn F)1974   template<typename Fn> void match(Fn F) const { F(Op); }
1975 
printLeft(OutputStream & S)1976   void printLeft(OutputStream &S) const override {
1977     S += "throw ";
1978     Op->print(S);
1979   }
1980 };
1981 
1982 // MSVC __uuidof extension, generated by clang in -fms-extensions mode.
1983 class UUIDOfExpr : public Node {
1984   Node *Operand;
1985 public:
UUIDOfExpr(Node * Operand_)1986   UUIDOfExpr(Node *Operand_) : Node(KUUIDOfExpr), Operand(Operand_) {}
1987 
match(Fn F)1988   template<typename Fn> void match(Fn F) const { F(Operand); }
1989 
printLeft(OutputStream & S)1990   void printLeft(OutputStream &S) const override {
1991     S << "__uuidof(";
1992     Operand->print(S);
1993     S << ")";
1994   }
1995 };
1996 
1997 class BoolExpr : public Node {
1998   bool Value;
1999 
2000 public:
BoolExpr(bool Value_)2001   BoolExpr(bool Value_) : Node(KBoolExpr), Value(Value_) {}
2002 
match(Fn F)2003   template<typename Fn> void match(Fn F) const { F(Value); }
2004 
printLeft(OutputStream & S)2005   void printLeft(OutputStream &S) const override {
2006     S += Value ? StringView("true") : StringView("false");
2007   }
2008 };
2009 
2010 class StringLiteral : public Node {
2011   const Node *Type;
2012 
2013 public:
StringLiteral(const Node * Type_)2014   StringLiteral(const Node *Type_) : Node(KStringLiteral), Type(Type_) {}
2015 
match(Fn F)2016   template<typename Fn> void match(Fn F) const { F(Type); }
2017 
printLeft(OutputStream & S)2018   void printLeft(OutputStream &S) const override {
2019     S += "\"<";
2020     Type->print(S);
2021     S += ">\"";
2022   }
2023 };
2024 
2025 class LambdaExpr : public Node {
2026   const Node *Type;
2027 
2028 public:
LambdaExpr(const Node * Type_)2029   LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
2030 
match(Fn F)2031   template<typename Fn> void match(Fn F) const { F(Type); }
2032 
printLeft(OutputStream & S)2033   void printLeft(OutputStream &S) const override {
2034     S += "[]";
2035     if (Type->getKind() == KClosureTypeName)
2036       static_cast<const ClosureTypeName *>(Type)->printDeclarator(S);
2037     S += "{...}";
2038   }
2039 };
2040 
2041 class IntegerCastExpr : public Node {
2042   // ty(integer)
2043   const Node *Ty;
2044   StringView Integer;
2045 
2046 public:
IntegerCastExpr(const Node * Ty_,StringView Integer_)2047   IntegerCastExpr(const Node *Ty_, StringView Integer_)
2048       : Node(KIntegerCastExpr), Ty(Ty_), Integer(Integer_) {}
2049 
match(Fn F)2050   template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
2051 
printLeft(OutputStream & S)2052   void printLeft(OutputStream &S) const override {
2053     S += "(";
2054     Ty->print(S);
2055     S += ")";
2056     S += Integer;
2057   }
2058 };
2059 
2060 class IntegerLiteral : public Node {
2061   StringView Type;
2062   StringView Value;
2063 
2064 public:
IntegerLiteral(StringView Type_,StringView Value_)2065   IntegerLiteral(StringView Type_, StringView Value_)
2066       : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
2067 
match(Fn F)2068   template<typename Fn> void match(Fn F) const { F(Type, Value); }
2069 
printLeft(OutputStream & S)2070   void printLeft(OutputStream &S) const override {
2071     if (Type.size() > 3) {
2072       S += "(";
2073       S += Type;
2074       S += ")";
2075     }
2076 
2077     if (Value[0] == 'n') {
2078       S += "-";
2079       S += Value.dropFront(1);
2080     } else
2081       S += Value;
2082 
2083     if (Type.size() <= 3)
2084       S += Type;
2085   }
2086 };
2087 
2088 template <class Float> struct FloatData;
2089 
2090 namespace float_literal_impl {
getFloatLiteralKind(float *)2091 constexpr Node::Kind getFloatLiteralKind(float *) {
2092   return Node::KFloatLiteral;
2093 }
getFloatLiteralKind(double *)2094 constexpr Node::Kind getFloatLiteralKind(double *) {
2095   return Node::KDoubleLiteral;
2096 }
getFloatLiteralKind(long double *)2097 constexpr Node::Kind getFloatLiteralKind(long double *) {
2098   return Node::KLongDoubleLiteral;
2099 }
2100 }
2101 
2102 template <class Float> class FloatLiteralImpl : public Node {
2103   const StringView Contents;
2104 
2105   static constexpr Kind KindForClass =
2106       float_literal_impl::getFloatLiteralKind((Float *)nullptr);
2107 
2108 public:
FloatLiteralImpl(StringView Contents_)2109   FloatLiteralImpl(StringView Contents_)
2110       : Node(KindForClass), Contents(Contents_) {}
2111 
match(Fn F)2112   template<typename Fn> void match(Fn F) const { F(Contents); }
2113 
printLeft(OutputStream & s)2114   void printLeft(OutputStream &s) const override {
2115     const char *first = Contents.begin();
2116     const char *last = Contents.end() + 1;
2117 
2118     const size_t N = FloatData<Float>::mangled_size;
2119     if (static_cast<std::size_t>(last - first) > N) {
2120       last = first + N;
2121       union {
2122         Float value;
2123         char buf[sizeof(Float)];
2124       };
2125       const char *t = first;
2126       char *e = buf;
2127       for (; t != last; ++t, ++e) {
2128         unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2129                                   : static_cast<unsigned>(*t - 'a' + 10);
2130         ++t;
2131         unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2132                                   : static_cast<unsigned>(*t - 'a' + 10);
2133         *e = static_cast<char>((d1 << 4) + d0);
2134       }
2135 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
2136       std::reverse(buf, e);
2137 #endif
2138       char num[FloatData<Float>::max_demangled_size] = {0};
2139       int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
2140       s += StringView(num, num + n);
2141     }
2142   }
2143 };
2144 
2145 using FloatLiteral = FloatLiteralImpl<float>;
2146 using DoubleLiteral = FloatLiteralImpl<double>;
2147 using LongDoubleLiteral = FloatLiteralImpl<long double>;
2148 
2149 /// Visit the node. Calls \c F(P), where \c P is the node cast to the
2150 /// appropriate derived class.
2151 template<typename Fn>
visit(Fn F)2152 void Node::visit(Fn F) const {
2153   switch (K) {
2154 #define CASE(X) case K ## X: return F(static_cast<const X*>(this));
2155     FOR_EACH_NODE_KIND(CASE)
2156 #undef CASE
2157   }
2158   assert(0 && "unknown mangling node kind");
2159 }
2160 
2161 /// Determine the kind of a node from its type.
2162 template<typename NodeT> struct NodeKind;
2163 #define SPECIALIZATION(X) \
2164   template<> struct NodeKind<X> { \
2165     static constexpr Node::Kind Kind = Node::K##X; \
2166     static constexpr const char *name() { return #X; } \
2167   };
FOR_EACH_NODE_KIND(SPECIALIZATION)2168 FOR_EACH_NODE_KIND(SPECIALIZATION)
2169 #undef SPECIALIZATION
2170 
2171 #undef FOR_EACH_NODE_KIND
2172 
2173 template <class T, size_t N>
2174 class PODSmallVector {
2175   static_assert(std::is_trivial<T>::value,
2176                 "T is required to be a trivial type");
2177 
2178   T* First = nullptr;
2179   T* Last = nullptr;
2180   T* Cap = nullptr;
2181   T Inline[N] = {};
2182 
2183   bool isInline() const { return First == Inline; }
2184 
2185   void clearInline() {
2186     First = Inline;
2187     Last = Inline;
2188     Cap = Inline + N;
2189   }
2190 
2191   void reserve(size_t NewCap) {
2192     size_t S = size();
2193     if (isInline()) {
2194       auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
2195       if (Tmp == nullptr)
2196         std::terminate();
2197       std::copy(First, Last, Tmp);
2198       First = Tmp;
2199     } else {
2200       First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
2201       if (First == nullptr)
2202         std::terminate();
2203     }
2204     Last = First + S;
2205     Cap = First + NewCap;
2206   }
2207 
2208 public:
2209   PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
2210 
2211   PODSmallVector(const PODSmallVector&) = delete;
2212   PODSmallVector& operator=(const PODSmallVector&) = delete;
2213 
2214   PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
2215     if (Other.isInline()) {
2216       std::copy(Other.begin(), Other.end(), First);
2217       Last = First + Other.size();
2218       Other.clear();
2219       return;
2220     }
2221 
2222     First = Other.First;
2223     Last = Other.Last;
2224     Cap = Other.Cap;
2225     Other.clearInline();
2226   }
2227 
2228   PODSmallVector& operator=(PODSmallVector&& Other) {
2229     if (Other.isInline()) {
2230       if (!isInline()) {
2231         std::free(First);
2232         clearInline();
2233       }
2234       std::copy(Other.begin(), Other.end(), First);
2235       Last = First + Other.size();
2236       Other.clear();
2237       return *this;
2238     }
2239 
2240     if (isInline()) {
2241       First = Other.First;
2242       Last = Other.Last;
2243       Cap = Other.Cap;
2244       Other.clearInline();
2245       return *this;
2246     }
2247 
2248     std::swap(First, Other.First);
2249     std::swap(Last, Other.Last);
2250     std::swap(Cap, Other.Cap);
2251     Other.clear();
2252     return *this;
2253   }
2254 
2255   void push_back(const T& Elem) {
2256     if (Last == Cap)
2257       reserve(size() * 2);
2258     *Last++ = Elem;
2259   }
2260 
2261   void pop_back() {
2262     assert(Last != First && "Popping empty vector!");
2263     --Last;
2264   }
2265 
2266   void dropBack(size_t Index) {
2267     assert(Index <= size() && "dropBack() can't expand!");
2268     Last = First + Index;
2269   }
2270 
2271   T* begin() { return First; }
2272   T* end() { return Last; }
2273 
2274   bool empty() const { return First == Last; }
2275   size_t size() const { return static_cast<size_t>(Last - First); }
2276   T& back() {
2277     assert(Last != First && "Calling back() on empty vector!");
2278     return *(Last - 1);
2279   }
2280   T& operator[](size_t Index) {
2281     assert(Index < size() && "Invalid access!");
2282     return *(begin() + Index);
2283   }
2284   void clear() { Last = First; }
2285 
2286   ~PODSmallVector() {
2287     if (!isInline())
2288       std::free(First);
2289   }
2290 };
2291 
2292 template <typename Derived, typename Alloc> struct AbstractManglingParser {
2293   const char *First;
2294   const char *Last;
2295 
2296   // Name stack, this is used by the parser to hold temporary names that were
2297   // parsed. The parser collapses multiple names into new nodes to construct
2298   // the AST. Once the parser is finished, names.size() == 1.
2299   PODSmallVector<Node *, 32> Names;
2300 
2301   // Substitution table. Itanium supports name substitutions as a means of
2302   // compression. The string "S42_" refers to the 44nd entry (base-36) in this
2303   // table.
2304   PODSmallVector<Node *, 32> Subs;
2305 
2306   using TemplateParamList = PODSmallVector<Node *, 8>;
2307 
2308   class ScopedTemplateParamList {
2309     AbstractManglingParser *Parser;
2310     size_t OldNumTemplateParamLists;
2311     TemplateParamList Params;
2312 
2313   public:
ScopedTemplateParamListAbstractManglingParser2314     ScopedTemplateParamList(AbstractManglingParser *Parser)
2315         : Parser(Parser),
2316           OldNumTemplateParamLists(Parser->TemplateParams.size()) {
2317       Parser->TemplateParams.push_back(&Params);
2318     }
~ScopedTemplateParamListAbstractManglingParser2319     ~ScopedTemplateParamList() {
2320       assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
2321       Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
2322     }
2323   };
2324 
2325   // Template parameter table. Like the above, but referenced like "T42_".
2326   // This has a smaller size compared to Subs and Names because it can be
2327   // stored on the stack.
2328   TemplateParamList OuterTemplateParams;
2329 
2330   // Lists of template parameters indexed by template parameter depth,
2331   // referenced like "TL2_4_". If nonempty, element 0 is always
2332   // OuterTemplateParams; inner elements are always template parameter lists of
2333   // lambda expressions. For a generic lambda with no explicit template
2334   // parameter list, the corresponding parameter list pointer will be null.
2335   PODSmallVector<TemplateParamList *, 4> TemplateParams;
2336 
2337   // Set of unresolved forward <template-param> references. These can occur in a
2338   // conversion operator's type, and are resolved in the enclosing <encoding>.
2339   PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
2340 
2341   bool TryToParseTemplateArgs = true;
2342   bool PermitForwardTemplateReferences = false;
2343   size_t ParsingLambdaParamsAtLevel = (size_t)-1;
2344 
2345   unsigned NumSyntheticTemplateParameters[3] = {};
2346 
2347   Alloc ASTAllocator;
2348 
AbstractManglingParserAbstractManglingParser2349   AbstractManglingParser(const char *First_, const char *Last_)
2350       : First(First_), Last(Last_) {}
2351 
getDerivedAbstractManglingParser2352   Derived &getDerived() { return static_cast<Derived &>(*this); }
2353 
resetAbstractManglingParser2354   void reset(const char *First_, const char *Last_) {
2355     First = First_;
2356     Last = Last_;
2357     Names.clear();
2358     Subs.clear();
2359     TemplateParams.clear();
2360     ParsingLambdaParamsAtLevel = (size_t)-1;
2361     TryToParseTemplateArgs = true;
2362     PermitForwardTemplateReferences = false;
2363     for (int I = 0; I != 3; ++I)
2364       NumSyntheticTemplateParameters[I] = 0;
2365     ASTAllocator.reset();
2366   }
2367 
makeAbstractManglingParser2368   template <class T, class... Args> Node *make(Args &&... args) {
2369     return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
2370   }
2371 
makeNodeArrayAbstractManglingParser2372   template <class It> NodeArray makeNodeArray(It begin, It end) {
2373     size_t sz = static_cast<size_t>(end - begin);
2374     void *mem = ASTAllocator.allocateNodeArray(sz);
2375     Node **data = new (mem) Node *[sz];
2376     std::copy(begin, end, data);
2377     return NodeArray(data, sz);
2378   }
2379 
popTrailingNodeArrayAbstractManglingParser2380   NodeArray popTrailingNodeArray(size_t FromPosition) {
2381     assert(FromPosition <= Names.size());
2382     NodeArray res =
2383         makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2384     Names.dropBack(FromPosition);
2385     return res;
2386   }
2387 
consumeIfAbstractManglingParser2388   bool consumeIf(StringView S) {
2389     if (StringView(First, Last).startsWith(S)) {
2390       First += S.size();
2391       return true;
2392     }
2393     return false;
2394   }
2395 
consumeIfAbstractManglingParser2396   bool consumeIf(char C) {
2397     if (First != Last && *First == C) {
2398       ++First;
2399       return true;
2400     }
2401     return false;
2402   }
2403 
consumeAbstractManglingParser2404   char consume() { return First != Last ? *First++ : '\0'; }
2405 
2406   char look(unsigned Lookahead = 0) {
2407     if (static_cast<size_t>(Last - First) <= Lookahead)
2408       return '\0';
2409     return First[Lookahead];
2410   }
2411 
numLeftAbstractManglingParser2412   size_t numLeft() const { return static_cast<size_t>(Last - First); }
2413 
2414   StringView parseNumber(bool AllowNegative = false);
2415   Qualifiers parseCVQualifiers();
2416   bool parsePositiveInteger(size_t *Out);
2417   StringView parseBareSourceName();
2418 
2419   bool parseSeqId(size_t *Out);
2420   Node *parseSubstitution();
2421   Node *parseTemplateParam();
2422   Node *parseTemplateParamDecl();
2423   Node *parseTemplateArgs(bool TagTemplates = false);
2424   Node *parseTemplateArg();
2425 
2426   /// Parse the <expr> production.
2427   Node *parseExpr();
2428   Node *parsePrefixExpr(StringView Kind);
2429   Node *parseBinaryExpr(StringView Kind);
2430   Node *parseIntegerLiteral(StringView Lit);
2431   Node *parseExprPrimary();
2432   template <class Float> Node *parseFloatingLiteral();
2433   Node *parseFunctionParam();
2434   Node *parseNewExpr();
2435   Node *parseConversionExpr();
2436   Node *parseBracedExpr();
2437   Node *parseFoldExpr();
2438 
2439   /// Parse the <type> production.
2440   Node *parseType();
2441   Node *parseFunctionType();
2442   Node *parseVectorType();
2443   Node *parseDecltype();
2444   Node *parseArrayType();
2445   Node *parsePointerToMemberType();
2446   Node *parseClassEnumType();
2447   Node *parseQualifiedType();
2448 
2449   Node *parseEncoding();
2450   bool parseCallOffset();
2451   Node *parseSpecialName();
2452 
2453   /// Holds some extra information about a <name> that is being parsed. This
2454   /// information is only pertinent if the <name> refers to an <encoding>.
2455   struct NameState {
2456     bool CtorDtorConversion = false;
2457     bool EndsWithTemplateArgs = false;
2458     Qualifiers CVQualifiers = QualNone;
2459     FunctionRefQual ReferenceQualifier = FrefQualNone;
2460     size_t ForwardTemplateRefsBegin;
2461 
NameStateAbstractManglingParser::NameState2462     NameState(AbstractManglingParser *Enclosing)
2463         : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
2464   };
2465 
resolveForwardTemplateRefsAbstractManglingParser2466   bool resolveForwardTemplateRefs(NameState &State) {
2467     size_t I = State.ForwardTemplateRefsBegin;
2468     size_t E = ForwardTemplateRefs.size();
2469     for (; I < E; ++I) {
2470       size_t Idx = ForwardTemplateRefs[I]->Index;
2471       if (TemplateParams.empty() || !TemplateParams[0] ||
2472           Idx >= TemplateParams[0]->size())
2473         return true;
2474       ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
2475     }
2476     ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
2477     return false;
2478   }
2479 
2480   /// Parse the <name> production>
2481   Node *parseName(NameState *State = nullptr);
2482   Node *parseLocalName(NameState *State);
2483   Node *parseOperatorName(NameState *State);
2484   Node *parseUnqualifiedName(NameState *State);
2485   Node *parseUnnamedTypeName(NameState *State);
2486   Node *parseSourceName(NameState *State);
2487   Node *parseUnscopedName(NameState *State);
2488   Node *parseNestedName(NameState *State);
2489   Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2490 
2491   Node *parseAbiTags(Node *N);
2492 
2493   /// Parse the <unresolved-name> production.
2494   Node *parseUnresolvedName();
2495   Node *parseSimpleId();
2496   Node *parseBaseUnresolvedName();
2497   Node *parseUnresolvedType();
2498   Node *parseDestructorName();
2499 
2500   /// Top-level entry point into the parser.
2501   Node *parse();
2502 };
2503 
2504 const char* parse_discriminator(const char* first, const char* last);
2505 
2506 // <name> ::= <nested-name> // N
2507 //        ::= <local-name> # See Scope Encoding below  // Z
2508 //        ::= <unscoped-template-name> <template-args>
2509 //        ::= <unscoped-name>
2510 //
2511 // <unscoped-template-name> ::= <unscoped-name>
2512 //                          ::= <substitution>
2513 template <typename Derived, typename Alloc>
parseName(NameState * State)2514 Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
2515   consumeIf('L'); // extension
2516 
2517   if (look() == 'N')
2518     return getDerived().parseNestedName(State);
2519   if (look() == 'Z')
2520     return getDerived().parseLocalName(State);
2521 
2522   //        ::= <unscoped-template-name> <template-args>
2523   if (look() == 'S' && look(1) != 't') {
2524     Node *S = getDerived().parseSubstitution();
2525     if (S == nullptr)
2526       return nullptr;
2527     if (look() != 'I')
2528       return nullptr;
2529     Node *TA = getDerived().parseTemplateArgs(State != nullptr);
2530     if (TA == nullptr)
2531       return nullptr;
2532     if (State) State->EndsWithTemplateArgs = true;
2533     return make<NameWithTemplateArgs>(S, TA);
2534   }
2535 
2536   Node *N = getDerived().parseUnscopedName(State);
2537   if (N == nullptr)
2538     return nullptr;
2539   //        ::= <unscoped-template-name> <template-args>
2540   if (look() == 'I') {
2541     Subs.push_back(N);
2542     Node *TA = getDerived().parseTemplateArgs(State != nullptr);
2543     if (TA == nullptr)
2544       return nullptr;
2545     if (State) State->EndsWithTemplateArgs = true;
2546     return make<NameWithTemplateArgs>(N, TA);
2547   }
2548   //        ::= <unscoped-name>
2549   return N;
2550 }
2551 
2552 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2553 //              := Z <function encoding> E s [<discriminator>]
2554 //              := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
2555 template <typename Derived, typename Alloc>
parseLocalName(NameState * State)2556 Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
2557   if (!consumeIf('Z'))
2558     return nullptr;
2559   Node *Encoding = getDerived().parseEncoding();
2560   if (Encoding == nullptr || !consumeIf('E'))
2561     return nullptr;
2562 
2563   if (consumeIf('s')) {
2564     First = parse_discriminator(First, Last);
2565     auto *StringLitName = make<NameType>("string literal");
2566     if (!StringLitName)
2567       return nullptr;
2568     return make<LocalName>(Encoding, StringLitName);
2569   }
2570 
2571   if (consumeIf('d')) {
2572     parseNumber(true);
2573     if (!consumeIf('_'))
2574       return nullptr;
2575     Node *N = getDerived().parseName(State);
2576     if (N == nullptr)
2577       return nullptr;
2578     return make<LocalName>(Encoding, N);
2579   }
2580 
2581   Node *Entity = getDerived().parseName(State);
2582   if (Entity == nullptr)
2583     return nullptr;
2584   First = parse_discriminator(First, Last);
2585   return make<LocalName>(Encoding, Entity);
2586 }
2587 
2588 // <unscoped-name> ::= <unqualified-name>
2589 //                 ::= St <unqualified-name>   # ::std::
2590 // extension       ::= StL<unqualified-name>
2591 template <typename Derived, typename Alloc>
2592 Node *
parseUnscopedName(NameState * State)2593 AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State) {
2594   if (consumeIf("StL") || consumeIf("St")) {
2595     Node *R = getDerived().parseUnqualifiedName(State);
2596     if (R == nullptr)
2597       return nullptr;
2598     return make<StdQualifiedName>(R);
2599   }
2600   return getDerived().parseUnqualifiedName(State);
2601 }
2602 
2603 // <unqualified-name> ::= <operator-name> [abi-tags]
2604 //                    ::= <ctor-dtor-name>
2605 //                    ::= <source-name>
2606 //                    ::= <unnamed-type-name>
2607 //                    ::= DC <source-name>+ E      # structured binding declaration
2608 template <typename Derived, typename Alloc>
2609 Node *
parseUnqualifiedName(NameState * State)2610 AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(NameState *State) {
2611   // <ctor-dtor-name>s are special-cased in parseNestedName().
2612   Node *Result;
2613   if (look() == 'U')
2614     Result = getDerived().parseUnnamedTypeName(State);
2615   else if (look() >= '1' && look() <= '9')
2616     Result = getDerived().parseSourceName(State);
2617   else if (consumeIf("DC")) {
2618     size_t BindingsBegin = Names.size();
2619     do {
2620       Node *Binding = getDerived().parseSourceName(State);
2621       if (Binding == nullptr)
2622         return nullptr;
2623       Names.push_back(Binding);
2624     } while (!consumeIf('E'));
2625     Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
2626   } else
2627     Result = getDerived().parseOperatorName(State);
2628   if (Result != nullptr)
2629     Result = getDerived().parseAbiTags(Result);
2630   return Result;
2631 }
2632 
2633 // <unnamed-type-name> ::= Ut [<nonnegative number>] _
2634 //                     ::= <closure-type-name>
2635 //
2636 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2637 //
2638 // <lambda-sig> ::= <parameter type>+  # Parameter types or "v" if the lambda has no parameters
2639 template <typename Derived, typename Alloc>
2640 Node *
parseUnnamedTypeName(NameState * State)2641 AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
2642   // <template-params> refer to the innermost <template-args>. Clear out any
2643   // outer args that we may have inserted into TemplateParams.
2644   if (State != nullptr)
2645     TemplateParams.clear();
2646 
2647   if (consumeIf("Ut")) {
2648     StringView Count = parseNumber();
2649     if (!consumeIf('_'))
2650       return nullptr;
2651     return make<UnnamedTypeName>(Count);
2652   }
2653   if (consumeIf("Ul")) {
2654     SwapAndRestore<size_t> SwapParams(ParsingLambdaParamsAtLevel,
2655                                       TemplateParams.size());
2656     ScopedTemplateParamList LambdaTemplateParams(this);
2657 
2658     size_t ParamsBegin = Names.size();
2659     while (look() == 'T' &&
2660            StringView("yptn").find(look(1)) != StringView::npos) {
2661       Node *T = parseTemplateParamDecl();
2662       if (!T)
2663         return nullptr;
2664       Names.push_back(T);
2665     }
2666     NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
2667 
2668     // FIXME: If TempParams is empty and none of the function parameters
2669     // includes 'auto', we should remove LambdaTemplateParams from the
2670     // TemplateParams list. Unfortunately, we don't find out whether there are
2671     // any 'auto' parameters until too late in an example such as:
2672     //
2673     //   template<typename T> void f(
2674     //       decltype([](decltype([]<typename T>(T v) {}),
2675     //                   auto) {})) {}
2676     //   template<typename T> void f(
2677     //       decltype([](decltype([]<typename T>(T w) {}),
2678     //                   int) {})) {}
2679     //
2680     // Here, the type of v is at level 2 but the type of w is at level 1. We
2681     // don't find this out until we encounter the type of the next parameter.
2682     //
2683     // However, compilers can't actually cope with the former example in
2684     // practice, and it's likely to be made ill-formed in future, so we don't
2685     // need to support it here.
2686     //
2687     // If we encounter an 'auto' in the function parameter types, we will
2688     // recreate a template parameter scope for it, but any intervening lambdas
2689     // will be parsed in the 'wrong' template parameter depth.
2690     if (TempParams.empty())
2691       TemplateParams.pop_back();
2692 
2693     if (!consumeIf("vE")) {
2694       do {
2695         Node *P = getDerived().parseType();
2696         if (P == nullptr)
2697           return nullptr;
2698         Names.push_back(P);
2699       } while (!consumeIf('E'));
2700     }
2701     NodeArray Params = popTrailingNodeArray(ParamsBegin);
2702 
2703     StringView Count = parseNumber();
2704     if (!consumeIf('_'))
2705       return nullptr;
2706     return make<ClosureTypeName>(TempParams, Params, Count);
2707   }
2708   if (consumeIf("Ub")) {
2709     (void)parseNumber();
2710     if (!consumeIf('_'))
2711       return nullptr;
2712     return make<NameType>("'block-literal'");
2713   }
2714   return nullptr;
2715 }
2716 
2717 // <source-name> ::= <positive length number> <identifier>
2718 template <typename Derived, typename Alloc>
parseSourceName(NameState *)2719 Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
2720   size_t Length = 0;
2721   if (parsePositiveInteger(&Length))
2722     return nullptr;
2723   if (numLeft() < Length || Length == 0)
2724     return nullptr;
2725   StringView Name(First, First + Length);
2726   First += Length;
2727   if (Name.startsWith("_GLOBAL__N"))
2728     return make<NameType>("(anonymous namespace)");
2729   return make<NameType>(Name);
2730 }
2731 
2732 //   <operator-name> ::= aa    # &&
2733 //                   ::= ad    # & (unary)
2734 //                   ::= an    # &
2735 //                   ::= aN    # &=
2736 //                   ::= aS    # =
2737 //                   ::= cl    # ()
2738 //                   ::= cm    # ,
2739 //                   ::= co    # ~
2740 //                   ::= cv <type>    # (cast)
2741 //                   ::= da    # delete[]
2742 //                   ::= de    # * (unary)
2743 //                   ::= dl    # delete
2744 //                   ::= dv    # /
2745 //                   ::= dV    # /=
2746 //                   ::= eo    # ^
2747 //                   ::= eO    # ^=
2748 //                   ::= eq    # ==
2749 //                   ::= ge    # >=
2750 //                   ::= gt    # >
2751 //                   ::= ix    # []
2752 //                   ::= le    # <=
2753 //                   ::= li <source-name>  # operator ""
2754 //                   ::= ls    # <<
2755 //                   ::= lS    # <<=
2756 //                   ::= lt    # <
2757 //                   ::= mi    # -
2758 //                   ::= mI    # -=
2759 //                   ::= ml    # *
2760 //                   ::= mL    # *=
2761 //                   ::= mm    # -- (postfix in <expression> context)
2762 //                   ::= na    # new[]
2763 //                   ::= ne    # !=
2764 //                   ::= ng    # - (unary)
2765 //                   ::= nt    # !
2766 //                   ::= nw    # new
2767 //                   ::= oo    # ||
2768 //                   ::= or    # |
2769 //                   ::= oR    # |=
2770 //                   ::= pm    # ->*
2771 //                   ::= pl    # +
2772 //                   ::= pL    # +=
2773 //                   ::= pp    # ++ (postfix in <expression> context)
2774 //                   ::= ps    # + (unary)
2775 //                   ::= pt    # ->
2776 //                   ::= qu    # ?
2777 //                   ::= rm    # %
2778 //                   ::= rM    # %=
2779 //                   ::= rs    # >>
2780 //                   ::= rS    # >>=
2781 //                   ::= ss    # <=> C++2a
2782 //                   ::= v <digit> <source-name>        # vendor extended operator
2783 template <typename Derived, typename Alloc>
2784 Node *
parseOperatorName(NameState * State)2785 AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
2786   switch (look()) {
2787   case 'a':
2788     switch (look(1)) {
2789     case 'a':
2790       First += 2;
2791       return make<NameType>("operator&&");
2792     case 'd':
2793     case 'n':
2794       First += 2;
2795       return make<NameType>("operator&");
2796     case 'N':
2797       First += 2;
2798       return make<NameType>("operator&=");
2799     case 'S':
2800       First += 2;
2801       return make<NameType>("operator=");
2802     }
2803     return nullptr;
2804   case 'c':
2805     switch (look(1)) {
2806     case 'l':
2807       First += 2;
2808       return make<NameType>("operator()");
2809     case 'm':
2810       First += 2;
2811       return make<NameType>("operator,");
2812     case 'o':
2813       First += 2;
2814       return make<NameType>("operator~");
2815     //                   ::= cv <type>    # (cast)
2816     case 'v': {
2817       First += 2;
2818       SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2819       // If we're parsing an encoding, State != nullptr and the conversion
2820       // operators' <type> could have a <template-param> that refers to some
2821       // <template-arg>s further ahead in the mangled name.
2822       SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences,
2823                                       PermitForwardTemplateReferences ||
2824                                           State != nullptr);
2825       Node *Ty = getDerived().parseType();
2826       if (Ty == nullptr)
2827         return nullptr;
2828       if (State) State->CtorDtorConversion = true;
2829       return make<ConversionOperatorType>(Ty);
2830     }
2831     }
2832     return nullptr;
2833   case 'd':
2834     switch (look(1)) {
2835     case 'a':
2836       First += 2;
2837       return make<NameType>("operator delete[]");
2838     case 'e':
2839       First += 2;
2840       return make<NameType>("operator*");
2841     case 'l':
2842       First += 2;
2843       return make<NameType>("operator delete");
2844     case 'v':
2845       First += 2;
2846       return make<NameType>("operator/");
2847     case 'V':
2848       First += 2;
2849       return make<NameType>("operator/=");
2850     }
2851     return nullptr;
2852   case 'e':
2853     switch (look(1)) {
2854     case 'o':
2855       First += 2;
2856       return make<NameType>("operator^");
2857     case 'O':
2858       First += 2;
2859       return make<NameType>("operator^=");
2860     case 'q':
2861       First += 2;
2862       return make<NameType>("operator==");
2863     }
2864     return nullptr;
2865   case 'g':
2866     switch (look(1)) {
2867     case 'e':
2868       First += 2;
2869       return make<NameType>("operator>=");
2870     case 't':
2871       First += 2;
2872       return make<NameType>("operator>");
2873     }
2874     return nullptr;
2875   case 'i':
2876     if (look(1) == 'x') {
2877       First += 2;
2878       return make<NameType>("operator[]");
2879     }
2880     return nullptr;
2881   case 'l':
2882     switch (look(1)) {
2883     case 'e':
2884       First += 2;
2885       return make<NameType>("operator<=");
2886     //                   ::= li <source-name>  # operator ""
2887     case 'i': {
2888       First += 2;
2889       Node *SN = getDerived().parseSourceName(State);
2890       if (SN == nullptr)
2891         return nullptr;
2892       return make<LiteralOperator>(SN);
2893     }
2894     case 's':
2895       First += 2;
2896       return make<NameType>("operator<<");
2897     case 'S':
2898       First += 2;
2899       return make<NameType>("operator<<=");
2900     case 't':
2901       First += 2;
2902       return make<NameType>("operator<");
2903     }
2904     return nullptr;
2905   case 'm':
2906     switch (look(1)) {
2907     case 'i':
2908       First += 2;
2909       return make<NameType>("operator-");
2910     case 'I':
2911       First += 2;
2912       return make<NameType>("operator-=");
2913     case 'l':
2914       First += 2;
2915       return make<NameType>("operator*");
2916     case 'L':
2917       First += 2;
2918       return make<NameType>("operator*=");
2919     case 'm':
2920       First += 2;
2921       return make<NameType>("operator--");
2922     }
2923     return nullptr;
2924   case 'n':
2925     switch (look(1)) {
2926     case 'a':
2927       First += 2;
2928       return make<NameType>("operator new[]");
2929     case 'e':
2930       First += 2;
2931       return make<NameType>("operator!=");
2932     case 'g':
2933       First += 2;
2934       return make<NameType>("operator-");
2935     case 't':
2936       First += 2;
2937       return make<NameType>("operator!");
2938     case 'w':
2939       First += 2;
2940       return make<NameType>("operator new");
2941     }
2942     return nullptr;
2943   case 'o':
2944     switch (look(1)) {
2945     case 'o':
2946       First += 2;
2947       return make<NameType>("operator||");
2948     case 'r':
2949       First += 2;
2950       return make<NameType>("operator|");
2951     case 'R':
2952       First += 2;
2953       return make<NameType>("operator|=");
2954     }
2955     return nullptr;
2956   case 'p':
2957     switch (look(1)) {
2958     case 'm':
2959       First += 2;
2960       return make<NameType>("operator->*");
2961     case 'l':
2962       First += 2;
2963       return make<NameType>("operator+");
2964     case 'L':
2965       First += 2;
2966       return make<NameType>("operator+=");
2967     case 'p':
2968       First += 2;
2969       return make<NameType>("operator++");
2970     case 's':
2971       First += 2;
2972       return make<NameType>("operator+");
2973     case 't':
2974       First += 2;
2975       return make<NameType>("operator->");
2976     }
2977     return nullptr;
2978   case 'q':
2979     if (look(1) == 'u') {
2980       First += 2;
2981       return make<NameType>("operator?");
2982     }
2983     return nullptr;
2984   case 'r':
2985     switch (look(1)) {
2986     case 'm':
2987       First += 2;
2988       return make<NameType>("operator%");
2989     case 'M':
2990       First += 2;
2991       return make<NameType>("operator%=");
2992     case 's':
2993       First += 2;
2994       return make<NameType>("operator>>");
2995     case 'S':
2996       First += 2;
2997       return make<NameType>("operator>>=");
2998     }
2999     return nullptr;
3000   case 's':
3001     if (look(1) == 's') {
3002       First += 2;
3003       return make<NameType>("operator<=>");
3004     }
3005     return nullptr;
3006   // ::= v <digit> <source-name>        # vendor extended operator
3007   case 'v':
3008     if (std::isdigit(look(1))) {
3009       First += 2;
3010       Node *SN = getDerived().parseSourceName(State);
3011       if (SN == nullptr)
3012         return nullptr;
3013       return make<ConversionOperatorType>(SN);
3014     }
3015     return nullptr;
3016   }
3017   return nullptr;
3018 }
3019 
3020 // <ctor-dtor-name> ::= C1  # complete object constructor
3021 //                  ::= C2  # base object constructor
3022 //                  ::= C3  # complete object allocating constructor
3023 //   extension      ::= C4  # gcc old-style "[unified]" constructor
3024 //   extension      ::= C5  # the COMDAT used for ctors
3025 //                  ::= D0  # deleting destructor
3026 //                  ::= D1  # complete object destructor
3027 //                  ::= D2  # base object destructor
3028 //   extension      ::= D4  # gcc old-style "[unified]" destructor
3029 //   extension      ::= D5  # the COMDAT used for dtors
3030 template <typename Derived, typename Alloc>
3031 Node *
parseCtorDtorName(Node * & SoFar,NameState * State)3032 AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
3033                                                           NameState *State) {
3034   if (SoFar->getKind() == Node::KSpecialSubstitution) {
3035     auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
3036     switch (SSK) {
3037     case SpecialSubKind::string:
3038     case SpecialSubKind::istream:
3039     case SpecialSubKind::ostream:
3040     case SpecialSubKind::iostream:
3041       SoFar = make<ExpandedSpecialSubstitution>(SSK);
3042       if (!SoFar)
3043         return nullptr;
3044       break;
3045     default:
3046       break;
3047     }
3048   }
3049 
3050   if (consumeIf('C')) {
3051     bool IsInherited = consumeIf('I');
3052     if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
3053         look() != '5')
3054       return nullptr;
3055     int Variant = look() - '0';
3056     ++First;
3057     if (State) State->CtorDtorConversion = true;
3058     if (IsInherited) {
3059       if (getDerived().parseName(State) == nullptr)
3060         return nullptr;
3061     }
3062     return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
3063   }
3064 
3065   if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
3066                         look(1) == '4' || look(1) == '5')) {
3067     int Variant = look(1) - '0';
3068     First += 2;
3069     if (State) State->CtorDtorConversion = true;
3070     return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
3071   }
3072 
3073   return nullptr;
3074 }
3075 
3076 // <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
3077 //               ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
3078 //
3079 // <prefix> ::= <prefix> <unqualified-name>
3080 //          ::= <template-prefix> <template-args>
3081 //          ::= <template-param>
3082 //          ::= <decltype>
3083 //          ::= # empty
3084 //          ::= <substitution>
3085 //          ::= <prefix> <data-member-prefix>
3086 //  extension ::= L
3087 //
3088 // <data-member-prefix> := <member source-name> [<template-args>] M
3089 //
3090 // <template-prefix> ::= <prefix> <template unqualified-name>
3091 //                   ::= <template-param>
3092 //                   ::= <substitution>
3093 template <typename Derived, typename Alloc>
3094 Node *
parseNestedName(NameState * State)3095 AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
3096   if (!consumeIf('N'))
3097     return nullptr;
3098 
3099   Qualifiers CVTmp = parseCVQualifiers();
3100   if (State) State->CVQualifiers = CVTmp;
3101 
3102   if (consumeIf('O')) {
3103     if (State) State->ReferenceQualifier = FrefQualRValue;
3104   } else if (consumeIf('R')) {
3105     if (State) State->ReferenceQualifier = FrefQualLValue;
3106   } else
3107     if (State) State->ReferenceQualifier = FrefQualNone;
3108 
3109   Node *SoFar = nullptr;
3110   auto PushComponent = [&](Node *Comp) {
3111     if (!Comp) return false;
3112     if (SoFar) SoFar = make<NestedName>(SoFar, Comp);
3113     else       SoFar = Comp;
3114     if (State) State->EndsWithTemplateArgs = false;
3115     return SoFar != nullptr;
3116   };
3117 
3118   if (consumeIf("St")) {
3119     SoFar = make<NameType>("std");
3120     if (!SoFar)
3121       return nullptr;
3122   }
3123 
3124   while (!consumeIf('E')) {
3125     consumeIf('L'); // extension
3126 
3127     // <data-member-prefix> := <member source-name> [<template-args>] M
3128     if (consumeIf('M')) {
3129       if (SoFar == nullptr)
3130         return nullptr;
3131       continue;
3132     }
3133 
3134     //          ::= <template-param>
3135     if (look() == 'T') {
3136       if (!PushComponent(getDerived().parseTemplateParam()))
3137         return nullptr;
3138       Subs.push_back(SoFar);
3139       continue;
3140     }
3141 
3142     //          ::= <template-prefix> <template-args>
3143     if (look() == 'I') {
3144       Node *TA = getDerived().parseTemplateArgs(State != nullptr);
3145       if (TA == nullptr || SoFar == nullptr)
3146         return nullptr;
3147       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
3148       if (!SoFar)
3149         return nullptr;
3150       if (State) State->EndsWithTemplateArgs = true;
3151       Subs.push_back(SoFar);
3152       continue;
3153     }
3154 
3155     //          ::= <decltype>
3156     if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
3157       if (!PushComponent(getDerived().parseDecltype()))
3158         return nullptr;
3159       Subs.push_back(SoFar);
3160       continue;
3161     }
3162 
3163     //          ::= <substitution>
3164     if (look() == 'S' && look(1) != 't') {
3165       Node *S = getDerived().parseSubstitution();
3166       if (!PushComponent(S))
3167         return nullptr;
3168       if (SoFar != S)
3169         Subs.push_back(S);
3170       continue;
3171     }
3172 
3173     // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
3174     if (look() == 'C' || (look() == 'D' && look(1) != 'C')) {
3175       if (SoFar == nullptr)
3176         return nullptr;
3177       if (!PushComponent(getDerived().parseCtorDtorName(SoFar, State)))
3178         return nullptr;
3179       SoFar = getDerived().parseAbiTags(SoFar);
3180       if (SoFar == nullptr)
3181         return nullptr;
3182       Subs.push_back(SoFar);
3183       continue;
3184     }
3185 
3186     //          ::= <prefix> <unqualified-name>
3187     if (!PushComponent(getDerived().parseUnqualifiedName(State)))
3188       return nullptr;
3189     Subs.push_back(SoFar);
3190   }
3191 
3192   if (SoFar == nullptr || Subs.empty())
3193     return nullptr;
3194 
3195   Subs.pop_back();
3196   return SoFar;
3197 }
3198 
3199 // <simple-id> ::= <source-name> [ <template-args> ]
3200 template <typename Derived, typename Alloc>
parseSimpleId()3201 Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
3202   Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
3203   if (SN == nullptr)
3204     return nullptr;
3205   if (look() == 'I') {
3206     Node *TA = getDerived().parseTemplateArgs();
3207     if (TA == nullptr)
3208       return nullptr;
3209     return make<NameWithTemplateArgs>(SN, TA);
3210   }
3211   return SN;
3212 }
3213 
3214 // <destructor-name> ::= <unresolved-type>  # e.g., ~T or ~decltype(f())
3215 //                   ::= <simple-id>        # e.g., ~A<2*N>
3216 template <typename Derived, typename Alloc>
parseDestructorName()3217 Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
3218   Node *Result;
3219   if (std::isdigit(look()))
3220     Result = getDerived().parseSimpleId();
3221   else
3222     Result = getDerived().parseUnresolvedType();
3223   if (Result == nullptr)
3224     return nullptr;
3225   return make<DtorName>(Result);
3226 }
3227 
3228 // <unresolved-type> ::= <template-param>
3229 //                   ::= <decltype>
3230 //                   ::= <substitution>
3231 template <typename Derived, typename Alloc>
parseUnresolvedType()3232 Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
3233   if (look() == 'T') {
3234     Node *TP = getDerived().parseTemplateParam();
3235     if (TP == nullptr)
3236       return nullptr;
3237     Subs.push_back(TP);
3238     return TP;
3239   }
3240   if (look() == 'D') {
3241     Node *DT = getDerived().parseDecltype();
3242     if (DT == nullptr)
3243       return nullptr;
3244     Subs.push_back(DT);
3245     return DT;
3246   }
3247   return getDerived().parseSubstitution();
3248 }
3249 
3250 // <base-unresolved-name> ::= <simple-id>                                # unresolved name
3251 //          extension     ::= <operator-name>                            # unresolved operator-function-id
3252 //          extension     ::= <operator-name> <template-args>            # unresolved operator template-id
3253 //                        ::= on <operator-name>                         # unresolved operator-function-id
3254 //                        ::= on <operator-name> <template-args>         # unresolved operator template-id
3255 //                        ::= dn <destructor-name>                       # destructor or pseudo-destructor;
3256 //                                                                         # e.g. ~X or ~X<N-1>
3257 template <typename Derived, typename Alloc>
parseBaseUnresolvedName()3258 Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
3259   if (std::isdigit(look()))
3260     return getDerived().parseSimpleId();
3261 
3262   if (consumeIf("dn"))
3263     return getDerived().parseDestructorName();
3264 
3265   consumeIf("on");
3266 
3267   Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
3268   if (Oper == nullptr)
3269     return nullptr;
3270   if (look() == 'I') {
3271     Node *TA = getDerived().parseTemplateArgs();
3272     if (TA == nullptr)
3273       return nullptr;
3274     return make<NameWithTemplateArgs>(Oper, TA);
3275   }
3276   return Oper;
3277 }
3278 
3279 // <unresolved-name>
3280 //  extension        ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3281 //                   ::= [gs] <base-unresolved-name>                     # x or (with "gs") ::x
3282 //                   ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3283 //                                                                       # A::x, N::y, A<T>::z; "gs" means leading "::"
3284 //                   ::= sr <unresolved-type> <base-unresolved-name>     # T::x / decltype(p)::x
3285 //  extension        ::= sr <unresolved-type> <template-args> <base-unresolved-name>
3286 //                                                                       # T::N::x /decltype(p)::N::x
3287 //  (ignored)        ::= srN <unresolved-type>  <unresolved-qualifier-level>+ E <base-unresolved-name>
3288 //
3289 // <unresolved-qualifier-level> ::= <simple-id>
3290 template <typename Derived, typename Alloc>
parseUnresolvedName()3291 Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName() {
3292   Node *SoFar = nullptr;
3293 
3294   // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3295   // srN <unresolved-type>                   <unresolved-qualifier-level>+ E <base-unresolved-name>
3296   if (consumeIf("srN")) {
3297     SoFar = getDerived().parseUnresolvedType();
3298     if (SoFar == nullptr)
3299       return nullptr;
3300 
3301     if (look() == 'I') {
3302       Node *TA = getDerived().parseTemplateArgs();
3303       if (TA == nullptr)
3304         return nullptr;
3305       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
3306       if (!SoFar)
3307         return nullptr;
3308     }
3309 
3310     while (!consumeIf('E')) {
3311       Node *Qual = getDerived().parseSimpleId();
3312       if (Qual == nullptr)
3313         return nullptr;
3314       SoFar = make<QualifiedName>(SoFar, Qual);
3315       if (!SoFar)
3316         return nullptr;
3317     }
3318 
3319     Node *Base = getDerived().parseBaseUnresolvedName();
3320     if (Base == nullptr)
3321       return nullptr;
3322     return make<QualifiedName>(SoFar, Base);
3323   }
3324 
3325   bool Global = consumeIf("gs");
3326 
3327   // [gs] <base-unresolved-name>                     # x or (with "gs") ::x
3328   if (!consumeIf("sr")) {
3329     SoFar = getDerived().parseBaseUnresolvedName();
3330     if (SoFar == nullptr)
3331       return nullptr;
3332     if (Global)
3333       SoFar = make<GlobalQualifiedName>(SoFar);
3334     return SoFar;
3335   }
3336 
3337   // [gs] sr <unresolved-qualifier-level>+ E   <base-unresolved-name>
3338   if (std::isdigit(look())) {
3339     do {
3340       Node *Qual = getDerived().parseSimpleId();
3341       if (Qual == nullptr)
3342         return nullptr;
3343       if (SoFar)
3344         SoFar = make<QualifiedName>(SoFar, Qual);
3345       else if (Global)
3346         SoFar = make<GlobalQualifiedName>(Qual);
3347       else
3348         SoFar = Qual;
3349       if (!SoFar)
3350         return nullptr;
3351     } while (!consumeIf('E'));
3352   }
3353   //      sr <unresolved-type>                 <base-unresolved-name>
3354   //      sr <unresolved-type> <template-args> <base-unresolved-name>
3355   else {
3356     SoFar = getDerived().parseUnresolvedType();
3357     if (SoFar == nullptr)
3358       return nullptr;
3359 
3360     if (look() == 'I') {
3361       Node *TA = getDerived().parseTemplateArgs();
3362       if (TA == nullptr)
3363         return nullptr;
3364       SoFar = make<NameWithTemplateArgs>(SoFar, TA);
3365       if (!SoFar)
3366         return nullptr;
3367     }
3368   }
3369 
3370   assert(SoFar != nullptr);
3371 
3372   Node *Base = getDerived().parseBaseUnresolvedName();
3373   if (Base == nullptr)
3374     return nullptr;
3375   return make<QualifiedName>(SoFar, Base);
3376 }
3377 
3378 // <abi-tags> ::= <abi-tag> [<abi-tags>]
3379 // <abi-tag> ::= B <source-name>
3380 template <typename Derived, typename Alloc>
parseAbiTags(Node * N)3381 Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
3382   while (consumeIf('B')) {
3383     StringView SN = parseBareSourceName();
3384     if (SN.empty())
3385       return nullptr;
3386     N = make<AbiTagAttr>(N, SN);
3387     if (!N)
3388       return nullptr;
3389   }
3390   return N;
3391 }
3392 
3393 // <number> ::= [n] <non-negative decimal integer>
3394 template <typename Alloc, typename Derived>
3395 StringView
parseNumber(bool AllowNegative)3396 AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
3397   const char *Tmp = First;
3398   if (AllowNegative)
3399     consumeIf('n');
3400   if (numLeft() == 0 || !std::isdigit(*First))
3401     return StringView();
3402   while (numLeft() != 0 && std::isdigit(*First))
3403     ++First;
3404   return StringView(Tmp, First);
3405 }
3406 
3407 // <positive length number> ::= [0-9]*
3408 template <typename Alloc, typename Derived>
parsePositiveInteger(size_t * Out)3409 bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
3410   *Out = 0;
3411   if (look() < '0' || look() > '9')
3412     return true;
3413   while (look() >= '0' && look() <= '9') {
3414     *Out *= 10;
3415     *Out += static_cast<size_t>(consume() - '0');
3416   }
3417   return false;
3418 }
3419 
3420 template <typename Alloc, typename Derived>
parseBareSourceName()3421 StringView AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
3422   size_t Int = 0;
3423   if (parsePositiveInteger(&Int) || numLeft() < Int)
3424     return StringView();
3425   StringView R(First, First + Int);
3426   First += Int;
3427   return R;
3428 }
3429 
3430 // <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
3431 //
3432 // <exception-spec> ::= Do                # non-throwing exception-specification (e.g., noexcept, throw())
3433 //                  ::= DO <expression> E # computed (instantiation-dependent) noexcept
3434 //                  ::= Dw <type>+ E      # dynamic exception specification with instantiation-dependent types
3435 //
3436 // <ref-qualifier> ::= R                   # & ref-qualifier
3437 // <ref-qualifier> ::= O                   # && ref-qualifier
3438 template <typename Derived, typename Alloc>
parseFunctionType()3439 Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
3440   Qualifiers CVQuals = parseCVQualifiers();
3441 
3442   Node *ExceptionSpec = nullptr;
3443   if (consumeIf("Do")) {
3444     ExceptionSpec = make<NameType>("noexcept");
3445     if (!ExceptionSpec)
3446       return nullptr;
3447   } else if (consumeIf("DO")) {
3448     Node *E = getDerived().parseExpr();
3449     if (E == nullptr || !consumeIf('E'))
3450       return nullptr;
3451     ExceptionSpec = make<NoexceptSpec>(E);
3452     if (!ExceptionSpec)
3453       return nullptr;
3454   } else if (consumeIf("Dw")) {
3455     size_t SpecsBegin = Names.size();
3456     while (!consumeIf('E')) {
3457       Node *T = getDerived().parseType();
3458       if (T == nullptr)
3459         return nullptr;
3460       Names.push_back(T);
3461     }
3462     ExceptionSpec =
3463       make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
3464     if (!ExceptionSpec)
3465       return nullptr;
3466   }
3467 
3468   consumeIf("Dx"); // transaction safe
3469 
3470   if (!consumeIf('F'))
3471     return nullptr;
3472   consumeIf('Y'); // extern "C"
3473   Node *ReturnType = getDerived().parseType();
3474   if (ReturnType == nullptr)
3475     return nullptr;
3476 
3477   FunctionRefQual ReferenceQualifier = FrefQualNone;
3478   size_t ParamsBegin = Names.size();
3479   while (true) {
3480     if (consumeIf('E'))
3481       break;
3482     if (consumeIf('v'))
3483       continue;
3484     if (consumeIf("RE")) {
3485       ReferenceQualifier = FrefQualLValue;
3486       break;
3487     }
3488     if (consumeIf("OE")) {
3489       ReferenceQualifier = FrefQualRValue;
3490       break;
3491     }
3492     Node *T = getDerived().parseType();
3493     if (T == nullptr)
3494       return nullptr;
3495     Names.push_back(T);
3496   }
3497 
3498   NodeArray Params = popTrailingNodeArray(ParamsBegin);
3499   return make<FunctionType>(ReturnType, Params, CVQuals,
3500                             ReferenceQualifier, ExceptionSpec);
3501 }
3502 
3503 // extension:
3504 // <vector-type>           ::= Dv <positive dimension number> _ <extended element type>
3505 //                         ::= Dv [<dimension expression>] _ <element type>
3506 // <extended element type> ::= <element type>
3507 //                         ::= p # AltiVec vector pixel
3508 template <typename Derived, typename Alloc>
parseVectorType()3509 Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
3510   if (!consumeIf("Dv"))
3511     return nullptr;
3512   if (look() >= '1' && look() <= '9') {
3513     Node *DimensionNumber = make<NameType>(parseNumber());
3514     if (!DimensionNumber)
3515       return nullptr;
3516     if (!consumeIf('_'))
3517       return nullptr;
3518     if (consumeIf('p'))
3519       return make<PixelVectorType>(DimensionNumber);
3520     Node *ElemType = getDerived().parseType();
3521     if (ElemType == nullptr)
3522       return nullptr;
3523     return make<VectorType>(ElemType, DimensionNumber);
3524   }
3525 
3526   if (!consumeIf('_')) {
3527     Node *DimExpr = getDerived().parseExpr();
3528     if (!DimExpr)
3529       return nullptr;
3530     if (!consumeIf('_'))
3531       return nullptr;
3532     Node *ElemType = getDerived().parseType();
3533     if (!ElemType)
3534       return nullptr;
3535     return make<VectorType>(ElemType, DimExpr);
3536   }
3537   Node *ElemType = getDerived().parseType();
3538   if (!ElemType)
3539     return nullptr;
3540   return make<VectorType>(ElemType, /*Dimension=*/nullptr);
3541 }
3542 
3543 // <decltype>  ::= Dt <expression> E  # decltype of an id-expression or class member access (C++0x)
3544 //             ::= DT <expression> E  # decltype of an expression (C++0x)
3545 template <typename Derived, typename Alloc>
parseDecltype()3546 Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
3547   if (!consumeIf('D'))
3548     return nullptr;
3549   if (!consumeIf('t') && !consumeIf('T'))
3550     return nullptr;
3551   Node *E = getDerived().parseExpr();
3552   if (E == nullptr)
3553     return nullptr;
3554   if (!consumeIf('E'))
3555     return nullptr;
3556   return make<EnclosingExpr>("decltype(", E, ")");
3557 }
3558 
3559 // <array-type> ::= A <positive dimension number> _ <element type>
3560 //              ::= A [<dimension expression>] _ <element type>
3561 template <typename Derived, typename Alloc>
parseArrayType()3562 Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
3563   if (!consumeIf('A'))
3564     return nullptr;
3565 
3566   Node *Dimension = nullptr;
3567 
3568   if (std::isdigit(look())) {
3569     Dimension = make<NameType>(parseNumber());
3570     if (!Dimension)
3571       return nullptr;
3572     if (!consumeIf('_'))
3573       return nullptr;
3574   } else if (!consumeIf('_')) {
3575     Node *DimExpr = getDerived().parseExpr();
3576     if (DimExpr == nullptr)
3577       return nullptr;
3578     if (!consumeIf('_'))
3579       return nullptr;
3580     Dimension = DimExpr;
3581   }
3582 
3583   Node *Ty = getDerived().parseType();
3584   if (Ty == nullptr)
3585     return nullptr;
3586   return make<ArrayType>(Ty, Dimension);
3587 }
3588 
3589 // <pointer-to-member-type> ::= M <class type> <member type>
3590 template <typename Derived, typename Alloc>
parsePointerToMemberType()3591 Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
3592   if (!consumeIf('M'))
3593     return nullptr;
3594   Node *ClassType = getDerived().parseType();
3595   if (ClassType == nullptr)
3596     return nullptr;
3597   Node *MemberType = getDerived().parseType();
3598   if (MemberType == nullptr)
3599     return nullptr;
3600   return make<PointerToMemberType>(ClassType, MemberType);
3601 }
3602 
3603 // <class-enum-type> ::= <name>     # non-dependent type name, dependent type name, or dependent typename-specifier
3604 //                   ::= Ts <name>  # dependent elaborated type specifier using 'struct' or 'class'
3605 //                   ::= Tu <name>  # dependent elaborated type specifier using 'union'
3606 //                   ::= Te <name>  # dependent elaborated type specifier using 'enum'
3607 template <typename Derived, typename Alloc>
parseClassEnumType()3608 Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
3609   StringView ElabSpef;
3610   if (consumeIf("Ts"))
3611     ElabSpef = "struct";
3612   else if (consumeIf("Tu"))
3613     ElabSpef = "union";
3614   else if (consumeIf("Te"))
3615     ElabSpef = "enum";
3616 
3617   Node *Name = getDerived().parseName();
3618   if (Name == nullptr)
3619     return nullptr;
3620 
3621   if (!ElabSpef.empty())
3622     return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3623 
3624   return Name;
3625 }
3626 
3627 // <qualified-type>     ::= <qualifiers> <type>
3628 // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3629 // <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
3630 template <typename Derived, typename Alloc>
parseQualifiedType()3631 Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
3632   if (consumeIf('U')) {
3633     StringView Qual = parseBareSourceName();
3634     if (Qual.empty())
3635       return nullptr;
3636 
3637     // FIXME parse the optional <template-args> here!
3638 
3639     // extension            ::= U <objc-name> <objc-type>  # objc-type<identifier>
3640     if (Qual.startsWith("objcproto")) {
3641       StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3642       StringView Proto;
3643       {
3644         SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3645                                      SaveLast(Last, ProtoSourceName.end());
3646         Proto = parseBareSourceName();
3647       }
3648       if (Proto.empty())
3649         return nullptr;
3650       Node *Child = getDerived().parseQualifiedType();
3651       if (Child == nullptr)
3652         return nullptr;
3653       return make<ObjCProtoName>(Child, Proto);
3654     }
3655 
3656     Node *Child = getDerived().parseQualifiedType();
3657     if (Child == nullptr)
3658       return nullptr;
3659     return make<VendorExtQualType>(Child, Qual);
3660   }
3661 
3662   Qualifiers Quals = parseCVQualifiers();
3663   Node *Ty = getDerived().parseType();
3664   if (Ty == nullptr)
3665     return nullptr;
3666   if (Quals != QualNone)
3667     Ty = make<QualType>(Ty, Quals);
3668   return Ty;
3669 }
3670 
3671 // <type>      ::= <builtin-type>
3672 //             ::= <qualified-type>
3673 //             ::= <function-type>
3674 //             ::= <class-enum-type>
3675 //             ::= <array-type>
3676 //             ::= <pointer-to-member-type>
3677 //             ::= <template-param>
3678 //             ::= <template-template-param> <template-args>
3679 //             ::= <decltype>
3680 //             ::= P <type>        # pointer
3681 //             ::= R <type>        # l-value reference
3682 //             ::= O <type>        # r-value reference (C++11)
3683 //             ::= C <type>        # complex pair (C99)
3684 //             ::= G <type>        # imaginary (C99)
3685 //             ::= <substitution>  # See Compression below
3686 // extension   ::= U <objc-name> <objc-type>  # objc-type<identifier>
3687 // extension   ::= <vector-type> # <vector-type> starts with Dv
3688 //
3689 // <objc-name> ::= <k0 number> objcproto <k1 number> <identifier>  # k0 = 9 + <number of digits in k1> + k1
3690 // <objc-type> ::= <source-name>  # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
3691 template <typename Derived, typename Alloc>
parseType()3692 Node *AbstractManglingParser<Derived, Alloc>::parseType() {
3693   Node *Result = nullptr;
3694 
3695   switch (look()) {
3696   //             ::= <qualified-type>
3697   case 'r':
3698   case 'V':
3699   case 'K': {
3700     unsigned AfterQuals = 0;
3701     if (look(AfterQuals) == 'r') ++AfterQuals;
3702     if (look(AfterQuals) == 'V') ++AfterQuals;
3703     if (look(AfterQuals) == 'K') ++AfterQuals;
3704 
3705     if (look(AfterQuals) == 'F' ||
3706         (look(AfterQuals) == 'D' &&
3707          (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3708           look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
3709       Result = getDerived().parseFunctionType();
3710       break;
3711     }
3712     DEMANGLE_FALLTHROUGH;
3713   }
3714   case 'U': {
3715     Result = getDerived().parseQualifiedType();
3716     break;
3717   }
3718   // <builtin-type> ::= v    # void
3719   case 'v':
3720     ++First;
3721     return make<NameType>("void");
3722   //                ::= w    # wchar_t
3723   case 'w':
3724     ++First;
3725     return make<NameType>("wchar_t");
3726   //                ::= b    # bool
3727   case 'b':
3728     ++First;
3729     return make<NameType>("bool");
3730   //                ::= c    # char
3731   case 'c':
3732     ++First;
3733     return make<NameType>("char");
3734   //                ::= a    # signed char
3735   case 'a':
3736     ++First;
3737     return make<NameType>("signed char");
3738   //                ::= h    # unsigned char
3739   case 'h':
3740     ++First;
3741     return make<NameType>("unsigned char");
3742   //                ::= s    # short
3743   case 's':
3744     ++First;
3745     return make<NameType>("short");
3746   //                ::= t    # unsigned short
3747   case 't':
3748     ++First;
3749     return make<NameType>("unsigned short");
3750   //                ::= i    # int
3751   case 'i':
3752     ++First;
3753     return make<NameType>("int");
3754   //                ::= j    # unsigned int
3755   case 'j':
3756     ++First;
3757     return make<NameType>("unsigned int");
3758   //                ::= l    # long
3759   case 'l':
3760     ++First;
3761     return make<NameType>("long");
3762   //                ::= m    # unsigned long
3763   case 'm':
3764     ++First;
3765     return make<NameType>("unsigned long");
3766   //                ::= x    # long long, __int64
3767   case 'x':
3768     ++First;
3769     return make<NameType>("long long");
3770   //                ::= y    # unsigned long long, __int64
3771   case 'y':
3772     ++First;
3773     return make<NameType>("unsigned long long");
3774   //                ::= n    # __int128
3775   case 'n':
3776     ++First;
3777     return make<NameType>("__int128");
3778   //                ::= o    # unsigned __int128
3779   case 'o':
3780     ++First;
3781     return make<NameType>("unsigned __int128");
3782   //                ::= f    # float
3783   case 'f':
3784     ++First;
3785     return make<NameType>("float");
3786   //                ::= d    # double
3787   case 'd':
3788     ++First;
3789     return make<NameType>("double");
3790   //                ::= e    # long double, __float80
3791   case 'e':
3792     ++First;
3793     return make<NameType>("long double");
3794   //                ::= g    # __float128
3795   case 'g':
3796     ++First;
3797     return make<NameType>("__float128");
3798   //                ::= z    # ellipsis
3799   case 'z':
3800     ++First;
3801     return make<NameType>("...");
3802 
3803   // <builtin-type> ::= u <source-name>    # vendor extended type
3804   case 'u': {
3805     ++First;
3806     StringView Res = parseBareSourceName();
3807     if (Res.empty())
3808       return nullptr;
3809     // Typically, <builtin-type>s are not considered substitution candidates,
3810     // but the exception to that exception is vendor extended types (Itanium C++
3811     // ABI 5.9.1).
3812     Result = make<NameType>(Res);
3813     break;
3814   }
3815   case 'D':
3816     switch (look(1)) {
3817     //                ::= Dd   # IEEE 754r decimal floating point (64 bits)
3818     case 'd':
3819       First += 2;
3820       return make<NameType>("decimal64");
3821     //                ::= De   # IEEE 754r decimal floating point (128 bits)
3822     case 'e':
3823       First += 2;
3824       return make<NameType>("decimal128");
3825     //                ::= Df   # IEEE 754r decimal floating point (32 bits)
3826     case 'f':
3827       First += 2;
3828       return make<NameType>("decimal32");
3829     //                ::= Dh   # IEEE 754r half-precision floating point (16 bits)
3830     case 'h':
3831       First += 2;
3832       return make<NameType>("decimal16");
3833     //                ::= Di   # char32_t
3834     case 'i':
3835       First += 2;
3836       return make<NameType>("char32_t");
3837     //                ::= Ds   # char16_t
3838     case 's':
3839       First += 2;
3840       return make<NameType>("char16_t");
3841     //                ::= Du   # char8_t (C++2a, not yet in the Itanium spec)
3842     case 'u':
3843       First += 2;
3844       return make<NameType>("char8_t");
3845     //                ::= Da   # auto (in dependent new-expressions)
3846     case 'a':
3847       First += 2;
3848       return make<NameType>("auto");
3849     //                ::= Dc   # decltype(auto)
3850     case 'c':
3851       First += 2;
3852       return make<NameType>("decltype(auto)");
3853     //                ::= Dn   # std::nullptr_t (i.e., decltype(nullptr))
3854     case 'n':
3855       First += 2;
3856       return make<NameType>("std::nullptr_t");
3857 
3858     //             ::= <decltype>
3859     case 't':
3860     case 'T': {
3861       Result = getDerived().parseDecltype();
3862       break;
3863     }
3864     // extension   ::= <vector-type> # <vector-type> starts with Dv
3865     case 'v': {
3866       Result = getDerived().parseVectorType();
3867       break;
3868     }
3869     //           ::= Dp <type>       # pack expansion (C++0x)
3870     case 'p': {
3871       First += 2;
3872       Node *Child = getDerived().parseType();
3873       if (!Child)
3874         return nullptr;
3875       Result = make<ParameterPackExpansion>(Child);
3876       break;
3877     }
3878     // Exception specifier on a function type.
3879     case 'o':
3880     case 'O':
3881     case 'w':
3882     // Transaction safe function type.
3883     case 'x':
3884       Result = getDerived().parseFunctionType();
3885       break;
3886     }
3887     break;
3888   //             ::= <function-type>
3889   case 'F': {
3890     Result = getDerived().parseFunctionType();
3891     break;
3892   }
3893   //             ::= <array-type>
3894   case 'A': {
3895     Result = getDerived().parseArrayType();
3896     break;
3897   }
3898   //             ::= <pointer-to-member-type>
3899   case 'M': {
3900     Result = getDerived().parsePointerToMemberType();
3901     break;
3902   }
3903   //             ::= <template-param>
3904   case 'T': {
3905     // This could be an elaborate type specifier on a <class-enum-type>.
3906     if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
3907       Result = getDerived().parseClassEnumType();
3908       break;
3909     }
3910 
3911     Result = getDerived().parseTemplateParam();
3912     if (Result == nullptr)
3913       return nullptr;
3914 
3915     // Result could be either of:
3916     //   <type>        ::= <template-param>
3917     //   <type>        ::= <template-template-param> <template-args>
3918     //
3919     //   <template-template-param> ::= <template-param>
3920     //                             ::= <substitution>
3921     //
3922     // If this is followed by some <template-args>, and we're permitted to
3923     // parse them, take the second production.
3924 
3925     if (TryToParseTemplateArgs && look() == 'I') {
3926       Node *TA = getDerived().parseTemplateArgs();
3927       if (TA == nullptr)
3928         return nullptr;
3929       Result = make<NameWithTemplateArgs>(Result, TA);
3930     }
3931     break;
3932   }
3933   //             ::= P <type>        # pointer
3934   case 'P': {
3935     ++First;
3936     Node *Ptr = getDerived().parseType();
3937     if (Ptr == nullptr)
3938       return nullptr;
3939     Result = make<PointerType>(Ptr);
3940     break;
3941   }
3942   //             ::= R <type>        # l-value reference
3943   case 'R': {
3944     ++First;
3945     Node *Ref = getDerived().parseType();
3946     if (Ref == nullptr)
3947       return nullptr;
3948     Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
3949     break;
3950   }
3951   //             ::= O <type>        # r-value reference (C++11)
3952   case 'O': {
3953     ++First;
3954     Node *Ref = getDerived().parseType();
3955     if (Ref == nullptr)
3956       return nullptr;
3957     Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
3958     break;
3959   }
3960   //             ::= C <type>        # complex pair (C99)
3961   case 'C': {
3962     ++First;
3963     Node *P = getDerived().parseType();
3964     if (P == nullptr)
3965       return nullptr;
3966     Result = make<PostfixQualifiedType>(P, " complex");
3967     break;
3968   }
3969   //             ::= G <type>        # imaginary (C99)
3970   case 'G': {
3971     ++First;
3972     Node *P = getDerived().parseType();
3973     if (P == nullptr)
3974       return P;
3975     Result = make<PostfixQualifiedType>(P, " imaginary");
3976     break;
3977   }
3978   //             ::= <substitution>  # See Compression below
3979   case 'S': {
3980     if (look(1) && look(1) != 't') {
3981       Node *Sub = getDerived().parseSubstitution();
3982       if (Sub == nullptr)
3983         return nullptr;
3984 
3985       // Sub could be either of:
3986       //   <type>        ::= <substitution>
3987       //   <type>        ::= <template-template-param> <template-args>
3988       //
3989       //   <template-template-param> ::= <template-param>
3990       //                             ::= <substitution>
3991       //
3992       // If this is followed by some <template-args>, and we're permitted to
3993       // parse them, take the second production.
3994 
3995       if (TryToParseTemplateArgs && look() == 'I') {
3996         Node *TA = getDerived().parseTemplateArgs();
3997         if (TA == nullptr)
3998           return nullptr;
3999         Result = make<NameWithTemplateArgs>(Sub, TA);
4000         break;
4001       }
4002 
4003       // If all we parsed was a substitution, don't re-insert into the
4004       // substitution table.
4005       return Sub;
4006     }
4007     DEMANGLE_FALLTHROUGH;
4008   }
4009   //        ::= <class-enum-type>
4010   default: {
4011     Result = getDerived().parseClassEnumType();
4012     break;
4013   }
4014   }
4015 
4016   // If we parsed a type, insert it into the substitution table. Note that all
4017   // <builtin-type>s and <substitution>s have already bailed out, because they
4018   // don't get substitutions.
4019   if (Result != nullptr)
4020     Subs.push_back(Result);
4021   return Result;
4022 }
4023 
4024 template <typename Derived, typename Alloc>
parsePrefixExpr(StringView Kind)4025 Node *AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(StringView Kind) {
4026   Node *E = getDerived().parseExpr();
4027   if (E == nullptr)
4028     return nullptr;
4029   return make<PrefixExpr>(Kind, E);
4030 }
4031 
4032 template <typename Derived, typename Alloc>
parseBinaryExpr(StringView Kind)4033 Node *AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(StringView Kind) {
4034   Node *LHS = getDerived().parseExpr();
4035   if (LHS == nullptr)
4036     return nullptr;
4037   Node *RHS = getDerived().parseExpr();
4038   if (RHS == nullptr)
4039     return nullptr;
4040   return make<BinaryExpr>(LHS, Kind, RHS);
4041 }
4042 
4043 template <typename Derived, typename Alloc>
4044 Node *
parseIntegerLiteral(StringView Lit)4045 AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(StringView Lit) {
4046   StringView Tmp = parseNumber(true);
4047   if (!Tmp.empty() && consumeIf('E'))
4048     return make<IntegerLiteral>(Lit, Tmp);
4049   return nullptr;
4050 }
4051 
4052 // <CV-Qualifiers> ::= [r] [V] [K]
4053 template <typename Alloc, typename Derived>
parseCVQualifiers()4054 Qualifiers AbstractManglingParser<Alloc, Derived>::parseCVQualifiers() {
4055   Qualifiers CVR = QualNone;
4056   if (consumeIf('r'))
4057     CVR |= QualRestrict;
4058   if (consumeIf('V'))
4059     CVR |= QualVolatile;
4060   if (consumeIf('K'))
4061     CVR |= QualConst;
4062   return CVR;
4063 }
4064 
4065 // <function-param> ::= fp <top-level CV-Qualifiers> _                                     # L == 0, first parameter
4066 //                  ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _   # L == 0, second and later parameters
4067 //                  ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _         # L > 0, first parameter
4068 //                  ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _   # L > 0, second and later parameters
4069 template <typename Derived, typename Alloc>
parseFunctionParam()4070 Node *AbstractManglingParser<Derived, Alloc>::parseFunctionParam() {
4071   if (consumeIf("fp")) {
4072     parseCVQualifiers();
4073     StringView Num = parseNumber();
4074     if (!consumeIf('_'))
4075       return nullptr;
4076     return make<FunctionParam>(Num);
4077   }
4078   if (consumeIf("fL")) {
4079     if (parseNumber().empty())
4080       return nullptr;
4081     if (!consumeIf('p'))
4082       return nullptr;
4083     parseCVQualifiers();
4084     StringView Num = parseNumber();
4085     if (!consumeIf('_'))
4086       return nullptr;
4087     return make<FunctionParam>(Num);
4088   }
4089   return nullptr;
4090 }
4091 
4092 // [gs] nw <expression>* _ <type> E                     # new (expr-list) type
4093 // [gs] nw <expression>* _ <type> <initializer>         # new (expr-list) type (init)
4094 // [gs] na <expression>* _ <type> E                     # new[] (expr-list) type
4095 // [gs] na <expression>* _ <type> <initializer>         # new[] (expr-list) type (init)
4096 // <initializer> ::= pi <expression>* E                 # parenthesized initialization
4097 template <typename Derived, typename Alloc>
parseNewExpr()4098 Node *AbstractManglingParser<Derived, Alloc>::parseNewExpr() {
4099   bool Global = consumeIf("gs");
4100   bool IsArray = look(1) == 'a';
4101   if (!consumeIf("nw") && !consumeIf("na"))
4102     return nullptr;
4103   size_t Exprs = Names.size();
4104   while (!consumeIf('_')) {
4105     Node *Ex = getDerived().parseExpr();
4106     if (Ex == nullptr)
4107       return nullptr;
4108     Names.push_back(Ex);
4109   }
4110   NodeArray ExprList = popTrailingNodeArray(Exprs);
4111   Node *Ty = getDerived().parseType();
4112   if (Ty == nullptr)
4113     return Ty;
4114   if (consumeIf("pi")) {
4115     size_t InitsBegin = Names.size();
4116     while (!consumeIf('E')) {
4117       Node *Init = getDerived().parseExpr();
4118       if (Init == nullptr)
4119         return Init;
4120       Names.push_back(Init);
4121     }
4122     NodeArray Inits = popTrailingNodeArray(InitsBegin);
4123     return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
4124   } else if (!consumeIf('E'))
4125     return nullptr;
4126   return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
4127 }
4128 
4129 // cv <type> <expression>                               # conversion with one argument
4130 // cv <type> _ <expression>* E                          # conversion with a different number of arguments
4131 template <typename Derived, typename Alloc>
parseConversionExpr()4132 Node *AbstractManglingParser<Derived, Alloc>::parseConversionExpr() {
4133   if (!consumeIf("cv"))
4134     return nullptr;
4135   Node *Ty;
4136   {
4137     SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
4138     Ty = getDerived().parseType();
4139   }
4140 
4141   if (Ty == nullptr)
4142     return nullptr;
4143 
4144   if (consumeIf('_')) {
4145     size_t ExprsBegin = Names.size();
4146     while (!consumeIf('E')) {
4147       Node *E = getDerived().parseExpr();
4148       if (E == nullptr)
4149         return E;
4150       Names.push_back(E);
4151     }
4152     NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
4153     return make<ConversionExpr>(Ty, Exprs);
4154   }
4155 
4156   Node *E[1] = {getDerived().parseExpr()};
4157   if (E[0] == nullptr)
4158     return nullptr;
4159   return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
4160 }
4161 
4162 // <expr-primary> ::= L <type> <value number> E                          # integer literal
4163 //                ::= L <type> <value float> E                           # floating literal
4164 //                ::= L <string type> E                                  # string literal
4165 //                ::= L <nullptr type> E                                 # nullptr literal (i.e., "LDnE")
4166 //                ::= L <lambda type> E                                  # lambda expression
4167 // FIXME:         ::= L <type> <real-part float> _ <imag-part float> E   # complex floating point literal (C 2000)
4168 //                ::= L <mangled-name> E                                 # external name
4169 template <typename Derived, typename Alloc>
parseExprPrimary()4170 Node *AbstractManglingParser<Derived, Alloc>::parseExprPrimary() {
4171   if (!consumeIf('L'))
4172     return nullptr;
4173   switch (look()) {
4174   case 'w':
4175     ++First;
4176     return getDerived().parseIntegerLiteral("wchar_t");
4177   case 'b':
4178     if (consumeIf("b0E"))
4179       return make<BoolExpr>(0);
4180     if (consumeIf("b1E"))
4181       return make<BoolExpr>(1);
4182     return nullptr;
4183   case 'c':
4184     ++First;
4185     return getDerived().parseIntegerLiteral("char");
4186   case 'a':
4187     ++First;
4188     return getDerived().parseIntegerLiteral("signed char");
4189   case 'h':
4190     ++First;
4191     return getDerived().parseIntegerLiteral("unsigned char");
4192   case 's':
4193     ++First;
4194     return getDerived().parseIntegerLiteral("short");
4195   case 't':
4196     ++First;
4197     return getDerived().parseIntegerLiteral("unsigned short");
4198   case 'i':
4199     ++First;
4200     return getDerived().parseIntegerLiteral("");
4201   case 'j':
4202     ++First;
4203     return getDerived().parseIntegerLiteral("u");
4204   case 'l':
4205     ++First;
4206     return getDerived().parseIntegerLiteral("l");
4207   case 'm':
4208     ++First;
4209     return getDerived().parseIntegerLiteral("ul");
4210   case 'x':
4211     ++First;
4212     return getDerived().parseIntegerLiteral("ll");
4213   case 'y':
4214     ++First;
4215     return getDerived().parseIntegerLiteral("ull");
4216   case 'n':
4217     ++First;
4218     return getDerived().parseIntegerLiteral("__int128");
4219   case 'o':
4220     ++First;
4221     return getDerived().parseIntegerLiteral("unsigned __int128");
4222   case 'f':
4223     ++First;
4224     return getDerived().template parseFloatingLiteral<float>();
4225   case 'd':
4226     ++First;
4227     return getDerived().template parseFloatingLiteral<double>();
4228   case 'e':
4229     ++First;
4230     return getDerived().template parseFloatingLiteral<long double>();
4231   case '_':
4232     if (consumeIf("_Z")) {
4233       Node *R = getDerived().parseEncoding();
4234       if (R != nullptr && consumeIf('E'))
4235         return R;
4236     }
4237     return nullptr;
4238   case 'A': {
4239     Node *T = getDerived().parseType();
4240     if (T == nullptr)
4241       return nullptr;
4242     // FIXME: We need to include the string contents in the mangling.
4243     if (consumeIf('E'))
4244       return make<StringLiteral>(T);
4245     return nullptr;
4246   }
4247   case 'D':
4248     if (consumeIf("DnE"))
4249       return make<NameType>("nullptr");
4250     return nullptr;
4251   case 'T':
4252     // Invalid mangled name per
4253     //   http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
4254     return nullptr;
4255   case 'U': {
4256     // FIXME: Should we support LUb... for block literals?
4257     if (look(1) != 'l')
4258       return nullptr;
4259     Node *T = parseUnnamedTypeName(nullptr);
4260     if (!T || !consumeIf('E'))
4261       return nullptr;
4262     return make<LambdaExpr>(T);
4263   }
4264   default: {
4265     // might be named type
4266     Node *T = getDerived().parseType();
4267     if (T == nullptr)
4268       return nullptr;
4269     StringView N = parseNumber();
4270     if (N.empty())
4271       return nullptr;
4272     if (!consumeIf('E'))
4273       return nullptr;
4274     return make<IntegerCastExpr>(T, N);
4275   }
4276   }
4277 }
4278 
4279 // <braced-expression> ::= <expression>
4280 //                     ::= di <field source-name> <braced-expression>    # .name = expr
4281 //                     ::= dx <index expression> <braced-expression>     # [expr] = expr
4282 //                     ::= dX <range begin expression> <range end expression> <braced-expression>
4283 template <typename Derived, typename Alloc>
parseBracedExpr()4284 Node *AbstractManglingParser<Derived, Alloc>::parseBracedExpr() {
4285   if (look() == 'd') {
4286     switch (look(1)) {
4287     case 'i': {
4288       First += 2;
4289       Node *Field = getDerived().parseSourceName(/*NameState=*/nullptr);
4290       if (Field == nullptr)
4291         return nullptr;
4292       Node *Init = getDerived().parseBracedExpr();
4293       if (Init == nullptr)
4294         return nullptr;
4295       return make<BracedExpr>(Field, Init, /*isArray=*/false);
4296     }
4297     case 'x': {
4298       First += 2;
4299       Node *Index = getDerived().parseExpr();
4300       if (Index == nullptr)
4301         return nullptr;
4302       Node *Init = getDerived().parseBracedExpr();
4303       if (Init == nullptr)
4304         return nullptr;
4305       return make<BracedExpr>(Index, Init, /*isArray=*/true);
4306     }
4307     case 'X': {
4308       First += 2;
4309       Node *RangeBegin = getDerived().parseExpr();
4310       if (RangeBegin == nullptr)
4311         return nullptr;
4312       Node *RangeEnd = getDerived().parseExpr();
4313       if (RangeEnd == nullptr)
4314         return nullptr;
4315       Node *Init = getDerived().parseBracedExpr();
4316       if (Init == nullptr)
4317         return nullptr;
4318       return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
4319     }
4320     }
4321   }
4322   return getDerived().parseExpr();
4323 }
4324 
4325 // (not yet in the spec)
4326 // <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
4327 //             ::= fR <binary-operator-name> <expression> <expression>
4328 //             ::= fl <binary-operator-name> <expression>
4329 //             ::= fr <binary-operator-name> <expression>
4330 template <typename Derived, typename Alloc>
parseFoldExpr()4331 Node *AbstractManglingParser<Derived, Alloc>::parseFoldExpr() {
4332   if (!consumeIf('f'))
4333     return nullptr;
4334 
4335   char FoldKind = look();
4336   bool IsLeftFold, HasInitializer;
4337   HasInitializer = FoldKind == 'L' || FoldKind == 'R';
4338   if (FoldKind == 'l' || FoldKind == 'L')
4339     IsLeftFold = true;
4340   else if (FoldKind == 'r' || FoldKind == 'R')
4341     IsLeftFold = false;
4342   else
4343     return nullptr;
4344   ++First;
4345 
4346   // FIXME: This map is duplicated in parseOperatorName and parseExpr.
4347   StringView OperatorName;
4348   if      (consumeIf("aa")) OperatorName = "&&";
4349   else if (consumeIf("an")) OperatorName = "&";
4350   else if (consumeIf("aN")) OperatorName = "&=";
4351   else if (consumeIf("aS")) OperatorName = "=";
4352   else if (consumeIf("cm")) OperatorName = ",";
4353   else if (consumeIf("ds")) OperatorName = ".*";
4354   else if (consumeIf("dv")) OperatorName = "/";
4355   else if (consumeIf("dV")) OperatorName = "/=";
4356   else if (consumeIf("eo")) OperatorName = "^";
4357   else if (consumeIf("eO")) OperatorName = "^=";
4358   else if (consumeIf("eq")) OperatorName = "==";
4359   else if (consumeIf("ge")) OperatorName = ">=";
4360   else if (consumeIf("gt")) OperatorName = ">";
4361   else if (consumeIf("le")) OperatorName = "<=";
4362   else if (consumeIf("ls")) OperatorName = "<<";
4363   else if (consumeIf("lS")) OperatorName = "<<=";
4364   else if (consumeIf("lt")) OperatorName = "<";
4365   else if (consumeIf("mi")) OperatorName = "-";
4366   else if (consumeIf("mI")) OperatorName = "-=";
4367   else if (consumeIf("ml")) OperatorName = "*";
4368   else if (consumeIf("mL")) OperatorName = "*=";
4369   else if (consumeIf("ne")) OperatorName = "!=";
4370   else if (consumeIf("oo")) OperatorName = "||";
4371   else if (consumeIf("or")) OperatorName = "|";
4372   else if (consumeIf("oR")) OperatorName = "|=";
4373   else if (consumeIf("pl")) OperatorName = "+";
4374   else if (consumeIf("pL")) OperatorName = "+=";
4375   else if (consumeIf("rm")) OperatorName = "%";
4376   else if (consumeIf("rM")) OperatorName = "%=";
4377   else if (consumeIf("rs")) OperatorName = ">>";
4378   else if (consumeIf("rS")) OperatorName = ">>=";
4379   else return nullptr;
4380 
4381   Node *Pack = getDerived().parseExpr(), *Init = nullptr;
4382   if (Pack == nullptr)
4383     return nullptr;
4384   if (HasInitializer) {
4385     Init = getDerived().parseExpr();
4386     if (Init == nullptr)
4387       return nullptr;
4388   }
4389 
4390   if (IsLeftFold && Init)
4391     std::swap(Pack, Init);
4392 
4393   return make<FoldExpr>(IsLeftFold, OperatorName, Pack, Init);
4394 }
4395 
4396 // <expression> ::= <unary operator-name> <expression>
4397 //              ::= <binary operator-name> <expression> <expression>
4398 //              ::= <ternary operator-name> <expression> <expression> <expression>
4399 //              ::= cl <expression>+ E                                   # call
4400 //              ::= cv <type> <expression>                               # conversion with one argument
4401 //              ::= cv <type> _ <expression>* E                          # conversion with a different number of arguments
4402 //              ::= [gs] nw <expression>* _ <type> E                     # new (expr-list) type
4403 //              ::= [gs] nw <expression>* _ <type> <initializer>         # new (expr-list) type (init)
4404 //              ::= [gs] na <expression>* _ <type> E                     # new[] (expr-list) type
4405 //              ::= [gs] na <expression>* _ <type> <initializer>         # new[] (expr-list) type (init)
4406 //              ::= [gs] dl <expression>                                 # delete expression
4407 //              ::= [gs] da <expression>                                 # delete[] expression
4408 //              ::= pp_ <expression>                                     # prefix ++
4409 //              ::= mm_ <expression>                                     # prefix --
4410 //              ::= ti <type>                                            # typeid (type)
4411 //              ::= te <expression>                                      # typeid (expression)
4412 //              ::= dc <type> <expression>                               # dynamic_cast<type> (expression)
4413 //              ::= sc <type> <expression>                               # static_cast<type> (expression)
4414 //              ::= cc <type> <expression>                               # const_cast<type> (expression)
4415 //              ::= rc <type> <expression>                               # reinterpret_cast<type> (expression)
4416 //              ::= st <type>                                            # sizeof (a type)
4417 //              ::= sz <expression>                                      # sizeof (an expression)
4418 //              ::= at <type>                                            # alignof (a type)
4419 //              ::= az <expression>                                      # alignof (an expression)
4420 //              ::= nx <expression>                                      # noexcept (expression)
4421 //              ::= <template-param>
4422 //              ::= <function-param>
4423 //              ::= dt <expression> <unresolved-name>                    # expr.name
4424 //              ::= pt <expression> <unresolved-name>                    # expr->name
4425 //              ::= ds <expression> <expression>                         # expr.*expr
4426 //              ::= sZ <template-param>                                  # size of a parameter pack
4427 //              ::= sZ <function-param>                                  # size of a function parameter pack
4428 //              ::= sP <template-arg>* E                                 # sizeof...(T), size of a captured template parameter pack from an alias template
4429 //              ::= sp <expression>                                      # pack expansion
4430 //              ::= tw <expression>                                      # throw expression
4431 //              ::= tr                                                   # throw with no operand (rethrow)
4432 //              ::= <unresolved-name>                                    # f(p), N::f(p), ::f(p),
4433 //                                                                       # freestanding dependent name (e.g., T::x),
4434 //                                                                       # objectless nonstatic member reference
4435 //              ::= fL <binary-operator-name> <expression> <expression>
4436 //              ::= fR <binary-operator-name> <expression> <expression>
4437 //              ::= fl <binary-operator-name> <expression>
4438 //              ::= fr <binary-operator-name> <expression>
4439 //              ::= <expr-primary>
4440 template <typename Derived, typename Alloc>
parseExpr()4441 Node *AbstractManglingParser<Derived, Alloc>::parseExpr() {
4442   bool Global = consumeIf("gs");
4443   if (numLeft() < 2)
4444     return nullptr;
4445 
4446   switch (*First) {
4447   case 'L':
4448     return getDerived().parseExprPrimary();
4449   case 'T':
4450     return getDerived().parseTemplateParam();
4451   case 'f': {
4452     // Disambiguate a fold expression from a <function-param>.
4453     if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
4454       return getDerived().parseFunctionParam();
4455     return getDerived().parseFoldExpr();
4456   }
4457   case 'a':
4458     switch (First[1]) {
4459     case 'a':
4460       First += 2;
4461       return getDerived().parseBinaryExpr("&&");
4462     case 'd':
4463       First += 2;
4464       return getDerived().parsePrefixExpr("&");
4465     case 'n':
4466       First += 2;
4467       return getDerived().parseBinaryExpr("&");
4468     case 'N':
4469       First += 2;
4470       return getDerived().parseBinaryExpr("&=");
4471     case 'S':
4472       First += 2;
4473       return getDerived().parseBinaryExpr("=");
4474     case 't': {
4475       First += 2;
4476       Node *Ty = getDerived().parseType();
4477       if (Ty == nullptr)
4478         return nullptr;
4479       return make<EnclosingExpr>("alignof (", Ty, ")");
4480     }
4481     case 'z': {
4482       First += 2;
4483       Node *Ty = getDerived().parseExpr();
4484       if (Ty == nullptr)
4485         return nullptr;
4486       return make<EnclosingExpr>("alignof (", Ty, ")");
4487     }
4488     }
4489     return nullptr;
4490   case 'c':
4491     switch (First[1]) {
4492     // cc <type> <expression>                               # const_cast<type>(expression)
4493     case 'c': {
4494       First += 2;
4495       Node *Ty = getDerived().parseType();
4496       if (Ty == nullptr)
4497         return Ty;
4498       Node *Ex = getDerived().parseExpr();
4499       if (Ex == nullptr)
4500         return Ex;
4501       return make<CastExpr>("const_cast", Ty, Ex);
4502     }
4503     // cl <expression>+ E                                   # call
4504     case 'l': {
4505       First += 2;
4506       Node *Callee = getDerived().parseExpr();
4507       if (Callee == nullptr)
4508         return Callee;
4509       size_t ExprsBegin = Names.size();
4510       while (!consumeIf('E')) {
4511         Node *E = getDerived().parseExpr();
4512         if (E == nullptr)
4513           return E;
4514         Names.push_back(E);
4515       }
4516       return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
4517     }
4518     case 'm':
4519       First += 2;
4520       return getDerived().parseBinaryExpr(",");
4521     case 'o':
4522       First += 2;
4523       return getDerived().parsePrefixExpr("~");
4524     case 'v':
4525       return getDerived().parseConversionExpr();
4526     }
4527     return nullptr;
4528   case 'd':
4529     switch (First[1]) {
4530     case 'a': {
4531       First += 2;
4532       Node *Ex = getDerived().parseExpr();
4533       if (Ex == nullptr)
4534         return Ex;
4535       return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
4536     }
4537     case 'c': {
4538       First += 2;
4539       Node *T = getDerived().parseType();
4540       if (T == nullptr)
4541         return T;
4542       Node *Ex = getDerived().parseExpr();
4543       if (Ex == nullptr)
4544         return Ex;
4545       return make<CastExpr>("dynamic_cast", T, Ex);
4546     }
4547     case 'e':
4548       First += 2;
4549       return getDerived().parsePrefixExpr("*");
4550     case 'l': {
4551       First += 2;
4552       Node *E = getDerived().parseExpr();
4553       if (E == nullptr)
4554         return E;
4555       return make<DeleteExpr>(E, Global, /*is_array=*/false);
4556     }
4557     case 'n':
4558       return getDerived().parseUnresolvedName();
4559     case 's': {
4560       First += 2;
4561       Node *LHS = getDerived().parseExpr();
4562       if (LHS == nullptr)
4563         return nullptr;
4564       Node *RHS = getDerived().parseExpr();
4565       if (RHS == nullptr)
4566         return nullptr;
4567       return make<MemberExpr>(LHS, ".*", RHS);
4568     }
4569     case 't': {
4570       First += 2;
4571       Node *LHS = getDerived().parseExpr();
4572       if (LHS == nullptr)
4573         return LHS;
4574       Node *RHS = getDerived().parseExpr();
4575       if (RHS == nullptr)
4576         return nullptr;
4577       return make<MemberExpr>(LHS, ".", RHS);
4578     }
4579     case 'v':
4580       First += 2;
4581       return getDerived().parseBinaryExpr("/");
4582     case 'V':
4583       First += 2;
4584       return getDerived().parseBinaryExpr("/=");
4585     }
4586     return nullptr;
4587   case 'e':
4588     switch (First[1]) {
4589     case 'o':
4590       First += 2;
4591       return getDerived().parseBinaryExpr("^");
4592     case 'O':
4593       First += 2;
4594       return getDerived().parseBinaryExpr("^=");
4595     case 'q':
4596       First += 2;
4597       return getDerived().parseBinaryExpr("==");
4598     }
4599     return nullptr;
4600   case 'g':
4601     switch (First[1]) {
4602     case 'e':
4603       First += 2;
4604       return getDerived().parseBinaryExpr(">=");
4605     case 't':
4606       First += 2;
4607       return getDerived().parseBinaryExpr(">");
4608     }
4609     return nullptr;
4610   case 'i':
4611     switch (First[1]) {
4612     case 'x': {
4613       First += 2;
4614       Node *Base = getDerived().parseExpr();
4615       if (Base == nullptr)
4616         return nullptr;
4617       Node *Index = getDerived().parseExpr();
4618       if (Index == nullptr)
4619         return Index;
4620       return make<ArraySubscriptExpr>(Base, Index);
4621     }
4622     case 'l': {
4623       First += 2;
4624       size_t InitsBegin = Names.size();
4625       while (!consumeIf('E')) {
4626         Node *E = getDerived().parseBracedExpr();
4627         if (E == nullptr)
4628           return nullptr;
4629         Names.push_back(E);
4630       }
4631       return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4632     }
4633     }
4634     return nullptr;
4635   case 'l':
4636     switch (First[1]) {
4637     case 'e':
4638       First += 2;
4639       return getDerived().parseBinaryExpr("<=");
4640     case 's':
4641       First += 2;
4642       return getDerived().parseBinaryExpr("<<");
4643     case 'S':
4644       First += 2;
4645       return getDerived().parseBinaryExpr("<<=");
4646     case 't':
4647       First += 2;
4648       return getDerived().parseBinaryExpr("<");
4649     }
4650     return nullptr;
4651   case 'm':
4652     switch (First[1]) {
4653     case 'i':
4654       First += 2;
4655       return getDerived().parseBinaryExpr("-");
4656     case 'I':
4657       First += 2;
4658       return getDerived().parseBinaryExpr("-=");
4659     case 'l':
4660       First += 2;
4661       return getDerived().parseBinaryExpr("*");
4662     case 'L':
4663       First += 2;
4664       return getDerived().parseBinaryExpr("*=");
4665     case 'm':
4666       First += 2;
4667       if (consumeIf('_'))
4668         return getDerived().parsePrefixExpr("--");
4669       Node *Ex = getDerived().parseExpr();
4670       if (Ex == nullptr)
4671         return nullptr;
4672       return make<PostfixExpr>(Ex, "--");
4673     }
4674     return nullptr;
4675   case 'n':
4676     switch (First[1]) {
4677     case 'a':
4678     case 'w':
4679       return getDerived().parseNewExpr();
4680     case 'e':
4681       First += 2;
4682       return getDerived().parseBinaryExpr("!=");
4683     case 'g':
4684       First += 2;
4685       return getDerived().parsePrefixExpr("-");
4686     case 't':
4687       First += 2;
4688       return getDerived().parsePrefixExpr("!");
4689     case 'x':
4690       First += 2;
4691       Node *Ex = getDerived().parseExpr();
4692       if (Ex == nullptr)
4693         return Ex;
4694       return make<EnclosingExpr>("noexcept (", Ex, ")");
4695     }
4696     return nullptr;
4697   case 'o':
4698     switch (First[1]) {
4699     case 'n':
4700       return getDerived().parseUnresolvedName();
4701     case 'o':
4702       First += 2;
4703       return getDerived().parseBinaryExpr("||");
4704     case 'r':
4705       First += 2;
4706       return getDerived().parseBinaryExpr("|");
4707     case 'R':
4708       First += 2;
4709       return getDerived().parseBinaryExpr("|=");
4710     }
4711     return nullptr;
4712   case 'p':
4713     switch (First[1]) {
4714     case 'm':
4715       First += 2;
4716       return getDerived().parseBinaryExpr("->*");
4717     case 'l':
4718       First += 2;
4719       return getDerived().parseBinaryExpr("+");
4720     case 'L':
4721       First += 2;
4722       return getDerived().parseBinaryExpr("+=");
4723     case 'p': {
4724       First += 2;
4725       if (consumeIf('_'))
4726         return getDerived().parsePrefixExpr("++");
4727       Node *Ex = getDerived().parseExpr();
4728       if (Ex == nullptr)
4729         return Ex;
4730       return make<PostfixExpr>(Ex, "++");
4731     }
4732     case 's':
4733       First += 2;
4734       return getDerived().parsePrefixExpr("+");
4735     case 't': {
4736       First += 2;
4737       Node *L = getDerived().parseExpr();
4738       if (L == nullptr)
4739         return nullptr;
4740       Node *R = getDerived().parseExpr();
4741       if (R == nullptr)
4742         return nullptr;
4743       return make<MemberExpr>(L, "->", R);
4744     }
4745     }
4746     return nullptr;
4747   case 'q':
4748     if (First[1] == 'u') {
4749       First += 2;
4750       Node *Cond = getDerived().parseExpr();
4751       if (Cond == nullptr)
4752         return nullptr;
4753       Node *LHS = getDerived().parseExpr();
4754       if (LHS == nullptr)
4755         return nullptr;
4756       Node *RHS = getDerived().parseExpr();
4757       if (RHS == nullptr)
4758         return nullptr;
4759       return make<ConditionalExpr>(Cond, LHS, RHS);
4760     }
4761     return nullptr;
4762   case 'r':
4763     switch (First[1]) {
4764     case 'c': {
4765       First += 2;
4766       Node *T = getDerived().parseType();
4767       if (T == nullptr)
4768         return T;
4769       Node *Ex = getDerived().parseExpr();
4770       if (Ex == nullptr)
4771         return Ex;
4772       return make<CastExpr>("reinterpret_cast", T, Ex);
4773     }
4774     case 'm':
4775       First += 2;
4776       return getDerived().parseBinaryExpr("%");
4777     case 'M':
4778       First += 2;
4779       return getDerived().parseBinaryExpr("%=");
4780     case 's':
4781       First += 2;
4782       return getDerived().parseBinaryExpr(">>");
4783     case 'S':
4784       First += 2;
4785       return getDerived().parseBinaryExpr(">>=");
4786     }
4787     return nullptr;
4788   case 's':
4789     switch (First[1]) {
4790     case 'c': {
4791       First += 2;
4792       Node *T = getDerived().parseType();
4793       if (T == nullptr)
4794         return T;
4795       Node *Ex = getDerived().parseExpr();
4796       if (Ex == nullptr)
4797         return Ex;
4798       return make<CastExpr>("static_cast", T, Ex);
4799     }
4800     case 'p': {
4801       First += 2;
4802       Node *Child = getDerived().parseExpr();
4803       if (Child == nullptr)
4804         return nullptr;
4805       return make<ParameterPackExpansion>(Child);
4806     }
4807     case 'r':
4808       return getDerived().parseUnresolvedName();
4809     case 't': {
4810       First += 2;
4811       Node *Ty = getDerived().parseType();
4812       if (Ty == nullptr)
4813         return Ty;
4814       return make<EnclosingExpr>("sizeof (", Ty, ")");
4815     }
4816     case 'z': {
4817       First += 2;
4818       Node *Ex = getDerived().parseExpr();
4819       if (Ex == nullptr)
4820         return Ex;
4821       return make<EnclosingExpr>("sizeof (", Ex, ")");
4822     }
4823     case 'Z':
4824       First += 2;
4825       if (look() == 'T') {
4826         Node *R = getDerived().parseTemplateParam();
4827         if (R == nullptr)
4828           return nullptr;
4829         return make<SizeofParamPackExpr>(R);
4830       } else if (look() == 'f') {
4831         Node *FP = getDerived().parseFunctionParam();
4832         if (FP == nullptr)
4833           return nullptr;
4834         return make<EnclosingExpr>("sizeof... (", FP, ")");
4835       }
4836       return nullptr;
4837     case 'P': {
4838       First += 2;
4839       size_t ArgsBegin = Names.size();
4840       while (!consumeIf('E')) {
4841         Node *Arg = getDerived().parseTemplateArg();
4842         if (Arg == nullptr)
4843           return nullptr;
4844         Names.push_back(Arg);
4845       }
4846       auto *Pack = make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin));
4847       if (!Pack)
4848         return nullptr;
4849       return make<EnclosingExpr>("sizeof... (", Pack, ")");
4850     }
4851     }
4852     return nullptr;
4853   case 't':
4854     switch (First[1]) {
4855     case 'e': {
4856       First += 2;
4857       Node *Ex = getDerived().parseExpr();
4858       if (Ex == nullptr)
4859         return Ex;
4860       return make<EnclosingExpr>("typeid (", Ex, ")");
4861     }
4862     case 'i': {
4863       First += 2;
4864       Node *Ty = getDerived().parseType();
4865       if (Ty == nullptr)
4866         return Ty;
4867       return make<EnclosingExpr>("typeid (", Ty, ")");
4868     }
4869     case 'l': {
4870       First += 2;
4871       Node *Ty = getDerived().parseType();
4872       if (Ty == nullptr)
4873         return nullptr;
4874       size_t InitsBegin = Names.size();
4875       while (!consumeIf('E')) {
4876         Node *E = getDerived().parseBracedExpr();
4877         if (E == nullptr)
4878           return nullptr;
4879         Names.push_back(E);
4880       }
4881       return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4882     }
4883     case 'r':
4884       First += 2;
4885       return make<NameType>("throw");
4886     case 'w': {
4887       First += 2;
4888       Node *Ex = getDerived().parseExpr();
4889       if (Ex == nullptr)
4890         return nullptr;
4891       return make<ThrowExpr>(Ex);
4892     }
4893     }
4894     return nullptr;
4895   case '1':
4896   case '2':
4897   case '3':
4898   case '4':
4899   case '5':
4900   case '6':
4901   case '7':
4902   case '8':
4903   case '9':
4904     return getDerived().parseUnresolvedName();
4905   }
4906 
4907   if (consumeIf("u8__uuidoft")) {
4908     Node *Ty = getDerived().parseType();
4909     if (!Ty)
4910       return nullptr;
4911     return make<UUIDOfExpr>(Ty);
4912   }
4913 
4914   if (consumeIf("u8__uuidofz")) {
4915     Node *Ex = getDerived().parseExpr();
4916     if (!Ex)
4917       return nullptr;
4918     return make<UUIDOfExpr>(Ex);
4919   }
4920 
4921   return nullptr;
4922 }
4923 
4924 // <call-offset> ::= h <nv-offset> _
4925 //               ::= v <v-offset> _
4926 //
4927 // <nv-offset> ::= <offset number>
4928 //               # non-virtual base override
4929 //
4930 // <v-offset>  ::= <offset number> _ <virtual offset number>
4931 //               # virtual base override, with vcall offset
4932 template <typename Alloc, typename Derived>
parseCallOffset()4933 bool AbstractManglingParser<Alloc, Derived>::parseCallOffset() {
4934   // Just scan through the call offset, we never add this information into the
4935   // output.
4936   if (consumeIf('h'))
4937     return parseNumber(true).empty() || !consumeIf('_');
4938   if (consumeIf('v'))
4939     return parseNumber(true).empty() || !consumeIf('_') ||
4940            parseNumber(true).empty() || !consumeIf('_');
4941   return true;
4942 }
4943 
4944 // <special-name> ::= TV <type>    # virtual table
4945 //                ::= TT <type>    # VTT structure (construction vtable index)
4946 //                ::= TI <type>    # typeinfo structure
4947 //                ::= TS <type>    # typeinfo name (null-terminated byte string)
4948 //                ::= Tc <call-offset> <call-offset> <base encoding>
4949 //                    # base is the nominal target function of thunk
4950 //                    # first call-offset is 'this' adjustment
4951 //                    # second call-offset is result adjustment
4952 //                ::= T <call-offset> <base encoding>
4953 //                    # base is the nominal target function of thunk
4954 //                ::= GV <object name> # Guard variable for one-time initialization
4955 //                                     # No <type>
4956 //                ::= TW <object name> # Thread-local wrapper
4957 //                ::= TH <object name> # Thread-local initialization
4958 //                ::= GR <object name> _             # First temporary
4959 //                ::= GR <object name> <seq-id> _    # Subsequent temporaries
4960 //      extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4961 //      extension ::= GR <object name> # reference temporary for object
4962 template <typename Derived, typename Alloc>
parseSpecialName()4963 Node *AbstractManglingParser<Derived, Alloc>::parseSpecialName() {
4964   switch (look()) {
4965   case 'T':
4966     switch (look(1)) {
4967     // TV <type>    # virtual table
4968     case 'V': {
4969       First += 2;
4970       Node *Ty = getDerived().parseType();
4971       if (Ty == nullptr)
4972         return nullptr;
4973       return make<SpecialName>("vtable for ", Ty);
4974     }
4975     // TT <type>    # VTT structure (construction vtable index)
4976     case 'T': {
4977       First += 2;
4978       Node *Ty = getDerived().parseType();
4979       if (Ty == nullptr)
4980         return nullptr;
4981       return make<SpecialName>("VTT for ", Ty);
4982     }
4983     // TI <type>    # typeinfo structure
4984     case 'I': {
4985       First += 2;
4986       Node *Ty = getDerived().parseType();
4987       if (Ty == nullptr)
4988         return nullptr;
4989       return make<SpecialName>("typeinfo for ", Ty);
4990     }
4991     // TS <type>    # typeinfo name (null-terminated byte string)
4992     case 'S': {
4993       First += 2;
4994       Node *Ty = getDerived().parseType();
4995       if (Ty == nullptr)
4996         return nullptr;
4997       return make<SpecialName>("typeinfo name for ", Ty);
4998     }
4999     // Tc <call-offset> <call-offset> <base encoding>
5000     case 'c': {
5001       First += 2;
5002       if (parseCallOffset() || parseCallOffset())
5003         return nullptr;
5004       Node *Encoding = getDerived().parseEncoding();
5005       if (Encoding == nullptr)
5006         return nullptr;
5007       return make<SpecialName>("covariant return thunk to ", Encoding);
5008     }
5009     // extension ::= TC <first type> <number> _ <second type>
5010     //               # construction vtable for second-in-first
5011     case 'C': {
5012       First += 2;
5013       Node *FirstType = getDerived().parseType();
5014       if (FirstType == nullptr)
5015         return nullptr;
5016       if (parseNumber(true).empty() || !consumeIf('_'))
5017         return nullptr;
5018       Node *SecondType = getDerived().parseType();
5019       if (SecondType == nullptr)
5020         return nullptr;
5021       return make<CtorVtableSpecialName>(SecondType, FirstType);
5022     }
5023     // TW <object name> # Thread-local wrapper
5024     case 'W': {
5025       First += 2;
5026       Node *Name = getDerived().parseName();
5027       if (Name == nullptr)
5028         return nullptr;
5029       return make<SpecialName>("thread-local wrapper routine for ", Name);
5030     }
5031     // TH <object name> # Thread-local initialization
5032     case 'H': {
5033       First += 2;
5034       Node *Name = getDerived().parseName();
5035       if (Name == nullptr)
5036         return nullptr;
5037       return make<SpecialName>("thread-local initialization routine for ", Name);
5038     }
5039     // T <call-offset> <base encoding>
5040     default: {
5041       ++First;
5042       bool IsVirt = look() == 'v';
5043       if (parseCallOffset())
5044         return nullptr;
5045       Node *BaseEncoding = getDerived().parseEncoding();
5046       if (BaseEncoding == nullptr)
5047         return nullptr;
5048       if (IsVirt)
5049         return make<SpecialName>("virtual thunk to ", BaseEncoding);
5050       else
5051         return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
5052     }
5053     }
5054   case 'G':
5055     switch (look(1)) {
5056     // GV <object name> # Guard variable for one-time initialization
5057     case 'V': {
5058       First += 2;
5059       Node *Name = getDerived().parseName();
5060       if (Name == nullptr)
5061         return nullptr;
5062       return make<SpecialName>("guard variable for ", Name);
5063     }
5064     // GR <object name> # reference temporary for object
5065     // GR <object name> _             # First temporary
5066     // GR <object name> <seq-id> _    # Subsequent temporaries
5067     case 'R': {
5068       First += 2;
5069       Node *Name = getDerived().parseName();
5070       if (Name == nullptr)
5071         return nullptr;
5072       size_t Count;
5073       bool ParsedSeqId = !parseSeqId(&Count);
5074       if (!consumeIf('_') && ParsedSeqId)
5075         return nullptr;
5076       return make<SpecialName>("reference temporary for ", Name);
5077     }
5078     }
5079   }
5080   return nullptr;
5081 }
5082 
5083 // <encoding> ::= <function name> <bare-function-type>
5084 //            ::= <data name>
5085 //            ::= <special-name>
5086 template <typename Derived, typename Alloc>
parseEncoding()5087 Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
5088   if (look() == 'G' || look() == 'T')
5089     return getDerived().parseSpecialName();
5090 
5091   auto IsEndOfEncoding = [&] {
5092     // The set of chars that can potentially follow an <encoding> (none of which
5093     // can start a <type>). Enumerating these allows us to avoid speculative
5094     // parsing.
5095     return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
5096   };
5097 
5098   NameState NameInfo(this);
5099   Node *Name = getDerived().parseName(&NameInfo);
5100   if (Name == nullptr)
5101     return nullptr;
5102 
5103   if (resolveForwardTemplateRefs(NameInfo))
5104     return nullptr;
5105 
5106   if (IsEndOfEncoding())
5107     return Name;
5108 
5109   Node *Attrs = nullptr;
5110   if (consumeIf("Ua9enable_ifI")) {
5111     size_t BeforeArgs = Names.size();
5112     while (!consumeIf('E')) {
5113       Node *Arg = getDerived().parseTemplateArg();
5114       if (Arg == nullptr)
5115         return nullptr;
5116       Names.push_back(Arg);
5117     }
5118     Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
5119     if (!Attrs)
5120       return nullptr;
5121   }
5122 
5123   Node *ReturnType = nullptr;
5124   if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
5125     ReturnType = getDerived().parseType();
5126     if (ReturnType == nullptr)
5127       return nullptr;
5128   }
5129 
5130   if (consumeIf('v'))
5131     return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
5132                                   Attrs, NameInfo.CVQualifiers,
5133                                   NameInfo.ReferenceQualifier);
5134 
5135   size_t ParamsBegin = Names.size();
5136   do {
5137     Node *Ty = getDerived().parseType();
5138     if (Ty == nullptr)
5139       return nullptr;
5140     Names.push_back(Ty);
5141   } while (!IsEndOfEncoding());
5142 
5143   return make<FunctionEncoding>(ReturnType, Name,
5144                                 popTrailingNodeArray(ParamsBegin),
5145                                 Attrs, NameInfo.CVQualifiers,
5146                                 NameInfo.ReferenceQualifier);
5147 }
5148 
5149 template <class Float>
5150 struct FloatData;
5151 
5152 template <>
5153 struct FloatData<float>
5154 {
5155     static const size_t mangled_size = 8;
5156     static const size_t max_demangled_size = 24;
5157     static constexpr const char* spec = "%af";
5158 };
5159 
5160 template <>
5161 struct FloatData<double>
5162 {
5163     static const size_t mangled_size = 16;
5164     static const size_t max_demangled_size = 32;
5165     static constexpr const char* spec = "%a";
5166 };
5167 
5168 template <>
5169 struct FloatData<long double>
5170 {
5171 #if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
5172     defined(__wasm__)
5173     static const size_t mangled_size = 32;
5174 #elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
5175     static const size_t mangled_size = 16;
5176 #else
5177     static const size_t mangled_size = 20;  // May need to be adjusted to 16 or 24 on other platforms
5178 #endif
5179     static const size_t max_demangled_size = 40;
5180     static constexpr const char *spec = "%LaL";
5181 };
5182 
5183 template <typename Alloc, typename Derived>
5184 template <class Float>
5185 Node *AbstractManglingParser<Alloc, Derived>::parseFloatingLiteral() {
5186   const size_t N = FloatData<Float>::mangled_size;
5187   if (numLeft() <= N)
5188     return nullptr;
5189   StringView Data(First, First + N);
5190   for (char C : Data)
5191     if (!std::isxdigit(C))
5192       return nullptr;
5193   First += N;
5194   if (!consumeIf('E'))
5195     return nullptr;
5196   return make<FloatLiteralImpl<Float>>(Data);
5197 }
5198 
5199 // <seq-id> ::= <0-9A-Z>+
5200 template <typename Alloc, typename Derived>
5201 bool AbstractManglingParser<Alloc, Derived>::parseSeqId(size_t *Out) {
5202   if (!(look() >= '0' && look() <= '9') &&
5203       !(look() >= 'A' && look() <= 'Z'))
5204     return true;
5205 
5206   size_t Id = 0;
5207   while (true) {
5208     if (look() >= '0' && look() <= '9') {
5209       Id *= 36;
5210       Id += static_cast<size_t>(look() - '0');
5211     } else if (look() >= 'A' && look() <= 'Z') {
5212       Id *= 36;
5213       Id += static_cast<size_t>(look() - 'A') + 10;
5214     } else {
5215       *Out = Id;
5216       return false;
5217     }
5218     ++First;
5219   }
5220 }
5221 
5222 // <substitution> ::= S <seq-id> _
5223 //                ::= S_
5224 // <substitution> ::= Sa # ::std::allocator
5225 // <substitution> ::= Sb # ::std::basic_string
5226 // <substitution> ::= Ss # ::std::basic_string < char,
5227 //                                               ::std::char_traits<char>,
5228 //                                               ::std::allocator<char> >
5229 // <substitution> ::= Si # ::std::basic_istream<char,  std::char_traits<char> >
5230 // <substitution> ::= So # ::std::basic_ostream<char,  std::char_traits<char> >
5231 // <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
5232 template <typename Derived, typename Alloc>
5233 Node *AbstractManglingParser<Derived, Alloc>::parseSubstitution() {
5234   if (!consumeIf('S'))
5235     return nullptr;
5236 
5237   if (std::islower(look())) {
5238     Node *SpecialSub;
5239     switch (look()) {
5240     case 'a':
5241       ++First;
5242       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
5243       break;
5244     case 'b':
5245       ++First;
5246       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
5247       break;
5248     case 's':
5249       ++First;
5250       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
5251       break;
5252     case 'i':
5253       ++First;
5254       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
5255       break;
5256     case 'o':
5257       ++First;
5258       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
5259       break;
5260     case 'd':
5261       ++First;
5262       SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
5263       break;
5264     default:
5265       return nullptr;
5266     }
5267     if (!SpecialSub)
5268       return nullptr;
5269     // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
5270     // has ABI tags, the tags are appended to the substitution; the result is a
5271     // substitutable component.
5272     Node *WithTags = getDerived().parseAbiTags(SpecialSub);
5273     if (WithTags != SpecialSub) {
5274       Subs.push_back(WithTags);
5275       SpecialSub = WithTags;
5276     }
5277     return SpecialSub;
5278   }
5279 
5280   //                ::= S_
5281   if (consumeIf('_')) {
5282     if (Subs.empty())
5283       return nullptr;
5284     return Subs[0];
5285   }
5286 
5287   //                ::= S <seq-id> _
5288   size_t Index = 0;
5289   if (parseSeqId(&Index))
5290     return nullptr;
5291   ++Index;
5292   if (!consumeIf('_') || Index >= Subs.size())
5293     return nullptr;
5294   return Subs[Index];
5295 }
5296 
5297 // <template-param> ::= T_    # first template parameter
5298 //                  ::= T <parameter-2 non-negative number> _
5299 //                  ::= TL <level-1> __
5300 //                  ::= TL <level-1> _ <parameter-2 non-negative number> _
5301 template <typename Derived, typename Alloc>
5302 Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParam() {
5303   if (!consumeIf('T'))
5304     return nullptr;
5305 
5306   size_t Level = 0;
5307   if (consumeIf('L')) {
5308     if (parsePositiveInteger(&Level))
5309       return nullptr;
5310     ++Level;
5311     if (!consumeIf('_'))
5312       return nullptr;
5313   }
5314 
5315   size_t Index = 0;
5316   if (!consumeIf('_')) {
5317     if (parsePositiveInteger(&Index))
5318       return nullptr;
5319     ++Index;
5320     if (!consumeIf('_'))
5321       return nullptr;
5322   }
5323 
5324   // If we're in a context where this <template-param> refers to a
5325   // <template-arg> further ahead in the mangled name (currently just conversion
5326   // operator types), then we should only look it up in the right context.
5327   // This can only happen at the outermost level.
5328   if (PermitForwardTemplateReferences && Level == 0) {
5329     Node *ForwardRef = make<ForwardTemplateReference>(Index);
5330     if (!ForwardRef)
5331       return nullptr;
5332     assert(ForwardRef->getKind() == Node::KForwardTemplateReference);
5333     ForwardTemplateRefs.push_back(
5334         static_cast<ForwardTemplateReference *>(ForwardRef));
5335     return ForwardRef;
5336   }
5337 
5338   if (Level >= TemplateParams.size() || !TemplateParams[Level] ||
5339       Index >= TemplateParams[Level]->size()) {
5340     // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter
5341     // list are mangled as the corresponding artificial template type parameter.
5342     if (ParsingLambdaParamsAtLevel == Level && Level <= TemplateParams.size()) {
5343       // This will be popped by the ScopedTemplateParamList in
5344       // parseUnnamedTypeName.
5345       if (Level == TemplateParams.size())
5346         TemplateParams.push_back(nullptr);
5347       return make<NameType>("auto");
5348     }
5349 
5350     return nullptr;
5351   }
5352 
5353   return (*TemplateParams[Level])[Index];
5354 }
5355 
5356 // <template-param-decl> ::= Ty                          # type parameter
5357 //                       ::= Tn <type>                   # non-type parameter
5358 //                       ::= Tt <template-param-decl>* E # template parameter
5359 //                       ::= Tp <template-param-decl>    # parameter pack
5360 template <typename Derived, typename Alloc>
5361 Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParamDecl() {
5362   auto InventTemplateParamName = [&](TemplateParamKind Kind) {
5363     unsigned Index = NumSyntheticTemplateParameters[(int)Kind]++;
5364     Node *N = make<SyntheticTemplateParamName>(Kind, Index);
5365     if (N) TemplateParams.back()->push_back(N);
5366     return N;
5367   };
5368 
5369   if (consumeIf("Ty")) {
5370     Node *Name = InventTemplateParamName(TemplateParamKind::Type);
5371     if (!Name)
5372       return nullptr;
5373     return make<TypeTemplateParamDecl>(Name);
5374   }
5375 
5376   if (consumeIf("Tn")) {
5377     Node *Name = InventTemplateParamName(TemplateParamKind::NonType);
5378     if (!Name)
5379       return nullptr;
5380     Node *Type = parseType();
5381     if (!Type)
5382       return nullptr;
5383     return make<NonTypeTemplateParamDecl>(Name, Type);
5384   }
5385 
5386   if (consumeIf("Tt")) {
5387     Node *Name = InventTemplateParamName(TemplateParamKind::Template);
5388     if (!Name)
5389       return nullptr;
5390     size_t ParamsBegin = Names.size();
5391     ScopedTemplateParamList TemplateTemplateParamParams(this);
5392     while (!consumeIf("E")) {
5393       Node *P = parseTemplateParamDecl();
5394       if (!P)
5395         return nullptr;
5396       Names.push_back(P);
5397     }
5398     NodeArray Params = popTrailingNodeArray(ParamsBegin);
5399     return make<TemplateTemplateParamDecl>(Name, Params);
5400   }
5401 
5402   if (consumeIf("Tp")) {
5403     Node *P = parseTemplateParamDecl();
5404     if (!P)
5405       return nullptr;
5406     return make<TemplateParamPackDecl>(P);
5407   }
5408 
5409   return nullptr;
5410 }
5411 
5412 // <template-arg> ::= <type>                    # type or template
5413 //                ::= X <expression> E          # expression
5414 //                ::= <expr-primary>            # simple expressions
5415 //                ::= J <template-arg>* E       # argument pack
5416 //                ::= LZ <encoding> E           # extension
5417 template <typename Derived, typename Alloc>
5418 Node *AbstractManglingParser<Derived, Alloc>::parseTemplateArg() {
5419   switch (look()) {
5420   case 'X': {
5421     ++First;
5422     Node *Arg = getDerived().parseExpr();
5423     if (Arg == nullptr || !consumeIf('E'))
5424       return nullptr;
5425     return Arg;
5426   }
5427   case 'J': {
5428     ++First;
5429     size_t ArgsBegin = Names.size();
5430     while (!consumeIf('E')) {
5431       Node *Arg = getDerived().parseTemplateArg();
5432       if (Arg == nullptr)
5433         return nullptr;
5434       Names.push_back(Arg);
5435     }
5436     NodeArray Args = popTrailingNodeArray(ArgsBegin);
5437     return make<TemplateArgumentPack>(Args);
5438   }
5439   case 'L': {
5440     //                ::= LZ <encoding> E           # extension
5441     if (look(1) == 'Z') {
5442       First += 2;
5443       Node *Arg = getDerived().parseEncoding();
5444       if (Arg == nullptr || !consumeIf('E'))
5445         return nullptr;
5446       return Arg;
5447     }
5448     //                ::= <expr-primary>            # simple expressions
5449     return getDerived().parseExprPrimary();
5450   }
5451   default:
5452     return getDerived().parseType();
5453   }
5454 }
5455 
5456 // <template-args> ::= I <template-arg>* E
5457 //     extension, the abi says <template-arg>+
5458 template <typename Derived, typename Alloc>
5459 Node *
5460 AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
5461   if (!consumeIf('I'))
5462     return nullptr;
5463 
5464   // <template-params> refer to the innermost <template-args>. Clear out any
5465   // outer args that we may have inserted into TemplateParams.
5466   if (TagTemplates) {
5467     TemplateParams.clear();
5468     TemplateParams.push_back(&OuterTemplateParams);
5469     OuterTemplateParams.clear();
5470   }
5471 
5472   size_t ArgsBegin = Names.size();
5473   while (!consumeIf('E')) {
5474     if (TagTemplates) {
5475       auto OldParams = std::move(TemplateParams);
5476       Node *Arg = getDerived().parseTemplateArg();
5477       TemplateParams = std::move(OldParams);
5478       if (Arg == nullptr)
5479         return nullptr;
5480       Names.push_back(Arg);
5481       Node *TableEntry = Arg;
5482       if (Arg->getKind() == Node::KTemplateArgumentPack) {
5483         TableEntry = make<ParameterPack>(
5484             static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
5485         if (!TableEntry)
5486           return nullptr;
5487       }
5488       TemplateParams.back()->push_back(TableEntry);
5489     } else {
5490       Node *Arg = getDerived().parseTemplateArg();
5491       if (Arg == nullptr)
5492         return nullptr;
5493       Names.push_back(Arg);
5494     }
5495   }
5496   return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
5497 }
5498 
5499 // <mangled-name> ::= _Z <encoding>
5500 //                ::= <type>
5501 // extension      ::= ___Z <encoding> _block_invoke
5502 // extension      ::= ___Z <encoding> _block_invoke<decimal-digit>+
5503 // extension      ::= ___Z <encoding> _block_invoke_<decimal-digit>+
5504 template <typename Derived, typename Alloc>
5505 Node *AbstractManglingParser<Derived, Alloc>::parse() {
5506   if (consumeIf("_Z") || consumeIf("__Z")) {
5507     Node *Encoding = getDerived().parseEncoding();
5508     if (Encoding == nullptr)
5509       return nullptr;
5510     if (look() == '.') {
5511       Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
5512       First = Last;
5513     }
5514     if (numLeft() != 0)
5515       return nullptr;
5516     return Encoding;
5517   }
5518 
5519   if (consumeIf("___Z") || consumeIf("____Z")) {
5520     Node *Encoding = getDerived().parseEncoding();
5521     if (Encoding == nullptr || !consumeIf("_block_invoke"))
5522       return nullptr;
5523     bool RequireNumber = consumeIf('_');
5524     if (parseNumber().empty() && RequireNumber)
5525       return nullptr;
5526     if (look() == '.')
5527       First = Last;
5528     if (numLeft() != 0)
5529       return nullptr;
5530     return make<SpecialName>("invocation function for block in ", Encoding);
5531   }
5532 
5533   Node *Ty = getDerived().parseType();
5534   if (numLeft() != 0)
5535     return nullptr;
5536   return Ty;
5537 }
5538 
5539 template <typename Alloc>
5540 struct ManglingParser : AbstractManglingParser<ManglingParser<Alloc>, Alloc> {
5541   using AbstractManglingParser<ManglingParser<Alloc>,
5542                                Alloc>::AbstractManglingParser;
5543 };
5544 
5545 DEMANGLE_NAMESPACE_END
5546 
5547 #endif // DEMANGLE_ITANIUMDEMANGLE_H
5548