blob: c1efd7ef4e34b3e86b2c1166681145e61ae4fe34 [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
2066 void printLambdaDeclarator(OutputStream &S) const;
2067
2068public:
2069 LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
2070
2071 template<typename Fn> void match(Fn F) const { F(Type); }
2072
2073 void printLeft(OutputStream &S) const override {
2074 S += "[]";
2075 printLambdaDeclarator(S);
2076 S += "{...}";
2077 }
2078};
2079
Richard Smithc20d1442018-08-20 20:14:49 +00002080class IntegerCastExpr : public Node {
2081 // ty(integer)
2082 const Node *Ty;
2083 StringView Integer;
2084
2085public:
2086 IntegerCastExpr(const Node *Ty_, StringView Integer_)
2087 : Node(KIntegerCastExpr), Ty(Ty_), Integer(Integer_) {}
2088
2089 template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
2090
2091 void printLeft(OutputStream &S) const override {
2092 S += "(";
2093 Ty->print(S);
2094 S += ")";
2095 S += Integer;
2096 }
2097};
2098
2099class IntegerLiteral : public Node {
2100 StringView Type;
2101 StringView Value;
2102
2103public:
2104 IntegerLiteral(StringView Type_, StringView Value_)
2105 : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
2106
2107 template<typename Fn> void match(Fn F) const { F(Type, Value); }
2108
2109 void printLeft(OutputStream &S) const override {
2110 if (Type.size() > 3) {
2111 S += "(";
2112 S += Type;
2113 S += ")";
2114 }
2115
2116 if (Value[0] == 'n') {
2117 S += "-";
2118 S += Value.dropFront(1);
2119 } else
2120 S += Value;
2121
2122 if (Type.size() <= 3)
2123 S += Type;
2124 }
2125};
2126
2127template <class Float> struct FloatData;
2128
2129namespace float_literal_impl {
2130constexpr Node::Kind getFloatLiteralKind(float *) {
2131 return Node::KFloatLiteral;
2132}
2133constexpr Node::Kind getFloatLiteralKind(double *) {
2134 return Node::KDoubleLiteral;
2135}
2136constexpr Node::Kind getFloatLiteralKind(long double *) {
2137 return Node::KLongDoubleLiteral;
2138}
2139}
2140
2141template <class Float> class FloatLiteralImpl : public Node {
2142 const StringView Contents;
2143
2144 static constexpr Kind KindForClass =
2145 float_literal_impl::getFloatLiteralKind((Float *)nullptr);
2146
2147public:
2148 FloatLiteralImpl(StringView Contents_)
2149 : Node(KindForClass), Contents(Contents_) {}
2150
2151 template<typename Fn> void match(Fn F) const { F(Contents); }
2152
2153 void printLeft(OutputStream &s) const override {
2154 const char *first = Contents.begin();
2155 const char *last = Contents.end() + 1;
2156
2157 const size_t N = FloatData<Float>::mangled_size;
2158 if (static_cast<std::size_t>(last - first) > N) {
2159 last = first + N;
2160 union {
2161 Float value;
2162 char buf[sizeof(Float)];
2163 };
2164 const char *t = first;
2165 char *e = buf;
2166 for (; t != last; ++t, ++e) {
2167 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2168 : static_cast<unsigned>(*t - 'a' + 10);
2169 ++t;
2170 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2171 : static_cast<unsigned>(*t - 'a' + 10);
2172 *e = static_cast<char>((d1 << 4) + d0);
2173 }
2174#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
2175 std::reverse(buf, e);
2176#endif
2177 char num[FloatData<Float>::max_demangled_size] = {0};
2178 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
2179 s += StringView(num, num + n);
2180 }
2181 }
2182};
2183
2184using FloatLiteral = FloatLiteralImpl<float>;
2185using DoubleLiteral = FloatLiteralImpl<double>;
2186using LongDoubleLiteral = FloatLiteralImpl<long double>;
2187
2188/// Visit the node. Calls \c F(P), where \c P is the node cast to the
2189/// appropriate derived class.
2190template<typename Fn>
2191void Node::visit(Fn F) const {
2192 switch (K) {
2193#define CASE(X) case K ## X: return F(static_cast<const X*>(this));
2194 FOR_EACH_NODE_KIND(CASE)
2195#undef CASE
2196 }
2197 assert(0 && "unknown mangling node kind");
2198}
2199
2200/// Determine the kind of a node from its type.
2201template<typename NodeT> struct NodeKind;
2202#define SPECIALIZATION(X) \
2203 template<> struct NodeKind<X> { \
2204 static constexpr Node::Kind Kind = Node::K##X; \
2205 static constexpr const char *name() { return #X; } \
2206 };
2207FOR_EACH_NODE_KIND(SPECIALIZATION)
2208#undef SPECIALIZATION
2209
2210#undef FOR_EACH_NODE_KIND
2211
Richard Smithdf1c14c2019-09-06 23:53:21 +00002212inline void LambdaExpr::printLambdaDeclarator(OutputStream &S) const {
2213 struct LambdaDeclaratorPrinter {
2214 OutputStream &S;
2215 void operator()(const ClosureTypeName *LambdaType) {
2216 LambdaType->printDeclarator(S);
2217 }
2218
2219 // Walk through any qualifiers to find the lambda-expression.
2220 void operator()(const SpecialName *Name) {
2221 Name->match([&](StringView, const Node *Name) { Name->visit(*this); });
2222 }
2223 void operator()(const NestedName *Name) {
2224 Name->match([&](const Node *, const Node *Name) { Name->visit(*this); });
2225 }
2226 void operator()(const LocalName *Name) {
2227 Name->match([&](const Node *, const Node *Name) { Name->visit(*this); });
2228 }
2229 void operator()(const QualifiedName *Name) {
2230 Name->match([&](const Node *, const Node *Name) { Name->visit(*this); });
2231 }
2232 void operator()(const GlobalQualifiedName *Name) {
2233 Name->match([&](const Node *Child) { Child->visit(*this); });
2234 }
2235 void operator()(const StdQualifiedName *Name) {
2236 Name->match([&](const Node *Child) { Child->visit(*this); });
2237 }
2238 void operator()(const Node *) {
2239 // If we can't find the lambda type, just print '[]{...}'.
2240 }
2241 };
2242 return Type->visit(LambdaDeclaratorPrinter{S});
2243}
2244
Richard Smithc20d1442018-08-20 20:14:49 +00002245template <class T, size_t N>
2246class PODSmallVector {
2247 static_assert(std::is_pod<T>::value,
2248 "T is required to be a plain old data type");
2249
2250 T* First;
2251 T* Last;
2252 T* Cap;
2253 T Inline[N];
2254
2255 bool isInline() const { return First == Inline; }
2256
2257 void clearInline() {
2258 First = Inline;
2259 Last = Inline;
2260 Cap = Inline + N;
2261 }
2262
2263 void reserve(size_t NewCap) {
2264 size_t S = size();
2265 if (isInline()) {
2266 auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
2267 if (Tmp == nullptr)
2268 std::terminate();
2269 std::copy(First, Last, Tmp);
2270 First = Tmp;
2271 } else {
2272 First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
2273 if (First == nullptr)
2274 std::terminate();
2275 }
2276 Last = First + S;
2277 Cap = First + NewCap;
2278 }
2279
2280public:
2281 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
2282
2283 PODSmallVector(const PODSmallVector&) = delete;
2284 PODSmallVector& operator=(const PODSmallVector&) = delete;
2285
2286 PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
2287 if (Other.isInline()) {
2288 std::copy(Other.begin(), Other.end(), First);
2289 Last = First + Other.size();
2290 Other.clear();
2291 return;
2292 }
2293
2294 First = Other.First;
2295 Last = Other.Last;
2296 Cap = Other.Cap;
2297 Other.clearInline();
2298 }
2299
2300 PODSmallVector& operator=(PODSmallVector&& Other) {
2301 if (Other.isInline()) {
2302 if (!isInline()) {
2303 std::free(First);
2304 clearInline();
2305 }
2306 std::copy(Other.begin(), Other.end(), First);
2307 Last = First + Other.size();
2308 Other.clear();
2309 return *this;
2310 }
2311
2312 if (isInline()) {
2313 First = Other.First;
2314 Last = Other.Last;
2315 Cap = Other.Cap;
2316 Other.clearInline();
2317 return *this;
2318 }
2319
2320 std::swap(First, Other.First);
2321 std::swap(Last, Other.Last);
2322 std::swap(Cap, Other.Cap);
2323 Other.clear();
2324 return *this;
2325 }
2326
2327 void push_back(const T& Elem) {
2328 if (Last == Cap)
2329 reserve(size() * 2);
2330 *Last++ = Elem;
2331 }
2332
2333 void pop_back() {
2334 assert(Last != First && "Popping empty vector!");
2335 --Last;
2336 }
2337
2338 void dropBack(size_t Index) {
2339 assert(Index <= size() && "dropBack() can't expand!");
2340 Last = First + Index;
2341 }
2342
2343 T* begin() { return First; }
2344 T* end() { return Last; }
2345
2346 bool empty() const { return First == Last; }
2347 size_t size() const { return static_cast<size_t>(Last - First); }
2348 T& back() {
2349 assert(Last != First && "Calling back() on empty vector!");
2350 return *(Last - 1);
2351 }
2352 T& operator[](size_t Index) {
2353 assert(Index < size() && "Invalid access!");
2354 return *(begin() + Index);
2355 }
2356 void clear() { Last = First; }
2357
2358 ~PODSmallVector() {
2359 if (!isInline())
2360 std::free(First);
2361 }
2362};
2363
Pavel Labathba825192018-10-16 14:29:14 +00002364template <typename Derived, typename Alloc> struct AbstractManglingParser {
Richard Smithc20d1442018-08-20 20:14:49 +00002365 const char *First;
2366 const char *Last;
2367
2368 // Name stack, this is used by the parser to hold temporary names that were
2369 // parsed. The parser collapses multiple names into new nodes to construct
2370 // the AST. Once the parser is finished, names.size() == 1.
2371 PODSmallVector<Node *, 32> Names;
2372
2373 // Substitution table. Itanium supports name substitutions as a means of
2374 // compression. The string "S42_" refers to the 44nd entry (base-36) in this
2375 // table.
2376 PODSmallVector<Node *, 32> Subs;
2377
Richard Smithdf1c14c2019-09-06 23:53:21 +00002378 using TemplateParamList = PODSmallVector<Node *, 8>;
2379
2380 class ScopedTemplateParamList {
2381 AbstractManglingParser *Parser;
2382 size_t OldNumTemplateParamLists;
2383 TemplateParamList Params;
2384
2385 public:
2386 ScopedTemplateParamList(AbstractManglingParser *Parser)
2387 : Parser(Parser),
2388 OldNumTemplateParamLists(Parser->TemplateParams.size()) {
2389 Parser->TemplateParams.push_back(&Params);
2390 }
2391 ~ScopedTemplateParamList() {
2392 assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
2393 Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
2394 }
2395 void push_back(Node *Param) {
2396 Params.push_back(Param);
2397 }
2398 };
2399
Richard Smithc20d1442018-08-20 20:14:49 +00002400 // Template parameter table. Like the above, but referenced like "T42_".
2401 // This has a smaller size compared to Subs and Names because it can be
2402 // stored on the stack.
Richard Smithdf1c14c2019-09-06 23:53:21 +00002403 TemplateParamList OuterTemplateParams;
2404
2405 // Lists of template parameters indexed by template parameter depth,
2406 // referenced like "TL2_4_". If nonempty, element 0 is always
2407 // OuterTemplateParams; inner elements are always template parameter lists of
2408 // lambda expressions. For a generic lambda with no explicit template
2409 // parameter list, the corresponding parameter list pointer will be null.
2410 PODSmallVector<TemplateParamList *, 4> TemplateParams;
Richard Smithc20d1442018-08-20 20:14:49 +00002411
2412 // Set of unresolved forward <template-param> references. These can occur in a
2413 // conversion operator's type, and are resolved in the enclosing <encoding>.
2414 PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
2415
Richard Smithc20d1442018-08-20 20:14:49 +00002416 bool TryToParseTemplateArgs = true;
2417 bool PermitForwardTemplateReferences = false;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002418 size_t ParsingLambdaParamsAtLevel = (size_t)-1;
2419
2420 unsigned NumSyntheticTemplateParameters[3] = {};
Richard Smithc20d1442018-08-20 20:14:49 +00002421
2422 Alloc ASTAllocator;
2423
Pavel Labathba825192018-10-16 14:29:14 +00002424 AbstractManglingParser(const char *First_, const char *Last_)
2425 : First(First_), Last(Last_) {}
2426
2427 Derived &getDerived() { return static_cast<Derived &>(*this); }
Richard Smithc20d1442018-08-20 20:14:49 +00002428
2429 void reset(const char *First_, const char *Last_) {
2430 First = First_;
2431 Last = Last_;
2432 Names.clear();
2433 Subs.clear();
2434 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002435 ParsingLambdaParamsAtLevel = (size_t)-1;
Richard Smithc20d1442018-08-20 20:14:49 +00002436 TryToParseTemplateArgs = true;
2437 PermitForwardTemplateReferences = false;
Richard Smith9a2307a2019-09-07 00:11:53 +00002438 for (int I = 0; I != 3; ++I)
2439 NumSyntheticTemplateParameters[I] = 0;
Richard Smithc20d1442018-08-20 20:14:49 +00002440 ASTAllocator.reset();
2441 }
2442
Richard Smithb485b352018-08-24 23:30:26 +00002443 template <class T, class... Args> Node *make(Args &&... args) {
Richard Smithc20d1442018-08-20 20:14:49 +00002444 return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
2445 }
2446
2447 template <class It> NodeArray makeNodeArray(It begin, It end) {
2448 size_t sz = static_cast<size_t>(end - begin);
2449 void *mem = ASTAllocator.allocateNodeArray(sz);
2450 Node **data = new (mem) Node *[sz];
2451 std::copy(begin, end, data);
2452 return NodeArray(data, sz);
2453 }
2454
2455 NodeArray popTrailingNodeArray(size_t FromPosition) {
2456 assert(FromPosition <= Names.size());
2457 NodeArray res =
2458 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2459 Names.dropBack(FromPosition);
2460 return res;
2461 }
2462
2463 bool consumeIf(StringView S) {
2464 if (StringView(First, Last).startsWith(S)) {
2465 First += S.size();
2466 return true;
2467 }
2468 return false;
2469 }
2470
2471 bool consumeIf(char C) {
2472 if (First != Last && *First == C) {
2473 ++First;
2474 return true;
2475 }
2476 return false;
2477 }
2478
2479 char consume() { return First != Last ? *First++ : '\0'; }
2480
2481 char look(unsigned Lookahead = 0) {
2482 if (static_cast<size_t>(Last - First) <= Lookahead)
2483 return '\0';
2484 return First[Lookahead];
2485 }
2486
2487 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2488
2489 StringView parseNumber(bool AllowNegative = false);
2490 Qualifiers parseCVQualifiers();
2491 bool parsePositiveInteger(size_t *Out);
2492 StringView parseBareSourceName();
2493
2494 bool parseSeqId(size_t *Out);
2495 Node *parseSubstitution();
2496 Node *parseTemplateParam();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002497 Node *parseTemplateParamDecl();
Richard Smithc20d1442018-08-20 20:14:49 +00002498 Node *parseTemplateArgs(bool TagTemplates = false);
2499 Node *parseTemplateArg();
2500
2501 /// Parse the <expr> production.
2502 Node *parseExpr();
2503 Node *parsePrefixExpr(StringView Kind);
2504 Node *parseBinaryExpr(StringView Kind);
2505 Node *parseIntegerLiteral(StringView Lit);
2506 Node *parseExprPrimary();
2507 template <class Float> Node *parseFloatingLiteral();
2508 Node *parseFunctionParam();
2509 Node *parseNewExpr();
2510 Node *parseConversionExpr();
2511 Node *parseBracedExpr();
2512 Node *parseFoldExpr();
2513
2514 /// Parse the <type> production.
2515 Node *parseType();
2516 Node *parseFunctionType();
2517 Node *parseVectorType();
2518 Node *parseDecltype();
2519 Node *parseArrayType();
2520 Node *parsePointerToMemberType();
2521 Node *parseClassEnumType();
2522 Node *parseQualifiedType();
2523
2524 Node *parseEncoding();
2525 bool parseCallOffset();
2526 Node *parseSpecialName();
2527
2528 /// Holds some extra information about a <name> that is being parsed. This
2529 /// information is only pertinent if the <name> refers to an <encoding>.
2530 struct NameState {
2531 bool CtorDtorConversion = false;
2532 bool EndsWithTemplateArgs = false;
2533 Qualifiers CVQualifiers = QualNone;
2534 FunctionRefQual ReferenceQualifier = FrefQualNone;
2535 size_t ForwardTemplateRefsBegin;
2536
Pavel Labathba825192018-10-16 14:29:14 +00002537 NameState(AbstractManglingParser *Enclosing)
Richard Smithc20d1442018-08-20 20:14:49 +00002538 : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
2539 };
2540
2541 bool resolveForwardTemplateRefs(NameState &State) {
2542 size_t I = State.ForwardTemplateRefsBegin;
2543 size_t E = ForwardTemplateRefs.size();
2544 for (; I < E; ++I) {
2545 size_t Idx = ForwardTemplateRefs[I]->Index;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002546 if (TemplateParams.empty() || !TemplateParams[0] ||
2547 Idx >= TemplateParams[0]->size())
Richard Smithc20d1442018-08-20 20:14:49 +00002548 return true;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002549 ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
Richard Smithc20d1442018-08-20 20:14:49 +00002550 }
2551 ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
2552 return false;
2553 }
2554
2555 /// Parse the <name> production>
2556 Node *parseName(NameState *State = nullptr);
2557 Node *parseLocalName(NameState *State);
2558 Node *parseOperatorName(NameState *State);
2559 Node *parseUnqualifiedName(NameState *State);
2560 Node *parseUnnamedTypeName(NameState *State);
2561 Node *parseSourceName(NameState *State);
2562 Node *parseUnscopedName(NameState *State);
2563 Node *parseNestedName(NameState *State);
2564 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2565
2566 Node *parseAbiTags(Node *N);
2567
2568 /// Parse the <unresolved-name> production.
2569 Node *parseUnresolvedName();
2570 Node *parseSimpleId();
2571 Node *parseBaseUnresolvedName();
2572 Node *parseUnresolvedType();
2573 Node *parseDestructorName();
2574
2575 /// Top-level entry point into the parser.
2576 Node *parse();
2577};
2578
2579const char* parse_discriminator(const char* first, const char* last);
2580
2581// <name> ::= <nested-name> // N
2582// ::= <local-name> # See Scope Encoding below // Z
2583// ::= <unscoped-template-name> <template-args>
2584// ::= <unscoped-name>
2585//
2586// <unscoped-template-name> ::= <unscoped-name>
2587// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00002588template <typename Derived, typename Alloc>
2589Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002590 consumeIf('L'); // extension
2591
2592 if (look() == 'N')
Pavel Labathba825192018-10-16 14:29:14 +00002593 return getDerived().parseNestedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002594 if (look() == 'Z')
Pavel Labathba825192018-10-16 14:29:14 +00002595 return getDerived().parseLocalName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002596
2597 // ::= <unscoped-template-name> <template-args>
2598 if (look() == 'S' && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00002599 Node *S = getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00002600 if (S == nullptr)
2601 return nullptr;
2602 if (look() != 'I')
2603 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002604 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00002605 if (TA == nullptr)
2606 return nullptr;
2607 if (State) State->EndsWithTemplateArgs = true;
2608 return make<NameWithTemplateArgs>(S, TA);
2609 }
2610
Pavel Labathba825192018-10-16 14:29:14 +00002611 Node *N = getDerived().parseUnscopedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002612 if (N == nullptr)
2613 return nullptr;
2614 // ::= <unscoped-template-name> <template-args>
2615 if (look() == 'I') {
2616 Subs.push_back(N);
Pavel Labathba825192018-10-16 14:29:14 +00002617 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00002618 if (TA == nullptr)
2619 return nullptr;
2620 if (State) State->EndsWithTemplateArgs = true;
2621 return make<NameWithTemplateArgs>(N, TA);
2622 }
2623 // ::= <unscoped-name>
2624 return N;
2625}
2626
2627// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2628// := Z <function encoding> E s [<discriminator>]
2629// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
Pavel Labathba825192018-10-16 14:29:14 +00002630template <typename Derived, typename Alloc>
2631Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002632 if (!consumeIf('Z'))
2633 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002634 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00002635 if (Encoding == nullptr || !consumeIf('E'))
2636 return nullptr;
2637
2638 if (consumeIf('s')) {
2639 First = parse_discriminator(First, Last);
Richard Smithb485b352018-08-24 23:30:26 +00002640 auto *StringLitName = make<NameType>("string literal");
2641 if (!StringLitName)
2642 return nullptr;
2643 return make<LocalName>(Encoding, StringLitName);
Richard Smithc20d1442018-08-20 20:14:49 +00002644 }
2645
2646 if (consumeIf('d')) {
2647 parseNumber(true);
2648 if (!consumeIf('_'))
2649 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002650 Node *N = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002651 if (N == nullptr)
2652 return nullptr;
2653 return make<LocalName>(Encoding, N);
2654 }
2655
Pavel Labathba825192018-10-16 14:29:14 +00002656 Node *Entity = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002657 if (Entity == nullptr)
2658 return nullptr;
2659 First = parse_discriminator(First, Last);
2660 return make<LocalName>(Encoding, Entity);
2661}
2662
2663// <unscoped-name> ::= <unqualified-name>
2664// ::= St <unqualified-name> # ::std::
2665// extension ::= StL<unqualified-name>
Pavel Labathba825192018-10-16 14:29:14 +00002666template <typename Derived, typename Alloc>
2667Node *
2668AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State) {
2669 if (consumeIf("StL") || consumeIf("St")) {
2670 Node *R = getDerived().parseUnqualifiedName(State);
2671 if (R == nullptr)
2672 return nullptr;
2673 return make<StdQualifiedName>(R);
2674 }
2675 return getDerived().parseUnqualifiedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002676}
2677
2678// <unqualified-name> ::= <operator-name> [abi-tags]
2679// ::= <ctor-dtor-name>
2680// ::= <source-name>
2681// ::= <unnamed-type-name>
2682// ::= DC <source-name>+ E # structured binding declaration
Pavel Labathba825192018-10-16 14:29:14 +00002683template <typename Derived, typename Alloc>
2684Node *
2685AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002686 // <ctor-dtor-name>s are special-cased in parseNestedName().
2687 Node *Result;
2688 if (look() == 'U')
Pavel Labathba825192018-10-16 14:29:14 +00002689 Result = getDerived().parseUnnamedTypeName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002690 else if (look() >= '1' && look() <= '9')
Pavel Labathba825192018-10-16 14:29:14 +00002691 Result = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002692 else if (consumeIf("DC")) {
2693 size_t BindingsBegin = Names.size();
2694 do {
Pavel Labathba825192018-10-16 14:29:14 +00002695 Node *Binding = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002696 if (Binding == nullptr)
2697 return nullptr;
2698 Names.push_back(Binding);
2699 } while (!consumeIf('E'));
2700 Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
2701 } else
Pavel Labathba825192018-10-16 14:29:14 +00002702 Result = getDerived().parseOperatorName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002703 if (Result != nullptr)
Pavel Labathba825192018-10-16 14:29:14 +00002704 Result = getDerived().parseAbiTags(Result);
Richard Smithc20d1442018-08-20 20:14:49 +00002705 return Result;
2706}
2707
2708// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2709// ::= <closure-type-name>
2710//
2711// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2712//
2713// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
Pavel Labathba825192018-10-16 14:29:14 +00002714template <typename Derived, typename Alloc>
2715Node *
Richard Smithdf1c14c2019-09-06 23:53:21 +00002716AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
2717 // <template-params> refer to the innermost <template-args>. Clear out any
2718 // outer args that we may have inserted into TemplateParams.
2719 if (State != nullptr)
2720 TemplateParams.clear();
2721
Richard Smithc20d1442018-08-20 20:14:49 +00002722 if (consumeIf("Ut")) {
2723 StringView Count = parseNumber();
2724 if (!consumeIf('_'))
2725 return nullptr;
2726 return make<UnnamedTypeName>(Count);
2727 }
2728 if (consumeIf("Ul")) {
Richard Smithdf1c14c2019-09-06 23:53:21 +00002729 SwapAndRestore<size_t> SwapParams(ParsingLambdaParamsAtLevel,
2730 TemplateParams.size());
2731 ScopedTemplateParamList LambdaTemplateParams(this);
2732
2733 size_t ParamsBegin = Names.size();
2734 while (look() == 'T' &&
2735 StringView("yptn").find(look(1)) != StringView::npos) {
2736 Node *T = parseTemplateParamDecl();
2737 if (!T)
2738 return nullptr;
2739 LambdaTemplateParams.push_back(T);
2740 Names.push_back(T);
2741 }
2742 NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
2743
2744 // FIXME: If TempParams is empty and none of the function parameters
2745 // includes 'auto', we should remove LambdaTemplateParams from the
2746 // TemplateParams list. Unfortunately, we don't find out whether there are
2747 // any 'auto' parameters until too late in an example such as:
2748 //
2749 // template<typename T> void f(
2750 // decltype([](decltype([]<typename T>(T v) {}),
2751 // auto) {})) {}
2752 // template<typename T> void f(
2753 // decltype([](decltype([]<typename T>(T w) {}),
2754 // int) {})) {}
2755 //
2756 // Here, the type of v is at level 2 but the type of w is at level 1. We
2757 // don't find this out until we encounter the type of the next parameter.
2758 //
2759 // However, compilers can't actually cope with the former example in
2760 // practice, and it's likely to be made ill-formed in future, so we don't
2761 // need to support it here.
2762 //
2763 // If we encounter an 'auto' in the function parameter types, we will
2764 // recreate a template parameter scope for it, but any intervening lambdas
2765 // will be parsed in the 'wrong' template parameter depth.
2766 if (TempParams.empty())
2767 TemplateParams.pop_back();
2768
Richard Smithc20d1442018-08-20 20:14:49 +00002769 if (!consumeIf("vE")) {
Richard Smithc20d1442018-08-20 20:14:49 +00002770 do {
Pavel Labathba825192018-10-16 14:29:14 +00002771 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00002772 if (P == nullptr)
2773 return nullptr;
2774 Names.push_back(P);
2775 } while (!consumeIf('E'));
Richard Smithc20d1442018-08-20 20:14:49 +00002776 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00002777 NodeArray Params = popTrailingNodeArray(ParamsBegin);
2778
Richard Smithc20d1442018-08-20 20:14:49 +00002779 StringView Count = parseNumber();
2780 if (!consumeIf('_'))
2781 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002782 return make<ClosureTypeName>(TempParams, Params, Count);
Richard Smithc20d1442018-08-20 20:14:49 +00002783 }
Erik Pilkington974b6542019-01-17 21:37:51 +00002784 if (consumeIf("Ub")) {
2785 (void)parseNumber();
2786 if (!consumeIf('_'))
2787 return nullptr;
2788 return make<NameType>("'block-literal'");
2789 }
Richard Smithc20d1442018-08-20 20:14:49 +00002790 return nullptr;
2791}
2792
2793// <source-name> ::= <positive length number> <identifier>
Pavel Labathba825192018-10-16 14:29:14 +00002794template <typename Derived, typename Alloc>
2795Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
Richard Smithc20d1442018-08-20 20:14:49 +00002796 size_t Length = 0;
2797 if (parsePositiveInteger(&Length))
2798 return nullptr;
2799 if (numLeft() < Length || Length == 0)
2800 return nullptr;
2801 StringView Name(First, First + Length);
2802 First += Length;
2803 if (Name.startsWith("_GLOBAL__N"))
2804 return make<NameType>("(anonymous namespace)");
2805 return make<NameType>(Name);
2806}
2807
2808// <operator-name> ::= aa # &&
2809// ::= ad # & (unary)
2810// ::= an # &
2811// ::= aN # &=
2812// ::= aS # =
2813// ::= cl # ()
2814// ::= cm # ,
2815// ::= co # ~
2816// ::= cv <type> # (cast)
2817// ::= da # delete[]
2818// ::= de # * (unary)
2819// ::= dl # delete
2820// ::= dv # /
2821// ::= dV # /=
2822// ::= eo # ^
2823// ::= eO # ^=
2824// ::= eq # ==
2825// ::= ge # >=
2826// ::= gt # >
2827// ::= ix # []
2828// ::= le # <=
2829// ::= li <source-name> # operator ""
2830// ::= ls # <<
2831// ::= lS # <<=
2832// ::= lt # <
2833// ::= mi # -
2834// ::= mI # -=
2835// ::= ml # *
2836// ::= mL # *=
2837// ::= mm # -- (postfix in <expression> context)
2838// ::= na # new[]
2839// ::= ne # !=
2840// ::= ng # - (unary)
2841// ::= nt # !
2842// ::= nw # new
2843// ::= oo # ||
2844// ::= or # |
2845// ::= oR # |=
2846// ::= pm # ->*
2847// ::= pl # +
2848// ::= pL # +=
2849// ::= pp # ++ (postfix in <expression> context)
2850// ::= ps # + (unary)
2851// ::= pt # ->
2852// ::= qu # ?
2853// ::= rm # %
2854// ::= rM # %=
2855// ::= rs # >>
2856// ::= rS # >>=
2857// ::= ss # <=> C++2a
2858// ::= v <digit> <source-name> # vendor extended operator
Pavel Labathba825192018-10-16 14:29:14 +00002859template <typename Derived, typename Alloc>
2860Node *
2861AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002862 switch (look()) {
2863 case 'a':
2864 switch (look(1)) {
2865 case 'a':
2866 First += 2;
2867 return make<NameType>("operator&&");
2868 case 'd':
2869 case 'n':
2870 First += 2;
2871 return make<NameType>("operator&");
2872 case 'N':
2873 First += 2;
2874 return make<NameType>("operator&=");
2875 case 'S':
2876 First += 2;
2877 return make<NameType>("operator=");
2878 }
2879 return nullptr;
2880 case 'c':
2881 switch (look(1)) {
2882 case 'l':
2883 First += 2;
2884 return make<NameType>("operator()");
2885 case 'm':
2886 First += 2;
2887 return make<NameType>("operator,");
2888 case 'o':
2889 First += 2;
2890 return make<NameType>("operator~");
2891 // ::= cv <type> # (cast)
2892 case 'v': {
2893 First += 2;
2894 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2895 // If we're parsing an encoding, State != nullptr and the conversion
2896 // operators' <type> could have a <template-param> that refers to some
2897 // <template-arg>s further ahead in the mangled name.
2898 SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences,
2899 PermitForwardTemplateReferences ||
2900 State != nullptr);
Pavel Labathba825192018-10-16 14:29:14 +00002901 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00002902 if (Ty == nullptr)
2903 return nullptr;
2904 if (State) State->CtorDtorConversion = true;
2905 return make<ConversionOperatorType>(Ty);
2906 }
2907 }
2908 return nullptr;
2909 case 'd':
2910 switch (look(1)) {
2911 case 'a':
2912 First += 2;
2913 return make<NameType>("operator delete[]");
2914 case 'e':
2915 First += 2;
2916 return make<NameType>("operator*");
2917 case 'l':
2918 First += 2;
2919 return make<NameType>("operator delete");
2920 case 'v':
2921 First += 2;
2922 return make<NameType>("operator/");
2923 case 'V':
2924 First += 2;
2925 return make<NameType>("operator/=");
2926 }
2927 return nullptr;
2928 case 'e':
2929 switch (look(1)) {
2930 case 'o':
2931 First += 2;
2932 return make<NameType>("operator^");
2933 case 'O':
2934 First += 2;
2935 return make<NameType>("operator^=");
2936 case 'q':
2937 First += 2;
2938 return make<NameType>("operator==");
2939 }
2940 return nullptr;
2941 case 'g':
2942 switch (look(1)) {
2943 case 'e':
2944 First += 2;
2945 return make<NameType>("operator>=");
2946 case 't':
2947 First += 2;
2948 return make<NameType>("operator>");
2949 }
2950 return nullptr;
2951 case 'i':
2952 if (look(1) == 'x') {
2953 First += 2;
2954 return make<NameType>("operator[]");
2955 }
2956 return nullptr;
2957 case 'l':
2958 switch (look(1)) {
2959 case 'e':
2960 First += 2;
2961 return make<NameType>("operator<=");
2962 // ::= li <source-name> # operator ""
2963 case 'i': {
2964 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00002965 Node *SN = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002966 if (SN == nullptr)
2967 return nullptr;
2968 return make<LiteralOperator>(SN);
2969 }
2970 case 's':
2971 First += 2;
2972 return make<NameType>("operator<<");
2973 case 'S':
2974 First += 2;
2975 return make<NameType>("operator<<=");
2976 case 't':
2977 First += 2;
2978 return make<NameType>("operator<");
2979 }
2980 return nullptr;
2981 case 'm':
2982 switch (look(1)) {
2983 case 'i':
2984 First += 2;
2985 return make<NameType>("operator-");
2986 case 'I':
2987 First += 2;
2988 return make<NameType>("operator-=");
2989 case 'l':
2990 First += 2;
2991 return make<NameType>("operator*");
2992 case 'L':
2993 First += 2;
2994 return make<NameType>("operator*=");
2995 case 'm':
2996 First += 2;
2997 return make<NameType>("operator--");
2998 }
2999 return nullptr;
3000 case 'n':
3001 switch (look(1)) {
3002 case 'a':
3003 First += 2;
3004 return make<NameType>("operator new[]");
3005 case 'e':
3006 First += 2;
3007 return make<NameType>("operator!=");
3008 case 'g':
3009 First += 2;
3010 return make<NameType>("operator-");
3011 case 't':
3012 First += 2;
3013 return make<NameType>("operator!");
3014 case 'w':
3015 First += 2;
3016 return make<NameType>("operator new");
3017 }
3018 return nullptr;
3019 case 'o':
3020 switch (look(1)) {
3021 case 'o':
3022 First += 2;
3023 return make<NameType>("operator||");
3024 case 'r':
3025 First += 2;
3026 return make<NameType>("operator|");
3027 case 'R':
3028 First += 2;
3029 return make<NameType>("operator|=");
3030 }
3031 return nullptr;
3032 case 'p':
3033 switch (look(1)) {
3034 case 'm':
3035 First += 2;
3036 return make<NameType>("operator->*");
3037 case 'l':
3038 First += 2;
3039 return make<NameType>("operator+");
3040 case 'L':
3041 First += 2;
3042 return make<NameType>("operator+=");
3043 case 'p':
3044 First += 2;
3045 return make<NameType>("operator++");
3046 case 's':
3047 First += 2;
3048 return make<NameType>("operator+");
3049 case 't':
3050 First += 2;
3051 return make<NameType>("operator->");
3052 }
3053 return nullptr;
3054 case 'q':
3055 if (look(1) == 'u') {
3056 First += 2;
3057 return make<NameType>("operator?");
3058 }
3059 return nullptr;
3060 case 'r':
3061 switch (look(1)) {
3062 case 'm':
3063 First += 2;
3064 return make<NameType>("operator%");
3065 case 'M':
3066 First += 2;
3067 return make<NameType>("operator%=");
3068 case 's':
3069 First += 2;
3070 return make<NameType>("operator>>");
3071 case 'S':
3072 First += 2;
3073 return make<NameType>("operator>>=");
3074 }
3075 return nullptr;
3076 case 's':
3077 if (look(1) == 's') {
3078 First += 2;
3079 return make<NameType>("operator<=>");
3080 }
3081 return nullptr;
3082 // ::= v <digit> <source-name> # vendor extended operator
3083 case 'v':
3084 if (std::isdigit(look(1))) {
3085 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00003086 Node *SN = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00003087 if (SN == nullptr)
3088 return nullptr;
3089 return make<ConversionOperatorType>(SN);
3090 }
3091 return nullptr;
3092 }
3093 return nullptr;
3094}
3095
3096// <ctor-dtor-name> ::= C1 # complete object constructor
3097// ::= C2 # base object constructor
3098// ::= C3 # complete object allocating constructor
Nico Weber29294792019-04-03 23:14:33 +00003099// extension ::= C4 # gcc old-style "[unified]" constructor
3100// extension ::= C5 # the COMDAT used for ctors
Richard Smithc20d1442018-08-20 20:14:49 +00003101// ::= D0 # deleting destructor
3102// ::= D1 # complete object destructor
3103// ::= D2 # base object destructor
Nico Weber29294792019-04-03 23:14:33 +00003104// extension ::= D4 # gcc old-style "[unified]" destructor
3105// extension ::= D5 # the COMDAT used for dtors
Pavel Labathba825192018-10-16 14:29:14 +00003106template <typename Derived, typename Alloc>
3107Node *
3108AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
3109 NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003110 if (SoFar->getKind() == Node::KSpecialSubstitution) {
3111 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
3112 switch (SSK) {
3113 case SpecialSubKind::string:
3114 case SpecialSubKind::istream:
3115 case SpecialSubKind::ostream:
3116 case SpecialSubKind::iostream:
3117 SoFar = make<ExpandedSpecialSubstitution>(SSK);
Richard Smithb485b352018-08-24 23:30:26 +00003118 if (!SoFar)
3119 return nullptr;
Reid Klecknere76aabe2018-11-01 18:24:03 +00003120 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003121 default:
3122 break;
3123 }
3124 }
3125
3126 if (consumeIf('C')) {
3127 bool IsInherited = consumeIf('I');
Nico Weber29294792019-04-03 23:14:33 +00003128 if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
3129 look() != '5')
Richard Smithc20d1442018-08-20 20:14:49 +00003130 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003131 int Variant = look() - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003132 ++First;
3133 if (State) State->CtorDtorConversion = true;
3134 if (IsInherited) {
Pavel Labathba825192018-10-16 14:29:14 +00003135 if (getDerived().parseName(State) == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00003136 return nullptr;
3137 }
Nico Weber29294792019-04-03 23:14:33 +00003138 return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003139 }
3140
Nico Weber29294792019-04-03 23:14:33 +00003141 if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
3142 look(1) == '4' || look(1) == '5')) {
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003143 int Variant = look(1) - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003144 First += 2;
3145 if (State) State->CtorDtorConversion = true;
Nico Weber29294792019-04-03 23:14:33 +00003146 return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003147 }
3148
3149 return nullptr;
3150}
3151
3152// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
3153// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
3154//
3155// <prefix> ::= <prefix> <unqualified-name>
3156// ::= <template-prefix> <template-args>
3157// ::= <template-param>
3158// ::= <decltype>
3159// ::= # empty
3160// ::= <substitution>
3161// ::= <prefix> <data-member-prefix>
3162// extension ::= L
3163//
3164// <data-member-prefix> := <member source-name> [<template-args>] M
3165//
3166// <template-prefix> ::= <prefix> <template unqualified-name>
3167// ::= <template-param>
3168// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003169template <typename Derived, typename Alloc>
3170Node *
3171AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003172 if (!consumeIf('N'))
3173 return nullptr;
3174
3175 Qualifiers CVTmp = parseCVQualifiers();
3176 if (State) State->CVQualifiers = CVTmp;
3177
3178 if (consumeIf('O')) {
3179 if (State) State->ReferenceQualifier = FrefQualRValue;
3180 } else if (consumeIf('R')) {
3181 if (State) State->ReferenceQualifier = FrefQualLValue;
3182 } else
3183 if (State) State->ReferenceQualifier = FrefQualNone;
3184
3185 Node *SoFar = nullptr;
3186 auto PushComponent = [&](Node *Comp) {
Richard Smithb485b352018-08-24 23:30:26 +00003187 if (!Comp) return false;
Richard Smithc20d1442018-08-20 20:14:49 +00003188 if (SoFar) SoFar = make<NestedName>(SoFar, Comp);
3189 else SoFar = Comp;
3190 if (State) State->EndsWithTemplateArgs = false;
Richard Smithb485b352018-08-24 23:30:26 +00003191 return SoFar != nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003192 };
3193
Richard Smithb485b352018-08-24 23:30:26 +00003194 if (consumeIf("St")) {
Richard Smithc20d1442018-08-20 20:14:49 +00003195 SoFar = make<NameType>("std");
Richard Smithb485b352018-08-24 23:30:26 +00003196 if (!SoFar)
3197 return nullptr;
3198 }
Richard Smithc20d1442018-08-20 20:14:49 +00003199
3200 while (!consumeIf('E')) {
3201 consumeIf('L'); // extension
3202
3203 // <data-member-prefix> := <member source-name> [<template-args>] M
3204 if (consumeIf('M')) {
3205 if (SoFar == nullptr)
3206 return nullptr;
3207 continue;
3208 }
3209
3210 // ::= <template-param>
3211 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00003212 if (!PushComponent(getDerived().parseTemplateParam()))
Richard Smithc20d1442018-08-20 20:14:49 +00003213 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003214 Subs.push_back(SoFar);
3215 continue;
3216 }
3217
3218 // ::= <template-prefix> <template-args>
3219 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003220 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003221 if (TA == nullptr || SoFar == nullptr)
3222 return nullptr;
3223 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003224 if (!SoFar)
3225 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003226 if (State) State->EndsWithTemplateArgs = true;
3227 Subs.push_back(SoFar);
3228 continue;
3229 }
3230
3231 // ::= <decltype>
3232 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
Pavel Labathba825192018-10-16 14:29:14 +00003233 if (!PushComponent(getDerived().parseDecltype()))
Richard Smithc20d1442018-08-20 20:14:49 +00003234 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003235 Subs.push_back(SoFar);
3236 continue;
3237 }
3238
3239 // ::= <substitution>
3240 if (look() == 'S' && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00003241 Node *S = getDerived().parseSubstitution();
Richard Smithb485b352018-08-24 23:30:26 +00003242 if (!PushComponent(S))
Richard Smithc20d1442018-08-20 20:14:49 +00003243 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003244 if (SoFar != S)
3245 Subs.push_back(S);
3246 continue;
3247 }
3248
3249 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
3250 if (look() == 'C' || (look() == 'D' && look(1) != 'C')) {
3251 if (SoFar == nullptr)
3252 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003253 if (!PushComponent(getDerived().parseCtorDtorName(SoFar, State)))
Richard Smithc20d1442018-08-20 20:14:49 +00003254 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003255 SoFar = getDerived().parseAbiTags(SoFar);
Richard Smithc20d1442018-08-20 20:14:49 +00003256 if (SoFar == nullptr)
3257 return nullptr;
3258 Subs.push_back(SoFar);
3259 continue;
3260 }
3261
3262 // ::= <prefix> <unqualified-name>
Pavel Labathba825192018-10-16 14:29:14 +00003263 if (!PushComponent(getDerived().parseUnqualifiedName(State)))
Richard Smithc20d1442018-08-20 20:14:49 +00003264 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003265 Subs.push_back(SoFar);
3266 }
3267
3268 if (SoFar == nullptr || Subs.empty())
3269 return nullptr;
3270
3271 Subs.pop_back();
3272 return SoFar;
3273}
3274
3275// <simple-id> ::= <source-name> [ <template-args> ]
Pavel Labathba825192018-10-16 14:29:14 +00003276template <typename Derived, typename Alloc>
3277Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
3278 Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003279 if (SN == nullptr)
3280 return nullptr;
3281 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003282 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003283 if (TA == nullptr)
3284 return nullptr;
3285 return make<NameWithTemplateArgs>(SN, TA);
3286 }
3287 return SN;
3288}
3289
3290// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
3291// ::= <simple-id> # e.g., ~A<2*N>
Pavel Labathba825192018-10-16 14:29:14 +00003292template <typename Derived, typename Alloc>
3293Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003294 Node *Result;
3295 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003296 Result = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003297 else
Pavel Labathba825192018-10-16 14:29:14 +00003298 Result = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003299 if (Result == nullptr)
3300 return nullptr;
3301 return make<DtorName>(Result);
3302}
3303
3304// <unresolved-type> ::= <template-param>
3305// ::= <decltype>
3306// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003307template <typename Derived, typename Alloc>
3308Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003309 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00003310 Node *TP = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003311 if (TP == nullptr)
3312 return nullptr;
3313 Subs.push_back(TP);
3314 return TP;
3315 }
3316 if (look() == 'D') {
Pavel Labathba825192018-10-16 14:29:14 +00003317 Node *DT = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003318 if (DT == nullptr)
3319 return nullptr;
3320 Subs.push_back(DT);
3321 return DT;
3322 }
Pavel Labathba825192018-10-16 14:29:14 +00003323 return getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00003324}
3325
3326// <base-unresolved-name> ::= <simple-id> # unresolved name
3327// extension ::= <operator-name> # unresolved operator-function-id
3328// extension ::= <operator-name> <template-args> # unresolved operator template-id
3329// ::= on <operator-name> # unresolved operator-function-id
3330// ::= on <operator-name> <template-args> # unresolved operator template-id
3331// ::= dn <destructor-name> # destructor or pseudo-destructor;
3332// # e.g. ~X or ~X<N-1>
Pavel Labathba825192018-10-16 14:29:14 +00003333template <typename Derived, typename Alloc>
3334Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003335 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003336 return getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003337
3338 if (consumeIf("dn"))
Pavel Labathba825192018-10-16 14:29:14 +00003339 return getDerived().parseDestructorName();
Richard Smithc20d1442018-08-20 20:14:49 +00003340
3341 consumeIf("on");
3342
Pavel Labathba825192018-10-16 14:29:14 +00003343 Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003344 if (Oper == nullptr)
3345 return nullptr;
3346 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003347 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003348 if (TA == nullptr)
3349 return nullptr;
3350 return make<NameWithTemplateArgs>(Oper, TA);
3351 }
3352 return Oper;
3353}
3354
3355// <unresolved-name>
3356// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3357// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
3358// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3359// # A::x, N::y, A<T>::z; "gs" means leading "::"
3360// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
3361// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
3362// # T::N::x /decltype(p)::N::x
3363// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3364//
3365// <unresolved-qualifier-level> ::= <simple-id>
Pavel Labathba825192018-10-16 14:29:14 +00003366template <typename Derived, typename Alloc>
3367Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003368 Node *SoFar = nullptr;
3369
3370 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3371 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3372 if (consumeIf("srN")) {
Pavel Labathba825192018-10-16 14:29:14 +00003373 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003374 if (SoFar == nullptr)
3375 return nullptr;
3376
3377 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003378 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003379 if (TA == nullptr)
3380 return nullptr;
3381 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003382 if (!SoFar)
3383 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003384 }
3385
3386 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003387 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003388 if (Qual == nullptr)
3389 return nullptr;
3390 SoFar = make<QualifiedName>(SoFar, Qual);
Richard Smithb485b352018-08-24 23:30:26 +00003391 if (!SoFar)
3392 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003393 }
3394
Pavel Labathba825192018-10-16 14:29:14 +00003395 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003396 if (Base == nullptr)
3397 return nullptr;
3398 return make<QualifiedName>(SoFar, Base);
3399 }
3400
3401 bool Global = consumeIf("gs");
3402
3403 // [gs] <base-unresolved-name> # x or (with "gs") ::x
3404 if (!consumeIf("sr")) {
Pavel Labathba825192018-10-16 14:29:14 +00003405 SoFar = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003406 if (SoFar == nullptr)
3407 return nullptr;
3408 if (Global)
3409 SoFar = make<GlobalQualifiedName>(SoFar);
3410 return SoFar;
3411 }
3412
3413 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3414 if (std::isdigit(look())) {
3415 do {
Pavel Labathba825192018-10-16 14:29:14 +00003416 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003417 if (Qual == nullptr)
3418 return nullptr;
3419 if (SoFar)
3420 SoFar = make<QualifiedName>(SoFar, Qual);
3421 else if (Global)
3422 SoFar = make<GlobalQualifiedName>(Qual);
3423 else
3424 SoFar = Qual;
Richard Smithb485b352018-08-24 23:30:26 +00003425 if (!SoFar)
3426 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003427 } while (!consumeIf('E'));
3428 }
3429 // sr <unresolved-type> <base-unresolved-name>
3430 // sr <unresolved-type> <template-args> <base-unresolved-name>
3431 else {
Pavel Labathba825192018-10-16 14:29:14 +00003432 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003433 if (SoFar == nullptr)
3434 return nullptr;
3435
3436 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003437 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003438 if (TA == nullptr)
3439 return nullptr;
3440 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003441 if (!SoFar)
3442 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003443 }
3444 }
3445
3446 assert(SoFar != nullptr);
3447
Pavel Labathba825192018-10-16 14:29:14 +00003448 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003449 if (Base == nullptr)
3450 return nullptr;
3451 return make<QualifiedName>(SoFar, Base);
3452}
3453
3454// <abi-tags> ::= <abi-tag> [<abi-tags>]
3455// <abi-tag> ::= B <source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003456template <typename Derived, typename Alloc>
3457Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
Richard Smithc20d1442018-08-20 20:14:49 +00003458 while (consumeIf('B')) {
3459 StringView SN = parseBareSourceName();
3460 if (SN.empty())
3461 return nullptr;
3462 N = make<AbiTagAttr>(N, SN);
Richard Smithb485b352018-08-24 23:30:26 +00003463 if (!N)
3464 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003465 }
3466 return N;
3467}
3468
3469// <number> ::= [n] <non-negative decimal integer>
Pavel Labathba825192018-10-16 14:29:14 +00003470template <typename Alloc, typename Derived>
3471StringView
3472AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
Richard Smithc20d1442018-08-20 20:14:49 +00003473 const char *Tmp = First;
3474 if (AllowNegative)
3475 consumeIf('n');
3476 if (numLeft() == 0 || !std::isdigit(*First))
3477 return StringView();
3478 while (numLeft() != 0 && std::isdigit(*First))
3479 ++First;
3480 return StringView(Tmp, First);
3481}
3482
3483// <positive length number> ::= [0-9]*
Pavel Labathba825192018-10-16 14:29:14 +00003484template <typename Alloc, typename Derived>
3485bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00003486 *Out = 0;
3487 if (look() < '0' || look() > '9')
3488 return true;
3489 while (look() >= '0' && look() <= '9') {
3490 *Out *= 10;
3491 *Out += static_cast<size_t>(consume() - '0');
3492 }
3493 return false;
3494}
3495
Pavel Labathba825192018-10-16 14:29:14 +00003496template <typename Alloc, typename Derived>
3497StringView AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003498 size_t Int = 0;
3499 if (parsePositiveInteger(&Int) || numLeft() < Int)
3500 return StringView();
3501 StringView R(First, First + Int);
3502 First += Int;
3503 return R;
3504}
3505
3506// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
3507//
3508// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
3509// ::= DO <expression> E # computed (instantiation-dependent) noexcept
3510// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
3511//
3512// <ref-qualifier> ::= R # & ref-qualifier
3513// <ref-qualifier> ::= O # && ref-qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003514template <typename Derived, typename Alloc>
3515Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003516 Qualifiers CVQuals = parseCVQualifiers();
3517
3518 Node *ExceptionSpec = nullptr;
3519 if (consumeIf("Do")) {
3520 ExceptionSpec = make<NameType>("noexcept");
Richard Smithb485b352018-08-24 23:30:26 +00003521 if (!ExceptionSpec)
3522 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003523 } else if (consumeIf("DO")) {
Pavel Labathba825192018-10-16 14:29:14 +00003524 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003525 if (E == nullptr || !consumeIf('E'))
3526 return nullptr;
3527 ExceptionSpec = make<NoexceptSpec>(E);
Richard Smithb485b352018-08-24 23:30:26 +00003528 if (!ExceptionSpec)
3529 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003530 } else if (consumeIf("Dw")) {
3531 size_t SpecsBegin = Names.size();
3532 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003533 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003534 if (T == nullptr)
3535 return nullptr;
3536 Names.push_back(T);
3537 }
3538 ExceptionSpec =
3539 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
Richard Smithb485b352018-08-24 23:30:26 +00003540 if (!ExceptionSpec)
3541 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003542 }
3543
3544 consumeIf("Dx"); // transaction safe
3545
3546 if (!consumeIf('F'))
3547 return nullptr;
3548 consumeIf('Y'); // extern "C"
Pavel Labathba825192018-10-16 14:29:14 +00003549 Node *ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003550 if (ReturnType == nullptr)
3551 return nullptr;
3552
3553 FunctionRefQual ReferenceQualifier = FrefQualNone;
3554 size_t ParamsBegin = Names.size();
3555 while (true) {
3556 if (consumeIf('E'))
3557 break;
3558 if (consumeIf('v'))
3559 continue;
3560 if (consumeIf("RE")) {
3561 ReferenceQualifier = FrefQualLValue;
3562 break;
3563 }
3564 if (consumeIf("OE")) {
3565 ReferenceQualifier = FrefQualRValue;
3566 break;
3567 }
Pavel Labathba825192018-10-16 14:29:14 +00003568 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003569 if (T == nullptr)
3570 return nullptr;
3571 Names.push_back(T);
3572 }
3573
3574 NodeArray Params = popTrailingNodeArray(ParamsBegin);
3575 return make<FunctionType>(ReturnType, Params, CVQuals,
3576 ReferenceQualifier, ExceptionSpec);
3577}
3578
3579// extension:
3580// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3581// ::= Dv [<dimension expression>] _ <element type>
3582// <extended element type> ::= <element type>
3583// ::= p # AltiVec vector pixel
Pavel Labathba825192018-10-16 14:29:14 +00003584template <typename Derived, typename Alloc>
3585Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003586 if (!consumeIf("Dv"))
3587 return nullptr;
3588 if (look() >= '1' && look() <= '9') {
3589 StringView DimensionNumber = parseNumber();
3590 if (!consumeIf('_'))
3591 return nullptr;
3592 if (consumeIf('p'))
3593 return make<PixelVectorType>(DimensionNumber);
Pavel Labathba825192018-10-16 14:29:14 +00003594 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003595 if (ElemType == nullptr)
3596 return nullptr;
3597 return make<VectorType>(ElemType, DimensionNumber);
3598 }
3599
3600 if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003601 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003602 if (!DimExpr)
3603 return nullptr;
3604 if (!consumeIf('_'))
3605 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003606 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003607 if (!ElemType)
3608 return nullptr;
3609 return make<VectorType>(ElemType, DimExpr);
3610 }
Pavel Labathba825192018-10-16 14:29:14 +00003611 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003612 if (!ElemType)
3613 return nullptr;
3614 return make<VectorType>(ElemType, StringView());
3615}
3616
3617// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3618// ::= DT <expression> E # decltype of an expression (C++0x)
Pavel Labathba825192018-10-16 14:29:14 +00003619template <typename Derived, typename Alloc>
3620Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
Richard Smithc20d1442018-08-20 20:14:49 +00003621 if (!consumeIf('D'))
3622 return nullptr;
3623 if (!consumeIf('t') && !consumeIf('T'))
3624 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003625 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003626 if (E == nullptr)
3627 return nullptr;
3628 if (!consumeIf('E'))
3629 return nullptr;
3630 return make<EnclosingExpr>("decltype(", E, ")");
3631}
3632
3633// <array-type> ::= A <positive dimension number> _ <element type>
3634// ::= A [<dimension expression>] _ <element type>
Pavel Labathba825192018-10-16 14:29:14 +00003635template <typename Derived, typename Alloc>
3636Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003637 if (!consumeIf('A'))
3638 return nullptr;
3639
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003640 NodeOrString Dimension;
3641
Richard Smithc20d1442018-08-20 20:14:49 +00003642 if (std::isdigit(look())) {
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003643 Dimension = parseNumber();
Richard Smithc20d1442018-08-20 20:14:49 +00003644 if (!consumeIf('_'))
3645 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003646 } else if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003647 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003648 if (DimExpr == nullptr)
3649 return nullptr;
3650 if (!consumeIf('_'))
3651 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003652 Dimension = DimExpr;
Richard Smithc20d1442018-08-20 20:14:49 +00003653 }
3654
Pavel Labathba825192018-10-16 14:29:14 +00003655 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003656 if (Ty == nullptr)
3657 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003658 return make<ArrayType>(Ty, Dimension);
Richard Smithc20d1442018-08-20 20:14:49 +00003659}
3660
3661// <pointer-to-member-type> ::= M <class type> <member type>
Pavel Labathba825192018-10-16 14:29:14 +00003662template <typename Derived, typename Alloc>
3663Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003664 if (!consumeIf('M'))
3665 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003666 Node *ClassType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003667 if (ClassType == nullptr)
3668 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003669 Node *MemberType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003670 if (MemberType == nullptr)
3671 return nullptr;
3672 return make<PointerToMemberType>(ClassType, MemberType);
3673}
3674
3675// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3676// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3677// ::= Tu <name> # dependent elaborated type specifier using 'union'
3678// ::= Te <name> # dependent elaborated type specifier using 'enum'
Pavel Labathba825192018-10-16 14:29:14 +00003679template <typename Derived, typename Alloc>
3680Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003681 StringView ElabSpef;
3682 if (consumeIf("Ts"))
3683 ElabSpef = "struct";
3684 else if (consumeIf("Tu"))
3685 ElabSpef = "union";
3686 else if (consumeIf("Te"))
3687 ElabSpef = "enum";
3688
Pavel Labathba825192018-10-16 14:29:14 +00003689 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00003690 if (Name == nullptr)
3691 return nullptr;
3692
3693 if (!ElabSpef.empty())
3694 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3695
3696 return Name;
3697}
3698
3699// <qualified-type> ::= <qualifiers> <type>
3700// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3701// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003702template <typename Derived, typename Alloc>
3703Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003704 if (consumeIf('U')) {
3705 StringView Qual = parseBareSourceName();
3706 if (Qual.empty())
3707 return nullptr;
3708
3709 // FIXME parse the optional <template-args> here!
3710
3711 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3712 if (Qual.startsWith("objcproto")) {
3713 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3714 StringView Proto;
3715 {
3716 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3717 SaveLast(Last, ProtoSourceName.end());
3718 Proto = parseBareSourceName();
3719 }
3720 if (Proto.empty())
3721 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003722 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003723 if (Child == nullptr)
3724 return nullptr;
3725 return make<ObjCProtoName>(Child, Proto);
3726 }
3727
Pavel Labathba825192018-10-16 14:29:14 +00003728 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003729 if (Child == nullptr)
3730 return nullptr;
3731 return make<VendorExtQualType>(Child, Qual);
3732 }
3733
3734 Qualifiers Quals = parseCVQualifiers();
Pavel Labathba825192018-10-16 14:29:14 +00003735 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003736 if (Ty == nullptr)
3737 return nullptr;
3738 if (Quals != QualNone)
3739 Ty = make<QualType>(Ty, Quals);
3740 return Ty;
3741}
3742
3743// <type> ::= <builtin-type>
3744// ::= <qualified-type>
3745// ::= <function-type>
3746// ::= <class-enum-type>
3747// ::= <array-type>
3748// ::= <pointer-to-member-type>
3749// ::= <template-param>
3750// ::= <template-template-param> <template-args>
3751// ::= <decltype>
3752// ::= P <type> # pointer
3753// ::= R <type> # l-value reference
3754// ::= O <type> # r-value reference (C++11)
3755// ::= C <type> # complex pair (C99)
3756// ::= G <type> # imaginary (C99)
3757// ::= <substitution> # See Compression below
3758// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3759// extension ::= <vector-type> # <vector-type> starts with Dv
3760//
3761// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3762// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003763template <typename Derived, typename Alloc>
3764Node *AbstractManglingParser<Derived, Alloc>::parseType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003765 Node *Result = nullptr;
3766
Richard Smithc20d1442018-08-20 20:14:49 +00003767 switch (look()) {
3768 // ::= <qualified-type>
3769 case 'r':
3770 case 'V':
3771 case 'K': {
3772 unsigned AfterQuals = 0;
3773 if (look(AfterQuals) == 'r') ++AfterQuals;
3774 if (look(AfterQuals) == 'V') ++AfterQuals;
3775 if (look(AfterQuals) == 'K') ++AfterQuals;
3776
3777 if (look(AfterQuals) == 'F' ||
3778 (look(AfterQuals) == 'D' &&
3779 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3780 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Pavel Labathba825192018-10-16 14:29:14 +00003781 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003782 break;
3783 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00003784 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00003785 }
3786 case 'U': {
Pavel Labathba825192018-10-16 14:29:14 +00003787 Result = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003788 break;
3789 }
3790 // <builtin-type> ::= v # void
3791 case 'v':
3792 ++First;
3793 return make<NameType>("void");
3794 // ::= w # wchar_t
3795 case 'w':
3796 ++First;
3797 return make<NameType>("wchar_t");
3798 // ::= b # bool
3799 case 'b':
3800 ++First;
3801 return make<NameType>("bool");
3802 // ::= c # char
3803 case 'c':
3804 ++First;
3805 return make<NameType>("char");
3806 // ::= a # signed char
3807 case 'a':
3808 ++First;
3809 return make<NameType>("signed char");
3810 // ::= h # unsigned char
3811 case 'h':
3812 ++First;
3813 return make<NameType>("unsigned char");
3814 // ::= s # short
3815 case 's':
3816 ++First;
3817 return make<NameType>("short");
3818 // ::= t # unsigned short
3819 case 't':
3820 ++First;
3821 return make<NameType>("unsigned short");
3822 // ::= i # int
3823 case 'i':
3824 ++First;
3825 return make<NameType>("int");
3826 // ::= j # unsigned int
3827 case 'j':
3828 ++First;
3829 return make<NameType>("unsigned int");
3830 // ::= l # long
3831 case 'l':
3832 ++First;
3833 return make<NameType>("long");
3834 // ::= m # unsigned long
3835 case 'm':
3836 ++First;
3837 return make<NameType>("unsigned long");
3838 // ::= x # long long, __int64
3839 case 'x':
3840 ++First;
3841 return make<NameType>("long long");
3842 // ::= y # unsigned long long, __int64
3843 case 'y':
3844 ++First;
3845 return make<NameType>("unsigned long long");
3846 // ::= n # __int128
3847 case 'n':
3848 ++First;
3849 return make<NameType>("__int128");
3850 // ::= o # unsigned __int128
3851 case 'o':
3852 ++First;
3853 return make<NameType>("unsigned __int128");
3854 // ::= f # float
3855 case 'f':
3856 ++First;
3857 return make<NameType>("float");
3858 // ::= d # double
3859 case 'd':
3860 ++First;
3861 return make<NameType>("double");
3862 // ::= e # long double, __float80
3863 case 'e':
3864 ++First;
3865 return make<NameType>("long double");
3866 // ::= g # __float128
3867 case 'g':
3868 ++First;
3869 return make<NameType>("__float128");
3870 // ::= z # ellipsis
3871 case 'z':
3872 ++First;
3873 return make<NameType>("...");
3874
3875 // <builtin-type> ::= u <source-name> # vendor extended type
3876 case 'u': {
3877 ++First;
3878 StringView Res = parseBareSourceName();
3879 if (Res.empty())
3880 return nullptr;
Erik Pilkingtonb94a1f42019-06-10 21:02:39 +00003881 // Typically, <builtin-type>s are not considered substitution candidates,
3882 // but the exception to that exception is vendor extended types (Itanium C++
3883 // ABI 5.9.1).
3884 Result = make<NameType>(Res);
3885 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003886 }
3887 case 'D':
3888 switch (look(1)) {
3889 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3890 case 'd':
3891 First += 2;
3892 return make<NameType>("decimal64");
3893 // ::= De # IEEE 754r decimal floating point (128 bits)
3894 case 'e':
3895 First += 2;
3896 return make<NameType>("decimal128");
3897 // ::= Df # IEEE 754r decimal floating point (32 bits)
3898 case 'f':
3899 First += 2;
3900 return make<NameType>("decimal32");
3901 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3902 case 'h':
3903 First += 2;
3904 return make<NameType>("decimal16");
3905 // ::= Di # char32_t
3906 case 'i':
3907 First += 2;
3908 return make<NameType>("char32_t");
3909 // ::= Ds # char16_t
3910 case 's':
3911 First += 2;
3912 return make<NameType>("char16_t");
Erik Pilkingtonc3780e82019-06-28 19:54:19 +00003913 // ::= Du # char8_t (C++2a, not yet in the Itanium spec)
3914 case 'u':
3915 First += 2;
3916 return make<NameType>("char8_t");
Richard Smithc20d1442018-08-20 20:14:49 +00003917 // ::= Da # auto (in dependent new-expressions)
3918 case 'a':
3919 First += 2;
3920 return make<NameType>("auto");
3921 // ::= Dc # decltype(auto)
3922 case 'c':
3923 First += 2;
3924 return make<NameType>("decltype(auto)");
3925 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3926 case 'n':
3927 First += 2;
3928 return make<NameType>("std::nullptr_t");
3929
3930 // ::= <decltype>
3931 case 't':
3932 case 'T': {
Pavel Labathba825192018-10-16 14:29:14 +00003933 Result = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003934 break;
3935 }
3936 // extension ::= <vector-type> # <vector-type> starts with Dv
3937 case 'v': {
Pavel Labathba825192018-10-16 14:29:14 +00003938 Result = getDerived().parseVectorType();
Richard Smithc20d1442018-08-20 20:14:49 +00003939 break;
3940 }
3941 // ::= Dp <type> # pack expansion (C++0x)
3942 case 'p': {
3943 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00003944 Node *Child = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003945 if (!Child)
3946 return nullptr;
3947 Result = make<ParameterPackExpansion>(Child);
3948 break;
3949 }
3950 // Exception specifier on a function type.
3951 case 'o':
3952 case 'O':
3953 case 'w':
3954 // Transaction safe function type.
3955 case 'x':
Pavel Labathba825192018-10-16 14:29:14 +00003956 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003957 break;
3958 }
3959 break;
3960 // ::= <function-type>
3961 case 'F': {
Pavel Labathba825192018-10-16 14:29:14 +00003962 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003963 break;
3964 }
3965 // ::= <array-type>
3966 case 'A': {
Pavel Labathba825192018-10-16 14:29:14 +00003967 Result = getDerived().parseArrayType();
Richard Smithc20d1442018-08-20 20:14:49 +00003968 break;
3969 }
3970 // ::= <pointer-to-member-type>
3971 case 'M': {
Pavel Labathba825192018-10-16 14:29:14 +00003972 Result = getDerived().parsePointerToMemberType();
Richard Smithc20d1442018-08-20 20:14:49 +00003973 break;
3974 }
3975 // ::= <template-param>
3976 case 'T': {
3977 // This could be an elaborate type specifier on a <class-enum-type>.
3978 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
Pavel Labathba825192018-10-16 14:29:14 +00003979 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00003980 break;
3981 }
3982
Pavel Labathba825192018-10-16 14:29:14 +00003983 Result = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003984 if (Result == nullptr)
3985 return nullptr;
3986
3987 // Result could be either of:
3988 // <type> ::= <template-param>
3989 // <type> ::= <template-template-param> <template-args>
3990 //
3991 // <template-template-param> ::= <template-param>
3992 // ::= <substitution>
3993 //
3994 // If this is followed by some <template-args>, and we're permitted to
3995 // parse them, take the second production.
3996
3997 if (TryToParseTemplateArgs && look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003998 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003999 if (TA == nullptr)
4000 return nullptr;
4001 Result = make<NameWithTemplateArgs>(Result, TA);
4002 }
4003 break;
4004 }
4005 // ::= P <type> # pointer
4006 case 'P': {
4007 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004008 Node *Ptr = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004009 if (Ptr == nullptr)
4010 return nullptr;
4011 Result = make<PointerType>(Ptr);
4012 break;
4013 }
4014 // ::= R <type> # l-value reference
4015 case 'R': {
4016 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004017 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004018 if (Ref == nullptr)
4019 return nullptr;
4020 Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
4021 break;
4022 }
4023 // ::= O <type> # r-value reference (C++11)
4024 case 'O': {
4025 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004026 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004027 if (Ref == nullptr)
4028 return nullptr;
4029 Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
4030 break;
4031 }
4032 // ::= C <type> # complex pair (C99)
4033 case 'C': {
4034 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004035 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004036 if (P == nullptr)
4037 return nullptr;
4038 Result = make<PostfixQualifiedType>(P, " complex");
4039 break;
4040 }
4041 // ::= G <type> # imaginary (C99)
4042 case 'G': {
4043 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004044 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004045 if (P == nullptr)
4046 return P;
4047 Result = make<PostfixQualifiedType>(P, " imaginary");
4048 break;
4049 }
4050 // ::= <substitution> # See Compression below
4051 case 'S': {
4052 if (look(1) && look(1) != 't') {
Pavel Labathba825192018-10-16 14:29:14 +00004053 Node *Sub = getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00004054 if (Sub == nullptr)
4055 return nullptr;
4056
4057 // Sub could be either of:
4058 // <type> ::= <substitution>
4059 // <type> ::= <template-template-param> <template-args>
4060 //
4061 // <template-template-param> ::= <template-param>
4062 // ::= <substitution>
4063 //
4064 // If this is followed by some <template-args>, and we're permitted to
4065 // parse them, take the second production.
4066
4067 if (TryToParseTemplateArgs && look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00004068 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00004069 if (TA == nullptr)
4070 return nullptr;
4071 Result = make<NameWithTemplateArgs>(Sub, TA);
4072 break;
4073 }
4074
4075 // If all we parsed was a substitution, don't re-insert into the
4076 // substitution table.
4077 return Sub;
4078 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00004079 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00004080 }
4081 // ::= <class-enum-type>
4082 default: {
Pavel Labathba825192018-10-16 14:29:14 +00004083 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00004084 break;
4085 }
4086 }
4087
4088 // If we parsed a type, insert it into the substitution table. Note that all
4089 // <builtin-type>s and <substitution>s have already bailed out, because they
4090 // don't get substitutions.
4091 if (Result != nullptr)
4092 Subs.push_back(Result);
4093 return Result;
4094}
4095
Pavel Labathba825192018-10-16 14:29:14 +00004096template <typename Derived, typename Alloc>
4097Node *AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(StringView Kind) {
4098 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004099 if (E == nullptr)
4100 return nullptr;
4101 return make<PrefixExpr>(Kind, E);
4102}
4103
Pavel Labathba825192018-10-16 14:29:14 +00004104template <typename Derived, typename Alloc>
4105Node *AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(StringView Kind) {
4106 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004107 if (LHS == nullptr)
4108 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004109 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004110 if (RHS == nullptr)
4111 return nullptr;
4112 return make<BinaryExpr>(LHS, Kind, RHS);
4113}
4114
Pavel Labathba825192018-10-16 14:29:14 +00004115template <typename Derived, typename Alloc>
4116Node *
4117AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(StringView Lit) {
Richard Smithc20d1442018-08-20 20:14:49 +00004118 StringView Tmp = parseNumber(true);
4119 if (!Tmp.empty() && consumeIf('E'))
4120 return make<IntegerLiteral>(Lit, Tmp);
4121 return nullptr;
4122}
4123
4124// <CV-Qualifiers> ::= [r] [V] [K]
Pavel Labathba825192018-10-16 14:29:14 +00004125template <typename Alloc, typename Derived>
4126Qualifiers AbstractManglingParser<Alloc, Derived>::parseCVQualifiers() {
Richard Smithc20d1442018-08-20 20:14:49 +00004127 Qualifiers CVR = QualNone;
4128 if (consumeIf('r'))
4129 CVR |= QualRestrict;
4130 if (consumeIf('V'))
4131 CVR |= QualVolatile;
4132 if (consumeIf('K'))
4133 CVR |= QualConst;
4134 return CVR;
4135}
4136
4137// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
4138// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
4139// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
4140// ::= 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 +00004141template <typename Derived, typename Alloc>
4142Node *AbstractManglingParser<Derived, Alloc>::parseFunctionParam() {
Richard Smithc20d1442018-08-20 20:14:49 +00004143 if (consumeIf("fp")) {
4144 parseCVQualifiers();
4145 StringView Num = parseNumber();
4146 if (!consumeIf('_'))
4147 return nullptr;
4148 return make<FunctionParam>(Num);
4149 }
4150 if (consumeIf("fL")) {
4151 if (parseNumber().empty())
4152 return nullptr;
4153 if (!consumeIf('p'))
4154 return nullptr;
4155 parseCVQualifiers();
4156 StringView Num = parseNumber();
4157 if (!consumeIf('_'))
4158 return nullptr;
4159 return make<FunctionParam>(Num);
4160 }
4161 return nullptr;
4162}
4163
4164// [gs] nw <expression>* _ <type> E # new (expr-list) type
4165// [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
4166// [gs] na <expression>* _ <type> E # new[] (expr-list) type
4167// [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
4168// <initializer> ::= pi <expression>* E # parenthesized initialization
Pavel Labathba825192018-10-16 14:29:14 +00004169template <typename Derived, typename Alloc>
4170Node *AbstractManglingParser<Derived, Alloc>::parseNewExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004171 bool Global = consumeIf("gs");
4172 bool IsArray = look(1) == 'a';
4173 if (!consumeIf("nw") && !consumeIf("na"))
4174 return nullptr;
4175 size_t Exprs = Names.size();
4176 while (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00004177 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004178 if (Ex == nullptr)
4179 return nullptr;
4180 Names.push_back(Ex);
4181 }
4182 NodeArray ExprList = popTrailingNodeArray(Exprs);
Pavel Labathba825192018-10-16 14:29:14 +00004183 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004184 if (Ty == nullptr)
4185 return Ty;
4186 if (consumeIf("pi")) {
4187 size_t InitsBegin = Names.size();
4188 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004189 Node *Init = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004190 if (Init == nullptr)
4191 return Init;
4192 Names.push_back(Init);
4193 }
4194 NodeArray Inits = popTrailingNodeArray(InitsBegin);
4195 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
4196 } else if (!consumeIf('E'))
4197 return nullptr;
4198 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
4199}
4200
4201// cv <type> <expression> # conversion with one argument
4202// cv <type> _ <expression>* E # conversion with a different number of arguments
Pavel Labathba825192018-10-16 14:29:14 +00004203template <typename Derived, typename Alloc>
4204Node *AbstractManglingParser<Derived, Alloc>::parseConversionExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004205 if (!consumeIf("cv"))
4206 return nullptr;
4207 Node *Ty;
4208 {
4209 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Pavel Labathba825192018-10-16 14:29:14 +00004210 Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004211 }
4212
4213 if (Ty == nullptr)
4214 return nullptr;
4215
4216 if (consumeIf('_')) {
4217 size_t ExprsBegin = Names.size();
4218 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004219 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004220 if (E == nullptr)
4221 return E;
4222 Names.push_back(E);
4223 }
4224 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
4225 return make<ConversionExpr>(Ty, Exprs);
4226 }
4227
Pavel Labathba825192018-10-16 14:29:14 +00004228 Node *E[1] = {getDerived().parseExpr()};
Richard Smithc20d1442018-08-20 20:14:49 +00004229 if (E[0] == nullptr)
4230 return nullptr;
4231 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
4232}
4233
4234// <expr-primary> ::= L <type> <value number> E # integer literal
4235// ::= L <type> <value float> E # floating literal
4236// ::= L <string type> E # string literal
4237// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
Richard Smithdf1c14c2019-09-06 23:53:21 +00004238// ::= L <lambda type> E # lambda expression
Richard Smithc20d1442018-08-20 20:14:49 +00004239// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
4240// ::= L <mangled-name> E # external name
Pavel Labathba825192018-10-16 14:29:14 +00004241template <typename Derived, typename Alloc>
4242Node *AbstractManglingParser<Derived, Alloc>::parseExprPrimary() {
Richard Smithc20d1442018-08-20 20:14:49 +00004243 if (!consumeIf('L'))
4244 return nullptr;
4245 switch (look()) {
4246 case 'w':
4247 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004248 return getDerived().parseIntegerLiteral("wchar_t");
Richard Smithc20d1442018-08-20 20:14:49 +00004249 case 'b':
4250 if (consumeIf("b0E"))
4251 return make<BoolExpr>(0);
4252 if (consumeIf("b1E"))
4253 return make<BoolExpr>(1);
4254 return nullptr;
4255 case 'c':
4256 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004257 return getDerived().parseIntegerLiteral("char");
Richard Smithc20d1442018-08-20 20:14:49 +00004258 case 'a':
4259 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004260 return getDerived().parseIntegerLiteral("signed char");
Richard Smithc20d1442018-08-20 20:14:49 +00004261 case 'h':
4262 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004263 return getDerived().parseIntegerLiteral("unsigned char");
Richard Smithc20d1442018-08-20 20:14:49 +00004264 case 's':
4265 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004266 return getDerived().parseIntegerLiteral("short");
Richard Smithc20d1442018-08-20 20:14:49 +00004267 case 't':
4268 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004269 return getDerived().parseIntegerLiteral("unsigned short");
Richard Smithc20d1442018-08-20 20:14:49 +00004270 case 'i':
4271 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004272 return getDerived().parseIntegerLiteral("");
Richard Smithc20d1442018-08-20 20:14:49 +00004273 case 'j':
4274 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004275 return getDerived().parseIntegerLiteral("u");
Richard Smithc20d1442018-08-20 20:14:49 +00004276 case 'l':
4277 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004278 return getDerived().parseIntegerLiteral("l");
Richard Smithc20d1442018-08-20 20:14:49 +00004279 case 'm':
4280 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004281 return getDerived().parseIntegerLiteral("ul");
Richard Smithc20d1442018-08-20 20:14:49 +00004282 case 'x':
4283 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004284 return getDerived().parseIntegerLiteral("ll");
Richard Smithc20d1442018-08-20 20:14:49 +00004285 case 'y':
4286 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004287 return getDerived().parseIntegerLiteral("ull");
Richard Smithc20d1442018-08-20 20:14:49 +00004288 case 'n':
4289 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004290 return getDerived().parseIntegerLiteral("__int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004291 case 'o':
4292 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004293 return getDerived().parseIntegerLiteral("unsigned __int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004294 case 'f':
4295 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004296 return getDerived().template parseFloatingLiteral<float>();
Richard Smithc20d1442018-08-20 20:14:49 +00004297 case 'd':
4298 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004299 return getDerived().template parseFloatingLiteral<double>();
Richard Smithc20d1442018-08-20 20:14:49 +00004300 case 'e':
4301 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004302 return getDerived().template parseFloatingLiteral<long double>();
Richard Smithc20d1442018-08-20 20:14:49 +00004303 case '_':
4304 if (consumeIf("_Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00004305 Node *R = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00004306 if (R != nullptr && consumeIf('E'))
4307 return R;
4308 }
4309 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00004310 case 'A': {
4311 Node *T = getDerived().parseType();
4312 if (T == nullptr)
4313 return nullptr;
4314 // FIXME: We need to include the string contents in the mangling.
4315 if (consumeIf('E'))
4316 return make<StringLiteral>(T);
4317 return nullptr;
4318 }
4319 case 'D':
4320 if (consumeIf("DnE"))
4321 return make<NameType>("nullptr");
4322 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004323 case 'T':
4324 // Invalid mangled name per
4325 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
4326 return nullptr;
4327 default: {
4328 // might be named type
Pavel Labathba825192018-10-16 14:29:14 +00004329 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004330 if (T == nullptr)
4331 return nullptr;
4332 StringView N = parseNumber();
4333 if (!N.empty()) {
4334 if (!consumeIf('E'))
4335 return nullptr;
4336 return make<IntegerCastExpr>(T, N);
4337 }
4338 if (consumeIf('E'))
Richard Smithdf1c14c2019-09-06 23:53:21 +00004339 return make<LambdaExpr>(T);
Richard Smithc20d1442018-08-20 20:14:49 +00004340 return nullptr;
4341 }
4342 }
4343}
4344
4345// <braced-expression> ::= <expression>
4346// ::= di <field source-name> <braced-expression> # .name = expr
4347// ::= dx <index expression> <braced-expression> # [expr] = expr
4348// ::= dX <range begin expression> <range end expression> <braced-expression>
Pavel Labathba825192018-10-16 14:29:14 +00004349template <typename Derived, typename Alloc>
4350Node *AbstractManglingParser<Derived, Alloc>::parseBracedExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004351 if (look() == 'd') {
4352 switch (look(1)) {
4353 case 'i': {
4354 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004355 Node *Field = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00004356 if (Field == nullptr)
4357 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004358 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004359 if (Init == nullptr)
4360 return nullptr;
4361 return make<BracedExpr>(Field, Init, /*isArray=*/false);
4362 }
4363 case 'x': {
4364 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004365 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004366 if (Index == nullptr)
4367 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004368 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004369 if (Init == nullptr)
4370 return nullptr;
4371 return make<BracedExpr>(Index, Init, /*isArray=*/true);
4372 }
4373 case 'X': {
4374 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004375 Node *RangeBegin = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004376 if (RangeBegin == nullptr)
4377 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004378 Node *RangeEnd = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004379 if (RangeEnd == nullptr)
4380 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004381 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004382 if (Init == nullptr)
4383 return nullptr;
4384 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
4385 }
4386 }
4387 }
Pavel Labathba825192018-10-16 14:29:14 +00004388 return getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004389}
4390
4391// (not yet in the spec)
4392// <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
4393// ::= fR <binary-operator-name> <expression> <expression>
4394// ::= fl <binary-operator-name> <expression>
4395// ::= fr <binary-operator-name> <expression>
Pavel Labathba825192018-10-16 14:29:14 +00004396template <typename Derived, typename Alloc>
4397Node *AbstractManglingParser<Derived, Alloc>::parseFoldExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004398 if (!consumeIf('f'))
4399 return nullptr;
4400
4401 char FoldKind = look();
4402 bool IsLeftFold, HasInitializer;
4403 HasInitializer = FoldKind == 'L' || FoldKind == 'R';
4404 if (FoldKind == 'l' || FoldKind == 'L')
4405 IsLeftFold = true;
4406 else if (FoldKind == 'r' || FoldKind == 'R')
4407 IsLeftFold = false;
4408 else
4409 return nullptr;
4410 ++First;
4411
4412 // FIXME: This map is duplicated in parseOperatorName and parseExpr.
4413 StringView OperatorName;
4414 if (consumeIf("aa")) OperatorName = "&&";
4415 else if (consumeIf("an")) OperatorName = "&";
4416 else if (consumeIf("aN")) OperatorName = "&=";
4417 else if (consumeIf("aS")) OperatorName = "=";
4418 else if (consumeIf("cm")) OperatorName = ",";
4419 else if (consumeIf("ds")) OperatorName = ".*";
4420 else if (consumeIf("dv")) OperatorName = "/";
4421 else if (consumeIf("dV")) OperatorName = "/=";
4422 else if (consumeIf("eo")) OperatorName = "^";
4423 else if (consumeIf("eO")) OperatorName = "^=";
4424 else if (consumeIf("eq")) OperatorName = "==";
4425 else if (consumeIf("ge")) OperatorName = ">=";
4426 else if (consumeIf("gt")) OperatorName = ">";
4427 else if (consumeIf("le")) OperatorName = "<=";
4428 else if (consumeIf("ls")) OperatorName = "<<";
4429 else if (consumeIf("lS")) OperatorName = "<<=";
4430 else if (consumeIf("lt")) OperatorName = "<";
4431 else if (consumeIf("mi")) OperatorName = "-";
4432 else if (consumeIf("mI")) OperatorName = "-=";
4433 else if (consumeIf("ml")) OperatorName = "*";
4434 else if (consumeIf("mL")) OperatorName = "*=";
4435 else if (consumeIf("ne")) OperatorName = "!=";
4436 else if (consumeIf("oo")) OperatorName = "||";
4437 else if (consumeIf("or")) OperatorName = "|";
4438 else if (consumeIf("oR")) OperatorName = "|=";
4439 else if (consumeIf("pl")) OperatorName = "+";
4440 else if (consumeIf("pL")) OperatorName = "+=";
4441 else if (consumeIf("rm")) OperatorName = "%";
4442 else if (consumeIf("rM")) OperatorName = "%=";
4443 else if (consumeIf("rs")) OperatorName = ">>";
4444 else if (consumeIf("rS")) OperatorName = ">>=";
4445 else return nullptr;
4446
Pavel Labathba825192018-10-16 14:29:14 +00004447 Node *Pack = getDerived().parseExpr(), *Init = nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004448 if (Pack == nullptr)
4449 return nullptr;
4450 if (HasInitializer) {
Pavel Labathba825192018-10-16 14:29:14 +00004451 Init = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004452 if (Init == nullptr)
4453 return nullptr;
4454 }
4455
4456 if (IsLeftFold && Init)
4457 std::swap(Pack, Init);
4458
4459 return make<FoldExpr>(IsLeftFold, OperatorName, Pack, Init);
4460}
4461
4462// <expression> ::= <unary operator-name> <expression>
4463// ::= <binary operator-name> <expression> <expression>
4464// ::= <ternary operator-name> <expression> <expression> <expression>
4465// ::= cl <expression>+ E # call
4466// ::= cv <type> <expression> # conversion with one argument
4467// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4468// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
4469// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
4470// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
4471// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
4472// ::= [gs] dl <expression> # delete expression
4473// ::= [gs] da <expression> # delete[] expression
4474// ::= pp_ <expression> # prefix ++
4475// ::= mm_ <expression> # prefix --
4476// ::= ti <type> # typeid (type)
4477// ::= te <expression> # typeid (expression)
4478// ::= dc <type> <expression> # dynamic_cast<type> (expression)
4479// ::= sc <type> <expression> # static_cast<type> (expression)
4480// ::= cc <type> <expression> # const_cast<type> (expression)
4481// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4482// ::= st <type> # sizeof (a type)
4483// ::= sz <expression> # sizeof (an expression)
4484// ::= at <type> # alignof (a type)
4485// ::= az <expression> # alignof (an expression)
4486// ::= nx <expression> # noexcept (expression)
4487// ::= <template-param>
4488// ::= <function-param>
4489// ::= dt <expression> <unresolved-name> # expr.name
4490// ::= pt <expression> <unresolved-name> # expr->name
4491// ::= ds <expression> <expression> # expr.*expr
4492// ::= sZ <template-param> # size of a parameter pack
4493// ::= sZ <function-param> # size of a function parameter pack
4494// ::= sP <template-arg>* E # sizeof...(T), size of a captured template parameter pack from an alias template
4495// ::= sp <expression> # pack expansion
4496// ::= tw <expression> # throw expression
4497// ::= tr # throw with no operand (rethrow)
4498// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
4499// # freestanding dependent name (e.g., T::x),
4500// # objectless nonstatic member reference
4501// ::= fL <binary-operator-name> <expression> <expression>
4502// ::= fR <binary-operator-name> <expression> <expression>
4503// ::= fl <binary-operator-name> <expression>
4504// ::= fr <binary-operator-name> <expression>
4505// ::= <expr-primary>
Pavel Labathba825192018-10-16 14:29:14 +00004506template <typename Derived, typename Alloc>
4507Node *AbstractManglingParser<Derived, Alloc>::parseExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004508 bool Global = consumeIf("gs");
4509 if (numLeft() < 2)
4510 return nullptr;
4511
4512 switch (*First) {
4513 case 'L':
Pavel Labathba825192018-10-16 14:29:14 +00004514 return getDerived().parseExprPrimary();
Richard Smithc20d1442018-08-20 20:14:49 +00004515 case 'T':
Pavel Labathba825192018-10-16 14:29:14 +00004516 return getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004517 case 'f': {
4518 // Disambiguate a fold expression from a <function-param>.
4519 if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
Pavel Labathba825192018-10-16 14:29:14 +00004520 return getDerived().parseFunctionParam();
4521 return getDerived().parseFoldExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004522 }
4523 case 'a':
4524 switch (First[1]) {
4525 case 'a':
4526 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004527 return getDerived().parseBinaryExpr("&&");
Richard Smithc20d1442018-08-20 20:14:49 +00004528 case 'd':
4529 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004530 return getDerived().parsePrefixExpr("&");
Richard Smithc20d1442018-08-20 20:14:49 +00004531 case 'n':
4532 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004533 return getDerived().parseBinaryExpr("&");
Richard Smithc20d1442018-08-20 20:14:49 +00004534 case 'N':
4535 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004536 return getDerived().parseBinaryExpr("&=");
Richard Smithc20d1442018-08-20 20:14:49 +00004537 case 'S':
4538 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004539 return getDerived().parseBinaryExpr("=");
Richard Smithc20d1442018-08-20 20:14:49 +00004540 case 't': {
4541 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004542 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004543 if (Ty == nullptr)
4544 return nullptr;
4545 return make<EnclosingExpr>("alignof (", Ty, ")");
4546 }
4547 case 'z': {
4548 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004549 Node *Ty = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004550 if (Ty == nullptr)
4551 return nullptr;
4552 return make<EnclosingExpr>("alignof (", Ty, ")");
4553 }
4554 }
4555 return nullptr;
4556 case 'c':
4557 switch (First[1]) {
4558 // cc <type> <expression> # const_cast<type>(expression)
4559 case 'c': {
4560 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004561 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004562 if (Ty == nullptr)
4563 return Ty;
Pavel Labathba825192018-10-16 14:29:14 +00004564 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004565 if (Ex == nullptr)
4566 return Ex;
4567 return make<CastExpr>("const_cast", Ty, Ex);
4568 }
4569 // cl <expression>+ E # call
4570 case 'l': {
4571 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004572 Node *Callee = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004573 if (Callee == nullptr)
4574 return Callee;
4575 size_t ExprsBegin = Names.size();
4576 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004577 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004578 if (E == nullptr)
4579 return E;
4580 Names.push_back(E);
4581 }
4582 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
4583 }
4584 case 'm':
4585 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004586 return getDerived().parseBinaryExpr(",");
Richard Smithc20d1442018-08-20 20:14:49 +00004587 case 'o':
4588 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004589 return getDerived().parsePrefixExpr("~");
Richard Smithc20d1442018-08-20 20:14:49 +00004590 case 'v':
Pavel Labathba825192018-10-16 14:29:14 +00004591 return getDerived().parseConversionExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004592 }
4593 return nullptr;
4594 case 'd':
4595 switch (First[1]) {
4596 case 'a': {
4597 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004598 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004599 if (Ex == nullptr)
4600 return Ex;
4601 return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
4602 }
4603 case 'c': {
4604 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004605 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004606 if (T == nullptr)
4607 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004608 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004609 if (Ex == nullptr)
4610 return Ex;
4611 return make<CastExpr>("dynamic_cast", T, Ex);
4612 }
4613 case 'e':
4614 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004615 return getDerived().parsePrefixExpr("*");
Richard Smithc20d1442018-08-20 20:14:49 +00004616 case 'l': {
4617 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004618 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004619 if (E == nullptr)
4620 return E;
4621 return make<DeleteExpr>(E, Global, /*is_array=*/false);
4622 }
4623 case 'n':
Pavel Labathba825192018-10-16 14:29:14 +00004624 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004625 case 's': {
4626 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004627 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004628 if (LHS == nullptr)
4629 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004630 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004631 if (RHS == nullptr)
4632 return nullptr;
4633 return make<MemberExpr>(LHS, ".*", RHS);
4634 }
4635 case 't': {
4636 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004637 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004638 if (LHS == nullptr)
4639 return LHS;
Pavel Labathba825192018-10-16 14:29:14 +00004640 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004641 if (RHS == nullptr)
4642 return nullptr;
4643 return make<MemberExpr>(LHS, ".", RHS);
4644 }
4645 case 'v':
4646 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004647 return getDerived().parseBinaryExpr("/");
Richard Smithc20d1442018-08-20 20:14:49 +00004648 case 'V':
4649 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004650 return getDerived().parseBinaryExpr("/=");
Richard Smithc20d1442018-08-20 20:14:49 +00004651 }
4652 return nullptr;
4653 case 'e':
4654 switch (First[1]) {
4655 case 'o':
4656 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004657 return getDerived().parseBinaryExpr("^");
Richard Smithc20d1442018-08-20 20:14:49 +00004658 case 'O':
4659 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004660 return getDerived().parseBinaryExpr("^=");
Richard Smithc20d1442018-08-20 20:14:49 +00004661 case 'q':
4662 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004663 return getDerived().parseBinaryExpr("==");
Richard Smithc20d1442018-08-20 20:14:49 +00004664 }
4665 return nullptr;
4666 case 'g':
4667 switch (First[1]) {
4668 case 'e':
4669 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004670 return getDerived().parseBinaryExpr(">=");
Richard Smithc20d1442018-08-20 20:14:49 +00004671 case 't':
4672 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004673 return getDerived().parseBinaryExpr(">");
Richard Smithc20d1442018-08-20 20:14:49 +00004674 }
4675 return nullptr;
4676 case 'i':
4677 switch (First[1]) {
4678 case 'x': {
4679 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004680 Node *Base = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004681 if (Base == nullptr)
4682 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004683 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004684 if (Index == nullptr)
4685 return Index;
4686 return make<ArraySubscriptExpr>(Base, Index);
4687 }
4688 case 'l': {
4689 First += 2;
4690 size_t InitsBegin = Names.size();
4691 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004692 Node *E = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004693 if (E == nullptr)
4694 return nullptr;
4695 Names.push_back(E);
4696 }
4697 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4698 }
4699 }
4700 return nullptr;
4701 case 'l':
4702 switch (First[1]) {
4703 case 'e':
4704 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004705 return getDerived().parseBinaryExpr("<=");
Richard Smithc20d1442018-08-20 20:14:49 +00004706 case 's':
4707 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004708 return getDerived().parseBinaryExpr("<<");
Richard Smithc20d1442018-08-20 20:14:49 +00004709 case 'S':
4710 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004711 return getDerived().parseBinaryExpr("<<=");
Richard Smithc20d1442018-08-20 20:14:49 +00004712 case 't':
4713 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004714 return getDerived().parseBinaryExpr("<");
Richard Smithc20d1442018-08-20 20:14:49 +00004715 }
4716 return nullptr;
4717 case 'm':
4718 switch (First[1]) {
4719 case 'i':
4720 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004721 return getDerived().parseBinaryExpr("-");
Richard Smithc20d1442018-08-20 20:14:49 +00004722 case 'I':
4723 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004724 return getDerived().parseBinaryExpr("-=");
Richard Smithc20d1442018-08-20 20:14:49 +00004725 case 'l':
4726 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004727 return getDerived().parseBinaryExpr("*");
Richard Smithc20d1442018-08-20 20:14:49 +00004728 case 'L':
4729 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004730 return getDerived().parseBinaryExpr("*=");
Richard Smithc20d1442018-08-20 20:14:49 +00004731 case 'm':
4732 First += 2;
4733 if (consumeIf('_'))
Pavel Labathba825192018-10-16 14:29:14 +00004734 return getDerived().parsePrefixExpr("--");
4735 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004736 if (Ex == nullptr)
4737 return nullptr;
4738 return make<PostfixExpr>(Ex, "--");
4739 }
4740 return nullptr;
4741 case 'n':
4742 switch (First[1]) {
4743 case 'a':
4744 case 'w':
Pavel Labathba825192018-10-16 14:29:14 +00004745 return getDerived().parseNewExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004746 case 'e':
4747 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004748 return getDerived().parseBinaryExpr("!=");
Richard Smithc20d1442018-08-20 20:14:49 +00004749 case 'g':
4750 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004751 return getDerived().parsePrefixExpr("-");
Richard Smithc20d1442018-08-20 20:14:49 +00004752 case 't':
4753 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004754 return getDerived().parsePrefixExpr("!");
Richard Smithc20d1442018-08-20 20:14:49 +00004755 case 'x':
4756 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004757 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004758 if (Ex == nullptr)
4759 return Ex;
4760 return make<EnclosingExpr>("noexcept (", Ex, ")");
4761 }
4762 return nullptr;
4763 case 'o':
4764 switch (First[1]) {
4765 case 'n':
Pavel Labathba825192018-10-16 14:29:14 +00004766 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004767 case 'o':
4768 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004769 return getDerived().parseBinaryExpr("||");
Richard Smithc20d1442018-08-20 20:14:49 +00004770 case 'r':
4771 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004772 return getDerived().parseBinaryExpr("|");
Richard Smithc20d1442018-08-20 20:14:49 +00004773 case 'R':
4774 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004775 return getDerived().parseBinaryExpr("|=");
Richard Smithc20d1442018-08-20 20:14:49 +00004776 }
4777 return nullptr;
4778 case 'p':
4779 switch (First[1]) {
4780 case 'm':
4781 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004782 return getDerived().parseBinaryExpr("->*");
Richard Smithc20d1442018-08-20 20:14:49 +00004783 case 'l':
4784 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004785 return getDerived().parseBinaryExpr("+");
Richard Smithc20d1442018-08-20 20:14:49 +00004786 case 'L':
4787 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004788 return getDerived().parseBinaryExpr("+=");
Richard Smithc20d1442018-08-20 20:14:49 +00004789 case 'p': {
4790 First += 2;
4791 if (consumeIf('_'))
Pavel Labathba825192018-10-16 14:29:14 +00004792 return getDerived().parsePrefixExpr("++");
4793 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004794 if (Ex == nullptr)
4795 return Ex;
4796 return make<PostfixExpr>(Ex, "++");
4797 }
4798 case 's':
4799 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004800 return getDerived().parsePrefixExpr("+");
Richard Smithc20d1442018-08-20 20:14:49 +00004801 case 't': {
4802 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004803 Node *L = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004804 if (L == nullptr)
4805 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004806 Node *R = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004807 if (R == nullptr)
4808 return nullptr;
4809 return make<MemberExpr>(L, "->", R);
4810 }
4811 }
4812 return nullptr;
4813 case 'q':
4814 if (First[1] == 'u') {
4815 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004816 Node *Cond = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004817 if (Cond == nullptr)
4818 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004819 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004820 if (LHS == nullptr)
4821 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004822 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004823 if (RHS == nullptr)
4824 return nullptr;
4825 return make<ConditionalExpr>(Cond, LHS, RHS);
4826 }
4827 return nullptr;
4828 case 'r':
4829 switch (First[1]) {
4830 case 'c': {
4831 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004832 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004833 if (T == nullptr)
4834 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004835 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004836 if (Ex == nullptr)
4837 return Ex;
4838 return make<CastExpr>("reinterpret_cast", T, Ex);
4839 }
4840 case 'm':
4841 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004842 return getDerived().parseBinaryExpr("%");
Richard Smithc20d1442018-08-20 20:14:49 +00004843 case 'M':
4844 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004845 return getDerived().parseBinaryExpr("%=");
Richard Smithc20d1442018-08-20 20:14:49 +00004846 case 's':
4847 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004848 return getDerived().parseBinaryExpr(">>");
Richard Smithc20d1442018-08-20 20:14:49 +00004849 case 'S':
4850 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004851 return getDerived().parseBinaryExpr(">>=");
Richard Smithc20d1442018-08-20 20:14:49 +00004852 }
4853 return nullptr;
4854 case 's':
4855 switch (First[1]) {
4856 case 'c': {
4857 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004858 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004859 if (T == nullptr)
4860 return T;
Pavel Labathba825192018-10-16 14:29:14 +00004861 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004862 if (Ex == nullptr)
4863 return Ex;
4864 return make<CastExpr>("static_cast", T, Ex);
4865 }
4866 case 'p': {
4867 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004868 Node *Child = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004869 if (Child == nullptr)
4870 return nullptr;
4871 return make<ParameterPackExpansion>(Child);
4872 }
4873 case 'r':
Pavel Labathba825192018-10-16 14:29:14 +00004874 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004875 case 't': {
4876 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004877 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004878 if (Ty == nullptr)
4879 return Ty;
4880 return make<EnclosingExpr>("sizeof (", Ty, ")");
4881 }
4882 case 'z': {
4883 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004884 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004885 if (Ex == nullptr)
4886 return Ex;
4887 return make<EnclosingExpr>("sizeof (", Ex, ")");
4888 }
4889 case 'Z':
4890 First += 2;
4891 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00004892 Node *R = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004893 if (R == nullptr)
4894 return nullptr;
4895 return make<SizeofParamPackExpr>(R);
4896 } else if (look() == 'f') {
Pavel Labathba825192018-10-16 14:29:14 +00004897 Node *FP = getDerived().parseFunctionParam();
Richard Smithc20d1442018-08-20 20:14:49 +00004898 if (FP == nullptr)
4899 return nullptr;
4900 return make<EnclosingExpr>("sizeof... (", FP, ")");
4901 }
4902 return nullptr;
4903 case 'P': {
4904 First += 2;
4905 size_t ArgsBegin = Names.size();
4906 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004907 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00004908 if (Arg == nullptr)
4909 return nullptr;
4910 Names.push_back(Arg);
4911 }
Richard Smithb485b352018-08-24 23:30:26 +00004912 auto *Pack = make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin));
4913 if (!Pack)
4914 return nullptr;
4915 return make<EnclosingExpr>("sizeof... (", Pack, ")");
Richard Smithc20d1442018-08-20 20:14:49 +00004916 }
4917 }
4918 return nullptr;
4919 case 't':
4920 switch (First[1]) {
4921 case 'e': {
4922 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004923 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004924 if (Ex == nullptr)
4925 return Ex;
4926 return make<EnclosingExpr>("typeid (", Ex, ")");
4927 }
4928 case 'i': {
4929 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004930 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004931 if (Ty == nullptr)
4932 return Ty;
4933 return make<EnclosingExpr>("typeid (", Ty, ")");
4934 }
4935 case 'l': {
4936 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004937 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004938 if (Ty == nullptr)
4939 return nullptr;
4940 size_t InitsBegin = Names.size();
4941 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004942 Node *E = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004943 if (E == nullptr)
4944 return nullptr;
4945 Names.push_back(E);
4946 }
4947 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4948 }
4949 case 'r':
4950 First += 2;
4951 return make<NameType>("throw");
4952 case 'w': {
4953 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004954 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004955 if (Ex == nullptr)
4956 return nullptr;
4957 return make<ThrowExpr>(Ex);
4958 }
4959 }
4960 return nullptr;
4961 case '1':
4962 case '2':
4963 case '3':
4964 case '4':
4965 case '5':
4966 case '6':
4967 case '7':
4968 case '8':
4969 case '9':
Pavel Labathba825192018-10-16 14:29:14 +00004970 return getDerived().parseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00004971 }
Erik Pilkingtone8457c62019-06-18 23:34:09 +00004972
4973 if (consumeIf("u8__uuidoft")) {
4974 Node *Ty = getDerived().parseType();
4975 if (!Ty)
4976 return nullptr;
4977 return make<UUIDOfExpr>(Ty);
4978 }
4979
4980 if (consumeIf("u8__uuidofz")) {
4981 Node *Ex = getDerived().parseExpr();
4982 if (!Ex)
4983 return nullptr;
4984 return make<UUIDOfExpr>(Ex);
4985 }
4986
Richard Smithc20d1442018-08-20 20:14:49 +00004987 return nullptr;
4988}
4989
4990// <call-offset> ::= h <nv-offset> _
4991// ::= v <v-offset> _
4992//
4993// <nv-offset> ::= <offset number>
4994// # non-virtual base override
4995//
4996// <v-offset> ::= <offset number> _ <virtual offset number>
4997// # virtual base override, with vcall offset
Pavel Labathba825192018-10-16 14:29:14 +00004998template <typename Alloc, typename Derived>
4999bool AbstractManglingParser<Alloc, Derived>::parseCallOffset() {
Richard Smithc20d1442018-08-20 20:14:49 +00005000 // Just scan through the call offset, we never add this information into the
5001 // output.
5002 if (consumeIf('h'))
5003 return parseNumber(true).empty() || !consumeIf('_');
5004 if (consumeIf('v'))
5005 return parseNumber(true).empty() || !consumeIf('_') ||
5006 parseNumber(true).empty() || !consumeIf('_');
5007 return true;
5008}
5009
5010// <special-name> ::= TV <type> # virtual table
5011// ::= TT <type> # VTT structure (construction vtable index)
5012// ::= TI <type> # typeinfo structure
5013// ::= TS <type> # typeinfo name (null-terminated byte string)
5014// ::= Tc <call-offset> <call-offset> <base encoding>
5015// # base is the nominal target function of thunk
5016// # first call-offset is 'this' adjustment
5017// # second call-offset is result adjustment
5018// ::= T <call-offset> <base encoding>
5019// # base is the nominal target function of thunk
5020// ::= GV <object name> # Guard variable for one-time initialization
5021// # No <type>
5022// ::= TW <object name> # Thread-local wrapper
5023// ::= TH <object name> # Thread-local initialization
5024// ::= GR <object name> _ # First temporary
5025// ::= GR <object name> <seq-id> _ # Subsequent temporaries
5026// extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
5027// extension ::= GR <object name> # reference temporary for object
Pavel Labathba825192018-10-16 14:29:14 +00005028template <typename Derived, typename Alloc>
5029Node *AbstractManglingParser<Derived, Alloc>::parseSpecialName() {
Richard Smithc20d1442018-08-20 20:14:49 +00005030 switch (look()) {
5031 case 'T':
5032 switch (look(1)) {
5033 // TV <type> # virtual table
5034 case 'V': {
5035 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005036 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005037 if (Ty == nullptr)
5038 return nullptr;
5039 return make<SpecialName>("vtable for ", Ty);
5040 }
5041 // TT <type> # VTT structure (construction vtable index)
5042 case 'T': {
5043 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005044 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005045 if (Ty == nullptr)
5046 return nullptr;
5047 return make<SpecialName>("VTT for ", Ty);
5048 }
5049 // TI <type> # typeinfo structure
5050 case 'I': {
5051 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005052 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005053 if (Ty == nullptr)
5054 return nullptr;
5055 return make<SpecialName>("typeinfo for ", Ty);
5056 }
5057 // TS <type> # typeinfo name (null-terminated byte string)
5058 case 'S': {
5059 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005060 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005061 if (Ty == nullptr)
5062 return nullptr;
5063 return make<SpecialName>("typeinfo name for ", Ty);
5064 }
5065 // Tc <call-offset> <call-offset> <base encoding>
5066 case 'c': {
5067 First += 2;
5068 if (parseCallOffset() || parseCallOffset())
5069 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005070 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005071 if (Encoding == nullptr)
5072 return nullptr;
5073 return make<SpecialName>("covariant return thunk to ", Encoding);
5074 }
5075 // extension ::= TC <first type> <number> _ <second type>
5076 // # construction vtable for second-in-first
5077 case 'C': {
5078 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005079 Node *FirstType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005080 if (FirstType == nullptr)
5081 return nullptr;
5082 if (parseNumber(true).empty() || !consumeIf('_'))
5083 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005084 Node *SecondType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005085 if (SecondType == nullptr)
5086 return nullptr;
5087 return make<CtorVtableSpecialName>(SecondType, FirstType);
5088 }
5089 // TW <object name> # Thread-local wrapper
5090 case 'W': {
5091 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005092 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005093 if (Name == nullptr)
5094 return nullptr;
5095 return make<SpecialName>("thread-local wrapper routine for ", Name);
5096 }
5097 // TH <object name> # Thread-local initialization
5098 case 'H': {
5099 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005100 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005101 if (Name == nullptr)
5102 return nullptr;
5103 return make<SpecialName>("thread-local initialization routine for ", Name);
5104 }
5105 // T <call-offset> <base encoding>
5106 default: {
5107 ++First;
5108 bool IsVirt = look() == 'v';
5109 if (parseCallOffset())
5110 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00005111 Node *BaseEncoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005112 if (BaseEncoding == nullptr)
5113 return nullptr;
5114 if (IsVirt)
5115 return make<SpecialName>("virtual thunk to ", BaseEncoding);
5116 else
5117 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
5118 }
5119 }
5120 case 'G':
5121 switch (look(1)) {
5122 // GV <object name> # Guard variable for one-time initialization
5123 case 'V': {
5124 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005125 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005126 if (Name == nullptr)
5127 return nullptr;
5128 return make<SpecialName>("guard variable for ", Name);
5129 }
5130 // GR <object name> # reference temporary for object
5131 // GR <object name> _ # First temporary
5132 // GR <object name> <seq-id> _ # Subsequent temporaries
5133 case 'R': {
5134 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005135 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00005136 if (Name == nullptr)
5137 return nullptr;
5138 size_t Count;
5139 bool ParsedSeqId = !parseSeqId(&Count);
5140 if (!consumeIf('_') && ParsedSeqId)
5141 return nullptr;
5142 return make<SpecialName>("reference temporary for ", Name);
5143 }
5144 }
5145 }
5146 return nullptr;
5147}
5148
5149// <encoding> ::= <function name> <bare-function-type>
5150// ::= <data name>
5151// ::= <special-name>
Pavel Labathba825192018-10-16 14:29:14 +00005152template <typename Derived, typename Alloc>
5153Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
Richard Smithc20d1442018-08-20 20:14:49 +00005154 if (look() == 'G' || look() == 'T')
Pavel Labathba825192018-10-16 14:29:14 +00005155 return getDerived().parseSpecialName();
Richard Smithc20d1442018-08-20 20:14:49 +00005156
5157 auto IsEndOfEncoding = [&] {
5158 // The set of chars that can potentially follow an <encoding> (none of which
5159 // can start a <type>). Enumerating these allows us to avoid speculative
5160 // parsing.
5161 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
5162 };
5163
5164 NameState NameInfo(this);
Pavel Labathba825192018-10-16 14:29:14 +00005165 Node *Name = getDerived().parseName(&NameInfo);
Richard Smithc20d1442018-08-20 20:14:49 +00005166 if (Name == nullptr)
5167 return nullptr;
5168
5169 if (resolveForwardTemplateRefs(NameInfo))
5170 return nullptr;
5171
5172 if (IsEndOfEncoding())
5173 return Name;
5174
5175 Node *Attrs = nullptr;
5176 if (consumeIf("Ua9enable_ifI")) {
5177 size_t BeforeArgs = Names.size();
5178 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005179 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005180 if (Arg == nullptr)
5181 return nullptr;
5182 Names.push_back(Arg);
5183 }
5184 Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
Richard Smithb485b352018-08-24 23:30:26 +00005185 if (!Attrs)
5186 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005187 }
5188
5189 Node *ReturnType = nullptr;
5190 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
Pavel Labathba825192018-10-16 14:29:14 +00005191 ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005192 if (ReturnType == nullptr)
5193 return nullptr;
5194 }
5195
5196 if (consumeIf('v'))
5197 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
5198 Attrs, NameInfo.CVQualifiers,
5199 NameInfo.ReferenceQualifier);
5200
5201 size_t ParamsBegin = Names.size();
5202 do {
Pavel Labathba825192018-10-16 14:29:14 +00005203 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005204 if (Ty == nullptr)
5205 return nullptr;
5206 Names.push_back(Ty);
5207 } while (!IsEndOfEncoding());
5208
5209 return make<FunctionEncoding>(ReturnType, Name,
5210 popTrailingNodeArray(ParamsBegin),
5211 Attrs, NameInfo.CVQualifiers,
5212 NameInfo.ReferenceQualifier);
5213}
5214
5215template <class Float>
5216struct FloatData;
5217
5218template <>
5219struct FloatData<float>
5220{
5221 static const size_t mangled_size = 8;
5222 static const size_t max_demangled_size = 24;
5223 static constexpr const char* spec = "%af";
5224};
5225
5226template <>
5227struct FloatData<double>
5228{
5229 static const size_t mangled_size = 16;
5230 static const size_t max_demangled_size = 32;
5231 static constexpr const char* spec = "%a";
5232};
5233
5234template <>
5235struct FloatData<long double>
5236{
5237#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
5238 defined(__wasm__)
5239 static const size_t mangled_size = 32;
5240#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
5241 static const size_t mangled_size = 16;
5242#else
5243 static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms
5244#endif
5245 static const size_t max_demangled_size = 40;
5246 static constexpr const char *spec = "%LaL";
5247};
5248
Pavel Labathba825192018-10-16 14:29:14 +00005249template <typename Alloc, typename Derived>
5250template <class Float>
5251Node *AbstractManglingParser<Alloc, Derived>::parseFloatingLiteral() {
Richard Smithc20d1442018-08-20 20:14:49 +00005252 const size_t N = FloatData<Float>::mangled_size;
5253 if (numLeft() <= N)
5254 return nullptr;
5255 StringView Data(First, First + N);
5256 for (char C : Data)
5257 if (!std::isxdigit(C))
5258 return nullptr;
5259 First += N;
5260 if (!consumeIf('E'))
5261 return nullptr;
5262 return make<FloatLiteralImpl<Float>>(Data);
5263}
5264
5265// <seq-id> ::= <0-9A-Z>+
Pavel Labathba825192018-10-16 14:29:14 +00005266template <typename Alloc, typename Derived>
5267bool AbstractManglingParser<Alloc, Derived>::parseSeqId(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00005268 if (!(look() >= '0' && look() <= '9') &&
5269 !(look() >= 'A' && look() <= 'Z'))
5270 return true;
5271
5272 size_t Id = 0;
5273 while (true) {
5274 if (look() >= '0' && look() <= '9') {
5275 Id *= 36;
5276 Id += static_cast<size_t>(look() - '0');
5277 } else if (look() >= 'A' && look() <= 'Z') {
5278 Id *= 36;
5279 Id += static_cast<size_t>(look() - 'A') + 10;
5280 } else {
5281 *Out = Id;
5282 return false;
5283 }
5284 ++First;
5285 }
5286}
5287
5288// <substitution> ::= S <seq-id> _
5289// ::= S_
5290// <substitution> ::= Sa # ::std::allocator
5291// <substitution> ::= Sb # ::std::basic_string
5292// <substitution> ::= Ss # ::std::basic_string < char,
5293// ::std::char_traits<char>,
5294// ::std::allocator<char> >
5295// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
5296// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
5297// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
Pavel Labathba825192018-10-16 14:29:14 +00005298template <typename Derived, typename Alloc>
5299Node *AbstractManglingParser<Derived, Alloc>::parseSubstitution() {
Richard Smithc20d1442018-08-20 20:14:49 +00005300 if (!consumeIf('S'))
5301 return nullptr;
5302
5303 if (std::islower(look())) {
5304 Node *SpecialSub;
5305 switch (look()) {
5306 case 'a':
5307 ++First;
5308 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
5309 break;
5310 case 'b':
5311 ++First;
5312 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
5313 break;
5314 case 's':
5315 ++First;
5316 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
5317 break;
5318 case 'i':
5319 ++First;
5320 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
5321 break;
5322 case 'o':
5323 ++First;
5324 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
5325 break;
5326 case 'd':
5327 ++First;
5328 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
5329 break;
5330 default:
5331 return nullptr;
5332 }
Richard Smithb485b352018-08-24 23:30:26 +00005333 if (!SpecialSub)
5334 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005335 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
5336 // has ABI tags, the tags are appended to the substitution; the result is a
5337 // substitutable component.
Pavel Labathba825192018-10-16 14:29:14 +00005338 Node *WithTags = getDerived().parseAbiTags(SpecialSub);
Richard Smithc20d1442018-08-20 20:14:49 +00005339 if (WithTags != SpecialSub) {
5340 Subs.push_back(WithTags);
5341 SpecialSub = WithTags;
5342 }
5343 return SpecialSub;
5344 }
5345
5346 // ::= S_
5347 if (consumeIf('_')) {
5348 if (Subs.empty())
5349 return nullptr;
5350 return Subs[0];
5351 }
5352
5353 // ::= S <seq-id> _
5354 size_t Index = 0;
5355 if (parseSeqId(&Index))
5356 return nullptr;
5357 ++Index;
5358 if (!consumeIf('_') || Index >= Subs.size())
5359 return nullptr;
5360 return Subs[Index];
5361}
5362
5363// <template-param> ::= T_ # first template parameter
5364// ::= T <parameter-2 non-negative number> _
Richard Smithdf1c14c2019-09-06 23:53:21 +00005365// ::= TL <level-1> __
5366// ::= TL <level-1> _ <parameter-2 non-negative number> _
Pavel Labathba825192018-10-16 14:29:14 +00005367template <typename Derived, typename Alloc>
5368Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParam() {
Richard Smithc20d1442018-08-20 20:14:49 +00005369 if (!consumeIf('T'))
5370 return nullptr;
5371
Richard Smithdf1c14c2019-09-06 23:53:21 +00005372 size_t Level = 0;
5373 if (consumeIf('L')) {
5374 if (parsePositiveInteger(&Level))
5375 return nullptr;
5376 ++Level;
5377 if (!consumeIf('_'))
5378 return nullptr;
5379 }
5380
Richard Smithc20d1442018-08-20 20:14:49 +00005381 size_t Index = 0;
5382 if (!consumeIf('_')) {
5383 if (parsePositiveInteger(&Index))
5384 return nullptr;
5385 ++Index;
5386 if (!consumeIf('_'))
5387 return nullptr;
5388 }
5389
Richard Smithc20d1442018-08-20 20:14:49 +00005390 // If we're in a context where this <template-param> refers to a
5391 // <template-arg> further ahead in the mangled name (currently just conversion
5392 // operator types), then we should only look it up in the right context.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005393 // This can only happen at the outermost level.
5394 if (PermitForwardTemplateReferences && Level == 0) {
Richard Smithb485b352018-08-24 23:30:26 +00005395 Node *ForwardRef = make<ForwardTemplateReference>(Index);
5396 if (!ForwardRef)
5397 return nullptr;
5398 assert(ForwardRef->getKind() == Node::KForwardTemplateReference);
5399 ForwardTemplateRefs.push_back(
5400 static_cast<ForwardTemplateReference *>(ForwardRef));
5401 return ForwardRef;
Richard Smithc20d1442018-08-20 20:14:49 +00005402 }
5403
Richard Smithdf1c14c2019-09-06 23:53:21 +00005404 if (Level >= TemplateParams.size() || !TemplateParams[Level] ||
5405 Index >= TemplateParams[Level]->size()) {
5406 // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter
5407 // list are mangled as the corresponding artificial template type parameter.
5408 if (ParsingLambdaParamsAtLevel == Level && Level <= TemplateParams.size()) {
5409 // This will be popped by the ScopedTemplateParamList in
5410 // parseUnnamedTypeName.
5411 if (Level == TemplateParams.size())
5412 TemplateParams.push_back(nullptr);
5413 return make<NameType>("auto");
5414 }
5415
Richard Smithc20d1442018-08-20 20:14:49 +00005416 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00005417 }
5418
5419 return (*TemplateParams[Level])[Index];
5420}
5421
5422// <template-param-decl> ::= Ty # type parameter
5423// ::= Tn <type> # non-type parameter
5424// ::= Tt <template-param-decl>* E # template parameter
5425// ::= Tp <template-param-decl> # parameter pack
5426template <typename Derived, typename Alloc>
5427Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParamDecl() {
5428 auto InventTemplateParamName = [&](TemplateParamKind Kind) {
5429 unsigned Index = NumSyntheticTemplateParameters[(int)Kind]++;
5430 Node *N = make<SyntheticTemplateParamName>(Kind, Index);
5431 if (N) TemplateParams.back()->push_back(N);
5432 return N;
5433 };
5434
5435 if (consumeIf("Ty")) {
5436 Node *Name = InventTemplateParamName(TemplateParamKind::Type);
5437 if (!Name)
5438 return nullptr;
5439 return make<TypeTemplateParamDecl>(Name);
5440 }
5441
5442 if (consumeIf("Tn")) {
5443 Node *Name = InventTemplateParamName(TemplateParamKind::NonType);
5444 if (!Name)
5445 return nullptr;
5446 Node *Type = parseType();
5447 if (!Type)
5448 return nullptr;
5449 return make<NonTypeTemplateParamDecl>(Name, Type);
5450 }
5451
5452 if (consumeIf("Tt")) {
5453 Node *Name = InventTemplateParamName(TemplateParamKind::Template);
5454 if (!Name)
5455 return nullptr;
5456 size_t ParamsBegin = Names.size();
5457 ScopedTemplateParamList TemplateTemplateParamParams(this);
5458 while (!consumeIf("E")) {
5459 Node *P = parseTemplateParamDecl();
5460 if (!P)
5461 return nullptr;
5462 Names.push_back(P);
5463 }
5464 NodeArray Params = popTrailingNodeArray(ParamsBegin);
5465 return make<TemplateTemplateParamDecl>(Name, Params);
5466 }
5467
5468 if (consumeIf("Tp")) {
5469 Node *P = parseTemplateParamDecl();
5470 if (!P)
5471 return nullptr;
5472 return make<TemplateParamPackDecl>(P);
5473 }
5474
5475 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005476}
5477
5478// <template-arg> ::= <type> # type or template
5479// ::= X <expression> E # expression
5480// ::= <expr-primary> # simple expressions
5481// ::= J <template-arg>* E # argument pack
5482// ::= LZ <encoding> E # extension
Pavel Labathba825192018-10-16 14:29:14 +00005483template <typename Derived, typename Alloc>
5484Node *AbstractManglingParser<Derived, Alloc>::parseTemplateArg() {
Richard Smithc20d1442018-08-20 20:14:49 +00005485 switch (look()) {
5486 case 'X': {
5487 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00005488 Node *Arg = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00005489 if (Arg == nullptr || !consumeIf('E'))
5490 return nullptr;
5491 return Arg;
5492 }
5493 case 'J': {
5494 ++First;
5495 size_t ArgsBegin = Names.size();
5496 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005497 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005498 if (Arg == nullptr)
5499 return nullptr;
5500 Names.push_back(Arg);
5501 }
5502 NodeArray Args = popTrailingNodeArray(ArgsBegin);
5503 return make<TemplateArgumentPack>(Args);
5504 }
5505 case 'L': {
5506 // ::= LZ <encoding> E # extension
5507 if (look(1) == 'Z') {
5508 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005509 Node *Arg = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005510 if (Arg == nullptr || !consumeIf('E'))
5511 return nullptr;
5512 return Arg;
5513 }
5514 // ::= <expr-primary> # simple expressions
Pavel Labathba825192018-10-16 14:29:14 +00005515 return getDerived().parseExprPrimary();
Richard Smithc20d1442018-08-20 20:14:49 +00005516 }
5517 default:
Pavel Labathba825192018-10-16 14:29:14 +00005518 return getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005519 }
5520}
5521
5522// <template-args> ::= I <template-arg>* E
5523// extension, the abi says <template-arg>+
Pavel Labathba825192018-10-16 14:29:14 +00005524template <typename Derived, typename Alloc>
5525Node *
5526AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005527 if (!consumeIf('I'))
5528 return nullptr;
5529
5530 // <template-params> refer to the innermost <template-args>. Clear out any
5531 // outer args that we may have inserted into TemplateParams.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005532 if (TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005533 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00005534 TemplateParams.push_back(&OuterTemplateParams);
5535 OuterTemplateParams.clear();
5536 }
Richard Smithc20d1442018-08-20 20:14:49 +00005537
5538 size_t ArgsBegin = Names.size();
5539 while (!consumeIf('E')) {
5540 if (TagTemplates) {
5541 auto OldParams = std::move(TemplateParams);
Pavel Labathba825192018-10-16 14:29:14 +00005542 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005543 TemplateParams = std::move(OldParams);
5544 if (Arg == nullptr)
5545 return nullptr;
5546 Names.push_back(Arg);
5547 Node *TableEntry = Arg;
5548 if (Arg->getKind() == Node::KTemplateArgumentPack) {
5549 TableEntry = make<ParameterPack>(
5550 static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
Richard Smithb485b352018-08-24 23:30:26 +00005551 if (!TableEntry)
5552 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005553 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00005554 TemplateParams.back()->push_back(TableEntry);
Richard Smithc20d1442018-08-20 20:14:49 +00005555 } else {
Pavel Labathba825192018-10-16 14:29:14 +00005556 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005557 if (Arg == nullptr)
5558 return nullptr;
5559 Names.push_back(Arg);
5560 }
5561 }
5562 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
5563}
5564
5565// <mangled-name> ::= _Z <encoding>
5566// ::= <type>
5567// extension ::= ___Z <encoding> _block_invoke
5568// extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
5569// extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
Pavel Labathba825192018-10-16 14:29:14 +00005570template <typename Derived, typename Alloc>
5571Node *AbstractManglingParser<Derived, Alloc>::parse() {
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005572 if (consumeIf("_Z") || consumeIf("__Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005573 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005574 if (Encoding == nullptr)
5575 return nullptr;
5576 if (look() == '.') {
5577 Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
5578 First = Last;
5579 }
5580 if (numLeft() != 0)
5581 return nullptr;
5582 return Encoding;
5583 }
5584
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005585 if (consumeIf("___Z") || consumeIf("____Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005586 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005587 if (Encoding == nullptr || !consumeIf("_block_invoke"))
5588 return nullptr;
5589 bool RequireNumber = consumeIf('_');
5590 if (parseNumber().empty() && RequireNumber)
5591 return nullptr;
5592 if (look() == '.')
5593 First = Last;
5594 if (numLeft() != 0)
5595 return nullptr;
5596 return make<SpecialName>("invocation function for block in ", Encoding);
5597 }
5598
Pavel Labathba825192018-10-16 14:29:14 +00005599 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005600 if (numLeft() != 0)
5601 return nullptr;
5602 return Ty;
5603}
5604
Pavel Labathba825192018-10-16 14:29:14 +00005605template <typename Alloc>
5606struct ManglingParser : AbstractManglingParser<ManglingParser<Alloc>, Alloc> {
5607 using AbstractManglingParser<ManglingParser<Alloc>,
5608 Alloc>::AbstractManglingParser;
5609};
5610
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005611DEMANGLE_NAMESPACE_END
Richard Smithc20d1442018-08-20 20:14:49 +00005612
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005613#endif // DEMANGLE_ITANIUMDEMANGLE_H