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