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