blob: edba17d396b02b08b37353f6dd8db965ab375bcf [file] [log] [blame]
Richard Smithc20d1442018-08-20 20:14:49 +00001//===------------------------- ItaniumDemangle.h ----------------*- C++ -*-===//
2//
Chandler Carruth8ee27c32019-01-19 10:56:40 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Richard Smithc20d1442018-08-20 20:14:49 +00006//
7//===----------------------------------------------------------------------===//
8//
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00009// Generic itanium demangler library. This file has two byte-per-byte identical
10// copies in the source tree, one in libcxxabi, and the other in llvm.
Richard Smithc20d1442018-08-20 20:14:49 +000011//
12//===----------------------------------------------------------------------===//
13
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +000014#ifndef DEMANGLE_ITANIUMDEMANGLE_H
15#define DEMANGLE_ITANIUMDEMANGLE_H
Richard Smithc20d1442018-08-20 20:14:49 +000016
17// FIXME: (possibly) incomplete list of features that clang mangles that this
18// file does not yet support:
19// - C++ modules TS
20
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +000021#include "DemangleConfig.h"
Richard Smithc20d1442018-08-20 20:14:49 +000022#include "StringView.h"
23#include "Utility.h"
Richard Smithc20d1442018-08-20 20:14:49 +000024#include <cassert>
25#include <cctype>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29#include <numeric>
30#include <utility>
31
32#define FOR_EACH_NODE_KIND(X) \
33 X(NodeArrayNode) \
34 X(DotSuffix) \
35 X(VendorExtQualType) \
36 X(QualType) \
37 X(ConversionOperatorType) \
38 X(PostfixQualifiedType) \
39 X(ElaboratedTypeSpefType) \
40 X(NameType) \
41 X(AbiTagAttr) \
42 X(EnableIfAttr) \
43 X(ObjCProtoName) \
44 X(PointerType) \
45 X(ReferenceType) \
46 X(PointerToMemberType) \
47 X(ArrayType) \
48 X(FunctionType) \
49 X(NoexceptSpec) \
50 X(DynamicExceptionSpec) \
51 X(FunctionEncoding) \
52 X(LiteralOperator) \
53 X(SpecialName) \
54 X(CtorVtableSpecialName) \
55 X(QualifiedName) \
56 X(NestedName) \
57 X(LocalName) \
58 X(VectorType) \
59 X(PixelVectorType) \
Richard Smithdf1c14c2019-09-06 23:53:21 +000060 X(SyntheticTemplateParamName) \
61 X(TypeTemplateParamDecl) \
62 X(NonTypeTemplateParamDecl) \
63 X(TemplateTemplateParamDecl) \
64 X(TemplateParamPackDecl) \
Richard Smithc20d1442018-08-20 20:14:49 +000065 X(ParameterPack) \
66 X(TemplateArgumentPack) \
67 X(ParameterPackExpansion) \
68 X(TemplateArgs) \
69 X(ForwardTemplateReference) \
70 X(NameWithTemplateArgs) \
71 X(GlobalQualifiedName) \
72 X(StdQualifiedName) \
73 X(ExpandedSpecialSubstitution) \
74 X(SpecialSubstitution) \
75 X(CtorDtorName) \
76 X(DtorName) \
77 X(UnnamedTypeName) \
78 X(ClosureTypeName) \
79 X(StructuredBindingName) \
80 X(BinaryExpr) \
81 X(ArraySubscriptExpr) \
82 X(PostfixExpr) \
83 X(ConditionalExpr) \
84 X(MemberExpr) \
85 X(EnclosingExpr) \
86 X(CastExpr) \
87 X(SizeofParamPackExpr) \
88 X(CallExpr) \
89 X(NewExpr) \
90 X(DeleteExpr) \
91 X(PrefixExpr) \
92 X(FunctionParam) \
93 X(ConversionExpr) \
94 X(InitListExpr) \
95 X(FoldExpr) \
96 X(ThrowExpr) \
Erik Pilkingtone8457c62019-06-18 23:34:09 +000097 X(UUIDOfExpr) \
Richard Smithc20d1442018-08-20 20:14:49 +000098 X(BoolExpr) \
Richard Smithdf1c14c2019-09-06 23:53:21 +000099 X(StringLiteral) \
100 X(LambdaExpr) \
Richard Smithc20d1442018-08-20 20:14:49 +0000101 X(IntegerCastExpr) \
102 X(IntegerLiteral) \
103 X(FloatLiteral) \
104 X(DoubleLiteral) \
105 X(LongDoubleLiteral) \
106 X(BracedExpr) \
107 X(BracedRangeExpr)
108
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +0000109DEMANGLE_NAMESPACE_BEGIN
110
Richard Smithc20d1442018-08-20 20:14:49 +0000111// Base class of all AST nodes. The AST is built by the parser, then is
112// traversed by the printLeft/Right functions to produce a demangled string.
113class Node {
114public:
115 enum Kind : unsigned char {
116#define ENUMERATOR(NodeKind) K ## NodeKind,
117 FOR_EACH_NODE_KIND(ENUMERATOR)
118#undef ENUMERATOR
119 };
120
121 /// Three-way bool to track a cached value. Unknown is possible if this node
122 /// has an unexpanded parameter pack below it that may affect this cache.
123 enum class Cache : unsigned char { Yes, No, Unknown, };
124
125private:
126 Kind K;
127
128 // FIXME: Make these protected.
129public:
130 /// Tracks if this node has a component on its right side, in which case we
131 /// need to call printRight.
132 Cache RHSComponentCache;
133
134 /// Track if this node is a (possibly qualified) array type. This can affect
135 /// how we format the output string.
136 Cache ArrayCache;
137
138 /// Track if this node is a (possibly qualified) function type. This can
139 /// affect how we format the output string.
140 Cache FunctionCache;
141
142public:
143 Node(Kind K_, Cache RHSComponentCache_ = Cache::No,
144 Cache ArrayCache_ = Cache::No, Cache FunctionCache_ = Cache::No)
145 : K(K_), RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
146 FunctionCache(FunctionCache_) {}
147
148 /// Visit the most-derived object corresponding to this object.
149 template<typename Fn> void visit(Fn F) const;
150
151 // The following function is provided by all derived classes:
152 //
153 // Call F with arguments that, when passed to the constructor of this node,
154 // would construct an equivalent node.
155 //template<typename Fn> void match(Fn F) const;
156
157 bool hasRHSComponent(OutputStream &S) const {
158 if (RHSComponentCache != Cache::Unknown)
159 return RHSComponentCache == Cache::Yes;
160 return hasRHSComponentSlow(S);
161 }
162
163 bool hasArray(OutputStream &S) const {
164 if (ArrayCache != Cache::Unknown)
165 return ArrayCache == Cache::Yes;
166 return hasArraySlow(S);
167 }
168
169 bool hasFunction(OutputStream &S) const {
170 if (FunctionCache != Cache::Unknown)
171 return FunctionCache == Cache::Yes;
172 return hasFunctionSlow(S);
173 }
174
175 Kind getKind() const { return K; }
176
177 virtual bool hasRHSComponentSlow(OutputStream &) const { return false; }
178 virtual bool hasArraySlow(OutputStream &) const { return false; }
179 virtual bool hasFunctionSlow(OutputStream &) const { return false; }
180
181 // Dig through "glue" nodes like ParameterPack and ForwardTemplateReference to
182 // get at a node that actually represents some concrete syntax.
183 virtual const Node *getSyntaxNode(OutputStream &) const {
184 return this;
185 }
186
187 void print(OutputStream &S) const {
188 printLeft(S);
189 if (RHSComponentCache != Cache::No)
190 printRight(S);
191 }
192
193 // Print the "left" side of this Node into OutputStream.
194 virtual void printLeft(OutputStream &) const = 0;
195
196 // Print the "right". This distinction is necessary to represent C++ types
197 // that appear on the RHS of their subtype, such as arrays or functions.
198 // Since most types don't have such a component, provide a default
199 // implementation.
200 virtual void printRight(OutputStream &) const {}
201
202 virtual StringView getBaseName() const { return StringView(); }
203
204 // Silence compiler warnings, this dtor will never be called.
205 virtual ~Node() = default;
206
207#ifndef NDEBUG
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +0000208 DEMANGLE_DUMP_METHOD void dump() const;
Richard Smithc20d1442018-08-20 20:14:49 +0000209#endif
210};
211
212class NodeArray {
213 Node **Elements;
214 size_t NumElements;
215
216public:
217 NodeArray() : Elements(nullptr), NumElements(0) {}
218 NodeArray(Node **Elements_, size_t NumElements_)
219 : Elements(Elements_), NumElements(NumElements_) {}
220
221 bool empty() const { return NumElements == 0; }
222 size_t size() const { return NumElements; }
223
224 Node **begin() const { return Elements; }
225 Node **end() const { return Elements + NumElements; }
226
227 Node *operator[](size_t Idx) const { return Elements[Idx]; }
228
229 void printWithComma(OutputStream &S) const {
230 bool FirstElement = true;
231 for (size_t Idx = 0; Idx != NumElements; ++Idx) {
232 size_t BeforeComma = S.getCurrentPosition();
233 if (!FirstElement)
234 S += ", ";
235 size_t AfterComma = S.getCurrentPosition();
236 Elements[Idx]->print(S);
237
238 // Elements[Idx] is an empty parameter pack expansion, we should erase the
239 // comma we just printed.
240 if (AfterComma == S.getCurrentPosition()) {
241 S.setCurrentPosition(BeforeComma);
242 continue;
243 }
244
245 FirstElement = false;
246 }
247 }
248};
249
250struct NodeArrayNode : Node {
251 NodeArray Array;
252 NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
253
254 template<typename Fn> void match(Fn F) const { F(Array); }
255
256 void printLeft(OutputStream &S) const override {
257 Array.printWithComma(S);
258 }
259};
260
261class DotSuffix final : public Node {
262 const Node *Prefix;
263 const StringView Suffix;
264
265public:
266 DotSuffix(const Node *Prefix_, StringView Suffix_)
267 : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
268
269 template<typename Fn> void match(Fn F) const { F(Prefix, Suffix); }
270
271 void printLeft(OutputStream &s) const override {
272 Prefix->print(s);
273 s += " (";
274 s += Suffix;
275 s += ")";
276 }
277};
278
279class VendorExtQualType final : public Node {
280 const Node *Ty;
281 StringView Ext;
282
283public:
284 VendorExtQualType(const Node *Ty_, StringView Ext_)
285 : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_) {}
286
287 template<typename Fn> void match(Fn F) const { F(Ty, Ext); }
288
289 void printLeft(OutputStream &S) const override {
290 Ty->print(S);
291 S += " ";
292 S += Ext;
293 }
294};
295
296enum FunctionRefQual : unsigned char {
297 FrefQualNone,
298 FrefQualLValue,
299 FrefQualRValue,
300};
301
302enum Qualifiers {
303 QualNone = 0,
304 QualConst = 0x1,
305 QualVolatile = 0x2,
306 QualRestrict = 0x4,
307};
308
309inline Qualifiers operator|=(Qualifiers &Q1, Qualifiers Q2) {
310 return Q1 = static_cast<Qualifiers>(Q1 | Q2);
311}
312
Richard Smithdf1c14c2019-09-06 23:53:21 +0000313class QualType final : public Node {
Richard Smithc20d1442018-08-20 20:14:49 +0000314protected:
315 const Qualifiers Quals;
316 const Node *Child;
317
318 void printQuals(OutputStream &S) const {
319 if (Quals & QualConst)
320 S += " const";
321 if (Quals & QualVolatile)
322 S += " volatile";
323 if (Quals & QualRestrict)
324 S += " restrict";
325 }
326
327public:
328 QualType(const Node *Child_, Qualifiers Quals_)
329 : Node(KQualType, Child_->RHSComponentCache,
330 Child_->ArrayCache, Child_->FunctionCache),
331 Quals(Quals_), Child(Child_) {}
332
333 template<typename Fn> void match(Fn F) const { F(Child, Quals); }
334
335 bool hasRHSComponentSlow(OutputStream &S) const override {
336 return Child->hasRHSComponent(S);
337 }
338 bool hasArraySlow(OutputStream &S) const override {
339 return Child->hasArray(S);
340 }
341 bool hasFunctionSlow(OutputStream &S) const override {
342 return Child->hasFunction(S);
343 }
344
345 void printLeft(OutputStream &S) const override {
346 Child->printLeft(S);
347 printQuals(S);
348 }
349
350 void printRight(OutputStream &S) const override { Child->printRight(S); }
351};
352
353class ConversionOperatorType final : public Node {
354 const Node *Ty;
355
356public:
357 ConversionOperatorType(const Node *Ty_)
358 : Node(KConversionOperatorType), Ty(Ty_) {}
359
360 template<typename Fn> void match(Fn F) const { F(Ty); }
361
362 void printLeft(OutputStream &S) const override {
363 S += "operator ";
364 Ty->print(S);
365 }
366};
367
368class PostfixQualifiedType final : public Node {
369 const Node *Ty;
370 const StringView Postfix;
371
372public:
373 PostfixQualifiedType(Node *Ty_, StringView Postfix_)
374 : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
375
376 template<typename Fn> void match(Fn F) const { F(Ty, Postfix); }
377
378 void printLeft(OutputStream &s) const override {
379 Ty->printLeft(s);
380 s += Postfix;
381 }
382};
383
384class NameType final : public Node {
385 const StringView Name;
386
387public:
388 NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
389
390 template<typename Fn> void match(Fn F) const { F(Name); }
391
392 StringView getName() const { return Name; }
393 StringView getBaseName() const override { return Name; }
394
395 void printLeft(OutputStream &s) const override { s += Name; }
396};
397
398class ElaboratedTypeSpefType : public Node {
399 StringView Kind;
400 Node *Child;
401public:
402 ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
403 : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
404
405 template<typename Fn> void match(Fn F) const { F(Kind, Child); }
406
407 void printLeft(OutputStream &S) const override {
408 S += Kind;
409 S += ' ';
410 Child->print(S);
411 }
412};
413
414struct AbiTagAttr : Node {
415 Node *Base;
416 StringView Tag;
417
418 AbiTagAttr(Node* Base_, StringView Tag_)
419 : Node(KAbiTagAttr, Base_->RHSComponentCache,
420 Base_->ArrayCache, Base_->FunctionCache),
421 Base(Base_), Tag(Tag_) {}
422
423 template<typename Fn> void match(Fn F) const { F(Base, Tag); }
424
425 void printLeft(OutputStream &S) const override {
426 Base->printLeft(S);
427 S += "[abi:";
428 S += Tag;
429 S += "]";
430 }
431};
432
433class EnableIfAttr : public Node {
434 NodeArray Conditions;
435public:
436 EnableIfAttr(NodeArray Conditions_)
437 : Node(KEnableIfAttr), Conditions(Conditions_) {}
438
439 template<typename Fn> void match(Fn F) const { F(Conditions); }
440
441 void printLeft(OutputStream &S) const override {
442 S += " [enable_if:";
443 Conditions.printWithComma(S);
444 S += ']';
445 }
446};
447
448class ObjCProtoName : public Node {
449 const Node *Ty;
450 StringView Protocol;
451
452 friend class PointerType;
453
454public:
455 ObjCProtoName(const Node *Ty_, StringView Protocol_)
456 : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
457
458 template<typename Fn> void match(Fn F) const { F(Ty, Protocol); }
459
460 bool isObjCObject() const {
461 return Ty->getKind() == KNameType &&
462 static_cast<const NameType *>(Ty)->getName() == "objc_object";
463 }
464
465 void printLeft(OutputStream &S) const override {
466 Ty->print(S);
467 S += "<";
468 S += Protocol;
469 S += ">";
470 }
471};
472
473class PointerType final : public Node {
474 const Node *Pointee;
475
476public:
477 PointerType(const Node *Pointee_)
478 : Node(KPointerType, Pointee_->RHSComponentCache),
479 Pointee(Pointee_) {}
480
481 template<typename Fn> void match(Fn F) const { F(Pointee); }
482
483 bool hasRHSComponentSlow(OutputStream &S) const override {
484 return Pointee->hasRHSComponent(S);
485 }
486
487 void printLeft(OutputStream &s) const override {
488 // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
489 if (Pointee->getKind() != KObjCProtoName ||
490 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
491 Pointee->printLeft(s);
492 if (Pointee->hasArray(s))
493 s += " ";
494 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
495 s += "(";
496 s += "*";
497 } else {
498 const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
499 s += "id<";
500 s += objcProto->Protocol;
501 s += ">";
502 }
503 }
504
505 void printRight(OutputStream &s) const override {
506 if (Pointee->getKind() != KObjCProtoName ||
507 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
508 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
509 s += ")";
510 Pointee->printRight(s);
511 }
512 }
513};
514
515enum class ReferenceKind {
516 LValue,
517 RValue,
518};
519
520// Represents either a LValue or an RValue reference type.
521class ReferenceType : public Node {
522 const Node *Pointee;
523 ReferenceKind RK;
524
525 mutable bool Printing = false;
526
527 // Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
528 // rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
529 // other combination collapses to a lvalue ref.
530 std::pair<ReferenceKind, const Node *> collapse(OutputStream &S) const {
531 auto SoFar = std::make_pair(RK, Pointee);
532 for (;;) {
533 const Node *SN = SoFar.second->getSyntaxNode(S);
534 if (SN->getKind() != KReferenceType)
535 break;
536 auto *RT = static_cast<const ReferenceType *>(SN);
537 SoFar.second = RT->Pointee;
538 SoFar.first = std::min(SoFar.first, RT->RK);
539 }
540 return SoFar;
541 }
542
543public:
544 ReferenceType(const Node *Pointee_, ReferenceKind RK_)
545 : Node(KReferenceType, Pointee_->RHSComponentCache),
546 Pointee(Pointee_), RK(RK_) {}
547
548 template<typename Fn> void match(Fn F) const { F(Pointee, RK); }
549
550 bool hasRHSComponentSlow(OutputStream &S) const override {
551 return Pointee->hasRHSComponent(S);
552 }
553
554 void printLeft(OutputStream &s) const override {
555 if (Printing)
556 return;
557 SwapAndRestore<bool> SavePrinting(Printing, true);
558 std::pair<ReferenceKind, const Node *> Collapsed = collapse(s);
559 Collapsed.second->printLeft(s);
560 if (Collapsed.second->hasArray(s))
561 s += " ";
562 if (Collapsed.second->hasArray(s) || Collapsed.second->hasFunction(s))
563 s += "(";
564
565 s += (Collapsed.first == ReferenceKind::LValue ? "&" : "&&");
566 }
567 void printRight(OutputStream &s) const override {
568 if (Printing)
569 return;
570 SwapAndRestore<bool> SavePrinting(Printing, true);
571 std::pair<ReferenceKind, const Node *> Collapsed = collapse(s);
572 if (Collapsed.second->hasArray(s) || Collapsed.second->hasFunction(s))
573 s += ")";
574 Collapsed.second->printRight(s);
575 }
576};
577
578class PointerToMemberType final : public Node {
579 const Node *ClassType;
580 const Node *MemberType;
581
582public:
583 PointerToMemberType(const Node *ClassType_, const Node *MemberType_)
584 : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
585 ClassType(ClassType_), MemberType(MemberType_) {}
586
587 template<typename Fn> void match(Fn F) const { F(ClassType, MemberType); }
588
589 bool hasRHSComponentSlow(OutputStream &S) const override {
590 return MemberType->hasRHSComponent(S);
591 }
592
593 void printLeft(OutputStream &s) const override {
594 MemberType->printLeft(s);
595 if (MemberType->hasArray(s) || MemberType->hasFunction(s))
596 s += "(";
597 else
598 s += " ";
599 ClassType->print(s);
600 s += "::*";
601 }
602
603 void printRight(OutputStream &s) const override {
604 if (MemberType->hasArray(s) || MemberType->hasFunction(s))
605 s += ")";
606 MemberType->printRight(s);
607 }
608};
609
610class NodeOrString {
611 const void *First;
612 const void *Second;
613
614public:
615 /* implicit */ NodeOrString(StringView Str) {
616 const char *FirstChar = Str.begin();
617 const char *SecondChar = Str.end();
618 if (SecondChar == nullptr) {
619 assert(FirstChar == SecondChar);
620 ++FirstChar, ++SecondChar;
621 }
622 First = static_cast<const void *>(FirstChar);
623 Second = static_cast<const void *>(SecondChar);
624 }
625
626 /* implicit */ NodeOrString(Node *N)
627 : First(static_cast<const void *>(N)), Second(nullptr) {}
628 NodeOrString() : First(nullptr), Second(nullptr) {}
629
630 bool isString() const { return Second && First; }
631 bool isNode() const { return First && !Second; }
632 bool isEmpty() const { return !First && !Second; }
633
634 StringView asString() const {
635 assert(isString());
636 return StringView(static_cast<const char *>(First),
637 static_cast<const char *>(Second));
638 }
639
640 const Node *asNode() const {
641 assert(isNode());
642 return static_cast<const Node *>(First);
643 }
644};
645
646class ArrayType final : public Node {
647 const Node *Base;
648 NodeOrString Dimension;
649
650public:
Pavel Labathf4e67eb2018-10-10 08:39:16 +0000651 ArrayType(const Node *Base_, NodeOrString Dimension_)
Richard Smithc20d1442018-08-20 20:14:49 +0000652 : Node(KArrayType,
653 /*RHSComponentCache=*/Cache::Yes,
654 /*ArrayCache=*/Cache::Yes),
655 Base(Base_), Dimension(Dimension_) {}
656
657 template<typename Fn> void match(Fn F) const { F(Base, Dimension); }
658
659 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
660 bool hasArraySlow(OutputStream &) const override { return true; }
661
662 void printLeft(OutputStream &S) const override { Base->printLeft(S); }
663
664 void printRight(OutputStream &S) const override {
665 if (S.back() != ']')
666 S += " ";
667 S += "[";
668 if (Dimension.isString())
669 S += Dimension.asString();
670 else if (Dimension.isNode())
671 Dimension.asNode()->print(S);
672 S += "]";
673 Base->printRight(S);
674 }
675};
676
677class FunctionType final : public Node {
678 const Node *Ret;
679 NodeArray Params;
680 Qualifiers CVQuals;
681 FunctionRefQual RefQual;
682 const Node *ExceptionSpec;
683
684public:
685 FunctionType(const Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
686 FunctionRefQual RefQual_, const Node *ExceptionSpec_)
687 : Node(KFunctionType,
688 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
689 /*FunctionCache=*/Cache::Yes),
690 Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
691 ExceptionSpec(ExceptionSpec_) {}
692
693 template<typename Fn> void match(Fn F) const {
694 F(Ret, Params, CVQuals, RefQual, ExceptionSpec);
695 }
696
697 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
698 bool hasFunctionSlow(OutputStream &) const override { return true; }
699
700 // Handle C++'s ... quirky decl grammar by using the left & right
701 // distinction. Consider:
702 // int (*f(float))(char) {}
703 // f is a function that takes a float and returns a pointer to a function
704 // that takes a char and returns an int. If we're trying to print f, start
705 // by printing out the return types's left, then print our parameters, then
706 // finally print right of the return type.
707 void printLeft(OutputStream &S) const override {
708 Ret->printLeft(S);
709 S += " ";
710 }
711
712 void printRight(OutputStream &S) const override {
713 S += "(";
714 Params.printWithComma(S);
715 S += ")";
716 Ret->printRight(S);
717
718 if (CVQuals & QualConst)
719 S += " const";
720 if (CVQuals & QualVolatile)
721 S += " volatile";
722 if (CVQuals & QualRestrict)
723 S += " restrict";
724
725 if (RefQual == FrefQualLValue)
726 S += " &";
727 else if (RefQual == FrefQualRValue)
728 S += " &&";
729
730 if (ExceptionSpec != nullptr) {
731 S += ' ';
732 ExceptionSpec->print(S);
733 }
734 }
735};
736
737class NoexceptSpec : public Node {
738 const Node *E;
739public:
740 NoexceptSpec(const Node *E_) : Node(KNoexceptSpec), E(E_) {}
741
742 template<typename Fn> void match(Fn F) const { F(E); }
743
744 void printLeft(OutputStream &S) const override {
745 S += "noexcept(";
746 E->print(S);
747 S += ")";
748 }
749};
750
751class DynamicExceptionSpec : public Node {
752 NodeArray Types;
753public:
754 DynamicExceptionSpec(NodeArray Types_)
755 : Node(KDynamicExceptionSpec), Types(Types_) {}
756
757 template<typename Fn> void match(Fn F) const { F(Types); }
758
759 void printLeft(OutputStream &S) const override {
760 S += "throw(";
761 Types.printWithComma(S);
762 S += ')';
763 }
764};
765
766class FunctionEncoding final : public Node {
767 const Node *Ret;
768 const Node *Name;
769 NodeArray Params;
770 const Node *Attrs;
771 Qualifiers CVQuals;
772 FunctionRefQual RefQual;
773
774public:
775 FunctionEncoding(const Node *Ret_, const Node *Name_, NodeArray Params_,
776 const Node *Attrs_, Qualifiers CVQuals_,
777 FunctionRefQual RefQual_)
778 : Node(KFunctionEncoding,
779 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
780 /*FunctionCache=*/Cache::Yes),
781 Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
782 CVQuals(CVQuals_), RefQual(RefQual_) {}
783
784 template<typename Fn> void match(Fn F) const {
785 F(Ret, Name, Params, Attrs, CVQuals, RefQual);
786 }
787
788 Qualifiers getCVQuals() const { return CVQuals; }
789 FunctionRefQual getRefQual() const { return RefQual; }
790 NodeArray getParams() const { return Params; }
791 const Node *getReturnType() const { return Ret; }
792
793 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
794 bool hasFunctionSlow(OutputStream &) const override { return true; }
795
796 const Node *getName() const { return Name; }
797
798 void printLeft(OutputStream &S) const override {
799 if (Ret) {
800 Ret->printLeft(S);
801 if (!Ret->hasRHSComponent(S))
802 S += " ";
803 }
804 Name->print(S);
805 }
806
807 void printRight(OutputStream &S) const override {
808 S += "(";
809 Params.printWithComma(S);
810 S += ")";
811 if (Ret)
812 Ret->printRight(S);
813
814 if (CVQuals & QualConst)
815 S += " const";
816 if (CVQuals & QualVolatile)
817 S += " volatile";
818 if (CVQuals & QualRestrict)
819 S += " restrict";
820
821 if (RefQual == FrefQualLValue)
822 S += " &";
823 else if (RefQual == FrefQualRValue)
824 S += " &&";
825
826 if (Attrs != nullptr)
827 Attrs->print(S);
828 }
829};
830
831class LiteralOperator : public Node {
832 const Node *OpName;
833
834public:
835 LiteralOperator(const Node *OpName_)
836 : Node(KLiteralOperator), OpName(OpName_) {}
837
838 template<typename Fn> void match(Fn F) const { F(OpName); }
839
840 void printLeft(OutputStream &S) const override {
841 S += "operator\"\" ";
842 OpName->print(S);
843 }
844};
845
846class SpecialName final : public Node {
847 const StringView Special;
848 const Node *Child;
849
850public:
851 SpecialName(StringView Special_, const Node *Child_)
852 : Node(KSpecialName), Special(Special_), Child(Child_) {}
853
854 template<typename Fn> void match(Fn F) const { F(Special, Child); }
855
856 void printLeft(OutputStream &S) const override {
857 S += Special;
858 Child->print(S);
859 }
860};
861
862class CtorVtableSpecialName final : public Node {
863 const Node *FirstType;
864 const Node *SecondType;
865
866public:
867 CtorVtableSpecialName(const Node *FirstType_, const Node *SecondType_)
868 : Node(KCtorVtableSpecialName),
869 FirstType(FirstType_), SecondType(SecondType_) {}
870
871 template<typename Fn> void match(Fn F) const { F(FirstType, SecondType); }
872
873 void printLeft(OutputStream &S) const override {
874 S += "construction vtable for ";
875 FirstType->print(S);
876 S += "-in-";
877 SecondType->print(S);
878 }
879};
880
881struct NestedName : Node {
882 Node *Qual;
883 Node *Name;
884
885 NestedName(Node *Qual_, Node *Name_)
886 : Node(KNestedName), Qual(Qual_), Name(Name_) {}
887
888 template<typename Fn> void match(Fn F) const { F(Qual, Name); }
889
890 StringView getBaseName() const override { return Name->getBaseName(); }
891
892 void printLeft(OutputStream &S) const override {
893 Qual->print(S);
894 S += "::";
895 Name->print(S);
896 }
897};
898
899struct LocalName : Node {
900 Node *Encoding;
901 Node *Entity;
902
903 LocalName(Node *Encoding_, Node *Entity_)
904 : Node(KLocalName), Encoding(Encoding_), Entity(Entity_) {}
905
906 template<typename Fn> void match(Fn F) const { F(Encoding, Entity); }
907
908 void printLeft(OutputStream &S) const override {
909 Encoding->print(S);
910 S += "::";
911 Entity->print(S);
912 }
913};
914
915class QualifiedName final : public Node {
916 // qualifier::name
917 const Node *Qualifier;
918 const Node *Name;
919
920public:
921 QualifiedName(const Node *Qualifier_, const Node *Name_)
922 : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
923
924 template<typename Fn> void match(Fn F) const { F(Qualifier, Name); }
925
926 StringView getBaseName() const override { return Name->getBaseName(); }
927
928 void printLeft(OutputStream &S) const override {
929 Qualifier->print(S);
930 S += "::";
931 Name->print(S);
932 }
933};
934
935class VectorType final : public Node {
936 const Node *BaseType;
937 const NodeOrString Dimension;
938
939public:
940 VectorType(const Node *BaseType_, NodeOrString Dimension_)
941 : Node(KVectorType), BaseType(BaseType_),
942 Dimension(Dimension_) {}
943
944 template<typename Fn> void match(Fn F) const { F(BaseType, Dimension); }
945
946 void printLeft(OutputStream &S) const override {
947 BaseType->print(S);
948 S += " vector[";
949 if (Dimension.isNode())
950 Dimension.asNode()->print(S);
951 else if (Dimension.isString())
952 S += Dimension.asString();
953 S += "]";
954 }
955};
956
957class PixelVectorType final : public Node {
958 const NodeOrString Dimension;
959
960public:
961 PixelVectorType(NodeOrString Dimension_)
962 : Node(KPixelVectorType), Dimension(Dimension_) {}
963
964 template<typename Fn> void match(Fn F) const { F(Dimension); }
965
966 void printLeft(OutputStream &S) const override {
967 // FIXME: This should demangle as "vector pixel".
968 S += "pixel vector[";
969 S += Dimension.asString();
970 S += "]";
971 }
972};
973
Richard Smithdf1c14c2019-09-06 23:53:21 +0000974enum class TemplateParamKind { Type, NonType, Template };
975
976/// An invented name for a template parameter for which we don't have a
977/// corresponding template argument.
978///
979/// This node is created when parsing the <lambda-sig> for a lambda with
980/// explicit template arguments, which might be referenced in the parameter
981/// types appearing later in the <lambda-sig>.
982class SyntheticTemplateParamName final : public Node {
983 TemplateParamKind Kind;
984 unsigned Index;
985
986public:
987 SyntheticTemplateParamName(TemplateParamKind Kind_, unsigned Index_)
988 : Node(KSyntheticTemplateParamName), Kind(Kind_), Index(Index_) {}
989
990 template<typename Fn> void match(Fn F) const { F(Kind, Index); }
991
992 void printLeft(OutputStream &S) const override {
993 switch (Kind) {
994 case TemplateParamKind::Type:
995 S += "$T";
996 break;
997 case TemplateParamKind::NonType:
998 S += "$N";
999 break;
1000 case TemplateParamKind::Template:
1001 S += "$TT";
1002 break;
1003 }
1004 if (Index > 0)
1005 S << Index - 1;
1006 }
1007};
1008
1009/// A template type parameter declaration, 'typename T'.
1010class TypeTemplateParamDecl final : public Node {
1011 Node *Name;
1012
1013public:
1014 TypeTemplateParamDecl(Node *Name_)
1015 : Node(KTypeTemplateParamDecl, Cache::Yes), Name(Name_) {}
1016
1017 template<typename Fn> void match(Fn F) const { F(Name); }
1018
1019 void printLeft(OutputStream &S) const override {
1020 S += "typename ";
1021 }
1022
1023 void printRight(OutputStream &S) const override {
1024 Name->print(S);
1025 }
1026};
1027
1028/// A non-type template parameter declaration, 'int N'.
1029class NonTypeTemplateParamDecl final : public Node {
1030 Node *Name;
1031 Node *Type;
1032
1033public:
1034 NonTypeTemplateParamDecl(Node *Name_, Node *Type_)
1035 : Node(KNonTypeTemplateParamDecl, Cache::Yes), Name(Name_), Type(Type_) {}
1036
1037 template<typename Fn> void match(Fn F) const { F(Name, Type); }
1038
1039 void printLeft(OutputStream &S) const override {
1040 Type->printLeft(S);
1041 if (!Type->hasRHSComponent(S))
1042 S += " ";
1043 }
1044
1045 void printRight(OutputStream &S) const override {
1046 Name->print(S);
1047 Type->printRight(S);
1048 }
1049};
1050
1051/// A template template parameter declaration,
1052/// 'template<typename T> typename N'.
1053class TemplateTemplateParamDecl final : public Node {
1054 Node *Name;
1055 NodeArray Params;
1056
1057public:
1058 TemplateTemplateParamDecl(Node *Name_, NodeArray Params_)
1059 : Node(KTemplateTemplateParamDecl, Cache::Yes), Name(Name_),
1060 Params(Params_) {}
1061
1062 template<typename Fn> void match(Fn F) const { F(Name, Params); }
1063
1064 void printLeft(OutputStream &S) const override {
1065 S += "template<";
1066 Params.printWithComma(S);
1067 S += "> typename ";
1068 }
1069
1070 void printRight(OutputStream &S) const override {
1071 Name->print(S);
1072 }
1073};
1074
1075/// A template parameter pack declaration, 'typename ...T'.
1076class TemplateParamPackDecl final : public Node {
1077 Node *Param;
1078
1079public:
1080 TemplateParamPackDecl(Node *Param_)
1081 : Node(KTemplateParamPackDecl, Cache::Yes), Param(Param_) {}
1082
1083 template<typename Fn> void match(Fn F) const { F(Param); }
1084
1085 void printLeft(OutputStream &S) const override {
1086 Param->printLeft(S);
1087 S += "...";
1088 }
1089
1090 void printRight(OutputStream &S) const override {
1091 Param->printRight(S);
1092 }
1093};
1094
Richard Smithc20d1442018-08-20 20:14:49 +00001095/// An unexpanded parameter pack (either in the expression or type context). If
1096/// this AST is correct, this node will have a ParameterPackExpansion node above
1097/// it.
1098///
1099/// This node is created when some <template-args> are found that apply to an
1100/// <encoding>, and is stored in the TemplateParams table. In order for this to
1101/// appear in the final AST, it has to referenced via a <template-param> (ie,
1102/// T_).
1103class ParameterPack final : public Node {
1104 NodeArray Data;
1105
1106 // Setup OutputStream for a pack expansion unless we're already expanding one.
1107 void initializePackExpansion(OutputStream &S) const {
1108 if (S.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
1109 S.CurrentPackMax = static_cast<unsigned>(Data.size());
1110 S.CurrentPackIndex = 0;
1111 }
1112 }
1113
1114public:
1115 ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
1116 ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
1117 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1118 return P->ArrayCache == Cache::No;
1119 }))
1120 ArrayCache = Cache::No;
1121 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1122 return P->FunctionCache == Cache::No;
1123 }))
1124 FunctionCache = Cache::No;
1125 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1126 return P->RHSComponentCache == Cache::No;
1127 }))
1128 RHSComponentCache = Cache::No;
1129 }
1130
1131 template<typename Fn> void match(Fn F) const { F(Data); }
1132
1133 bool hasRHSComponentSlow(OutputStream &S) const override {
1134 initializePackExpansion(S);
1135 size_t Idx = S.CurrentPackIndex;
1136 return Idx < Data.size() && Data[Idx]->hasRHSComponent(S);
1137 }
1138 bool hasArraySlow(OutputStream &S) const override {
1139 initializePackExpansion(S);
1140 size_t Idx = S.CurrentPackIndex;
1141 return Idx < Data.size() && Data[Idx]->hasArray(S);
1142 }
1143 bool hasFunctionSlow(OutputStream &S) const override {
1144 initializePackExpansion(S);
1145 size_t Idx = S.CurrentPackIndex;
1146 return Idx < Data.size() && Data[Idx]->hasFunction(S);
1147 }
1148 const Node *getSyntaxNode(OutputStream &S) const override {
1149 initializePackExpansion(S);
1150 size_t Idx = S.CurrentPackIndex;
1151 return Idx < Data.size() ? Data[Idx]->getSyntaxNode(S) : this;
1152 }
1153
1154 void printLeft(OutputStream &S) const override {
1155 initializePackExpansion(S);
1156 size_t Idx = S.CurrentPackIndex;
1157 if (Idx < Data.size())
1158 Data[Idx]->printLeft(S);
1159 }
1160 void printRight(OutputStream &S) const override {
1161 initializePackExpansion(S);
1162 size_t Idx = S.CurrentPackIndex;
1163 if (Idx < Data.size())
1164 Data[Idx]->printRight(S);
1165 }
1166};
1167
1168/// A variadic template argument. This node represents an occurrence of
1169/// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1170/// one of it's Elements is. The parser inserts a ParameterPack into the
1171/// TemplateParams table if the <template-args> this pack belongs to apply to an
1172/// <encoding>.
1173class TemplateArgumentPack final : public Node {
1174 NodeArray Elements;
1175public:
1176 TemplateArgumentPack(NodeArray Elements_)
1177 : Node(KTemplateArgumentPack), Elements(Elements_) {}
1178
1179 template<typename Fn> void match(Fn F) const { F(Elements); }
1180
1181 NodeArray getElements() const { return Elements; }
1182
1183 void printLeft(OutputStream &S) const override {
1184 Elements.printWithComma(S);
1185 }
1186};
1187
1188/// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1189/// which each have Child->ParameterPackSize elements.
1190class ParameterPackExpansion final : public Node {
1191 const Node *Child;
1192
1193public:
1194 ParameterPackExpansion(const Node *Child_)
1195 : Node(KParameterPackExpansion), Child(Child_) {}
1196
1197 template<typename Fn> void match(Fn F) const { F(Child); }
1198
1199 const Node *getChild() const { return Child; }
1200
1201 void printLeft(OutputStream &S) const override {
1202 constexpr unsigned Max = std::numeric_limits<unsigned>::max();
1203 SwapAndRestore<unsigned> SavePackIdx(S.CurrentPackIndex, Max);
1204 SwapAndRestore<unsigned> SavePackMax(S.CurrentPackMax, Max);
1205 size_t StreamPos = S.getCurrentPosition();
1206
1207 // Print the first element in the pack. If Child contains a ParameterPack,
1208 // it will set up S.CurrentPackMax and print the first element.
1209 Child->print(S);
1210
1211 // No ParameterPack was found in Child. This can occur if we've found a pack
1212 // expansion on a <function-param>.
1213 if (S.CurrentPackMax == Max) {
1214 S += "...";
1215 return;
1216 }
1217
1218 // We found a ParameterPack, but it has no elements. Erase whatever we may
1219 // of printed.
1220 if (S.CurrentPackMax == 0) {
1221 S.setCurrentPosition(StreamPos);
1222 return;
1223 }
1224
1225 // Else, iterate through the rest of the elements in the pack.
1226 for (unsigned I = 1, E = S.CurrentPackMax; I < E; ++I) {
1227 S += ", ";
1228 S.CurrentPackIndex = I;
1229 Child->print(S);
1230 }
1231 }
1232};
1233
1234class TemplateArgs final : public Node {
1235 NodeArray Params;
1236
1237public:
1238 TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
1239
1240 template<typename Fn> void match(Fn F) const { F(Params); }
1241
1242 NodeArray getParams() { return Params; }
1243
1244 void printLeft(OutputStream &S) const override {
1245 S += "<";
1246 Params.printWithComma(S);
1247 if (S.back() == '>')
1248 S += " ";
1249 S += ">";
1250 }
1251};
1252
Richard Smithb485b352018-08-24 23:30:26 +00001253/// A forward-reference to a template argument that was not known at the point
1254/// where the template parameter name was parsed in a mangling.
1255///
1256/// This is created when demangling the name of a specialization of a
1257/// conversion function template:
1258///
1259/// \code
1260/// struct A {
1261/// template<typename T> operator T*();
1262/// };
1263/// \endcode
1264///
1265/// When demangling a specialization of the conversion function template, we
1266/// encounter the name of the template (including the \c T) before we reach
1267/// the template argument list, so we cannot substitute the parameter name
1268/// for the corresponding argument while parsing. Instead, we create a
1269/// \c ForwardTemplateReference node that is resolved after we parse the
1270/// template arguments.
Richard Smithc20d1442018-08-20 20:14:49 +00001271struct ForwardTemplateReference : Node {
1272 size_t Index;
1273 Node *Ref = nullptr;
1274
1275 // If we're currently printing this node. It is possible (though invalid) for
1276 // a forward template reference to refer to itself via a substitution. This
1277 // creates a cyclic AST, which will stack overflow printing. To fix this, bail
1278 // out if more than one print* function is active.
1279 mutable bool Printing = false;
1280
1281 ForwardTemplateReference(size_t Index_)
1282 : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
1283 Cache::Unknown),
1284 Index(Index_) {}
1285
1286 // We don't provide a matcher for these, because the value of the node is
1287 // not determined by its construction parameters, and it generally needs
1288 // special handling.
1289 template<typename Fn> void match(Fn F) const = delete;
1290
1291 bool hasRHSComponentSlow(OutputStream &S) const override {
1292 if (Printing)
1293 return false;
1294 SwapAndRestore<bool> SavePrinting(Printing, true);
1295 return Ref->hasRHSComponent(S);
1296 }
1297 bool hasArraySlow(OutputStream &S) const override {
1298 if (Printing)
1299 return false;
1300 SwapAndRestore<bool> SavePrinting(Printing, true);
1301 return Ref->hasArray(S);
1302 }
1303 bool hasFunctionSlow(OutputStream &S) const override {
1304 if (Printing)
1305 return false;
1306 SwapAndRestore<bool> SavePrinting(Printing, true);
1307 return Ref->hasFunction(S);
1308 }
1309 const Node *getSyntaxNode(OutputStream &S) const override {
1310 if (Printing)
1311 return this;
1312 SwapAndRestore<bool> SavePrinting(Printing, true);
1313 return Ref->getSyntaxNode(S);
1314 }
1315
1316 void printLeft(OutputStream &S) const override {
1317 if (Printing)
1318 return;
1319 SwapAndRestore<bool> SavePrinting(Printing, true);
1320 Ref->printLeft(S);
1321 }
1322 void printRight(OutputStream &S) const override {
1323 if (Printing)
1324 return;
1325 SwapAndRestore<bool> SavePrinting(Printing, true);
1326 Ref->printRight(S);
1327 }
1328};
1329
1330struct NameWithTemplateArgs : Node {
1331 // name<template_args>
1332 Node *Name;
1333 Node *TemplateArgs;
1334
1335 NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
1336 : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
1337
1338 template<typename Fn> void match(Fn F) const { F(Name, TemplateArgs); }
1339
1340 StringView getBaseName() const override { return Name->getBaseName(); }
1341
1342 void printLeft(OutputStream &S) const override {
1343 Name->print(S);
1344 TemplateArgs->print(S);
1345 }
1346};
1347
1348class GlobalQualifiedName final : public Node {
1349 Node *Child;
1350
1351public:
1352 GlobalQualifiedName(Node* Child_)
1353 : Node(KGlobalQualifiedName), Child(Child_) {}
1354
1355 template<typename Fn> void match(Fn F) const { F(Child); }
1356
1357 StringView getBaseName() const override { return Child->getBaseName(); }
1358
1359 void printLeft(OutputStream &S) const override {
1360 S += "::";
1361 Child->print(S);
1362 }
1363};
1364
1365struct StdQualifiedName : Node {
1366 Node *Child;
1367
1368 StdQualifiedName(Node *Child_) : Node(KStdQualifiedName), Child(Child_) {}
1369
1370 template<typename Fn> void match(Fn F) const { F(Child); }
1371
1372 StringView getBaseName() const override { return Child->getBaseName(); }
1373
1374 void printLeft(OutputStream &S) const override {
1375 S += "std::";
1376 Child->print(S);
1377 }
1378};
1379
1380enum class SpecialSubKind {
1381 allocator,
1382 basic_string,
1383 string,
1384 istream,
1385 ostream,
1386 iostream,
1387};
1388
1389class ExpandedSpecialSubstitution final : public Node {
1390 SpecialSubKind SSK;
1391
1392public:
1393 ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1394 : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
1395
1396 template<typename Fn> void match(Fn F) const { F(SSK); }
1397
1398 StringView getBaseName() const override {
1399 switch (SSK) {
1400 case SpecialSubKind::allocator:
1401 return StringView("allocator");
1402 case SpecialSubKind::basic_string:
1403 return StringView("basic_string");
1404 case SpecialSubKind::string:
1405 return StringView("basic_string");
1406 case SpecialSubKind::istream:
1407 return StringView("basic_istream");
1408 case SpecialSubKind::ostream:
1409 return StringView("basic_ostream");
1410 case SpecialSubKind::iostream:
1411 return StringView("basic_iostream");
1412 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00001413 DEMANGLE_UNREACHABLE;
Richard Smithc20d1442018-08-20 20:14:49 +00001414 }
1415
1416 void printLeft(OutputStream &S) const override {
1417 switch (SSK) {
1418 case SpecialSubKind::allocator:
Richard Smithb485b352018-08-24 23:30:26 +00001419 S += "std::allocator";
Richard Smithc20d1442018-08-20 20:14:49 +00001420 break;
1421 case SpecialSubKind::basic_string:
Richard Smithb485b352018-08-24 23:30:26 +00001422 S += "std::basic_string";
1423 break;
Richard Smithc20d1442018-08-20 20:14:49 +00001424 case SpecialSubKind::string:
1425 S += "std::basic_string<char, std::char_traits<char>, "
1426 "std::allocator<char> >";
1427 break;
1428 case SpecialSubKind::istream:
1429 S += "std::basic_istream<char, std::char_traits<char> >";
1430 break;
1431 case SpecialSubKind::ostream:
1432 S += "std::basic_ostream<char, std::char_traits<char> >";
1433 break;
1434 case SpecialSubKind::iostream:
1435 S += "std::basic_iostream<char, std::char_traits<char> >";
1436 break;
1437 }
1438 }
1439};
1440
1441class SpecialSubstitution final : public Node {
1442public:
1443 SpecialSubKind SSK;
1444
1445 SpecialSubstitution(SpecialSubKind SSK_)
1446 : Node(KSpecialSubstitution), SSK(SSK_) {}
1447
1448 template<typename Fn> void match(Fn F) const { F(SSK); }
1449
1450 StringView getBaseName() const override {
1451 switch (SSK) {
1452 case SpecialSubKind::allocator:
1453 return StringView("allocator");
1454 case SpecialSubKind::basic_string:
1455 return StringView("basic_string");
1456 case SpecialSubKind::string:
1457 return StringView("string");
1458 case SpecialSubKind::istream:
1459 return StringView("istream");
1460 case SpecialSubKind::ostream:
1461 return StringView("ostream");
1462 case SpecialSubKind::iostream:
1463 return StringView("iostream");
1464 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00001465 DEMANGLE_UNREACHABLE;
Richard Smithc20d1442018-08-20 20:14:49 +00001466 }
1467
1468 void printLeft(OutputStream &S) const override {
1469 switch (SSK) {
1470 case SpecialSubKind::allocator:
1471 S += "std::allocator";
1472 break;
1473 case SpecialSubKind::basic_string:
1474 S += "std::basic_string";
1475 break;
1476 case SpecialSubKind::string:
1477 S += "std::string";
1478 break;
1479 case SpecialSubKind::istream:
1480 S += "std::istream";
1481 break;
1482 case SpecialSubKind::ostream:
1483 S += "std::ostream";
1484 break;
1485 case SpecialSubKind::iostream:
1486 S += "std::iostream";
1487 break;
1488 }
1489 }
1490};
1491
1492class CtorDtorName final : public Node {
1493 const Node *Basename;
1494 const bool IsDtor;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001495 const int Variant;
Richard Smithc20d1442018-08-20 20:14:49 +00001496
1497public:
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001498 CtorDtorName(const Node *Basename_, bool IsDtor_, int Variant_)
1499 : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_),
1500 Variant(Variant_) {}
Richard Smithc20d1442018-08-20 20:14:49 +00001501
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001502 template<typename Fn> void match(Fn F) const { F(Basename, IsDtor, Variant); }
Richard Smithc20d1442018-08-20 20:14:49 +00001503
1504 void printLeft(OutputStream &S) const override {
1505 if (IsDtor)
1506 S += "~";
1507 S += Basename->getBaseName();
1508 }
1509};
1510
1511class DtorName : public Node {
1512 const Node *Base;
1513
1514public:
1515 DtorName(const Node *Base_) : Node(KDtorName), Base(Base_) {}
1516
1517 template<typename Fn> void match(Fn F) const { F(Base); }
1518
1519 void printLeft(OutputStream &S) const override {
1520 S += "~";
1521 Base->printLeft(S);
1522 }
1523};
1524
1525class UnnamedTypeName : public Node {
1526 const StringView Count;
1527
1528public:
1529 UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
1530
1531 template<typename Fn> void match(Fn F) const { F(Count); }
1532
1533 void printLeft(OutputStream &S) const override {
1534 S += "'unnamed";
1535 S += Count;
1536 S += "\'";
1537 }
1538};
1539
1540class ClosureTypeName : public Node {
Richard Smithdf1c14c2019-09-06 23:53:21 +00001541 NodeArray TemplateParams;
Richard Smithc20d1442018-08-20 20:14:49 +00001542 NodeArray Params;
1543 StringView Count;
1544
1545public:
Richard Smithdf1c14c2019-09-06 23:53:21 +00001546 ClosureTypeName(NodeArray TemplateParams_, NodeArray Params_,
1547 StringView Count_)
1548 : Node(KClosureTypeName), TemplateParams(TemplateParams_),
1549 Params(Params_), Count(Count_) {}
Richard Smithc20d1442018-08-20 20:14:49 +00001550
Richard Smithdf1c14c2019-09-06 23:53:21 +00001551 template<typename Fn> void match(Fn F) const {
1552 F(TemplateParams, Params, Count);
1553 }
1554
1555 void printDeclarator(OutputStream &S) const {
1556 if (!TemplateParams.empty()) {
1557 S += "<";
1558 TemplateParams.printWithComma(S);
1559 S += ">";
1560 }
1561 S += "(";
1562 Params.printWithComma(S);
1563 S += ")";
1564 }
Richard Smithc20d1442018-08-20 20:14:49 +00001565
1566 void printLeft(OutputStream &S) const override {
1567 S += "\'lambda";
1568 S += Count;
Richard Smithdf1c14c2019-09-06 23:53:21 +00001569 S += "\'";
1570 printDeclarator(S);
Richard Smithc20d1442018-08-20 20:14:49 +00001571 }
1572};
1573
1574class StructuredBindingName : public Node {
1575 NodeArray Bindings;
1576public:
1577 StructuredBindingName(NodeArray Bindings_)
1578 : Node(KStructuredBindingName), Bindings(Bindings_) {}
1579
1580 template<typename Fn> void match(Fn F) const { F(Bindings); }
1581
1582 void printLeft(OutputStream &S) const override {
1583 S += '[';
1584 Bindings.printWithComma(S);
1585 S += ']';
1586 }
1587};
1588
1589// -- Expression Nodes --
1590
1591class BinaryExpr : public Node {
1592 const Node *LHS;
1593 const StringView InfixOperator;
1594 const Node *RHS;
1595
1596public:
1597 BinaryExpr(const Node *LHS_, StringView InfixOperator_, const Node *RHS_)
1598 : Node(KBinaryExpr), LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {
1599 }
1600
1601 template<typename Fn> void match(Fn F) const { F(LHS, InfixOperator, RHS); }
1602
1603 void printLeft(OutputStream &S) const override {
1604 // might be a template argument expression, then we need to disambiguate
1605 // with parens.
1606 if (InfixOperator == ">")
1607 S += "(";
1608
1609 S += "(";
1610 LHS->print(S);
1611 S += ") ";
1612 S += InfixOperator;
1613 S += " (";
1614 RHS->print(S);
1615 S += ")";
1616
1617 if (InfixOperator == ">")
1618 S += ")";
1619 }
1620};
1621
1622class ArraySubscriptExpr : public Node {
1623 const Node *Op1;
1624 const Node *Op2;
1625
1626public:
1627 ArraySubscriptExpr(const Node *Op1_, const Node *Op2_)
1628 : Node(KArraySubscriptExpr), Op1(Op1_), Op2(Op2_) {}
1629
1630 template<typename Fn> void match(Fn F) const { F(Op1, Op2); }
1631
1632 void printLeft(OutputStream &S) const override {
1633 S += "(";
1634 Op1->print(S);
1635 S += ")[";
1636 Op2->print(S);
1637 S += "]";
1638 }
1639};
1640
1641class PostfixExpr : public Node {
1642 const Node *Child;
1643 const StringView Operator;
1644
1645public:
1646 PostfixExpr(const Node *Child_, StringView Operator_)
1647 : Node(KPostfixExpr), Child(Child_), Operator(Operator_) {}
1648
1649 template<typename Fn> void match(Fn F) const { F(Child, Operator); }
1650
1651 void printLeft(OutputStream &S) const override {
1652 S += "(";
1653 Child->print(S);
1654 S += ")";
1655 S += Operator;
1656 }
1657};
1658
1659class ConditionalExpr : public Node {
1660 const Node *Cond;
1661 const Node *Then;
1662 const Node *Else;
1663
1664public:
1665 ConditionalExpr(const Node *Cond_, const Node *Then_, const Node *Else_)
1666 : Node(KConditionalExpr), Cond(Cond_), Then(Then_), Else(Else_) {}
1667
1668 template<typename Fn> void match(Fn F) const { F(Cond, Then, Else); }
1669
1670 void printLeft(OutputStream &S) const override {
1671 S += "(";
1672 Cond->print(S);
1673 S += ") ? (";
1674 Then->print(S);
1675 S += ") : (";
1676 Else->print(S);
1677 S += ")";
1678 }
1679};
1680
1681class MemberExpr : public Node {
1682 const Node *LHS;
1683 const StringView Kind;
1684 const Node *RHS;
1685
1686public:
1687 MemberExpr(const Node *LHS_, StringView Kind_, const Node *RHS_)
1688 : Node(KMemberExpr), LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
1689
1690 template<typename Fn> void match(Fn F) const { F(LHS, Kind, RHS); }
1691
1692 void printLeft(OutputStream &S) const override {
1693 LHS->print(S);
1694 S += Kind;
1695 RHS->print(S);
1696 }
1697};
1698
1699class EnclosingExpr : public Node {
1700 const StringView Prefix;
1701 const Node *Infix;
1702 const StringView Postfix;
1703
1704public:
1705 EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
1706 : Node(KEnclosingExpr), Prefix(Prefix_), Infix(Infix_),
1707 Postfix(Postfix_) {}
1708
1709 template<typename Fn> void match(Fn F) const { F(Prefix, Infix, Postfix); }
1710
1711 void printLeft(OutputStream &S) const override {
1712 S += Prefix;
1713 Infix->print(S);
1714 S += Postfix;
1715 }
1716};
1717
1718class CastExpr : public Node {
1719 // cast_kind<to>(from)
1720 const StringView CastKind;
1721 const Node *To;
1722 const Node *From;
1723
1724public:
1725 CastExpr(StringView CastKind_, const Node *To_, const Node *From_)
1726 : Node(KCastExpr), CastKind(CastKind_), To(To_), From(From_) {}
1727
1728 template<typename Fn> void match(Fn F) const { F(CastKind, To, From); }
1729
1730 void printLeft(OutputStream &S) const override {
1731 S += CastKind;
1732 S += "<";
1733 To->printLeft(S);
1734 S += ">(";
1735 From->printLeft(S);
1736 S += ")";
1737 }
1738};
1739
1740class SizeofParamPackExpr : public Node {
1741 const Node *Pack;
1742
1743public:
1744 SizeofParamPackExpr(const Node *Pack_)
1745 : Node(KSizeofParamPackExpr), Pack(Pack_) {}
1746
1747 template<typename Fn> void match(Fn F) const { F(Pack); }
1748
1749 void printLeft(OutputStream &S) const override {
1750 S += "sizeof...(";
1751 ParameterPackExpansion PPE(Pack);
1752 PPE.printLeft(S);
1753 S += ")";
1754 }
1755};
1756
1757class CallExpr : public Node {
1758 const Node *Callee;
1759 NodeArray Args;
1760
1761public:
1762 CallExpr(const Node *Callee_, NodeArray Args_)
1763 : Node(KCallExpr), Callee(Callee_), Args(Args_) {}
1764
1765 template<typename Fn> void match(Fn F) const { F(Callee, Args); }
1766
1767 void printLeft(OutputStream &S) const override {
1768 Callee->print(S);
1769 S += "(";
1770 Args.printWithComma(S);
1771 S += ")";
1772 }
1773};
1774
1775class NewExpr : public Node {
1776 // new (expr_list) type(init_list)
1777 NodeArray ExprList;
1778 Node *Type;
1779 NodeArray InitList;
1780 bool IsGlobal; // ::operator new ?
1781 bool IsArray; // new[] ?
1782public:
1783 NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1784 bool IsArray_)
1785 : Node(KNewExpr), ExprList(ExprList_), Type(Type_), InitList(InitList_),
1786 IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1787
1788 template<typename Fn> void match(Fn F) const {
1789 F(ExprList, Type, InitList, IsGlobal, IsArray);
1790 }
1791
1792 void printLeft(OutputStream &S) const override {
1793 if (IsGlobal)
1794 S += "::operator ";
1795 S += "new";
1796 if (IsArray)
1797 S += "[]";
1798 S += ' ';
1799 if (!ExprList.empty()) {
1800 S += "(";
1801 ExprList.printWithComma(S);
1802 S += ")";
1803 }
1804 Type->print(S);
1805 if (!InitList.empty()) {
1806 S += "(";
1807 InitList.printWithComma(S);
1808 S += ")";
1809 }
1810
1811 }
1812};
1813
1814class DeleteExpr : public Node {
1815 Node *Op;
1816 bool IsGlobal;
1817 bool IsArray;
1818
1819public:
1820 DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
1821 : Node(KDeleteExpr), Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1822
1823 template<typename Fn> void match(Fn F) const { F(Op, IsGlobal, IsArray); }
1824
1825 void printLeft(OutputStream &S) const override {
1826 if (IsGlobal)
1827 S += "::";
1828 S += "delete";
1829 if (IsArray)
1830 S += "[] ";
1831 Op->print(S);
1832 }
1833};
1834
1835class PrefixExpr : public Node {
1836 StringView Prefix;
1837 Node *Child;
1838
1839public:
1840 PrefixExpr(StringView Prefix_, Node *Child_)
1841 : Node(KPrefixExpr), Prefix(Prefix_), Child(Child_) {}
1842
1843 template<typename Fn> void match(Fn F) const { F(Prefix, Child); }
1844
1845 void printLeft(OutputStream &S) const override {
1846 S += Prefix;
1847 S += "(";
1848 Child->print(S);
1849 S += ")";
1850 }
1851};
1852
1853class FunctionParam : public Node {
1854 StringView Number;
1855
1856public:
1857 FunctionParam(StringView Number_) : Node(KFunctionParam), Number(Number_) {}
1858
1859 template<typename Fn> void match(Fn F) const { F(Number); }
1860
1861 void printLeft(OutputStream &S) const override {
1862 S += "fp";
1863 S += Number;
1864 }
1865};
1866
1867class ConversionExpr : public Node {
1868 const Node *Type;
1869 NodeArray Expressions;
1870
1871public:
1872 ConversionExpr(const Node *Type_, NodeArray Expressions_)
1873 : Node(KConversionExpr), Type(Type_), Expressions(Expressions_) {}
1874
1875 template<typename Fn> void match(Fn F) const { F(Type, Expressions); }
1876
1877 void printLeft(OutputStream &S) const override {
1878 S += "(";
1879 Type->print(S);
1880 S += ")(";
1881 Expressions.printWithComma(S);
1882 S += ")";
1883 }
1884};
1885
1886class InitListExpr : public Node {
1887 const Node *Ty;
1888 NodeArray Inits;
1889public:
1890 InitListExpr(const Node *Ty_, NodeArray Inits_)
1891 : Node(KInitListExpr), Ty(Ty_), Inits(Inits_) {}
1892
1893 template<typename Fn> void match(Fn F) const { F(Ty, Inits); }
1894
1895 void printLeft(OutputStream &S) const override {
1896 if (Ty)
1897 Ty->print(S);
1898 S += '{';
1899 Inits.printWithComma(S);
1900 S += '}';
1901 }
1902};
1903
1904class BracedExpr : public Node {
1905 const Node *Elem;
1906 const Node *Init;
1907 bool IsArray;
1908public:
1909 BracedExpr(const Node *Elem_, const Node *Init_, bool IsArray_)
1910 : Node(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
1911
1912 template<typename Fn> void match(Fn F) const { F(Elem, Init, IsArray); }
1913
1914 void printLeft(OutputStream &S) const override {
1915 if (IsArray) {
1916 S += '[';
1917 Elem->print(S);
1918 S += ']';
1919 } else {
1920 S += '.';
1921 Elem->print(S);
1922 }
1923 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1924 S += " = ";
1925 Init->print(S);
1926 }
1927};
1928
1929class BracedRangeExpr : public Node {
1930 const Node *First;
1931 const Node *Last;
1932 const Node *Init;
1933public:
1934 BracedRangeExpr(const Node *First_, const Node *Last_, const Node *Init_)
1935 : Node(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
1936
1937 template<typename Fn> void match(Fn F) const { F(First, Last, Init); }
1938
1939 void printLeft(OutputStream &S) const override {
1940 S += '[';
1941 First->print(S);
1942 S += " ... ";
1943 Last->print(S);
1944 S += ']';
1945 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1946 S += " = ";
1947 Init->print(S);
1948 }
1949};
1950
1951class FoldExpr : public Node {
1952 const Node *Pack, *Init;
1953 StringView OperatorName;
1954 bool IsLeftFold;
1955
1956public:
1957 FoldExpr(bool IsLeftFold_, StringView OperatorName_, const Node *Pack_,
1958 const Node *Init_)
1959 : Node(KFoldExpr), Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
1960 IsLeftFold(IsLeftFold_) {}
1961
1962 template<typename Fn> void match(Fn F) const {
1963 F(IsLeftFold, OperatorName, Pack, Init);
1964 }
1965
1966 void printLeft(OutputStream &S) const override {
1967 auto PrintPack = [&] {
1968 S += '(';
1969 ParameterPackExpansion(Pack).print(S);
1970 S += ')';
1971 };
1972
1973 S += '(';
1974
1975 if (IsLeftFold) {
1976 // init op ... op pack
1977 if (Init != nullptr) {
1978 Init->print(S);
1979 S += ' ';
1980 S += OperatorName;
1981 S += ' ';
1982 }
1983 // ... op pack
1984 S += "... ";
1985 S += OperatorName;
1986 S += ' ';
1987 PrintPack();
1988 } else { // !IsLeftFold
1989 // pack op ...
1990 PrintPack();
1991 S += ' ';
1992 S += OperatorName;
1993 S += " ...";
1994 // pack op ... op init
1995 if (Init != nullptr) {
1996 S += ' ';
1997 S += OperatorName;
1998 S += ' ';
1999 Init->print(S);
2000 }
2001 }
2002 S += ')';
2003 }
2004};
2005
2006class ThrowExpr : public Node {
2007 const Node *Op;
2008
2009public:
2010 ThrowExpr(const Node *Op_) : Node(KThrowExpr), Op(Op_) {}
2011
2012 template<typename Fn> void match(Fn F) const { F(Op); }
2013
2014 void printLeft(OutputStream &S) const override {
2015 S += "throw ";
2016 Op->print(S);
2017 }
2018};
2019
Erik Pilkingtone8457c62019-06-18 23:34:09 +00002020// MSVC __uuidof extension, generated by clang in -fms-extensions mode.
2021class UUIDOfExpr : public Node {
2022 Node *Operand;
2023public:
2024 UUIDOfExpr(Node *Operand_) : Node(KUUIDOfExpr), Operand(Operand_) {}
2025
2026 template<typename Fn> void match(Fn F) const { F(Operand); }
2027
2028 void printLeft(OutputStream &S) const override {
2029 S << "__uuidof(";
2030 Operand->print(S);
2031 S << ")";
2032 }
2033};
2034
Richard Smithc20d1442018-08-20 20:14:49 +00002035class BoolExpr : public Node {
2036 bool Value;
2037
2038public:
2039 BoolExpr(bool Value_) : Node(KBoolExpr), Value(Value_) {}
2040
2041 template<typename Fn> void match(Fn F) const { F(Value); }
2042
2043 void printLeft(OutputStream &S) const override {
2044 S += Value ? StringView("true") : StringView("false");
2045 }
2046};
2047
Richard Smithdf1c14c2019-09-06 23:53:21 +00002048class StringLiteral : public Node {
2049 const Node *Type;
2050
2051public:
2052 StringLiteral(const Node *Type_) : Node(KStringLiteral), Type(Type_) {}
2053
2054 template<typename Fn> void match(Fn F) const { F(Type); }
2055
2056 void printLeft(OutputStream &S) const override {
2057 S += "\"<";
2058 Type->print(S);
2059 S += ">\"";
2060 }
2061};
2062
2063class LambdaExpr : public Node {
2064 const Node *Type;
2065
Richard Smithdf1c14c2019-09-06 23:53:21 +00002066public:
2067 LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
2068
2069 template<typename Fn> void match(Fn F) const { F(Type); }
2070
2071 void printLeft(OutputStream &S) const override {
2072 S += "[]";
Richard Smithfb917462019-09-09 22:26:04 +00002073 if (Type->getKind() == KClosureTypeName)
2074 static_cast<const ClosureTypeName *>(Type)->printDeclarator(S);
Richard Smithdf1c14c2019-09-06 23:53:21 +00002075 S += "{...}";
2076 }
2077};
2078
Richard Smithc20d1442018-08-20 20:14:49 +00002079class IntegerCastExpr : public Node {
2080 // ty(integer)
2081 const Node *Ty;
2082 StringView Integer;
2083
2084public:
2085 IntegerCastExpr(const Node *Ty_, StringView Integer_)
2086 : Node(KIntegerCastExpr), Ty(Ty_), Integer(Integer_) {}
2087
2088 template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
2089
2090 void printLeft(OutputStream &S) const override {
2091 S += "(";
2092 Ty->print(S);
2093 S += ")";
2094 S += Integer;
2095 }
2096};
2097
2098class IntegerLiteral : public Node {
2099 StringView Type;
2100 StringView Value;
2101
2102public:
2103 IntegerLiteral(StringView Type_, StringView Value_)
2104 : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
2105
2106 template<typename Fn> void match(Fn F) const { F(Type, Value); }
2107
2108 void printLeft(OutputStream &S) const override {
2109 if (Type.size() > 3) {
2110 S += "(";
2111 S += Type;
2112 S += ")";
2113 }
2114
2115 if (Value[0] == 'n') {
2116 S += "-";
2117 S += Value.dropFront(1);
2118 } else
2119 S += Value;
2120
2121 if (Type.size() <= 3)
2122 S += Type;
2123 }
2124};
2125
2126template <class Float> struct FloatData;
2127
2128namespace float_literal_impl {
2129constexpr Node::Kind getFloatLiteralKind(float *) {
2130 return Node::KFloatLiteral;
2131}
2132constexpr Node::Kind getFloatLiteralKind(double *) {
2133 return Node::KDoubleLiteral;
2134}
2135constexpr Node::Kind getFloatLiteralKind(long double *) {
2136 return Node::KLongDoubleLiteral;
2137}
2138}
2139
2140template <class Float> class FloatLiteralImpl : public Node {
2141 const StringView Contents;
2142
2143 static constexpr Kind KindForClass =
2144 float_literal_impl::getFloatLiteralKind((Float *)nullptr);
2145
2146public:
2147 FloatLiteralImpl(StringView Contents_)
2148 : Node(KindForClass), Contents(Contents_) {}
2149
2150 template<typename Fn> void match(Fn F) const { F(Contents); }
2151
2152 void printLeft(OutputStream &s) const override {
2153 const char *first = Contents.begin();
2154 const char *last = Contents.end() + 1;
2155
2156 const size_t N = FloatData<Float>::mangled_size;
2157 if (static_cast<std::size_t>(last - first) > N) {
2158 last = first + N;
2159 union {
2160 Float value;
2161 char buf[sizeof(Float)];
2162 };
2163 const char *t = first;
2164 char *e = buf;
2165 for (; t != last; ++t, ++e) {
2166 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2167 : static_cast<unsigned>(*t - 'a' + 10);
2168 ++t;
2169 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2170 : static_cast<unsigned>(*t - 'a' + 10);
2171 *e = static_cast<char>((d1 << 4) + d0);
2172 }
2173#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
2174 std::reverse(buf, e);
2175#endif
2176 char num[FloatData<Float>::max_demangled_size] = {0};
2177 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
2178 s += StringView(num, num + n);
2179 }
2180 }
2181};
2182
2183using FloatLiteral = FloatLiteralImpl<float>;
2184using DoubleLiteral = FloatLiteralImpl<double>;
2185using LongDoubleLiteral = FloatLiteralImpl<long double>;
2186
2187/// Visit the node. Calls \c F(P), where \c P is the node cast to the
2188/// appropriate derived class.
2189template<typename Fn>
2190void Node::visit(Fn F) const {
2191 switch (K) {
2192#define CASE(X) case K ## X: return F(static_cast<const X*>(this));
2193 FOR_EACH_NODE_KIND(CASE)
2194#undef CASE
2195 }
2196 assert(0 && "unknown mangling node kind");
2197}
2198
2199/// Determine the kind of a node from its type.
2200template<typename NodeT> struct NodeKind;
2201#define SPECIALIZATION(X) \
2202 template<> struct NodeKind<X> { \
2203 static constexpr Node::Kind Kind = Node::K##X; \
2204 static constexpr const char *name() { return #X; } \
2205 };
2206FOR_EACH_NODE_KIND(SPECIALIZATION)
2207#undef SPECIALIZATION
2208
2209#undef FOR_EACH_NODE_KIND
2210
2211template <class T, size_t N>
2212class PODSmallVector {
2213 static_assert(std::is_pod<T>::value,
2214 "T is required to be a plain old data type");
2215
2216 T* First;
2217 T* Last;
2218 T* Cap;
2219 T Inline[N];
2220
2221 bool isInline() const { return First == Inline; }
2222
2223 void clearInline() {
2224 First = Inline;
2225 Last = Inline;
2226 Cap = Inline + N;
2227 }
2228
2229 void reserve(size_t NewCap) {
2230 size_t S = size();
2231 if (isInline()) {
2232 auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
2233 if (Tmp == nullptr)
2234 std::terminate();
2235 std::copy(First, Last, Tmp);
2236 First = Tmp;
2237 } else {
2238 First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
2239 if (First == nullptr)
2240 std::terminate();
2241 }
2242 Last = First + S;
2243 Cap = First + NewCap;
2244 }
2245
2246public:
2247 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
2248
2249 PODSmallVector(const PODSmallVector&) = delete;
2250 PODSmallVector& operator=(const PODSmallVector&) = delete;
2251
2252 PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
2253 if (Other.isInline()) {
2254 std::copy(Other.begin(), Other.end(), First);
2255 Last = First + Other.size();
2256 Other.clear();
2257 return;
2258 }
2259
2260 First = Other.First;
2261 Last = Other.Last;
2262 Cap = Other.Cap;
2263 Other.clearInline();
2264 }
2265
2266 PODSmallVector& operator=(PODSmallVector&& Other) {
2267 if (Other.isInline()) {
2268 if (!isInline()) {
2269 std::free(First);
2270 clearInline();
2271 }
2272 std::copy(Other.begin(), Other.end(), First);
2273 Last = First + Other.size();
2274 Other.clear();
2275 return *this;
2276 }
2277
2278 if (isInline()) {
2279 First = Other.First;
2280 Last = Other.Last;
2281 Cap = Other.Cap;
2282 Other.clearInline();
2283 return *this;
2284 }
2285
2286 std::swap(First, Other.First);
2287 std::swap(Last, Other.Last);
2288 std::swap(Cap, Other.Cap);
2289 Other.clear();
2290 return *this;
2291 }
2292
2293 void push_back(const T& Elem) {
2294 if (Last == Cap)
2295 reserve(size() * 2);
2296 *Last++ = Elem;
2297 }
2298
2299 void pop_back() {
2300 assert(Last != First && "Popping empty vector!");
2301 --Last;
2302 }
2303
2304 void dropBack(size_t Index) {
2305 assert(Index <= size() && "dropBack() can't expand!");
2306 Last = First + Index;
2307 }
2308
2309 T* begin() { return First; }
2310 T* end() { return Last; }
2311
2312 bool empty() const { return First == Last; }
2313 size_t size() const { return static_cast<size_t>(Last - First); }
2314 T& back() {
2315 assert(Last != First && "Calling back() on empty vector!");
2316 return *(Last - 1);
2317 }
2318 T& operator[](size_t Index) {
2319 assert(Index < size() && "Invalid access!");
2320 return *(begin() + Index);
2321 }
2322 void clear() { Last = First; }
2323
2324 ~PODSmallVector() {
2325 if (!isInline())
2326 std::free(First);
2327 }
2328};
2329
Pavel Labathba825192018-10-16 14:29:14 +00002330template <typename Derived, typename Alloc> struct AbstractManglingParser {
Richard Smithc20d1442018-08-20 20:14:49 +00002331 const char *First;
2332 const char *Last;
2333
2334 // Name stack, this is used by the parser to hold temporary names that were
2335 // parsed. The parser collapses multiple names into new nodes to construct
2336 // the AST. Once the parser is finished, names.size() == 1.
2337 PODSmallVector<Node *, 32> Names;
2338
2339 // Substitution table. Itanium supports name substitutions as a means of
2340 // compression. The string "S42_" refers to the 44nd entry (base-36) in this
2341 // table.
2342 PODSmallVector<Node *, 32> Subs;
2343
Richard Smithdf1c14c2019-09-06 23:53:21 +00002344 using TemplateParamList = PODSmallVector<Node *, 8>;
2345
2346 class ScopedTemplateParamList {
2347 AbstractManglingParser *Parser;
2348 size_t OldNumTemplateParamLists;
2349 TemplateParamList Params;
2350
2351 public:
2352 ScopedTemplateParamList(AbstractManglingParser *Parser)
2353 : Parser(Parser),
2354 OldNumTemplateParamLists(Parser->TemplateParams.size()) {
2355 Parser->TemplateParams.push_back(&Params);
2356 }
2357 ~ScopedTemplateParamList() {
2358 assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
2359 Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
2360 }
2361 void push_back(Node *Param) {
2362 Params.push_back(Param);
2363 }
2364 };
2365
Richard Smithc20d1442018-08-20 20:14:49 +00002366 // Template parameter table. Like the above, but referenced like "T42_".
2367 // This has a smaller size compared to Subs and Names because it can be
2368 // stored on the stack.
Richard Smithdf1c14c2019-09-06 23:53:21 +00002369 TemplateParamList OuterTemplateParams;
2370
2371 // Lists of template parameters indexed by template parameter depth,
2372 // referenced like "TL2_4_". If nonempty, element 0 is always
2373 // OuterTemplateParams; inner elements are always template parameter lists of
2374 // lambda expressions. For a generic lambda with no explicit template
2375 // parameter list, the corresponding parameter list pointer will be null.
2376 PODSmallVector<TemplateParamList *, 4> TemplateParams;
Richard Smithc20d1442018-08-20 20:14:49 +00002377
2378 // Set of unresolved forward <template-param> references. These can occur in a
2379 // conversion operator's type, and are resolved in the enclosing <encoding>.
2380 PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
2381
Richard Smithc20d1442018-08-20 20:14:49 +00002382 bool TryToParseTemplateArgs = true;
2383 bool PermitForwardTemplateReferences = false;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002384 size_t ParsingLambdaParamsAtLevel = (size_t)-1;
2385
2386 unsigned NumSyntheticTemplateParameters[3] = {};
Richard Smithc20d1442018-08-20 20:14:49 +00002387
2388 Alloc ASTAllocator;
2389
Pavel Labathba825192018-10-16 14:29:14 +00002390 AbstractManglingParser(const char *First_, const char *Last_)
2391 : First(First_), Last(Last_) {}
2392
2393 Derived &getDerived() { return static_cast<Derived &>(*this); }
Richard Smithc20d1442018-08-20 20:14:49 +00002394
2395 void reset(const char *First_, const char *Last_) {
2396 First = First_;
2397 Last = Last_;
2398 Names.clear();
2399 Subs.clear();
2400 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002401 ParsingLambdaParamsAtLevel = (size_t)-1;
Richard Smithc20d1442018-08-20 20:14:49 +00002402 TryToParseTemplateArgs = true;
2403 PermitForwardTemplateReferences = false;
Richard Smith9a2307a2019-09-07 00:11:53 +00002404 for (int I = 0; I != 3; ++I)
2405 NumSyntheticTemplateParameters[I] = 0;
Richard Smithc20d1442018-08-20 20:14:49 +00002406 ASTAllocator.reset();
2407 }
2408
Richard Smithb485b352018-08-24 23:30:26 +00002409 template <class T, class... Args> Node *make(Args &&... args) {
Richard Smithc20d1442018-08-20 20:14:49 +00002410 return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
2411 }
2412
2413 template <class It> NodeArray makeNodeArray(It begin, It end) {
2414 size_t sz = static_cast<size_t>(end - begin);
2415 void *mem = ASTAllocator.allocateNodeArray(sz);
2416 Node **data = new (mem) Node *[sz];
2417 std::copy(begin, end, data);
2418 return NodeArray(data, sz);
2419 }
2420
2421 NodeArray popTrailingNodeArray(size_t FromPosition) {
2422 assert(FromPosition <= Names.size());
2423 NodeArray res =
2424 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2425 Names.dropBack(FromPosition);
2426 return res;
2427 }
2428
2429 bool consumeIf(StringView S) {
2430 if (StringView(First, Last).startsWith(S)) {
2431 First += S.size();
2432 return true;
2433 }
2434 return false;
2435 }
2436
2437 bool consumeIf(char C) {
2438 if (First != Last && *First == C) {
2439 ++First;
2440 return true;
2441 }
2442 return false;
2443 }
2444
2445 char consume() { return First != Last ? *First++ : '\0'; }
2446
2447 char look(unsigned Lookahead = 0) {
2448 if (static_cast<size_t>(Last - First) <= Lookahead)
2449 return '\0';
2450 return First[Lookahead];
2451 }
2452
2453 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2454
2455 StringView parseNumber(bool AllowNegative = false);
2456 Qualifiers parseCVQualifiers();
2457 bool parsePositiveInteger(size_t *Out);
2458 StringView parseBareSourceName();
2459
2460 bool parseSeqId(size_t *Out);
2461 Node *parseSubstitution();
2462 Node *parseTemplateParam();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002463 Node *parseTemplateParamDecl();
Richard Smithc20d1442018-08-20 20:14:49 +00002464 Node *parseTemplateArgs(bool TagTemplates = false);
2465 Node *parseTemplateArg();
2466
2467 /// Parse the <expr> production.
2468 Node *parseExpr();
2469 Node *parsePrefixExpr(StringView Kind);
2470 Node *parseBinaryExpr(StringView Kind);
2471 Node *parseIntegerLiteral(StringView Lit);
2472 Node *parseExprPrimary();
2473 template <class Float> Node *parseFloatingLiteral();
2474 Node *parseFunctionParam();
2475 Node *parseNewExpr();
2476 Node *parseConversionExpr();
2477 Node *parseBracedExpr();
2478 Node *parseFoldExpr();
2479
2480 /// Parse the <type> production.
2481 Node *parseType();
2482 Node *parseFunctionType();
2483 Node *parseVectorType();
2484 Node *parseDecltype();
2485 Node *parseArrayType();
2486 Node *parsePointerToMemberType();
2487 Node *parseClassEnumType();
2488 Node *parseQualifiedType();
2489
2490 Node *parseEncoding();
2491 bool parseCallOffset();
2492 Node *parseSpecialName();
2493
2494 /// Holds some extra information about a <name> that is being parsed. This
2495 /// information is only pertinent if the <name> refers to an <encoding>.
2496 struct NameState {
2497 bool CtorDtorConversion = false;
2498 bool EndsWithTemplateArgs = false;
2499 Qualifiers CVQualifiers = QualNone;
2500 FunctionRefQual ReferenceQualifier = FrefQualNone;
2501 size_t ForwardTemplateRefsBegin;
2502
Pavel Labathba825192018-10-16 14:29:14 +00002503 NameState(AbstractManglingParser *Enclosing)
Richard Smithc20d1442018-08-20 20:14:49 +00002504 : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
2505 };
2506
2507 bool resolveForwardTemplateRefs(NameState &State) {
2508 size_t I = State.ForwardTemplateRefsBegin;
2509 size_t E = ForwardTemplateRefs.size();
2510 for (; I < E; ++I) {
2511 size_t Idx = ForwardTemplateRefs[I]->Index;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002512 if (TemplateParams.empty() || !TemplateParams[0] ||
2513 Idx >= TemplateParams[0]->size())
Richard Smithc20d1442018-08-20 20:14:49 +00002514 return true;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002515 ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
Richard Smithc20d1442018-08-20 20:14:49 +00002516 }
2517 ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
2518 return false;
2519 }
2520
2521 /// Parse the <name> production>
2522 Node *parseName(NameState *State = nullptr);
2523 Node *parseLocalName(NameState *State);
2524 Node *parseOperatorName(NameState *State);
2525 Node *parseUnqualifiedName(NameState *State);
2526 Node *parseUnnamedTypeName(NameState *State);
2527 Node *parseSourceName(NameState *State);
2528 Node *parseUnscopedName(NameState *State);
2529 Node *parseNestedName(NameState *State);
2530 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2531
2532 Node *parseAbiTags(Node *N);
2533
2534 /// Parse the <unresolved-name> production.
2535 Node *parseUnresolvedName();
2536 Node *parseSimpleId();
2537 Node *parseBaseUnresolvedName();
2538 Node *parseUnresolvedType();
2539 Node *parseDestructorName();
2540
2541 /// Top-level entry point into the parser.
2542 Node *parse();
2543};
2544
2545const char* parse_discriminator(const char* first, const char* last);
2546
2547// <name> ::= <nested-name> // N
2548// ::= <local-name> # See Scope Encoding below // Z
2549// ::= <unscoped-template-name> <template-args>
2550// ::= <unscoped-name>
2551//
2552// <unscoped-template-name> ::= <unscoped-name>
2553// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00002554template <typename Derived, typename Alloc>
2555Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002556 consumeIf('L'); // extension
2557
2558 if (look() == 'N')
Pavel Labathba825192018-10-16 14:29:14 +00002559 return getDerived().parseNestedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002560 if (look() == 'Z')
Pavel Labathba825192018-10-16 14:29:14 +00002561 return getDerived().parseLocalName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002562
2563 // ::= <unscoped-template-name> <template-args>
2564 if (look() == 'S' && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00002565 Node *S = getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00002566 if (S == nullptr)
2567 return nullptr;
2568 if (look() != 'I')
2569 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002570 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00002571 if (TA == nullptr)
2572 return nullptr;
2573 if (State) State->EndsWithTemplateArgs = true;
2574 return make<NameWithTemplateArgs>(S, TA);
2575 }
2576
Pavel Labathba825192018-10-16 14:29:14 +00002577 Node *N = getDerived().parseUnscopedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002578 if (N == nullptr)
2579 return nullptr;
2580 // ::= <unscoped-template-name> <template-args>
2581 if (look() == 'I') {
2582 Subs.push_back(N);
Pavel Labathba825192018-10-16 14:29:14 +00002583 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00002584 if (TA == nullptr)
2585 return nullptr;
2586 if (State) State->EndsWithTemplateArgs = true;
2587 return make<NameWithTemplateArgs>(N, TA);
2588 }
2589 // ::= <unscoped-name>
2590 return N;
2591}
2592
2593// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2594// := Z <function encoding> E s [<discriminator>]
2595// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
Pavel Labathba825192018-10-16 14:29:14 +00002596template <typename Derived, typename Alloc>
2597Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002598 if (!consumeIf('Z'))
2599 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002600 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00002601 if (Encoding == nullptr || !consumeIf('E'))
2602 return nullptr;
2603
2604 if (consumeIf('s')) {
2605 First = parse_discriminator(First, Last);
Richard Smithb485b352018-08-24 23:30:26 +00002606 auto *StringLitName = make<NameType>("string literal");
2607 if (!StringLitName)
2608 return nullptr;
2609 return make<LocalName>(Encoding, StringLitName);
Richard Smithc20d1442018-08-20 20:14:49 +00002610 }
2611
2612 if (consumeIf('d')) {
2613 parseNumber(true);
2614 if (!consumeIf('_'))
2615 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002616 Node *N = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002617 if (N == nullptr)
2618 return nullptr;
2619 return make<LocalName>(Encoding, N);
2620 }
2621
Pavel Labathba825192018-10-16 14:29:14 +00002622 Node *Entity = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002623 if (Entity == nullptr)
2624 return nullptr;
2625 First = parse_discriminator(First, Last);
2626 return make<LocalName>(Encoding, Entity);
2627}
2628
2629// <unscoped-name> ::= <unqualified-name>
2630// ::= St <unqualified-name> # ::std::
2631// extension ::= StL<unqualified-name>
Pavel Labathba825192018-10-16 14:29:14 +00002632template <typename Derived, typename Alloc>
2633Node *
2634AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State) {
2635 if (consumeIf("StL") || consumeIf("St")) {
2636 Node *R = getDerived().parseUnqualifiedName(State);
2637 if (R == nullptr)
2638 return nullptr;
2639 return make<StdQualifiedName>(R);
2640 }
2641 return getDerived().parseUnqualifiedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002642}
2643
2644// <unqualified-name> ::= <operator-name> [abi-tags]
2645// ::= <ctor-dtor-name>
2646// ::= <source-name>
2647// ::= <unnamed-type-name>
2648// ::= DC <source-name>+ E # structured binding declaration
Pavel Labathba825192018-10-16 14:29:14 +00002649template <typename Derived, typename Alloc>
2650Node *
2651AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002652 // <ctor-dtor-name>s are special-cased in parseNestedName().
2653 Node *Result;
2654 if (look() == 'U')
Pavel Labathba825192018-10-16 14:29:14 +00002655 Result = getDerived().parseUnnamedTypeName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002656 else if (look() >= '1' && look() <= '9')
Pavel Labathba825192018-10-16 14:29:14 +00002657 Result = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002658 else if (consumeIf("DC")) {
2659 size_t BindingsBegin = Names.size();
2660 do {
Pavel Labathba825192018-10-16 14:29:14 +00002661 Node *Binding = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002662 if (Binding == nullptr)
2663 return nullptr;
2664 Names.push_back(Binding);
2665 } while (!consumeIf('E'));
2666 Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
2667 } else
Pavel Labathba825192018-10-16 14:29:14 +00002668 Result = getDerived().parseOperatorName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002669 if (Result != nullptr)
Pavel Labathba825192018-10-16 14:29:14 +00002670 Result = getDerived().parseAbiTags(Result);
Richard Smithc20d1442018-08-20 20:14:49 +00002671 return Result;
2672}
2673
2674// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2675// ::= <closure-type-name>
2676//
2677// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2678//
2679// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
Pavel Labathba825192018-10-16 14:29:14 +00002680template <typename Derived, typename Alloc>
2681Node *
Richard Smithdf1c14c2019-09-06 23:53:21 +00002682AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
2683 // <template-params> refer to the innermost <template-args>. Clear out any
2684 // outer args that we may have inserted into TemplateParams.
2685 if (State != nullptr)
2686 TemplateParams.clear();
2687
Richard Smithc20d1442018-08-20 20:14:49 +00002688 if (consumeIf("Ut")) {
2689 StringView Count = parseNumber();
2690 if (!consumeIf('_'))
2691 return nullptr;
2692 return make<UnnamedTypeName>(Count);
2693 }
2694 if (consumeIf("Ul")) {
Richard Smithdf1c14c2019-09-06 23:53:21 +00002695 SwapAndRestore<size_t> SwapParams(ParsingLambdaParamsAtLevel,
2696 TemplateParams.size());
2697 ScopedTemplateParamList LambdaTemplateParams(this);
2698
2699 size_t ParamsBegin = Names.size();
2700 while (look() == 'T' &&
2701 StringView("yptn").find(look(1)) != StringView::npos) {
2702 Node *T = parseTemplateParamDecl();
2703 if (!T)
2704 return nullptr;
2705 LambdaTemplateParams.push_back(T);
2706 Names.push_back(T);
2707 }
2708 NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
2709
2710 // FIXME: If TempParams is empty and none of the function parameters
2711 // includes 'auto', we should remove LambdaTemplateParams from the
2712 // TemplateParams list. Unfortunately, we don't find out whether there are
2713 // any 'auto' parameters until too late in an example such as:
2714 //
2715 // template<typename T> void f(
2716 // decltype([](decltype([]<typename T>(T v) {}),
2717 // auto) {})) {}
2718 // template<typename T> void f(
2719 // decltype([](decltype([]<typename T>(T w) {}),
2720 // int) {})) {}
2721 //
2722 // Here, the type of v is at level 2 but the type of w is at level 1. We
2723 // don't find this out until we encounter the type of the next parameter.
2724 //
2725 // However, compilers can't actually cope with the former example in
2726 // practice, and it's likely to be made ill-formed in future, so we don't
2727 // need to support it here.
2728 //
2729 // If we encounter an 'auto' in the function parameter types, we will
2730 // recreate a template parameter scope for it, but any intervening lambdas
2731 // will be parsed in the 'wrong' template parameter depth.
2732 if (TempParams.empty())
2733 TemplateParams.pop_back();
2734
Richard Smithc20d1442018-08-20 20:14:49 +00002735 if (!consumeIf("vE")) {
Richard Smithc20d1442018-08-20 20:14:49 +00002736 do {
Pavel Labathba825192018-10-16 14:29:14 +00002737 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00002738 if (P == nullptr)
2739 return nullptr;
2740 Names.push_back(P);
2741 } while (!consumeIf('E'));
Richard Smithc20d1442018-08-20 20:14:49 +00002742 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00002743 NodeArray Params = popTrailingNodeArray(ParamsBegin);
2744
Richard Smithc20d1442018-08-20 20:14:49 +00002745 StringView Count = parseNumber();
2746 if (!consumeIf('_'))
2747 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002748 return make<ClosureTypeName>(TempParams, Params, Count);
Richard Smithc20d1442018-08-20 20:14:49 +00002749 }
Erik Pilkington974b6542019-01-17 21:37:51 +00002750 if (consumeIf("Ub")) {
2751 (void)parseNumber();
2752 if (!consumeIf('_'))
2753 return nullptr;
2754 return make<NameType>("'block-literal'");
2755 }
Richard Smithc20d1442018-08-20 20:14:49 +00002756 return nullptr;
2757}
2758
2759// <source-name> ::= <positive length number> <identifier>
Pavel Labathba825192018-10-16 14:29:14 +00002760template <typename Derived, typename Alloc>
2761Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
Richard Smithc20d1442018-08-20 20:14:49 +00002762 size_t Length = 0;
2763 if (parsePositiveInteger(&Length))
2764 return nullptr;
2765 if (numLeft() < Length || Length == 0)
2766 return nullptr;
2767 StringView Name(First, First + Length);
2768 First += Length;
2769 if (Name.startsWith("_GLOBAL__N"))
2770 return make<NameType>("(anonymous namespace)");
2771 return make<NameType>(Name);
2772}
2773
2774// <operator-name> ::= aa # &&
2775// ::= ad # & (unary)
2776// ::= an # &
2777// ::= aN # &=
2778// ::= aS # =
2779// ::= cl # ()
2780// ::= cm # ,
2781// ::= co # ~
2782// ::= cv <type> # (cast)
2783// ::= da # delete[]
2784// ::= de # * (unary)
2785// ::= dl # delete
2786// ::= dv # /
2787// ::= dV # /=
2788// ::= eo # ^
2789// ::= eO # ^=
2790// ::= eq # ==
2791// ::= ge # >=
2792// ::= gt # >
2793// ::= ix # []
2794// ::= le # <=
2795// ::= li <source-name> # operator ""
2796// ::= ls # <<
2797// ::= lS # <<=
2798// ::= lt # <
2799// ::= mi # -
2800// ::= mI # -=
2801// ::= ml # *
2802// ::= mL # *=
2803// ::= mm # -- (postfix in <expression> context)
2804// ::= na # new[]
2805// ::= ne # !=
2806// ::= ng # - (unary)
2807// ::= nt # !
2808// ::= nw # new
2809// ::= oo # ||
2810// ::= or # |
2811// ::= oR # |=
2812// ::= pm # ->*
2813// ::= pl # +
2814// ::= pL # +=
2815// ::= pp # ++ (postfix in <expression> context)
2816// ::= ps # + (unary)
2817// ::= pt # ->
2818// ::= qu # ?
2819// ::= rm # %
2820// ::= rM # %=
2821// ::= rs # >>
2822// ::= rS # >>=
2823// ::= ss # <=> C++2a
2824// ::= v <digit> <source-name> # vendor extended operator
Pavel Labathba825192018-10-16 14:29:14 +00002825template <typename Derived, typename Alloc>
2826Node *
2827AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002828 switch (look()) {
2829 case 'a':
2830 switch (look(1)) {
2831 case 'a':
2832 First += 2;
2833 return make<NameType>("operator&&");
2834 case 'd':
2835 case 'n':
2836 First += 2;
2837 return make<NameType>("operator&");
2838 case 'N':
2839 First += 2;
2840 return make<NameType>("operator&=");
2841 case 'S':
2842 First += 2;
2843 return make<NameType>("operator=");
2844 }
2845 return nullptr;
2846 case 'c':
2847 switch (look(1)) {
2848 case 'l':
2849 First += 2;
2850 return make<NameType>("operator()");
2851 case 'm':
2852 First += 2;
2853 return make<NameType>("operator,");
2854 case 'o':
2855 First += 2;
2856 return make<NameType>("operator~");
2857 // ::= cv <type> # (cast)
2858 case 'v': {
2859 First += 2;
2860 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2861 // If we're parsing an encoding, State != nullptr and the conversion
2862 // operators' <type> could have a <template-param> that refers to some
2863 // <template-arg>s further ahead in the mangled name.
2864 SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences,
2865 PermitForwardTemplateReferences ||
2866 State != nullptr);
Pavel Labathba825192018-10-16 14:29:14 +00002867 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00002868 if (Ty == nullptr)
2869 return nullptr;
2870 if (State) State->CtorDtorConversion = true;
2871 return make<ConversionOperatorType>(Ty);
2872 }
2873 }
2874 return nullptr;
2875 case 'd':
2876 switch (look(1)) {
2877 case 'a':
2878 First += 2;
2879 return make<NameType>("operator delete[]");
2880 case 'e':
2881 First += 2;
2882 return make<NameType>("operator*");
2883 case 'l':
2884 First += 2;
2885 return make<NameType>("operator delete");
2886 case 'v':
2887 First += 2;
2888 return make<NameType>("operator/");
2889 case 'V':
2890 First += 2;
2891 return make<NameType>("operator/=");
2892 }
2893 return nullptr;
2894 case 'e':
2895 switch (look(1)) {
2896 case 'o':
2897 First += 2;
2898 return make<NameType>("operator^");
2899 case 'O':
2900 First += 2;
2901 return make<NameType>("operator^=");
2902 case 'q':
2903 First += 2;
2904 return make<NameType>("operator==");
2905 }
2906 return nullptr;
2907 case 'g':
2908 switch (look(1)) {
2909 case 'e':
2910 First += 2;
2911 return make<NameType>("operator>=");
2912 case 't':
2913 First += 2;
2914 return make<NameType>("operator>");
2915 }
2916 return nullptr;
2917 case 'i':
2918 if (look(1) == 'x') {
2919 First += 2;
2920 return make<NameType>("operator[]");
2921 }
2922 return nullptr;
2923 case 'l':
2924 switch (look(1)) {
2925 case 'e':
2926 First += 2;
2927 return make<NameType>("operator<=");
2928 // ::= li <source-name> # operator ""
2929 case 'i': {
2930 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00002931 Node *SN = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002932 if (SN == nullptr)
2933 return nullptr;
2934 return make<LiteralOperator>(SN);
2935 }
2936 case 's':
2937 First += 2;
2938 return make<NameType>("operator<<");
2939 case 'S':
2940 First += 2;
2941 return make<NameType>("operator<<=");
2942 case 't':
2943 First += 2;
2944 return make<NameType>("operator<");
2945 }
2946 return nullptr;
2947 case 'm':
2948 switch (look(1)) {
2949 case 'i':
2950 First += 2;
2951 return make<NameType>("operator-");
2952 case 'I':
2953 First += 2;
2954 return make<NameType>("operator-=");
2955 case 'l':
2956 First += 2;
2957 return make<NameType>("operator*");
2958 case 'L':
2959 First += 2;
2960 return make<NameType>("operator*=");
2961 case 'm':
2962 First += 2;
2963 return make<NameType>("operator--");
2964 }
2965 return nullptr;
2966 case 'n':
2967 switch (look(1)) {
2968 case 'a':
2969 First += 2;
2970 return make<NameType>("operator new[]");
2971 case 'e':
2972 First += 2;
2973 return make<NameType>("operator!=");
2974 case 'g':
2975 First += 2;
2976 return make<NameType>("operator-");
2977 case 't':
2978 First += 2;
2979 return make<NameType>("operator!");
2980 case 'w':
2981 First += 2;
2982 return make<NameType>("operator new");
2983 }
2984 return nullptr;
2985 case 'o':
2986 switch (look(1)) {
2987 case 'o':
2988 First += 2;
2989 return make<NameType>("operator||");
2990 case 'r':
2991 First += 2;
2992 return make<NameType>("operator|");
2993 case 'R':
2994 First += 2;
2995 return make<NameType>("operator|=");
2996 }
2997 return nullptr;
2998 case 'p':
2999 switch (look(1)) {
3000 case 'm':
3001 First += 2;
3002 return make<NameType>("operator->*");
3003 case 'l':
3004 First += 2;
3005 return make<NameType>("operator+");
3006 case 'L':
3007 First += 2;
3008 return make<NameType>("operator+=");
3009 case 'p':
3010 First += 2;
3011 return make<NameType>("operator++");
3012 case 's':
3013 First += 2;
3014 return make<NameType>("operator+");
3015 case 't':
3016 First += 2;
3017 return make<NameType>("operator->");
3018 }
3019 return nullptr;
3020 case 'q':
3021 if (look(1) == 'u') {
3022 First += 2;
3023 return make<NameType>("operator?");
3024 }
3025 return nullptr;
3026 case 'r':
3027 switch (look(1)) {
3028 case 'm':
3029 First += 2;
3030 return make<NameType>("operator%");
3031 case 'M':
3032 First += 2;
3033 return make<NameType>("operator%=");
3034 case 's':
3035 First += 2;
3036 return make<NameType>("operator>>");
3037 case 'S':
3038 First += 2;
3039 return make<NameType>("operator>>=");
3040 }
3041 return nullptr;
3042 case 's':
3043 if (look(1) == 's') {
3044 First += 2;
3045 return make<NameType>("operator<=>");
3046 }
3047 return nullptr;
3048 // ::= v <digit> <source-name> # vendor extended operator
3049 case 'v':
3050 if (std::isdigit(look(1))) {
3051 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00003052 Node *SN = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00003053 if (SN == nullptr)
3054 return nullptr;
3055 return make<ConversionOperatorType>(SN);
3056 }
3057 return nullptr;
3058 }
3059 return nullptr;
3060}
3061
3062// <ctor-dtor-name> ::= C1 # complete object constructor
3063// ::= C2 # base object constructor
3064// ::= C3 # complete object allocating constructor
Nico Weber29294792019-04-03 23:14:33 +00003065// extension ::= C4 # gcc old-style "[unified]" constructor
3066// extension ::= C5 # the COMDAT used for ctors
Richard Smithc20d1442018-08-20 20:14:49 +00003067// ::= D0 # deleting destructor
3068// ::= D1 # complete object destructor
3069// ::= D2 # base object destructor
Nico Weber29294792019-04-03 23:14:33 +00003070// extension ::= D4 # gcc old-style "[unified]" destructor
3071// extension ::= D5 # the COMDAT used for dtors
Pavel Labathba825192018-10-16 14:29:14 +00003072template <typename Derived, typename Alloc>
3073Node *
3074AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
3075 NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003076 if (SoFar->getKind() == Node::KSpecialSubstitution) {
3077 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
3078 switch (SSK) {
3079 case SpecialSubKind::string:
3080 case SpecialSubKind::istream:
3081 case SpecialSubKind::ostream:
3082 case SpecialSubKind::iostream:
3083 SoFar = make<ExpandedSpecialSubstitution>(SSK);
Richard Smithb485b352018-08-24 23:30:26 +00003084 if (!SoFar)
3085 return nullptr;
Reid Klecknere76aabe2018-11-01 18:24:03 +00003086 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003087 default:
3088 break;
3089 }
3090 }
3091
3092 if (consumeIf('C')) {
3093 bool IsInherited = consumeIf('I');
Nico Weber29294792019-04-03 23:14:33 +00003094 if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
3095 look() != '5')
Richard Smithc20d1442018-08-20 20:14:49 +00003096 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003097 int Variant = look() - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003098 ++First;
3099 if (State) State->CtorDtorConversion = true;
3100 if (IsInherited) {
Pavel Labathba825192018-10-16 14:29:14 +00003101 if (getDerived().parseName(State) == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00003102 return nullptr;
3103 }
Nico Weber29294792019-04-03 23:14:33 +00003104 return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003105 }
3106
Nico Weber29294792019-04-03 23:14:33 +00003107 if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
3108 look(1) == '4' || look(1) == '5')) {
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003109 int Variant = look(1) - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003110 First += 2;
3111 if (State) State->CtorDtorConversion = true;
Nico Weber29294792019-04-03 23:14:33 +00003112 return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003113 }
3114
3115 return nullptr;
3116}
3117
3118// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
3119// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
3120//
3121// <prefix> ::= <prefix> <unqualified-name>
3122// ::= <template-prefix> <template-args>
3123// ::= <template-param>
3124// ::= <decltype>
3125// ::= # empty
3126// ::= <substitution>
3127// ::= <prefix> <data-member-prefix>
3128// extension ::= L
3129//
3130// <data-member-prefix> := <member source-name> [<template-args>] M
3131//
3132// <template-prefix> ::= <prefix> <template unqualified-name>
3133// ::= <template-param>
3134// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003135template <typename Derived, typename Alloc>
3136Node *
3137AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003138 if (!consumeIf('N'))
3139 return nullptr;
3140
3141 Qualifiers CVTmp = parseCVQualifiers();
3142 if (State) State->CVQualifiers = CVTmp;
3143
3144 if (consumeIf('O')) {
3145 if (State) State->ReferenceQualifier = FrefQualRValue;
3146 } else if (consumeIf('R')) {
3147 if (State) State->ReferenceQualifier = FrefQualLValue;
3148 } else
3149 if (State) State->ReferenceQualifier = FrefQualNone;
3150
3151 Node *SoFar = nullptr;
3152 auto PushComponent = [&](Node *Comp) {
Richard Smithb485b352018-08-24 23:30:26 +00003153 if (!Comp) return false;
Richard Smithc20d1442018-08-20 20:14:49 +00003154 if (SoFar) SoFar = make<NestedName>(SoFar, Comp);
3155 else SoFar = Comp;
3156 if (State) State->EndsWithTemplateArgs = false;
Richard Smithb485b352018-08-24 23:30:26 +00003157 return SoFar != nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003158 };
3159
Richard Smithb485b352018-08-24 23:30:26 +00003160 if (consumeIf("St")) {
Richard Smithc20d1442018-08-20 20:14:49 +00003161 SoFar = make<NameType>("std");
Richard Smithb485b352018-08-24 23:30:26 +00003162 if (!SoFar)
3163 return nullptr;
3164 }
Richard Smithc20d1442018-08-20 20:14:49 +00003165
3166 while (!consumeIf('E')) {
3167 consumeIf('L'); // extension
3168
3169 // <data-member-prefix> := <member source-name> [<template-args>] M
3170 if (consumeIf('M')) {
3171 if (SoFar == nullptr)
3172 return nullptr;
3173 continue;
3174 }
3175
3176 // ::= <template-param>
3177 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00003178 if (!PushComponent(getDerived().parseTemplateParam()))
Richard Smithc20d1442018-08-20 20:14:49 +00003179 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003180 Subs.push_back(SoFar);
3181 continue;
3182 }
3183
3184 // ::= <template-prefix> <template-args>
3185 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003186 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003187 if (TA == nullptr || SoFar == nullptr)
3188 return nullptr;
3189 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003190 if (!SoFar)
3191 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003192 if (State) State->EndsWithTemplateArgs = true;
3193 Subs.push_back(SoFar);
3194 continue;
3195 }
3196
3197 // ::= <decltype>
3198 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
Pavel Labathba825192018-10-16 14:29:14 +00003199 if (!PushComponent(getDerived().parseDecltype()))
Richard Smithc20d1442018-08-20 20:14:49 +00003200 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003201 Subs.push_back(SoFar);
3202 continue;
3203 }
3204
3205 // ::= <substitution>
3206 if (look() == 'S' && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00003207 Node *S = getDerived().parseSubstitution();
Richard Smithb485b352018-08-24 23:30:26 +00003208 if (!PushComponent(S))
Richard Smithc20d1442018-08-20 20:14:49 +00003209 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003210 if (SoFar != S)
3211 Subs.push_back(S);
3212 continue;
3213 }
3214
3215 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
3216 if (look() == 'C' || (look() == 'D' && look(1) != 'C')) {
3217 if (SoFar == nullptr)
3218 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003219 if (!PushComponent(getDerived().parseCtorDtorName(SoFar, State)))
Richard Smithc20d1442018-08-20 20:14:49 +00003220 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003221 SoFar = getDerived().parseAbiTags(SoFar);
Richard Smithc20d1442018-08-20 20:14:49 +00003222 if (SoFar == nullptr)
3223 return nullptr;
3224 Subs.push_back(SoFar);
3225 continue;
3226 }
3227
3228 // ::= <prefix> <unqualified-name>
Pavel Labathba825192018-10-16 14:29:14 +00003229 if (!PushComponent(getDerived().parseUnqualifiedName(State)))
Richard Smithc20d1442018-08-20 20:14:49 +00003230 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003231 Subs.push_back(SoFar);
3232 }
3233
3234 if (SoFar == nullptr || Subs.empty())
3235 return nullptr;
3236
3237 Subs.pop_back();
3238 return SoFar;
3239}
3240
3241// <simple-id> ::= <source-name> [ <template-args> ]
Pavel Labathba825192018-10-16 14:29:14 +00003242template <typename Derived, typename Alloc>
3243Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
3244 Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003245 if (SN == nullptr)
3246 return nullptr;
3247 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003248 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003249 if (TA == nullptr)
3250 return nullptr;
3251 return make<NameWithTemplateArgs>(SN, TA);
3252 }
3253 return SN;
3254}
3255
3256// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
3257// ::= <simple-id> # e.g., ~A<2*N>
Pavel Labathba825192018-10-16 14:29:14 +00003258template <typename Derived, typename Alloc>
3259Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003260 Node *Result;
3261 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003262 Result = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003263 else
Pavel Labathba825192018-10-16 14:29:14 +00003264 Result = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003265 if (Result == nullptr)
3266 return nullptr;
3267 return make<DtorName>(Result);
3268}
3269
3270// <unresolved-type> ::= <template-param>
3271// ::= <decltype>
3272// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003273template <typename Derived, typename Alloc>
3274Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003275 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00003276 Node *TP = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003277 if (TP == nullptr)
3278 return nullptr;
3279 Subs.push_back(TP);
3280 return TP;
3281 }
3282 if (look() == 'D') {
Pavel Labathba825192018-10-16 14:29:14 +00003283 Node *DT = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003284 if (DT == nullptr)
3285 return nullptr;
3286 Subs.push_back(DT);
3287 return DT;
3288 }
Pavel Labathba825192018-10-16 14:29:14 +00003289 return getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00003290}
3291
3292// <base-unresolved-name> ::= <simple-id> # unresolved name
3293// extension ::= <operator-name> # unresolved operator-function-id
3294// extension ::= <operator-name> <template-args> # unresolved operator template-id
3295// ::= on <operator-name> # unresolved operator-function-id
3296// ::= on <operator-name> <template-args> # unresolved operator template-id
3297// ::= dn <destructor-name> # destructor or pseudo-destructor;
3298// # e.g. ~X or ~X<N-1>
Pavel Labathba825192018-10-16 14:29:14 +00003299template <typename Derived, typename Alloc>
3300Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003301 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003302 return getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003303
3304 if (consumeIf("dn"))
Pavel Labathba825192018-10-16 14:29:14 +00003305 return getDerived().parseDestructorName();
Richard Smithc20d1442018-08-20 20:14:49 +00003306
3307 consumeIf("on");
3308
Pavel Labathba825192018-10-16 14:29:14 +00003309 Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003310 if (Oper == nullptr)
3311 return nullptr;
3312 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003313 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003314 if (TA == nullptr)
3315 return nullptr;
3316 return make<NameWithTemplateArgs>(Oper, TA);
3317 }
3318 return Oper;
3319}
3320
3321// <unresolved-name>
3322// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3323// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
3324// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3325// # A::x, N::y, A<T>::z; "gs" means leading "::"
3326// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
3327// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
3328// # T::N::x /decltype(p)::N::x
3329// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3330//
3331// <unresolved-qualifier-level> ::= <simple-id>
Pavel Labathba825192018-10-16 14:29:14 +00003332template <typename Derived, typename Alloc>
3333Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003334 Node *SoFar = nullptr;
3335
3336 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3337 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3338 if (consumeIf("srN")) {
Pavel Labathba825192018-10-16 14:29:14 +00003339 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003340 if (SoFar == nullptr)
3341 return nullptr;
3342
3343 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003344 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003345 if (TA == nullptr)
3346 return nullptr;
3347 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003348 if (!SoFar)
3349 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003350 }
3351
3352 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003353 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003354 if (Qual == nullptr)
3355 return nullptr;
3356 SoFar = make<QualifiedName>(SoFar, Qual);
Richard Smithb485b352018-08-24 23:30:26 +00003357 if (!SoFar)
3358 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003359 }
3360
Pavel Labathba825192018-10-16 14:29:14 +00003361 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003362 if (Base == nullptr)
3363 return nullptr;
3364 return make<QualifiedName>(SoFar, Base);
3365 }
3366
3367 bool Global = consumeIf("gs");
3368
3369 // [gs] <base-unresolved-name> # x or (with "gs") ::x
3370 if (!consumeIf("sr")) {
Pavel Labathba825192018-10-16 14:29:14 +00003371 SoFar = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003372 if (SoFar == nullptr)
3373 return nullptr;
3374 if (Global)
3375 SoFar = make<GlobalQualifiedName>(SoFar);
3376 return SoFar;
3377 }
3378
3379 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3380 if (std::isdigit(look())) {
3381 do {
Pavel Labathba825192018-10-16 14:29:14 +00003382 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003383 if (Qual == nullptr)
3384 return nullptr;
3385 if (SoFar)
3386 SoFar = make<QualifiedName>(SoFar, Qual);
3387 else if (Global)
3388 SoFar = make<GlobalQualifiedName>(Qual);
3389 else
3390 SoFar = Qual;
Richard Smithb485b352018-08-24 23:30:26 +00003391 if (!SoFar)
3392 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003393 } while (!consumeIf('E'));
3394 }
3395 // sr <unresolved-type> <base-unresolved-name>
3396 // sr <unresolved-type> <template-args> <base-unresolved-name>
3397 else {
Pavel Labathba825192018-10-16 14:29:14 +00003398 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003399 if (SoFar == nullptr)
3400 return nullptr;
3401
3402 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003403 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003404 if (TA == nullptr)
3405 return nullptr;
3406 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003407 if (!SoFar)
3408 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003409 }
3410 }
3411
3412 assert(SoFar != nullptr);
3413
Pavel Labathba825192018-10-16 14:29:14 +00003414 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003415 if (Base == nullptr)
3416 return nullptr;
3417 return make<QualifiedName>(SoFar, Base);
3418}
3419
3420// <abi-tags> ::= <abi-tag> [<abi-tags>]
3421// <abi-tag> ::= B <source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003422template <typename Derived, typename Alloc>
3423Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
Richard Smithc20d1442018-08-20 20:14:49 +00003424 while (consumeIf('B')) {
3425 StringView SN = parseBareSourceName();
3426 if (SN.empty())
3427 return nullptr;
3428 N = make<AbiTagAttr>(N, SN);
Richard Smithb485b352018-08-24 23:30:26 +00003429 if (!N)
3430 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003431 }
3432 return N;
3433}
3434
3435// <number> ::= [n] <non-negative decimal integer>
Pavel Labathba825192018-10-16 14:29:14 +00003436template <typename Alloc, typename Derived>
3437StringView
3438AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
Richard Smithc20d1442018-08-20 20:14:49 +00003439 const char *Tmp = First;
3440 if (AllowNegative)
3441 consumeIf('n');
3442 if (numLeft() == 0 || !std::isdigit(*First))
3443 return StringView();
3444 while (numLeft() != 0 && std::isdigit(*First))
3445 ++First;
3446 return StringView(Tmp, First);
3447}
3448
3449// <positive length number> ::= [0-9]*
Pavel Labathba825192018-10-16 14:29:14 +00003450template <typename Alloc, typename Derived>
3451bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00003452 *Out = 0;
3453 if (look() < '0' || look() > '9')
3454 return true;
3455 while (look() >= '0' && look() <= '9') {
3456 *Out *= 10;
3457 *Out += static_cast<size_t>(consume() - '0');
3458 }
3459 return false;
3460}
3461
Pavel Labathba825192018-10-16 14:29:14 +00003462template <typename Alloc, typename Derived>
3463StringView AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003464 size_t Int = 0;
3465 if (parsePositiveInteger(&Int) || numLeft() < Int)
3466 return StringView();
3467 StringView R(First, First + Int);
3468 First += Int;
3469 return R;
3470}
3471
3472// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
3473//
3474// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
3475// ::= DO <expression> E # computed (instantiation-dependent) noexcept
3476// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
3477//
3478// <ref-qualifier> ::= R # & ref-qualifier
3479// <ref-qualifier> ::= O # && ref-qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003480template <typename Derived, typename Alloc>
3481Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003482 Qualifiers CVQuals = parseCVQualifiers();
3483
3484 Node *ExceptionSpec = nullptr;
3485 if (consumeIf("Do")) {
3486 ExceptionSpec = make<NameType>("noexcept");
Richard Smithb485b352018-08-24 23:30:26 +00003487 if (!ExceptionSpec)
3488 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003489 } else if (consumeIf("DO")) {
Pavel Labathba825192018-10-16 14:29:14 +00003490 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003491 if (E == nullptr || !consumeIf('E'))
3492 return nullptr;
3493 ExceptionSpec = make<NoexceptSpec>(E);
Richard Smithb485b352018-08-24 23:30:26 +00003494 if (!ExceptionSpec)
3495 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003496 } else if (consumeIf("Dw")) {
3497 size_t SpecsBegin = Names.size();
3498 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003499 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003500 if (T == nullptr)
3501 return nullptr;
3502 Names.push_back(T);
3503 }
3504 ExceptionSpec =
3505 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
Richard Smithb485b352018-08-24 23:30:26 +00003506 if (!ExceptionSpec)
3507 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003508 }
3509
3510 consumeIf("Dx"); // transaction safe
3511
3512 if (!consumeIf('F'))
3513 return nullptr;
3514 consumeIf('Y'); // extern "C"
Pavel Labathba825192018-10-16 14:29:14 +00003515 Node *ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003516 if (ReturnType == nullptr)
3517 return nullptr;
3518
3519 FunctionRefQual ReferenceQualifier = FrefQualNone;
3520 size_t ParamsBegin = Names.size();
3521 while (true) {
3522 if (consumeIf('E'))
3523 break;
3524 if (consumeIf('v'))
3525 continue;
3526 if (consumeIf("RE")) {
3527 ReferenceQualifier = FrefQualLValue;
3528 break;
3529 }
3530 if (consumeIf("OE")) {
3531 ReferenceQualifier = FrefQualRValue;
3532 break;
3533 }
Pavel Labathba825192018-10-16 14:29:14 +00003534 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003535 if (T == nullptr)
3536 return nullptr;
3537 Names.push_back(T);
3538 }
3539
3540 NodeArray Params = popTrailingNodeArray(ParamsBegin);
3541 return make<FunctionType>(ReturnType, Params, CVQuals,
3542 ReferenceQualifier, ExceptionSpec);
3543}
3544
3545// extension:
3546// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3547// ::= Dv [<dimension expression>] _ <element type>
3548// <extended element type> ::= <element type>
3549// ::= p # AltiVec vector pixel
Pavel Labathba825192018-10-16 14:29:14 +00003550template <typename Derived, typename Alloc>
3551Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003552 if (!consumeIf("Dv"))
3553 return nullptr;
3554 if (look() >= '1' && look() <= '9') {
3555 StringView DimensionNumber = parseNumber();
3556 if (!consumeIf('_'))
3557 return nullptr;
3558 if (consumeIf('p'))
3559 return make<PixelVectorType>(DimensionNumber);
Pavel Labathba825192018-10-16 14:29:14 +00003560 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003561 if (ElemType == nullptr)
3562 return nullptr;
3563 return make<VectorType>(ElemType, DimensionNumber);
3564 }
3565
3566 if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003567 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003568 if (!DimExpr)
3569 return nullptr;
3570 if (!consumeIf('_'))
3571 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003572 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003573 if (!ElemType)
3574 return nullptr;
3575 return make<VectorType>(ElemType, DimExpr);
3576 }
Pavel Labathba825192018-10-16 14:29:14 +00003577 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003578 if (!ElemType)
3579 return nullptr;
3580 return make<VectorType>(ElemType, StringView());
3581}
3582
3583// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3584// ::= DT <expression> E # decltype of an expression (C++0x)
Pavel Labathba825192018-10-16 14:29:14 +00003585template <typename Derived, typename Alloc>
3586Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
Richard Smithc20d1442018-08-20 20:14:49 +00003587 if (!consumeIf('D'))
3588 return nullptr;
3589 if (!consumeIf('t') && !consumeIf('T'))
3590 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003591 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003592 if (E == nullptr)
3593 return nullptr;
3594 if (!consumeIf('E'))
3595 return nullptr;
3596 return make<EnclosingExpr>("decltype(", E, ")");
3597}
3598
3599// <array-type> ::= A <positive dimension number> _ <element type>
3600// ::= A [<dimension expression>] _ <element type>
Pavel Labathba825192018-10-16 14:29:14 +00003601template <typename Derived, typename Alloc>
3602Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003603 if (!consumeIf('A'))
3604 return nullptr;
3605
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003606 NodeOrString Dimension;
3607
Richard Smithc20d1442018-08-20 20:14:49 +00003608 if (std::isdigit(look())) {
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003609 Dimension = parseNumber();
Richard Smithc20d1442018-08-20 20:14:49 +00003610 if (!consumeIf('_'))
3611 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003612 } else if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003613 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003614 if (DimExpr == nullptr)
3615 return nullptr;
3616 if (!consumeIf('_'))
3617 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003618 Dimension = DimExpr;
Richard Smithc20d1442018-08-20 20:14:49 +00003619 }
3620
Pavel Labathba825192018-10-16 14:29:14 +00003621 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003622 if (Ty == nullptr)
3623 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003624 return make<ArrayType>(Ty, Dimension);
Richard Smithc20d1442018-08-20 20:14:49 +00003625}
3626
3627// <pointer-to-member-type> ::= M <class type> <member type>
Pavel Labathba825192018-10-16 14:29:14 +00003628template <typename Derived, typename Alloc>
3629Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003630 if (!consumeIf('M'))
3631 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003632 Node *ClassType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003633 if (ClassType == nullptr)
3634 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003635 Node *MemberType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003636 if (MemberType == nullptr)
3637 return nullptr;
3638 return make<PointerToMemberType>(ClassType, MemberType);
3639}
3640
3641// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3642// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3643// ::= Tu <name> # dependent elaborated type specifier using 'union'
3644// ::= Te <name> # dependent elaborated type specifier using 'enum'
Pavel Labathba825192018-10-16 14:29:14 +00003645template <typename Derived, typename Alloc>
3646Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003647 StringView ElabSpef;
3648 if (consumeIf("Ts"))
3649 ElabSpef = "struct";
3650 else if (consumeIf("Tu"))
3651 ElabSpef = "union";
3652 else if (consumeIf("Te"))
3653 ElabSpef = "enum";
3654
Pavel Labathba825192018-10-16 14:29:14 +00003655 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00003656 if (Name == nullptr)
3657 return nullptr;
3658
3659 if (!ElabSpef.empty())
3660 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3661
3662 return Name;
3663}
3664
3665// <qualified-type> ::= <qualifiers> <type>
3666// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3667// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003668template <typename Derived, typename Alloc>
3669Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003670 if (consumeIf('U')) {
3671 StringView Qual = parseBareSourceName();
3672 if (Qual.empty())
3673 return nullptr;
3674
3675 // FIXME parse the optional <template-args> here!
3676
3677 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3678 if (Qual.startsWith("objcproto")) {
3679 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3680 StringView Proto;
3681 {
3682 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3683 SaveLast(Last, ProtoSourceName.end());
3684 Proto = parseBareSourceName();
3685 }
3686 if (Proto.empty())
3687 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003688 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003689 if (Child == nullptr)
3690 return nullptr;
3691 return make<ObjCProtoName>(Child, Proto);
3692 }
3693
Pavel Labathba825192018-10-16 14:29:14 +00003694 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003695 if (Child == nullptr)
3696 return nullptr;
3697 return make<VendorExtQualType>(Child, Qual);
3698 }
3699
3700 Qualifiers Quals = parseCVQualifiers();
Pavel Labathba825192018-10-16 14:29:14 +00003701 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003702 if (Ty == nullptr)
3703 return nullptr;
3704 if (Quals != QualNone)
3705 Ty = make<QualType>(Ty, Quals);
3706 return Ty;
3707}
3708
3709// <type> ::= <builtin-type>
3710// ::= <qualified-type>
3711// ::= <function-type>
3712// ::= <class-enum-type>
3713// ::= <array-type>
3714// ::= <pointer-to-member-type>
3715// ::= <template-param>
3716// ::= <template-template-param> <template-args>
3717// ::= <decltype>
3718// ::= P <type> # pointer
3719// ::= R <type> # l-value reference
3720// ::= O <type> # r-value reference (C++11)
3721// ::= C <type> # complex pair (C99)
3722// ::= G <type> # imaginary (C99)
3723// ::= <substitution> # See Compression below
3724// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3725// extension ::= <vector-type> # <vector-type> starts with Dv
3726//
3727// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3728// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003729template <typename Derived, typename Alloc>
3730Node *AbstractManglingParser<Derived, Alloc>::parseType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003731 Node *Result = nullptr;
3732
Richard Smithc20d1442018-08-20 20:14:49 +00003733 switch (look()) {
3734 // ::= <qualified-type>
3735 case 'r':
3736 case 'V':
3737 case 'K': {
3738 unsigned AfterQuals = 0;
3739 if (look(AfterQuals) == 'r') ++AfterQuals;
3740 if (look(AfterQuals) == 'V') ++AfterQuals;
3741 if (look(AfterQuals) == 'K') ++AfterQuals;
3742
3743 if (look(AfterQuals) == 'F' ||
3744 (look(AfterQuals) == 'D' &&
3745 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3746 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Pavel Labathba825192018-10-16 14:29:14 +00003747 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003748 break;
3749 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00003750 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00003751 }
3752 case 'U': {
Pavel Labathba825192018-10-16 14:29:14 +00003753 Result = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003754 break;
3755 }
3756 // <builtin-type> ::= v # void
3757 case 'v':
3758 ++First;
3759 return make<NameType>("void");
3760 // ::= w # wchar_t
3761 case 'w':
3762 ++First;
3763 return make<NameType>("wchar_t");
3764 // ::= b # bool
3765 case 'b':
3766 ++First;
3767 return make<NameType>("bool");
3768 // ::= c # char
3769 case 'c':
3770 ++First;
3771 return make<NameType>("char");
3772 // ::= a # signed char
3773 case 'a':
3774 ++First;
3775 return make<NameType>("signed char");
3776 // ::= h # unsigned char
3777 case 'h':
3778 ++First;
3779 return make<NameType>("unsigned char");
3780 // ::= s # short
3781 case 's':
3782 ++First;
3783 return make<NameType>("short");
3784 // ::= t # unsigned short
3785 case 't':
3786 ++First;
3787 return make<NameType>("unsigned short");
3788 // ::= i # int
3789 case 'i':
3790 ++First;
3791 return make<NameType>("int");
3792 // ::= j # unsigned int
3793 case 'j':
3794 ++First;
3795 return make<NameType>("unsigned int");
3796 // ::= l # long
3797 case 'l':
3798 ++First;
3799 return make<NameType>("long");
3800 // ::= m # unsigned long
3801 case 'm':
3802 ++First;
3803 return make<NameType>("unsigned long");
3804 // ::= x # long long, __int64
3805 case 'x':
3806 ++First;
3807 return make<NameType>("long long");
3808 // ::= y # unsigned long long, __int64
3809 case 'y':
3810 ++First;
3811 return make<NameType>("unsigned long long");
3812 // ::= n # __int128
3813 case 'n':
3814 ++First;
3815 return make<NameType>("__int128");
3816 // ::= o # unsigned __int128
3817 case 'o':
3818 ++First;
3819 return make<NameType>("unsigned __int128");
3820 // ::= f # float
3821 case 'f':
3822 ++First;
3823 return make<NameType>("float");
3824 // ::= d # double
3825 case 'd':
3826 ++First;
3827 return make<NameType>("double");
3828 // ::= e # long double, __float80
3829 case 'e':
3830 ++First;
3831 return make<NameType>("long double");
3832 // ::= g # __float128
3833 case 'g':
3834 ++First;
3835 return make<NameType>("__float128");
3836 // ::= z # ellipsis
3837 case 'z':
3838 ++First;
3839 return make<NameType>("...");
3840
3841 // <builtin-type> ::= u <source-name> # vendor extended type
3842 case 'u': {
3843 ++First;
3844 StringView Res = parseBareSourceName();
3845 if (Res.empty())
3846 return nullptr;
Erik Pilkingtonb94a1f42019-06-10 21:02:39 +00003847 // Typically, <builtin-type>s are not considered substitution candidates,
3848 // but the exception to that exception is vendor extended types (Itanium C++
3849 // ABI 5.9.1).
3850 Result = make<NameType>(Res);
3851 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003852 }
3853 case 'D':
3854 switch (look(1)) {
3855 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3856 case 'd':
3857 First += 2;
3858 return make<NameType>("decimal64");
3859 // ::= De # IEEE 754r decimal floating point (128 bits)
3860 case 'e':
3861 First += 2;
3862 return make<NameType>("decimal128");
3863 // ::= Df # IEEE 754r decimal floating point (32 bits)
3864 case 'f':
3865 First += 2;
3866 return make<NameType>("decimal32");
3867 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3868 case 'h':
3869 First += 2;
3870 return make<NameType>("decimal16");
3871 // ::= Di # char32_t
3872 case 'i':
3873 First += 2;
3874 return make<NameType>("char32_t");
3875 // ::= Ds # char16_t
3876 case 's':
3877 First += 2;
3878 return make<NameType>("char16_t");
Erik Pilkingtonc3780e82019-06-28 19:54:19 +00003879 // ::= Du # char8_t (C++2a, not yet in the Itanium spec)
3880 case 'u':
3881 First += 2;
3882 return make<NameType>("char8_t");
Richard Smithc20d1442018-08-20 20:14:49 +00003883 // ::= Da # auto (in dependent new-expressions)
3884 case 'a':
3885 First += 2;
3886 return make<NameType>("auto");
3887 // ::= Dc # decltype(auto)
3888 case 'c':
3889 First += 2;
3890 return make<NameType>("decltype(auto)");
3891 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3892 case 'n':
3893 First += 2;
3894 return make<NameType>("std::nullptr_t");
3895
3896 // ::= <decltype>
3897 case 't':
3898 case 'T': {
Pavel Labathba825192018-10-16 14:29:14 +00003899 Result = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003900 break;
3901 }
3902 // extension ::= <vector-type> # <vector-type> starts with Dv
3903 case 'v': {
Pavel Labathba825192018-10-16 14:29:14 +00003904 Result = getDerived().parseVectorType();
Richard Smithc20d1442018-08-20 20:14:49 +00003905 break;
3906 }
3907 // ::= Dp <type> # pack expansion (C++0x)
3908 case 'p': {
3909 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00003910 Node *Child = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003911 if (!Child)
3912 return nullptr;
3913 Result = make<ParameterPackExpansion>(Child);
3914 break;
3915 }
3916 // Exception specifier on a function type.
3917 case 'o':
3918 case 'O':
3919 case 'w':
3920 // Transaction safe function type.
3921 case 'x':
Pavel Labathba825192018-10-16 14:29:14 +00003922 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003923 break;
3924 }
3925 break;
3926 // ::= <function-type>
3927 case 'F': {
Pavel Labathba825192018-10-16 14:29:14 +00003928 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003929 break;
3930 }
3931 // ::= <array-type>
3932 case 'A': {
Pavel Labathba825192018-10-16 14:29:14 +00003933 Result = getDerived().parseArrayType();
Richard Smithc20d1442018-08-20 20:14:49 +00003934 break;
3935 }
3936 // ::= <pointer-to-member-type>
3937 case 'M': {
Pavel Labathba825192018-10-16 14:29:14 +00003938 Result = getDerived().parsePointerToMemberType();
Richard Smithc20d1442018-08-20 20:14:49 +00003939 break;
3940 }
3941 // ::= <template-param>
3942 case 'T': {
3943 // This could be an elaborate type specifier on a <class-enum-type>.
3944 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
Pavel Labathba825192018-10-16 14:29:14 +00003945 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00003946 break;
3947 }
3948
Pavel Labathba825192018-10-16 14:29:14 +00003949 Result = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003950 if (Result == nullptr)
3951 return nullptr;
3952
3953 // Result could be either of:
3954 // <type> ::= <template-param>
3955 // <type> ::= <template-template-param> <template-args>
3956 //
3957 // <template-template-param> ::= <template-param>
3958 // ::= <substitution>
3959 //
3960 // If this is followed by some <template-args>, and we're permitted to
3961 // parse them, take the second production.
3962
3963 if (TryToParseTemplateArgs && look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003964 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003965 if (TA == nullptr)
3966 return nullptr;
3967 Result = make<NameWithTemplateArgs>(Result, TA);
3968 }
3969 break;
3970 }
3971 // ::= P <type> # pointer
3972 case 'P': {
3973 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00003974 Node *Ptr = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003975 if (Ptr == nullptr)
3976 return nullptr;
3977 Result = make<PointerType>(Ptr);
3978 break;
3979 }
3980 // ::= R <type> # l-value reference
3981 case 'R': {
3982 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00003983 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003984 if (Ref == nullptr)
3985 return nullptr;
3986 Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
3987 break;
3988 }
3989 // ::= O <type> # r-value reference (C++11)
3990 case 'O': {
3991 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00003992 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003993 if (Ref == nullptr)
3994 return nullptr;
3995 Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
3996 break;
3997 }
3998 // ::= C <type> # complex pair (C99)
3999 case 'C': {
4000 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004001 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004002 if (P == nullptr)
4003 return nullptr;
4004 Result = make<PostfixQualifiedType>(P, " complex");
4005 break;
4006 }
4007 // ::= G <type> # imaginary (C99)
4008 case 'G': {
4009 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004010 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004011 if (P == nullptr)
4012 return P;
4013 Result = make<PostfixQualifiedType>(P, " imaginary");
4014 break;
4015 }
4016 // ::= <substitution> # See Compression below
4017 case 'S': {
4018 if (look(1) && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00004019 Node *Sub = getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00004020 if (Sub == nullptr)
4021 return nullptr;
4022
4023 // Sub could be either of:
4024 // <type> ::= <substitution>
4025 // <type> ::= <template-template-param> <template-args>
4026 //
4027 // <template-template-param> ::= <template-param>
4028 // ::= <substitution>
4029 //
4030 // If this is followed by some <template-args>, and we're permitted to
4031 // parse them, take the second production.
4032
4033 if (TryToParseTemplateArgs && look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00004034 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00004035 if (TA == nullptr)
4036 return nullptr;
4037 Result = make<NameWithTemplateArgs>(Sub, TA);
4038 break;
4039 }
4040
4041 // If all we parsed was a substitution, don't re-insert into the
4042 // substitution table.
4043 return Sub;
4044 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00004045 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00004046 }
4047 // ::= <class-enum-type>
4048 default: {
Pavel Labathba825192018-10-16 14:29:14 +00004049 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00004050 break;
4051 }
4052 }
4053
4054 // If we parsed a type, insert it into the substitution table. Note that all
4055 // <builtin-type>s and <substitution>s have already bailed out, because they
4056 // don't get substitutions.
4057 if (Result != nullptr)
4058 Subs.push_back(Result);
4059 return Result;
4060}
4061
Pavel Labathba825192018-10-16 14:29:14 +00004062template <typename Derived, typename Alloc>
4063Node *AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(StringView Kind) {
4064 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004065 if (E == nullptr)
4066 return nullptr;
4067 return make<PrefixExpr>(Kind, E);
4068}
4069
Pavel Labathba825192018-10-16 14:29:14 +00004070template <typename Derived, typename Alloc>
4071Node *AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(StringView Kind) {
4072 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004073 if (LHS == nullptr)
4074 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004075 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004076 if (RHS == nullptr)
4077 return nullptr;
4078 return make<BinaryExpr>(LHS, Kind, RHS);
4079}
4080
Pavel Labathba825192018-10-16 14:29:14 +00004081template <typename Derived, typename Alloc>
4082Node *
4083AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(StringView Lit) {
Richard Smithc20d1442018-08-20 20:14:49 +00004084 StringView Tmp = parseNumber(true);
4085 if (!Tmp.empty() && consumeIf('E'))
4086 return make<IntegerLiteral>(Lit, Tmp);
4087 return nullptr;
4088}
4089
4090// <CV-Qualifiers> ::= [r] [V] [K]
Pavel Labathba825192018-10-16 14:29:14 +00004091template <typename Alloc, typename Derived>
4092Qualifiers AbstractManglingParser<Alloc, Derived>::parseCVQualifiers() {
Richard Smithc20d1442018-08-20 20:14:49 +00004093 Qualifiers CVR = QualNone;
4094 if (consumeIf('r'))
4095 CVR |= QualRestrict;
4096 if (consumeIf('V'))
4097 CVR |= QualVolatile;
4098 if (consumeIf('K'))
4099 CVR |= QualConst;
4100 return CVR;
4101}
4102
4103// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
4104// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
4105// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
4106// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
Pavel Labathba825192018-10-16 14:29:14 +00004107template <typename Derived, typename Alloc>
4108Node *AbstractManglingParser<Derived, Alloc>::parseFunctionParam() {
Richard Smithc20d1442018-08-20 20:14:49 +00004109 if (consumeIf("fp")) {
4110 parseCVQualifiers();
4111 StringView Num = parseNumber();
4112 if (!consumeIf('_'))
4113 return nullptr;
4114 return make<FunctionParam>(Num);
4115 }
4116 if (consumeIf("fL")) {
4117 if (parseNumber().empty())
4118 return nullptr;
4119 if (!consumeIf('p'))
4120 return nullptr;
4121 parseCVQualifiers();
4122 StringView Num = parseNumber();
4123 if (!consumeIf('_'))
4124 return nullptr;
4125 return make<FunctionParam>(Num);
4126 }
4127 return nullptr;
4128}
4129
4130// [gs] nw <expression>* _ <type> E # new (expr-list) type
4131// [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
4132// [gs] na <expression>* _ <type> E # new[] (expr-list) type
4133// [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
4134// <initializer> ::= pi <expression>* E # parenthesized initialization
Pavel Labathba825192018-10-16 14:29:14 +00004135template <typename Derived, typename Alloc>
4136Node *AbstractManglingParser<Derived, Alloc>::parseNewExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004137 bool Global = consumeIf("gs");
4138 bool IsArray = look(1) == 'a';
4139 if (!consumeIf("nw") && !consumeIf("na"))
4140 return nullptr;
4141 size_t Exprs = Names.size();
4142 while (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00004143 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004144 if (Ex == nullptr)
4145 return nullptr;
4146 Names.push_back(Ex);
4147 }
4148 NodeArray ExprList = popTrailingNodeArray(Exprs);
Pavel Labathba825192018-10-16 14:29:14 +00004149 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004150 if (Ty == nullptr)
4151 return Ty;
4152 if (consumeIf("pi")) {
4153 size_t InitsBegin = Names.size();
4154 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004155 Node *Init = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004156 if (Init == nullptr)
4157 return Init;
4158 Names.push_back(Init);
4159 }
4160 NodeArray Inits = popTrailingNodeArray(InitsBegin);
4161 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
4162 } else if (!consumeIf('E'))
4163 return nullptr;
4164 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
4165}
4166
4167// cv <type> <expression> # conversion with one argument
4168// cv <type> _ <expression>* E # conversion with a different number of arguments
Pavel Labathba825192018-10-16 14:29:14 +00004169template <typename Derived, typename Alloc>
4170Node *AbstractManglingParser<Derived, Alloc>::parseConversionExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004171 if (!consumeIf("cv"))
4172 return nullptr;
4173 Node *Ty;
4174 {
4175 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Pavel Labathba825192018-10-16 14:29:14 +00004176 Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004177 }
4178
4179 if (Ty == nullptr)
4180 return nullptr;
4181
4182 if (consumeIf('_')) {
4183 size_t ExprsBegin = Names.size();
4184 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004185 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004186 if (E == nullptr)
4187 return E;
4188 Names.push_back(E);
4189 }
4190 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
4191 return make<ConversionExpr>(Ty, Exprs);
4192 }
4193
Pavel Labathba825192018-10-16 14:29:14 +00004194 Node *E[1] = {getDerived().parseExpr()};
Richard Smithc20d1442018-08-20 20:14:49 +00004195 if (E[0] == nullptr)
4196 return nullptr;
4197 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
4198}
4199
4200// <expr-primary> ::= L <type> <value number> E # integer literal
4201// ::= L <type> <value float> E # floating literal
4202// ::= L <string type> E # string literal
4203// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
Richard Smithdf1c14c2019-09-06 23:53:21 +00004204// ::= L <lambda type> E # lambda expression
Richard Smithc20d1442018-08-20 20:14:49 +00004205// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
4206// ::= L <mangled-name> E # external name
Pavel Labathba825192018-10-16 14:29:14 +00004207template <typename Derived, typename Alloc>
4208Node *AbstractManglingParser<Derived, Alloc>::parseExprPrimary() {
Richard Smithc20d1442018-08-20 20:14:49 +00004209 if (!consumeIf('L'))
4210 return nullptr;
4211 switch (look()) {
4212 case 'w':
4213 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004214 return getDerived().parseIntegerLiteral("wchar_t");
Richard Smithc20d1442018-08-20 20:14:49 +00004215 case 'b':
4216 if (consumeIf("b0E"))
4217 return make<BoolExpr>(0);
4218 if (consumeIf("b1E"))
4219 return make<BoolExpr>(1);
4220 return nullptr;
4221 case 'c':
4222 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004223 return getDerived().parseIntegerLiteral("char");
Richard Smithc20d1442018-08-20 20:14:49 +00004224 case 'a':
4225 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004226 return getDerived().parseIntegerLiteral("signed char");
Richard Smithc20d1442018-08-20 20:14:49 +00004227 case 'h':
4228 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004229 return getDerived().parseIntegerLiteral("unsigned char");
Richard Smithc20d1442018-08-20 20:14:49 +00004230 case 's':
4231 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004232 return getDerived().parseIntegerLiteral("short");
Richard Smithc20d1442018-08-20 20:14:49 +00004233 case 't':
4234 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004235 return getDerived().parseIntegerLiteral("unsigned short");
Richard Smithc20d1442018-08-20 20:14:49 +00004236 case 'i':
4237 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004238 return getDerived().parseIntegerLiteral("");
Richard Smithc20d1442018-08-20 20:14:49 +00004239 case 'j':
4240 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004241 return getDerived().parseIntegerLiteral("u");
Richard Smithc20d1442018-08-20 20:14:49 +00004242 case 'l':
4243 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004244 return getDerived().parseIntegerLiteral("l");
Richard Smithc20d1442018-08-20 20:14:49 +00004245 case 'm':
4246 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004247 return getDerived().parseIntegerLiteral("ul");
Richard Smithc20d1442018-08-20 20:14:49 +00004248 case 'x':
4249 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004250 return getDerived().parseIntegerLiteral("ll");
Richard Smithc20d1442018-08-20 20:14:49 +00004251 case 'y':
4252 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004253 return getDerived().parseIntegerLiteral("ull");
Richard Smithc20d1442018-08-20 20:14:49 +00004254 case 'n':
4255 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004256 return getDerived().parseIntegerLiteral("__int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004257 case 'o':
4258 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004259 return getDerived().parseIntegerLiteral("unsigned __int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004260 case 'f':
4261 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004262 return getDerived().template parseFloatingLiteral<float>();
Richard Smithc20d1442018-08-20 20:14:49 +00004263 case 'd':
4264 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004265 return getDerived().template parseFloatingLiteral<double>();
Richard Smithc20d1442018-08-20 20:14:49 +00004266 case 'e':
4267 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004268 return getDerived().template parseFloatingLiteral<long double>();
Richard Smithc20d1442018-08-20 20:14:49 +00004269 case '_':
4270 if (consumeIf("_Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00004271 Node *R = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00004272 if (R != nullptr && consumeIf('E'))
4273 return R;
4274 }
4275 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00004276 case 'A': {
4277 Node *T = getDerived().parseType();
4278 if (T == nullptr)
4279 return nullptr;
4280 // FIXME: We need to include the string contents in the mangling.
4281 if (consumeIf('E'))
4282 return make<StringLiteral>(T);
4283 return nullptr;
4284 }
4285 case 'D':
4286 if (consumeIf("DnE"))
4287 return make<NameType>("nullptr");
4288 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004289 case 'T':
4290 // Invalid mangled name per
4291 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
4292 return nullptr;
Richard Smithfb917462019-09-09 22:26:04 +00004293 case 'U': {
4294 // FIXME: Should we support LUb... for block literals?
4295 if (look(1) != 'l')
4296 return nullptr;
4297 Node *T = parseUnnamedTypeName(nullptr);
4298 if (!T || !consumeIf('E'))
4299 return nullptr;
4300 return make<LambdaExpr>(T);
4301 }
Richard Smithc20d1442018-08-20 20:14:49 +00004302 default: {
4303 // might be named type
Pavel Labathba825192018-10-16 14:29:14 +00004304 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004305 if (T == nullptr)
4306 return nullptr;
4307 StringView N = parseNumber();
Richard Smithfb917462019-09-09 22:26:04 +00004308 if (N.empty())
4309 return nullptr;
4310 if (!consumeIf('E'))
4311 return nullptr;
4312 return make<IntegerCastExpr>(T, N);
Richard Smithc20d1442018-08-20 20:14:49 +00004313 }
4314 }
4315}
4316
4317// <braced-expression> ::= <expression>
4318// ::= di <field source-name> <braced-expression> # .name = expr
4319// ::= dx <index expression> <braced-expression> # [expr] = expr
4320// ::= dX <range begin expression> <range end expression> <braced-expression>
Pavel Labathba825192018-10-16 14:29:14 +00004321template <typename Derived, typename Alloc>
4322Node *AbstractManglingParser<Derived, Alloc>::parseBracedExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004323 if (look() == 'd') {
4324 switch (look(1)) {
4325 case 'i': {
4326 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004327 Node *Field = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00004328 if (Field == nullptr)
4329 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004330 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004331 if (Init == nullptr)
4332 return nullptr;
4333 return make<BracedExpr>(Field, Init, /*isArray=*/false);
4334 }
4335 case 'x': {
4336 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004337 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004338 if (Index == nullptr)
4339 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004340 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004341 if (Init == nullptr)
4342 return nullptr;
4343 return make<BracedExpr>(Index, Init, /*isArray=*/true);
4344 }
4345 case 'X': {
4346 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004347 Node *RangeBegin = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004348 if (RangeBegin == nullptr)
4349 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004350 Node *RangeEnd = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004351 if (RangeEnd == nullptr)
4352 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004353 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004354 if (Init == nullptr)
4355 return nullptr;
4356 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
4357 }
4358 }
4359 }
Pavel Labathba825192018-10-16 14:29:14 +00004360 return getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004361}
4362
4363// (not yet in the spec)
4364// <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
4365// ::= fR <binary-operator-name> <expression> <expression>
4366// ::= fl <binary-operator-name> <expression>
4367// ::= fr <binary-operator-name> <expression>
Pavel Labathba825192018-10-16 14:29:14 +00004368template <typename Derived, typename Alloc>
4369Node *AbstractManglingParser<Derived, Alloc>::parseFoldExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004370 if (!consumeIf('f'))
4371 return nullptr;
4372
4373 char FoldKind = look();
4374 bool IsLeftFold, HasInitializer;
4375 HasInitializer = FoldKind == 'L' || FoldKind == 'R';
4376 if (FoldKind == 'l' || FoldKind == 'L')
4377 IsLeftFold = true;
4378 else if (FoldKind == 'r' || FoldKind == 'R')
4379 IsLeftFold = false;
4380 else
4381 return nullptr;
4382 ++First;
4383
4384 // FIXME: This map is duplicated in parseOperatorName and parseExpr.
4385 StringView OperatorName;
4386 if (consumeIf("aa")) OperatorName = "&&";
4387 else if (consumeIf("an")) OperatorName = "&";
4388 else if (consumeIf("aN")) OperatorName = "&=";
4389 else if (consumeIf("aS")) OperatorName = "=";
4390 else if (consumeIf("cm")) OperatorName = ",";
4391 else if (consumeIf("ds")) OperatorName = ".*";
4392 else if (consumeIf("dv")) OperatorName = "/";
4393 else if (consumeIf("dV")) OperatorName = "/=";
4394 else if (consumeIf("eo")) OperatorName = "^";
4395 else if (consumeIf("eO")) OperatorName = "^=";
4396 else if (consumeIf("eq")) OperatorName = "==";
4397 else if (consumeIf("ge")) OperatorName = ">=";
4398 else if (consumeIf("gt")) OperatorName = ">";
4399 else if (consumeIf("le")) OperatorName = "<=";
4400 else if (consumeIf("ls")) OperatorName = "<<";
4401 else if (consumeIf("lS")) OperatorName = "<<=";
4402 else if (consumeIf("lt")) OperatorName = "<";
4403 else if (consumeIf("mi")) OperatorName = "-";
4404 else if (consumeIf("mI")) OperatorName = "-=";
4405 else if (consumeIf("ml")) OperatorName = "*";
4406 else if (consumeIf("mL")) OperatorName = "*=";
4407 else if (consumeIf("ne")) OperatorName = "!=";
4408 else if (consumeIf("oo")) OperatorName = "||";
4409 else if (consumeIf("or")) OperatorName = "|";
4410 else if (consumeIf("oR")) OperatorName = "|=";
4411 else if (consumeIf("pl")) OperatorName = "+";
4412 else if (consumeIf("pL")) OperatorName = "+=";
4413 else if (consumeIf("rm")) OperatorName = "%";
4414 else if (consumeIf("rM")) OperatorName = "%=";
4415 else if (consumeIf("rs")) OperatorName = ">>";
4416 else if (consumeIf("rS")) OperatorName = ">>=";
4417 else return nullptr;
4418
Pavel Labathba825192018-10-16 14:29:14 +00004419 Node *Pack = getDerived().parseExpr(), *Init = nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004420 if (Pack == nullptr)
4421 return nullptr;
4422 if (HasInitializer) {
Pavel Labathba825192018-10-16 14:29:14 +00004423 Init = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004424 if (Init == nullptr)
4425 return nullptr;
4426 }
4427
4428 if (IsLeftFold && Init)
4429 std::swap(Pack, Init);
4430
4431 return make<FoldExpr>(IsLeftFold, OperatorName, Pack, Init);
4432}
4433
4434// <expression> ::= <unary operator-name> <expression>
4435// ::= <binary operator-name> <expression> <expression>
4436// ::= <ternary operator-name> <expression> <expression> <expression>
4437// ::= cl <expression>+ E # call
4438// ::= cv <type> <expression> # conversion with one argument
4439// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4440// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
4441// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
4442// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
4443// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
4444// ::= [gs] dl <expression> # delete expression
4445// ::= [gs] da <expression> # delete[] expression
4446// ::= pp_ <expression> # prefix ++
4447// ::= mm_ <expression> # prefix --
4448// ::= ti <type> # typeid (type)
4449// ::= te <expression> # typeid (expression)
4450// ::= dc <type> <expression> # dynamic_cast<type> (expression)
4451// ::= sc <type> <expression> # static_cast<type> (expression)
4452// ::= cc <type> <expression> # const_cast<type> (expression)
4453// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4454// ::= st <type> # sizeof (a type)
4455// ::= sz <expression> # sizeof (an expression)
4456// ::= at <type> # alignof (a type)
4457// ::= az <expression> # alignof (an expression)
4458// ::= nx <expression> # noexcept (expression)
4459// ::= <template-param>
4460// ::= <function-param>
4461// ::= dt <expression> <unresolved-name> # expr.name
4462// ::= pt <expression> <unresolved-name> # expr->name
4463// ::= ds <expression> <expression> # expr.*expr
4464// ::= sZ <template-param> # size of a parameter pack
4465// ::= sZ <function-param> # size of a function parameter pack
4466// ::= sP <template-arg>* E # sizeof...(T), size of a captured template parameter pack from an alias template
4467// ::= sp <expression> # pack expansion
4468// ::= tw <expression> # throw expression
4469// ::= tr # throw with no operand (rethrow)
4470// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
4471// # freestanding dependent name (e.g., T::x),
4472// # objectless nonstatic member reference
4473// ::= fL <binary-operator-name> <expression> <expression>
4474// ::= fR <binary-operator-name> <expression> <expression>
4475// ::= fl <binary-operator-name> <expression>
4476// ::= fr <binary-operator-name> <expression>
4477// ::= <expr-primary>
Pavel Labathba825192018-10-16 14:29:14 +00004478template <typename Derived, typename Alloc>
4479Node *AbstractManglingParser<Derived, Alloc>::parseExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004480 bool Global = consumeIf("gs");
4481 if (numLeft() < 2)
4482 return nullptr;
4483
4484 switch (*First) {
4485 case 'L':
Pavel Labathba825192018-10-16 14:29:14 +00004486 return getDerived().parseExprPrimary();
Richard Smithc20d1442018-08-20 20:14:49 +00004487 case 'T':
Pavel Labathba825192018-10-16 14:29:14 +00004488 return getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004489 case 'f': {
4490 // Disambiguate a fold expression from a <function-param>.
4491 if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
Pavel Labathba825192018-10-16 14:29:14 +00004492 return getDerived().parseFunctionParam();
4493 return getDerived().parseFoldExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004494 }
4495 case 'a':
4496 switch (First[1]) {
4497 case 'a':
4498 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004499 return getDerived().parseBinaryExpr("&&");
Richard Smithc20d1442018-08-20 20:14:49 +00004500 case 'd':
4501 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004502 return getDerived().parsePrefixExpr("&");
Richard Smithc20d1442018-08-20 20:14:49 +00004503 case 'n':
4504 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004505 return getDerived().parseBinaryExpr("&");
Richard Smithc20d1442018-08-20 20:14:49 +00004506 case 'N':
4507 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004508 return getDerived().parseBinaryExpr("&=");
Richard Smithc20d1442018-08-20 20:14:49 +00004509 case 'S':
4510 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004511 return getDerived().parseBinaryExpr("=");
Richard Smithc20d1442018-08-20 20:14:49 +00004512 case 't': {
4513 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004514 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004515 if (Ty == nullptr)
4516 return nullptr;
4517 return make<EnclosingExpr>("alignof (", Ty, ")");
4518 }
4519 case 'z': {
4520 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004521 Node *Ty = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004522 if (Ty == nullptr)
4523 return nullptr;
4524 return make<EnclosingExpr>("alignof (", Ty, ")");
4525 }
4526 }
4527 return nullptr;
4528 case 'c':
4529 switch (First[1]) {
4530 // cc <type> <expression> # const_cast<type>(expression)
4531 case 'c': {
4532 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004533 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004534 if (Ty == nullptr)
4535 return Ty;
Pavel Labathba825192018-10-16 14:29:14 +00004536 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004537 if (Ex == nullptr)
4538 return Ex;
4539 return make<CastExpr>("const_cast", Ty, Ex);
4540 }
4541 // cl <expression>+ E # call
4542 case 'l': {
4543 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004544 Node *Callee = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004545 if (Callee == nullptr)
4546 return Callee;
4547 size_t ExprsBegin = Names.size();
4548 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004549 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004550 if (E == nullptr)
4551 return E;
4552 Names.push_back(E);
4553 }
4554 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
4555 }
4556 case 'm':
4557 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004558 return getDerived().parseBinaryExpr(",");
Richard Smithc20d1442018-08-20 20:14:49 +00004559 case 'o':
4560 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004561 return getDerived().parsePrefixExpr("~");
Richard Smithc20d1442018-08-20 20:14:49 +00004562 case 'v':
Pavel Labathba825192018-10-16 14:29:14 +00004563 return getDerived().parseConversionExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004564 }
4565 return nullptr;
4566 case 'd':
4567 switch (First[1]) {
4568 case 'a': {
4569 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004570 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004571 if (Ex == nullptr)
4572 return Ex;
4573 return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
4574 }
4575 case 'c': {
4576 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004577 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004578 if (T == nullptr)
4579 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004580 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004581 if (Ex == nullptr)
4582 return Ex;
4583 return make<CastExpr>("dynamic_cast", T, Ex);
4584 }
4585 case 'e':
4586 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004587 return getDerived().parsePrefixExpr("*");
Richard Smithc20d1442018-08-20 20:14:49 +00004588 case 'l': {
4589 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004590 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004591 if (E == nullptr)
4592 return E;
4593 return make<DeleteExpr>(E, Global, /*is_array=*/false);
4594 }
4595 case 'n':
Pavel Labathba825192018-10-16 14:29:14 +00004596 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004597 case 's': {
4598 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004599 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004600 if (LHS == nullptr)
4601 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004602 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004603 if (RHS == nullptr)
4604 return nullptr;
4605 return make<MemberExpr>(LHS, ".*", RHS);
4606 }
4607 case 't': {
4608 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004609 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004610 if (LHS == nullptr)
4611 return LHS;
Pavel Labathba825192018-10-16 14:29:14 +00004612 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004613 if (RHS == nullptr)
4614 return nullptr;
4615 return make<MemberExpr>(LHS, ".", RHS);
4616 }
4617 case 'v':
4618 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004619 return getDerived().parseBinaryExpr("/");
Richard Smithc20d1442018-08-20 20:14:49 +00004620 case 'V':
4621 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004622 return getDerived().parseBinaryExpr("/=");
Richard Smithc20d1442018-08-20 20:14:49 +00004623 }
4624 return nullptr;
4625 case 'e':
4626 switch (First[1]) {
4627 case 'o':
4628 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004629 return getDerived().parseBinaryExpr("^");
Richard Smithc20d1442018-08-20 20:14:49 +00004630 case 'O':
4631 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004632 return getDerived().parseBinaryExpr("^=");
Richard Smithc20d1442018-08-20 20:14:49 +00004633 case 'q':
4634 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004635 return getDerived().parseBinaryExpr("==");
Richard Smithc20d1442018-08-20 20:14:49 +00004636 }
4637 return nullptr;
4638 case 'g':
4639 switch (First[1]) {
4640 case 'e':
4641 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004642 return getDerived().parseBinaryExpr(">=");
Richard Smithc20d1442018-08-20 20:14:49 +00004643 case 't':
4644 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004645 return getDerived().parseBinaryExpr(">");
Richard Smithc20d1442018-08-20 20:14:49 +00004646 }
4647 return nullptr;
4648 case 'i':
4649 switch (First[1]) {
4650 case 'x': {
4651 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004652 Node *Base = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004653 if (Base == nullptr)
4654 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004655 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004656 if (Index == nullptr)
4657 return Index;
4658 return make<ArraySubscriptExpr>(Base, Index);
4659 }
4660 case 'l': {
4661 First += 2;
4662 size_t InitsBegin = Names.size();
4663 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004664 Node *E = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004665 if (E == nullptr)
4666 return nullptr;
4667 Names.push_back(E);
4668 }
4669 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4670 }
4671 }
4672 return nullptr;
4673 case 'l':
4674 switch (First[1]) {
4675 case 'e':
4676 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004677 return getDerived().parseBinaryExpr("<=");
Richard Smithc20d1442018-08-20 20:14:49 +00004678 case 's':
4679 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004680 return getDerived().parseBinaryExpr("<<");
Richard Smithc20d1442018-08-20 20:14:49 +00004681 case 'S':
4682 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004683 return getDerived().parseBinaryExpr("<<=");
Richard Smithc20d1442018-08-20 20:14:49 +00004684 case 't':
4685 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004686 return getDerived().parseBinaryExpr("<");
Richard Smithc20d1442018-08-20 20:14:49 +00004687 }
4688 return nullptr;
4689 case 'm':
4690 switch (First[1]) {
4691 case 'i':
4692 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004693 return getDerived().parseBinaryExpr("-");
Richard Smithc20d1442018-08-20 20:14:49 +00004694 case 'I':
4695 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004696 return getDerived().parseBinaryExpr("-=");
Richard Smithc20d1442018-08-20 20:14:49 +00004697 case 'l':
4698 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004699 return getDerived().parseBinaryExpr("*");
Richard Smithc20d1442018-08-20 20:14:49 +00004700 case 'L':
4701 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004702 return getDerived().parseBinaryExpr("*=");
Richard Smithc20d1442018-08-20 20:14:49 +00004703 case 'm':
4704 First += 2;
4705 if (consumeIf('_'))
Pavel Labathba825192018-10-16 14:29:14 +00004706 return getDerived().parsePrefixExpr("--");
4707 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004708 if (Ex == nullptr)
4709 return nullptr;
4710 return make<PostfixExpr>(Ex, "--");
4711 }
4712 return nullptr;
4713 case 'n':
4714 switch (First[1]) {
4715 case 'a':
4716 case 'w':
Pavel Labathba825192018-10-16 14:29:14 +00004717 return getDerived().parseNewExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004718 case 'e':
4719 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004720 return getDerived().parseBinaryExpr("!=");
Richard Smithc20d1442018-08-20 20:14:49 +00004721 case 'g':
4722 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004723 return getDerived().parsePrefixExpr("-");
Richard Smithc20d1442018-08-20 20:14:49 +00004724 case 't':
4725 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004726 return getDerived().parsePrefixExpr("!");
Richard Smithc20d1442018-08-20 20:14:49 +00004727 case 'x':
4728 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004729 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004730 if (Ex == nullptr)
4731 return Ex;
4732 return make<EnclosingExpr>("noexcept (", Ex, ")");
4733 }
4734 return nullptr;
4735 case 'o':
4736 switch (First[1]) {
4737 case 'n':
Pavel Labathba825192018-10-16 14:29:14 +00004738 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004739 case 'o':
4740 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004741 return getDerived().parseBinaryExpr("||");
Richard Smithc20d1442018-08-20 20:14:49 +00004742 case 'r':
4743 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004744 return getDerived().parseBinaryExpr("|");
Richard Smithc20d1442018-08-20 20:14:49 +00004745 case 'R':
4746 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004747 return getDerived().parseBinaryExpr("|=");
Richard Smithc20d1442018-08-20 20:14:49 +00004748 }
4749 return nullptr;
4750 case 'p':
4751 switch (First[1]) {
4752 case 'm':
4753 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004754 return getDerived().parseBinaryExpr("->*");
Richard Smithc20d1442018-08-20 20:14:49 +00004755 case 'l':
4756 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004757 return getDerived().parseBinaryExpr("+");
Richard Smithc20d1442018-08-20 20:14:49 +00004758 case 'L':
4759 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004760 return getDerived().parseBinaryExpr("+=");
Richard Smithc20d1442018-08-20 20:14:49 +00004761 case 'p': {
4762 First += 2;
4763 if (consumeIf('_'))
Pavel Labathba825192018-10-16 14:29:14 +00004764 return getDerived().parsePrefixExpr("++");
4765 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004766 if (Ex == nullptr)
4767 return Ex;
4768 return make<PostfixExpr>(Ex, "++");
4769 }
4770 case 's':
4771 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004772 return getDerived().parsePrefixExpr("+");
Richard Smithc20d1442018-08-20 20:14:49 +00004773 case 't': {
4774 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004775 Node *L = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004776 if (L == nullptr)
4777 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004778 Node *R = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004779 if (R == nullptr)
4780 return nullptr;
4781 return make<MemberExpr>(L, "->", R);
4782 }
4783 }
4784 return nullptr;
4785 case 'q':
4786 if (First[1] == 'u') {
4787 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004788 Node *Cond = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004789 if (Cond == nullptr)
4790 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004791 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004792 if (LHS == nullptr)
4793 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004794 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004795 if (RHS == nullptr)
4796 return nullptr;
4797 return make<ConditionalExpr>(Cond, LHS, RHS);
4798 }
4799 return nullptr;
4800 case 'r':
4801 switch (First[1]) {
4802 case 'c': {
4803 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004804 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004805 if (T == nullptr)
4806 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004807 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004808 if (Ex == nullptr)
4809 return Ex;
4810 return make<CastExpr>("reinterpret_cast", T, Ex);
4811 }
4812 case 'm':
4813 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004814 return getDerived().parseBinaryExpr("%");
Richard Smithc20d1442018-08-20 20:14:49 +00004815 case 'M':
4816 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004817 return getDerived().parseBinaryExpr("%=");
Richard Smithc20d1442018-08-20 20:14:49 +00004818 case 's':
4819 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004820 return getDerived().parseBinaryExpr(">>");
Richard Smithc20d1442018-08-20 20:14:49 +00004821 case 'S':
4822 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004823 return getDerived().parseBinaryExpr(">>=");
Richard Smithc20d1442018-08-20 20:14:49 +00004824 }
4825 return nullptr;
4826 case 's':
4827 switch (First[1]) {
4828 case 'c': {
4829 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004830 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004831 if (T == nullptr)
4832 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004833 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004834 if (Ex == nullptr)
4835 return Ex;
4836 return make<CastExpr>("static_cast", T, Ex);
4837 }
4838 case 'p': {
4839 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004840 Node *Child = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004841 if (Child == nullptr)
4842 return nullptr;
4843 return make<ParameterPackExpansion>(Child);
4844 }
4845 case 'r':
Pavel Labathba825192018-10-16 14:29:14 +00004846 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004847 case 't': {
4848 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004849 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004850 if (Ty == nullptr)
4851 return Ty;
4852 return make<EnclosingExpr>("sizeof (", Ty, ")");
4853 }
4854 case 'z': {
4855 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004856 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004857 if (Ex == nullptr)
4858 return Ex;
4859 return make<EnclosingExpr>("sizeof (", Ex, ")");
4860 }
4861 case 'Z':
4862 First += 2;
4863 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00004864 Node *R = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004865 if (R == nullptr)
4866 return nullptr;
4867 return make<SizeofParamPackExpr>(R);
4868 } else if (look() == 'f') {
Pavel Labathba825192018-10-16 14:29:14 +00004869 Node *FP = getDerived().parseFunctionParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004870 if (FP == nullptr)
4871 return nullptr;
4872 return make<EnclosingExpr>("sizeof... (", FP, ")");
4873 }
4874 return nullptr;
4875 case 'P': {
4876 First += 2;
4877 size_t ArgsBegin = Names.size();
4878 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004879 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00004880 if (Arg == nullptr)
4881 return nullptr;
4882 Names.push_back(Arg);
4883 }
Richard Smithb485b352018-08-24 23:30:26 +00004884 auto *Pack = make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin));
4885 if (!Pack)
4886 return nullptr;
4887 return make<EnclosingExpr>("sizeof... (", Pack, ")");
Richard Smithc20d1442018-08-20 20:14:49 +00004888 }
4889 }
4890 return nullptr;
4891 case 't':
4892 switch (First[1]) {
4893 case 'e': {
4894 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004895 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004896 if (Ex == nullptr)
4897 return Ex;
4898 return make<EnclosingExpr>("typeid (", Ex, ")");
4899 }
4900 case 'i': {
4901 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004902 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004903 if (Ty == nullptr)
4904 return Ty;
4905 return make<EnclosingExpr>("typeid (", Ty, ")");
4906 }
4907 case 'l': {
4908 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004909 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004910 if (Ty == nullptr)
4911 return nullptr;
4912 size_t InitsBegin = Names.size();
4913 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004914 Node *E = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004915 if (E == nullptr)
4916 return nullptr;
4917 Names.push_back(E);
4918 }
4919 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4920 }
4921 case 'r':
4922 First += 2;
4923 return make<NameType>("throw");
4924 case 'w': {
4925 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004926 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004927 if (Ex == nullptr)
4928 return nullptr;
4929 return make<ThrowExpr>(Ex);
4930 }
4931 }
4932 return nullptr;
4933 case '1':
4934 case '2':
4935 case '3':
4936 case '4':
4937 case '5':
4938 case '6':
4939 case '7':
4940 case '8':
4941 case '9':
Pavel Labathba825192018-10-16 14:29:14 +00004942 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004943 }
Erik Pilkingtone8457c62019-06-18 23:34:09 +00004944
4945 if (consumeIf("u8__uuidoft")) {
4946 Node *Ty = getDerived().parseType();
4947 if (!Ty)
4948 return nullptr;
4949 return make<UUIDOfExpr>(Ty);
4950 }
4951
4952 if (consumeIf("u8__uuidofz")) {
4953 Node *Ex = getDerived().parseExpr();
4954 if (!Ex)
4955 return nullptr;
4956 return make<UUIDOfExpr>(Ex);
4957 }
4958
Richard Smithc20d1442018-08-20 20:14:49 +00004959 return nullptr;
4960}
4961
4962// <call-offset> ::= h <nv-offset> _
4963// ::= v <v-offset> _
4964//
4965// <nv-offset> ::= <offset number>
4966// # non-virtual base override
4967//
4968// <v-offset> ::= <offset number> _ <virtual offset number>
4969// # virtual base override, with vcall offset
Pavel Labathba825192018-10-16 14:29:14 +00004970template <typename Alloc, typename Derived>
4971bool AbstractManglingParser<Alloc, Derived>::parseCallOffset() {
Richard Smithc20d1442018-08-20 20:14:49 +00004972 // Just scan through the call offset, we never add this information into the
4973 // output.
4974 if (consumeIf('h'))
4975 return parseNumber(true).empty() || !consumeIf('_');
4976 if (consumeIf('v'))
4977 return parseNumber(true).empty() || !consumeIf('_') ||
4978 parseNumber(true).empty() || !consumeIf('_');
4979 return true;
4980}
4981
4982// <special-name> ::= TV <type> # virtual table
4983// ::= TT <type> # VTT structure (construction vtable index)
4984// ::= TI <type> # typeinfo structure
4985// ::= TS <type> # typeinfo name (null-terminated byte string)
4986// ::= Tc <call-offset> <call-offset> <base encoding>
4987// # base is the nominal target function of thunk
4988// # first call-offset is 'this' adjustment
4989// # second call-offset is result adjustment
4990// ::= T <call-offset> <base encoding>
4991// # base is the nominal target function of thunk
4992// ::= GV <object name> # Guard variable for one-time initialization
4993// # No <type>
4994// ::= TW <object name> # Thread-local wrapper
4995// ::= TH <object name> # Thread-local initialization
4996// ::= GR <object name> _ # First temporary
4997// ::= GR <object name> <seq-id> _ # Subsequent temporaries
4998// extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4999// extension ::= GR <object name> # reference temporary for object
Pavel Labathba825192018-10-16 14:29:14 +00005000template <typename Derived, typename Alloc>
5001Node *AbstractManglingParser<Derived, Alloc>::parseSpecialName() {
Richard Smithc20d1442018-08-20 20:14:49 +00005002 switch (look()) {
5003 case 'T':
5004 switch (look(1)) {
5005 // TV <type> # virtual table
5006 case 'V': {
5007 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005008 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005009 if (Ty == nullptr)
5010 return nullptr;
5011 return make<SpecialName>("vtable for ", Ty);
5012 }
5013 // TT <type> # VTT structure (construction vtable index)
5014 case 'T': {
5015 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005016 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005017 if (Ty == nullptr)
5018 return nullptr;
5019 return make<SpecialName>("VTT for ", Ty);
5020 }
5021 // TI <type> # typeinfo structure
5022 case 'I': {
5023 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005024 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005025 if (Ty == nullptr)
5026 return nullptr;
5027 return make<SpecialName>("typeinfo for ", Ty);
5028 }
5029 // TS <type> # typeinfo name (null-terminated byte string)
5030 case 'S': {
5031 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005032 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005033 if (Ty == nullptr)
5034 return nullptr;
5035 return make<SpecialName>("typeinfo name for ", Ty);
5036 }
5037 // Tc <call-offset> <call-offset> <base encoding>
5038 case 'c': {
5039 First += 2;
5040 if (parseCallOffset() || parseCallOffset())
5041 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005042 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005043 if (Encoding == nullptr)
5044 return nullptr;
5045 return make<SpecialName>("covariant return thunk to ", Encoding);
5046 }
5047 // extension ::= TC <first type> <number> _ <second type>
5048 // # construction vtable for second-in-first
5049 case 'C': {
5050 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005051 Node *FirstType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005052 if (FirstType == nullptr)
5053 return nullptr;
5054 if (parseNumber(true).empty() || !consumeIf('_'))
5055 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005056 Node *SecondType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005057 if (SecondType == nullptr)
5058 return nullptr;
5059 return make<CtorVtableSpecialName>(SecondType, FirstType);
5060 }
5061 // TW <object name> # Thread-local wrapper
5062 case 'W': {
5063 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005064 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005065 if (Name == nullptr)
5066 return nullptr;
5067 return make<SpecialName>("thread-local wrapper routine for ", Name);
5068 }
5069 // TH <object name> # Thread-local initialization
5070 case 'H': {
5071 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005072 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005073 if (Name == nullptr)
5074 return nullptr;
5075 return make<SpecialName>("thread-local initialization routine for ", Name);
5076 }
5077 // T <call-offset> <base encoding>
5078 default: {
5079 ++First;
5080 bool IsVirt = look() == 'v';
5081 if (parseCallOffset())
5082 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005083 Node *BaseEncoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005084 if (BaseEncoding == nullptr)
5085 return nullptr;
5086 if (IsVirt)
5087 return make<SpecialName>("virtual thunk to ", BaseEncoding);
5088 else
5089 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
5090 }
5091 }
5092 case 'G':
5093 switch (look(1)) {
5094 // GV <object name> # Guard variable for one-time initialization
5095 case 'V': {
5096 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005097 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005098 if (Name == nullptr)
5099 return nullptr;
5100 return make<SpecialName>("guard variable for ", Name);
5101 }
5102 // GR <object name> # reference temporary for object
5103 // GR <object name> _ # First temporary
5104 // GR <object name> <seq-id> _ # Subsequent temporaries
5105 case 'R': {
5106 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005107 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005108 if (Name == nullptr)
5109 return nullptr;
5110 size_t Count;
5111 bool ParsedSeqId = !parseSeqId(&Count);
5112 if (!consumeIf('_') && ParsedSeqId)
5113 return nullptr;
5114 return make<SpecialName>("reference temporary for ", Name);
5115 }
5116 }
5117 }
5118 return nullptr;
5119}
5120
5121// <encoding> ::= <function name> <bare-function-type>
5122// ::= <data name>
5123// ::= <special-name>
Pavel Labathba825192018-10-16 14:29:14 +00005124template <typename Derived, typename Alloc>
5125Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
Richard Smithc20d1442018-08-20 20:14:49 +00005126 if (look() == 'G' || look() == 'T')
Pavel Labathba825192018-10-16 14:29:14 +00005127 return getDerived().parseSpecialName();
Richard Smithc20d1442018-08-20 20:14:49 +00005128
5129 auto IsEndOfEncoding = [&] {
5130 // The set of chars that can potentially follow an <encoding> (none of which
5131 // can start a <type>). Enumerating these allows us to avoid speculative
5132 // parsing.
5133 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
5134 };
5135
5136 NameState NameInfo(this);
Pavel Labathba825192018-10-16 14:29:14 +00005137 Node *Name = getDerived().parseName(&NameInfo);
Richard Smithc20d1442018-08-20 20:14:49 +00005138 if (Name == nullptr)
5139 return nullptr;
5140
5141 if (resolveForwardTemplateRefs(NameInfo))
5142 return nullptr;
5143
5144 if (IsEndOfEncoding())
5145 return Name;
5146
5147 Node *Attrs = nullptr;
5148 if (consumeIf("Ua9enable_ifI")) {
5149 size_t BeforeArgs = Names.size();
5150 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005151 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005152 if (Arg == nullptr)
5153 return nullptr;
5154 Names.push_back(Arg);
5155 }
5156 Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
Richard Smithb485b352018-08-24 23:30:26 +00005157 if (!Attrs)
5158 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005159 }
5160
5161 Node *ReturnType = nullptr;
5162 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
Pavel Labathba825192018-10-16 14:29:14 +00005163 ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005164 if (ReturnType == nullptr)
5165 return nullptr;
5166 }
5167
5168 if (consumeIf('v'))
5169 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
5170 Attrs, NameInfo.CVQualifiers,
5171 NameInfo.ReferenceQualifier);
5172
5173 size_t ParamsBegin = Names.size();
5174 do {
Pavel Labathba825192018-10-16 14:29:14 +00005175 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005176 if (Ty == nullptr)
5177 return nullptr;
5178 Names.push_back(Ty);
5179 } while (!IsEndOfEncoding());
5180
5181 return make<FunctionEncoding>(ReturnType, Name,
5182 popTrailingNodeArray(ParamsBegin),
5183 Attrs, NameInfo.CVQualifiers,
5184 NameInfo.ReferenceQualifier);
5185}
5186
5187template <class Float>
5188struct FloatData;
5189
5190template <>
5191struct FloatData<float>
5192{
5193 static const size_t mangled_size = 8;
5194 static const size_t max_demangled_size = 24;
5195 static constexpr const char* spec = "%af";
5196};
5197
5198template <>
5199struct FloatData<double>
5200{
5201 static const size_t mangled_size = 16;
5202 static const size_t max_demangled_size = 32;
5203 static constexpr const char* spec = "%a";
5204};
5205
5206template <>
5207struct FloatData<long double>
5208{
5209#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
5210 defined(__wasm__)
5211 static const size_t mangled_size = 32;
5212#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
5213 static const size_t mangled_size = 16;
5214#else
5215 static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms
5216#endif
5217 static const size_t max_demangled_size = 40;
5218 static constexpr const char *spec = "%LaL";
5219};
5220
Pavel Labathba825192018-10-16 14:29:14 +00005221template <typename Alloc, typename Derived>
5222template <class Float>
5223Node *AbstractManglingParser<Alloc, Derived>::parseFloatingLiteral() {
Richard Smithc20d1442018-08-20 20:14:49 +00005224 const size_t N = FloatData<Float>::mangled_size;
5225 if (numLeft() <= N)
5226 return nullptr;
5227 StringView Data(First, First + N);
5228 for (char C : Data)
5229 if (!std::isxdigit(C))
5230 return nullptr;
5231 First += N;
5232 if (!consumeIf('E'))
5233 return nullptr;
5234 return make<FloatLiteralImpl<Float>>(Data);
5235}
5236
5237// <seq-id> ::= <0-9A-Z>+
Pavel Labathba825192018-10-16 14:29:14 +00005238template <typename Alloc, typename Derived>
5239bool AbstractManglingParser<Alloc, Derived>::parseSeqId(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00005240 if (!(look() >= '0' && look() <= '9') &&
5241 !(look() >= 'A' && look() <= 'Z'))
5242 return true;
5243
5244 size_t Id = 0;
5245 while (true) {
5246 if (look() >= '0' && look() <= '9') {
5247 Id *= 36;
5248 Id += static_cast<size_t>(look() - '0');
5249 } else if (look() >= 'A' && look() <= 'Z') {
5250 Id *= 36;
5251 Id += static_cast<size_t>(look() - 'A') + 10;
5252 } else {
5253 *Out = Id;
5254 return false;
5255 }
5256 ++First;
5257 }
5258}
5259
5260// <substitution> ::= S <seq-id> _
5261// ::= S_
5262// <substitution> ::= Sa # ::std::allocator
5263// <substitution> ::= Sb # ::std::basic_string
5264// <substitution> ::= Ss # ::std::basic_string < char,
5265// ::std::char_traits<char>,
5266// ::std::allocator<char> >
5267// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
5268// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
5269// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
Pavel Labathba825192018-10-16 14:29:14 +00005270template <typename Derived, typename Alloc>
5271Node *AbstractManglingParser<Derived, Alloc>::parseSubstitution() {
Richard Smithc20d1442018-08-20 20:14:49 +00005272 if (!consumeIf('S'))
5273 return nullptr;
5274
5275 if (std::islower(look())) {
5276 Node *SpecialSub;
5277 switch (look()) {
5278 case 'a':
5279 ++First;
5280 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
5281 break;
5282 case 'b':
5283 ++First;
5284 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
5285 break;
5286 case 's':
5287 ++First;
5288 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
5289 break;
5290 case 'i':
5291 ++First;
5292 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
5293 break;
5294 case 'o':
5295 ++First;
5296 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
5297 break;
5298 case 'd':
5299 ++First;
5300 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
5301 break;
5302 default:
5303 return nullptr;
5304 }
Richard Smithb485b352018-08-24 23:30:26 +00005305 if (!SpecialSub)
5306 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005307 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
5308 // has ABI tags, the tags are appended to the substitution; the result is a
5309 // substitutable component.
Pavel Labathba825192018-10-16 14:29:14 +00005310 Node *WithTags = getDerived().parseAbiTags(SpecialSub);
Richard Smithc20d1442018-08-20 20:14:49 +00005311 if (WithTags != SpecialSub) {
5312 Subs.push_back(WithTags);
5313 SpecialSub = WithTags;
5314 }
5315 return SpecialSub;
5316 }
5317
5318 // ::= S_
5319 if (consumeIf('_')) {
5320 if (Subs.empty())
5321 return nullptr;
5322 return Subs[0];
5323 }
5324
5325 // ::= S <seq-id> _
5326 size_t Index = 0;
5327 if (parseSeqId(&Index))
5328 return nullptr;
5329 ++Index;
5330 if (!consumeIf('_') || Index >= Subs.size())
5331 return nullptr;
5332 return Subs[Index];
5333}
5334
5335// <template-param> ::= T_ # first template parameter
5336// ::= T <parameter-2 non-negative number> _
Richard Smithdf1c14c2019-09-06 23:53:21 +00005337// ::= TL <level-1> __
5338// ::= TL <level-1> _ <parameter-2 non-negative number> _
Pavel Labathba825192018-10-16 14:29:14 +00005339template <typename Derived, typename Alloc>
5340Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParam() {
Richard Smithc20d1442018-08-20 20:14:49 +00005341 if (!consumeIf('T'))
5342 return nullptr;
5343
Richard Smithdf1c14c2019-09-06 23:53:21 +00005344 size_t Level = 0;
5345 if (consumeIf('L')) {
5346 if (parsePositiveInteger(&Level))
5347 return nullptr;
5348 ++Level;
5349 if (!consumeIf('_'))
5350 return nullptr;
5351 }
5352
Richard Smithc20d1442018-08-20 20:14:49 +00005353 size_t Index = 0;
5354 if (!consumeIf('_')) {
5355 if (parsePositiveInteger(&Index))
5356 return nullptr;
5357 ++Index;
5358 if (!consumeIf('_'))
5359 return nullptr;
5360 }
5361
Richard Smithc20d1442018-08-20 20:14:49 +00005362 // If we're in a context where this <template-param> refers to a
5363 // <template-arg> further ahead in the mangled name (currently just conversion
5364 // operator types), then we should only look it up in the right context.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005365 // This can only happen at the outermost level.
5366 if (PermitForwardTemplateReferences && Level == 0) {
Richard Smithb485b352018-08-24 23:30:26 +00005367 Node *ForwardRef = make<ForwardTemplateReference>(Index);
5368 if (!ForwardRef)
5369 return nullptr;
5370 assert(ForwardRef->getKind() == Node::KForwardTemplateReference);
5371 ForwardTemplateRefs.push_back(
5372 static_cast<ForwardTemplateReference *>(ForwardRef));
5373 return ForwardRef;
Richard Smithc20d1442018-08-20 20:14:49 +00005374 }
5375
Richard Smithdf1c14c2019-09-06 23:53:21 +00005376 if (Level >= TemplateParams.size() || !TemplateParams[Level] ||
5377 Index >= TemplateParams[Level]->size()) {
5378 // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter
5379 // list are mangled as the corresponding artificial template type parameter.
5380 if (ParsingLambdaParamsAtLevel == Level && Level <= TemplateParams.size()) {
5381 // This will be popped by the ScopedTemplateParamList in
5382 // parseUnnamedTypeName.
5383 if (Level == TemplateParams.size())
5384 TemplateParams.push_back(nullptr);
5385 return make<NameType>("auto");
5386 }
5387
Richard Smithc20d1442018-08-20 20:14:49 +00005388 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00005389 }
5390
5391 return (*TemplateParams[Level])[Index];
5392}
5393
5394// <template-param-decl> ::= Ty # type parameter
5395// ::= Tn <type> # non-type parameter
5396// ::= Tt <template-param-decl>* E # template parameter
5397// ::= Tp <template-param-decl> # parameter pack
5398template <typename Derived, typename Alloc>
5399Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParamDecl() {
5400 auto InventTemplateParamName = [&](TemplateParamKind Kind) {
5401 unsigned Index = NumSyntheticTemplateParameters[(int)Kind]++;
5402 Node *N = make<SyntheticTemplateParamName>(Kind, Index);
5403 if (N) TemplateParams.back()->push_back(N);
5404 return N;
5405 };
5406
5407 if (consumeIf("Ty")) {
5408 Node *Name = InventTemplateParamName(TemplateParamKind::Type);
5409 if (!Name)
5410 return nullptr;
5411 return make<TypeTemplateParamDecl>(Name);
5412 }
5413
5414 if (consumeIf("Tn")) {
5415 Node *Name = InventTemplateParamName(TemplateParamKind::NonType);
5416 if (!Name)
5417 return nullptr;
5418 Node *Type = parseType();
5419 if (!Type)
5420 return nullptr;
5421 return make<NonTypeTemplateParamDecl>(Name, Type);
5422 }
5423
5424 if (consumeIf("Tt")) {
5425 Node *Name = InventTemplateParamName(TemplateParamKind::Template);
5426 if (!Name)
5427 return nullptr;
5428 size_t ParamsBegin = Names.size();
5429 ScopedTemplateParamList TemplateTemplateParamParams(this);
5430 while (!consumeIf("E")) {
5431 Node *P = parseTemplateParamDecl();
5432 if (!P)
5433 return nullptr;
5434 Names.push_back(P);
5435 }
5436 NodeArray Params = popTrailingNodeArray(ParamsBegin);
5437 return make<TemplateTemplateParamDecl>(Name, Params);
5438 }
5439
5440 if (consumeIf("Tp")) {
5441 Node *P = parseTemplateParamDecl();
5442 if (!P)
5443 return nullptr;
5444 return make<TemplateParamPackDecl>(P);
5445 }
5446
5447 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005448}
5449
5450// <template-arg> ::= <type> # type or template
5451// ::= X <expression> E # expression
5452// ::= <expr-primary> # simple expressions
5453// ::= J <template-arg>* E # argument pack
5454// ::= LZ <encoding> E # extension
Pavel Labathba825192018-10-16 14:29:14 +00005455template <typename Derived, typename Alloc>
5456Node *AbstractManglingParser<Derived, Alloc>::parseTemplateArg() {
Richard Smithc20d1442018-08-20 20:14:49 +00005457 switch (look()) {
5458 case 'X': {
5459 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00005460 Node *Arg = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00005461 if (Arg == nullptr || !consumeIf('E'))
5462 return nullptr;
5463 return Arg;
5464 }
5465 case 'J': {
5466 ++First;
5467 size_t ArgsBegin = Names.size();
5468 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005469 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005470 if (Arg == nullptr)
5471 return nullptr;
5472 Names.push_back(Arg);
5473 }
5474 NodeArray Args = popTrailingNodeArray(ArgsBegin);
5475 return make<TemplateArgumentPack>(Args);
5476 }
5477 case 'L': {
5478 // ::= LZ <encoding> E # extension
5479 if (look(1) == 'Z') {
5480 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005481 Node *Arg = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005482 if (Arg == nullptr || !consumeIf('E'))
5483 return nullptr;
5484 return Arg;
5485 }
5486 // ::= <expr-primary> # simple expressions
Pavel Labathba825192018-10-16 14:29:14 +00005487 return getDerived().parseExprPrimary();
Richard Smithc20d1442018-08-20 20:14:49 +00005488 }
5489 default:
Pavel Labathba825192018-10-16 14:29:14 +00005490 return getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005491 }
5492}
5493
5494// <template-args> ::= I <template-arg>* E
5495// extension, the abi says <template-arg>+
Pavel Labathba825192018-10-16 14:29:14 +00005496template <typename Derived, typename Alloc>
5497Node *
5498AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005499 if (!consumeIf('I'))
5500 return nullptr;
5501
5502 // <template-params> refer to the innermost <template-args>. Clear out any
5503 // outer args that we may have inserted into TemplateParams.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005504 if (TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005505 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00005506 TemplateParams.push_back(&OuterTemplateParams);
5507 OuterTemplateParams.clear();
5508 }
Richard Smithc20d1442018-08-20 20:14:49 +00005509
5510 size_t ArgsBegin = Names.size();
5511 while (!consumeIf('E')) {
5512 if (TagTemplates) {
5513 auto OldParams = std::move(TemplateParams);
Pavel Labathba825192018-10-16 14:29:14 +00005514 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005515 TemplateParams = std::move(OldParams);
5516 if (Arg == nullptr)
5517 return nullptr;
5518 Names.push_back(Arg);
5519 Node *TableEntry = Arg;
5520 if (Arg->getKind() == Node::KTemplateArgumentPack) {
5521 TableEntry = make<ParameterPack>(
5522 static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
Richard Smithb485b352018-08-24 23:30:26 +00005523 if (!TableEntry)
5524 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005525 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00005526 TemplateParams.back()->push_back(TableEntry);
Richard Smithc20d1442018-08-20 20:14:49 +00005527 } else {
Pavel Labathba825192018-10-16 14:29:14 +00005528 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005529 if (Arg == nullptr)
5530 return nullptr;
5531 Names.push_back(Arg);
5532 }
5533 }
5534 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
5535}
5536
5537// <mangled-name> ::= _Z <encoding>
5538// ::= <type>
5539// extension ::= ___Z <encoding> _block_invoke
5540// extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
5541// extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
Pavel Labathba825192018-10-16 14:29:14 +00005542template <typename Derived, typename Alloc>
5543Node *AbstractManglingParser<Derived, Alloc>::parse() {
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005544 if (consumeIf("_Z") || consumeIf("__Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005545 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005546 if (Encoding == nullptr)
5547 return nullptr;
5548 if (look() == '.') {
5549 Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
5550 First = Last;
5551 }
5552 if (numLeft() != 0)
5553 return nullptr;
5554 return Encoding;
5555 }
5556
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005557 if (consumeIf("___Z") || consumeIf("____Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005558 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005559 if (Encoding == nullptr || !consumeIf("_block_invoke"))
5560 return nullptr;
5561 bool RequireNumber = consumeIf('_');
5562 if (parseNumber().empty() && RequireNumber)
5563 return nullptr;
5564 if (look() == '.')
5565 First = Last;
5566 if (numLeft() != 0)
5567 return nullptr;
5568 return make<SpecialName>("invocation function for block in ", Encoding);
5569 }
5570
Pavel Labathba825192018-10-16 14:29:14 +00005571 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005572 if (numLeft() != 0)
5573 return nullptr;
5574 return Ty;
5575}
5576
Pavel Labathba825192018-10-16 14:29:14 +00005577template <typename Alloc>
5578struct ManglingParser : AbstractManglingParser<ManglingParser<Alloc>, Alloc> {
5579 using AbstractManglingParser<ManglingParser<Alloc>,
5580 Alloc>::AbstractManglingParser;
5581};
5582
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005583DEMANGLE_NAMESPACE_END
Richard Smithc20d1442018-08-20 20:14:49 +00005584
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005585#endif // DEMANGLE_ITANIUMDEMANGLE_H