blob: e084cbfc7b80375bc5648533ac4a06e45fb3fcb1 [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//
Nathan Sidwell5b0a8cf2022-01-24 06:38:47 -08009// Generic itanium demangler library.
10// There are two copies of this file in the source tree. The one under
11// libcxxabi is the original and the one under llvm is the copy. Use
12// cp-to-llvm.sh to update the copy. See README.txt for more details.
Richard Smithc20d1442018-08-20 20:14:49 +000013//
14//===----------------------------------------------------------------------===//
15
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +000016#ifndef DEMANGLE_ITANIUMDEMANGLE_H
17#define DEMANGLE_ITANIUMDEMANGLE_H
Richard Smithc20d1442018-08-20 20:14:49 +000018
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +000019#include "DemangleConfig.h"
Richard Smithc20d1442018-08-20 20:14:49 +000020#include "StringView.h"
21#include "Utility.h"
Nathan Sidwellbbc632f2022-01-24 04:11:59 -080022#include <algorithm>
Richard Smithc20d1442018-08-20 20:14:49 +000023#include <cassert>
24#include <cctype>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
Nathan Sidwellbbc632f2022-01-24 04:11:59 -080028#include <limits>
Richard Smithc20d1442018-08-20 20:14:49 +000029#include <utility>
30
Nathan Sidwellf19ccea2022-02-18 04:05:06 -080031#define FOR_EACH_NODE_KIND(X) \
32 X(NodeArrayNode) \
33 X(DotSuffix) \
34 X(VendorExtQualType) \
35 X(QualType) \
36 X(ConversionOperatorType) \
37 X(PostfixQualifiedType) \
38 X(ElaboratedTypeSpefType) \
39 X(NameType) \
40 X(AbiTagAttr) \
41 X(EnableIfAttr) \
42 X(ObjCProtoName) \
43 X(PointerType) \
44 X(ReferenceType) \
45 X(PointerToMemberType) \
46 X(ArrayType) \
47 X(FunctionType) \
48 X(NoexceptSpec) \
49 X(DynamicExceptionSpec) \
50 X(FunctionEncoding) \
51 X(LiteralOperator) \
52 X(SpecialName) \
53 X(CtorVtableSpecialName) \
54 X(QualifiedName) \
55 X(NestedName) \
56 X(LocalName) \
Nathan Sidwelledde7bb2022-01-26 07:22:04 -080057 X(ModuleName) \
58 X(ModuleEntity) \
Nathan Sidwellf19ccea2022-02-18 04:05:06 -080059 X(VectorType) \
60 X(PixelVectorType) \
61 X(BinaryFPType) \
62 X(SyntheticTemplateParamName) \
63 X(TypeTemplateParamDecl) \
64 X(NonTypeTemplateParamDecl) \
65 X(TemplateTemplateParamDecl) \
66 X(TemplateParamPackDecl) \
67 X(ParameterPack) \
68 X(TemplateArgumentPack) \
69 X(ParameterPackExpansion) \
70 X(TemplateArgs) \
71 X(ForwardTemplateReference) \
72 X(NameWithTemplateArgs) \
73 X(GlobalQualifiedName) \
74 X(ExpandedSpecialSubstitution) \
75 X(SpecialSubstitution) \
76 X(CtorDtorName) \
77 X(DtorName) \
78 X(UnnamedTypeName) \
79 X(ClosureTypeName) \
80 X(StructuredBindingName) \
81 X(BinaryExpr) \
82 X(ArraySubscriptExpr) \
83 X(PostfixExpr) \
84 X(ConditionalExpr) \
85 X(MemberExpr) \
86 X(SubobjectExpr) \
87 X(EnclosingExpr) \
88 X(CastExpr) \
89 X(SizeofParamPackExpr) \
90 X(CallExpr) \
91 X(NewExpr) \
92 X(DeleteExpr) \
93 X(PrefixExpr) \
94 X(FunctionParam) \
95 X(ConversionExpr) \
96 X(PointerToMemberConversionExpr) \
97 X(InitListExpr) \
98 X(FoldExpr) \
99 X(ThrowExpr) \
100 X(BoolExpr) \
101 X(StringLiteral) \
102 X(LambdaExpr) \
103 X(EnumLiteral) \
104 X(IntegerLiteral) \
105 X(FloatLiteral) \
106 X(DoubleLiteral) \
107 X(LongDoubleLiteral) \
108 X(BracedExpr) \
109 X(BracedRangeExpr)
Richard Smithc20d1442018-08-20 20:14:49 +0000110
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +0000111DEMANGLE_NAMESPACE_BEGIN
112
Mikhail Borisov8452f062021-08-17 18:06:53 -0400113template <class T, size_t N> class PODSmallVector {
114 static_assert(std::is_pod<T>::value,
115 "T is required to be a plain old data type");
116
117 T *First = nullptr;
118 T *Last = nullptr;
119 T *Cap = nullptr;
120 T Inline[N] = {0};
121
122 bool isInline() const { return First == Inline; }
123
124 void clearInline() {
125 First = Inline;
126 Last = Inline;
127 Cap = Inline + N;
128 }
129
130 void reserve(size_t NewCap) {
131 size_t S = size();
132 if (isInline()) {
133 auto *Tmp = static_cast<T *>(std::malloc(NewCap * sizeof(T)));
134 if (Tmp == nullptr)
135 std::terminate();
136 std::copy(First, Last, Tmp);
137 First = Tmp;
138 } else {
139 First = static_cast<T *>(std::realloc(First, NewCap * sizeof(T)));
140 if (First == nullptr)
141 std::terminate();
142 }
143 Last = First + S;
144 Cap = First + NewCap;
145 }
146
147public:
148 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
149
150 PODSmallVector(const PODSmallVector &) = delete;
151 PODSmallVector &operator=(const PODSmallVector &) = delete;
152
153 PODSmallVector(PODSmallVector &&Other) : PODSmallVector() {
154 if (Other.isInline()) {
155 std::copy(Other.begin(), Other.end(), First);
156 Last = First + Other.size();
157 Other.clear();
158 return;
159 }
160
161 First = Other.First;
162 Last = Other.Last;
163 Cap = Other.Cap;
164 Other.clearInline();
165 }
166
167 PODSmallVector &operator=(PODSmallVector &&Other) {
168 if (Other.isInline()) {
169 if (!isInline()) {
170 std::free(First);
171 clearInline();
172 }
173 std::copy(Other.begin(), Other.end(), First);
174 Last = First + Other.size();
175 Other.clear();
176 return *this;
177 }
178
179 if (isInline()) {
180 First = Other.First;
181 Last = Other.Last;
182 Cap = Other.Cap;
183 Other.clearInline();
184 return *this;
185 }
186
187 std::swap(First, Other.First);
188 std::swap(Last, Other.Last);
189 std::swap(Cap, Other.Cap);
190 Other.clear();
191 return *this;
192 }
193
194 // NOLINTNEXTLINE(readability-identifier-naming)
195 void push_back(const T &Elem) {
196 if (Last == Cap)
197 reserve(size() * 2);
198 *Last++ = Elem;
199 }
200
201 // NOLINTNEXTLINE(readability-identifier-naming)
202 void pop_back() {
203 assert(Last != First && "Popping empty vector!");
204 --Last;
205 }
206
207 void dropBack(size_t Index) {
208 assert(Index <= size() && "dropBack() can't expand!");
209 Last = First + Index;
210 }
211
212 T *begin() { return First; }
213 T *end() { return Last; }
214
215 bool empty() const { return First == Last; }
216 size_t size() const { return static_cast<size_t>(Last - First); }
217 T &back() {
218 assert(Last != First && "Calling back() on empty vector!");
219 return *(Last - 1);
220 }
221 T &operator[](size_t Index) {
222 assert(Index < size() && "Invalid access!");
223 return *(begin() + Index);
224 }
225 void clear() { Last = First; }
226
227 ~PODSmallVector() {
228 if (!isInline())
229 std::free(First);
230 }
231};
232
Richard Smithc20d1442018-08-20 20:14:49 +0000233// Base class of all AST nodes. The AST is built by the parser, then is
234// traversed by the printLeft/Right functions to produce a demangled string.
235class Node {
236public:
237 enum Kind : unsigned char {
238#define ENUMERATOR(NodeKind) K ## NodeKind,
239 FOR_EACH_NODE_KIND(ENUMERATOR)
240#undef ENUMERATOR
241 };
242
243 /// Three-way bool to track a cached value. Unknown is possible if this node
244 /// has an unexpanded parameter pack below it that may affect this cache.
245 enum class Cache : unsigned char { Yes, No, Unknown, };
246
247private:
248 Kind K;
249
250 // FIXME: Make these protected.
251public:
252 /// Tracks if this node has a component on its right side, in which case we
253 /// need to call printRight.
254 Cache RHSComponentCache;
255
256 /// Track if this node is a (possibly qualified) array type. This can affect
257 /// how we format the output string.
258 Cache ArrayCache;
259
260 /// Track if this node is a (possibly qualified) function type. This can
261 /// affect how we format the output string.
262 Cache FunctionCache;
263
264public:
265 Node(Kind K_, Cache RHSComponentCache_ = Cache::No,
266 Cache ArrayCache_ = Cache::No, Cache FunctionCache_ = Cache::No)
267 : K(K_), RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
268 FunctionCache(FunctionCache_) {}
269
270 /// Visit the most-derived object corresponding to this object.
271 template<typename Fn> void visit(Fn F) const;
272
273 // The following function is provided by all derived classes:
274 //
275 // Call F with arguments that, when passed to the constructor of this node,
276 // would construct an equivalent node.
277 //template<typename Fn> void match(Fn F) const;
278
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700279 bool hasRHSComponent(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000280 if (RHSComponentCache != Cache::Unknown)
281 return RHSComponentCache == Cache::Yes;
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700282 return hasRHSComponentSlow(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000283 }
284
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700285 bool hasArray(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000286 if (ArrayCache != Cache::Unknown)
287 return ArrayCache == Cache::Yes;
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700288 return hasArraySlow(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000289 }
290
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700291 bool hasFunction(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000292 if (FunctionCache != Cache::Unknown)
293 return FunctionCache == Cache::Yes;
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700294 return hasFunctionSlow(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000295 }
296
297 Kind getKind() const { return K; }
298
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700299 virtual bool hasRHSComponentSlow(OutputBuffer &) const { return false; }
300 virtual bool hasArraySlow(OutputBuffer &) const { return false; }
301 virtual bool hasFunctionSlow(OutputBuffer &) const { return false; }
Richard Smithc20d1442018-08-20 20:14:49 +0000302
303 // Dig through "glue" nodes like ParameterPack and ForwardTemplateReference to
304 // get at a node that actually represents some concrete syntax.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700305 virtual const Node *getSyntaxNode(OutputBuffer &) const { return this; }
Richard Smithc20d1442018-08-20 20:14:49 +0000306
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700307 void print(OutputBuffer &OB) const {
308 printLeft(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000309 if (RHSComponentCache != Cache::No)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700310 printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000311 }
312
Nathan Sidwellfd0ef6d2022-01-20 07:40:12 -0800313 // Print the "left" side of this Node into OutputBuffer.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700314 virtual void printLeft(OutputBuffer &) const = 0;
Richard Smithc20d1442018-08-20 20:14:49 +0000315
316 // Print the "right". This distinction is necessary to represent C++ types
317 // that appear on the RHS of their subtype, such as arrays or functions.
318 // Since most types don't have such a component, provide a default
319 // implementation.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700320 virtual void printRight(OutputBuffer &) const {}
Richard Smithc20d1442018-08-20 20:14:49 +0000321
322 virtual StringView getBaseName() const { return StringView(); }
323
324 // Silence compiler warnings, this dtor will never be called.
325 virtual ~Node() = default;
326
327#ifndef NDEBUG
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +0000328 DEMANGLE_DUMP_METHOD void dump() const;
Richard Smithc20d1442018-08-20 20:14:49 +0000329#endif
330};
331
332class NodeArray {
333 Node **Elements;
334 size_t NumElements;
335
336public:
337 NodeArray() : Elements(nullptr), NumElements(0) {}
338 NodeArray(Node **Elements_, size_t NumElements_)
339 : Elements(Elements_), NumElements(NumElements_) {}
340
341 bool empty() const { return NumElements == 0; }
342 size_t size() const { return NumElements; }
343
344 Node **begin() const { return Elements; }
345 Node **end() const { return Elements + NumElements; }
346
347 Node *operator[](size_t Idx) const { return Elements[Idx]; }
348
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700349 void printWithComma(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000350 bool FirstElement = true;
351 for (size_t Idx = 0; Idx != NumElements; ++Idx) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700352 size_t BeforeComma = OB.getCurrentPosition();
Richard Smithc20d1442018-08-20 20:14:49 +0000353 if (!FirstElement)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700354 OB += ", ";
355 size_t AfterComma = OB.getCurrentPosition();
356 Elements[Idx]->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000357
358 // Elements[Idx] is an empty parameter pack expansion, we should erase the
359 // comma we just printed.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700360 if (AfterComma == OB.getCurrentPosition()) {
361 OB.setCurrentPosition(BeforeComma);
Richard Smithc20d1442018-08-20 20:14:49 +0000362 continue;
363 }
364
365 FirstElement = false;
366 }
367 }
368};
369
370struct NodeArrayNode : Node {
371 NodeArray Array;
372 NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
373
374 template<typename Fn> void match(Fn F) const { F(Array); }
375
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700376 void printLeft(OutputBuffer &OB) const override { Array.printWithComma(OB); }
Richard Smithc20d1442018-08-20 20:14:49 +0000377};
378
379class DotSuffix final : public Node {
380 const Node *Prefix;
381 const StringView Suffix;
382
383public:
384 DotSuffix(const Node *Prefix_, StringView Suffix_)
385 : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
386
387 template<typename Fn> void match(Fn F) const { F(Prefix, Suffix); }
388
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700389 void printLeft(OutputBuffer &OB) const override {
390 Prefix->print(OB);
391 OB += " (";
392 OB += Suffix;
393 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +0000394 }
395};
396
397class VendorExtQualType final : public Node {
398 const Node *Ty;
399 StringView Ext;
Alex Orlovf50df922021-03-24 10:21:32 +0400400 const Node *TA;
Richard Smithc20d1442018-08-20 20:14:49 +0000401
402public:
Alex Orlovf50df922021-03-24 10:21:32 +0400403 VendorExtQualType(const Node *Ty_, StringView Ext_, const Node *TA_)
404 : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_), TA(TA_) {}
Richard Smithc20d1442018-08-20 20:14:49 +0000405
Alex Orlovf50df922021-03-24 10:21:32 +0400406 template <typename Fn> void match(Fn F) const { F(Ty, Ext, TA); }
Richard Smithc20d1442018-08-20 20:14:49 +0000407
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700408 void printLeft(OutputBuffer &OB) const override {
409 Ty->print(OB);
410 OB += " ";
411 OB += Ext;
Alex Orlovf50df922021-03-24 10:21:32 +0400412 if (TA != nullptr)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700413 TA->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000414 }
415};
416
417enum FunctionRefQual : unsigned char {
418 FrefQualNone,
419 FrefQualLValue,
420 FrefQualRValue,
421};
422
423enum Qualifiers {
424 QualNone = 0,
425 QualConst = 0x1,
426 QualVolatile = 0x2,
427 QualRestrict = 0x4,
428};
429
430inline Qualifiers operator|=(Qualifiers &Q1, Qualifiers Q2) {
431 return Q1 = static_cast<Qualifiers>(Q1 | Q2);
432}
433
Richard Smithdf1c14c2019-09-06 23:53:21 +0000434class QualType final : public Node {
Richard Smithc20d1442018-08-20 20:14:49 +0000435protected:
436 const Qualifiers Quals;
437 const Node *Child;
438
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700439 void printQuals(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000440 if (Quals & QualConst)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700441 OB += " const";
Richard Smithc20d1442018-08-20 20:14:49 +0000442 if (Quals & QualVolatile)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700443 OB += " volatile";
Richard Smithc20d1442018-08-20 20:14:49 +0000444 if (Quals & QualRestrict)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700445 OB += " restrict";
Richard Smithc20d1442018-08-20 20:14:49 +0000446 }
447
448public:
449 QualType(const Node *Child_, Qualifiers Quals_)
450 : Node(KQualType, Child_->RHSComponentCache,
451 Child_->ArrayCache, Child_->FunctionCache),
452 Quals(Quals_), Child(Child_) {}
453
454 template<typename Fn> void match(Fn F) const { F(Child, Quals); }
455
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700456 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
457 return Child->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000458 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700459 bool hasArraySlow(OutputBuffer &OB) const override {
460 return Child->hasArray(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000461 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700462 bool hasFunctionSlow(OutputBuffer &OB) const override {
463 return Child->hasFunction(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000464 }
465
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700466 void printLeft(OutputBuffer &OB) const override {
467 Child->printLeft(OB);
468 printQuals(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000469 }
470
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700471 void printRight(OutputBuffer &OB) const override { Child->printRight(OB); }
Richard Smithc20d1442018-08-20 20:14:49 +0000472};
473
474class ConversionOperatorType final : public Node {
475 const Node *Ty;
476
477public:
478 ConversionOperatorType(const Node *Ty_)
479 : Node(KConversionOperatorType), Ty(Ty_) {}
480
481 template<typename Fn> void match(Fn F) const { F(Ty); }
482
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700483 void printLeft(OutputBuffer &OB) const override {
484 OB += "operator ";
485 Ty->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000486 }
487};
488
489class PostfixQualifiedType final : public Node {
490 const Node *Ty;
491 const StringView Postfix;
492
493public:
494 PostfixQualifiedType(Node *Ty_, StringView Postfix_)
495 : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
496
497 template<typename Fn> void match(Fn F) const { F(Ty, Postfix); }
498
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700499 void printLeft(OutputBuffer &OB) const override {
500 Ty->printLeft(OB);
501 OB += Postfix;
Richard Smithc20d1442018-08-20 20:14:49 +0000502 }
503};
504
505class NameType final : public Node {
506 const StringView Name;
507
508public:
509 NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
510
511 template<typename Fn> void match(Fn F) const { F(Name); }
512
513 StringView getName() const { return Name; }
514 StringView getBaseName() const override { return Name; }
515
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700516 void printLeft(OutputBuffer &OB) const override { OB += Name; }
Richard Smithc20d1442018-08-20 20:14:49 +0000517};
518
519class ElaboratedTypeSpefType : public Node {
520 StringView Kind;
521 Node *Child;
522public:
523 ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
524 : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
525
526 template<typename Fn> void match(Fn F) const { F(Kind, Child); }
527
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700528 void printLeft(OutputBuffer &OB) const override {
529 OB += Kind;
530 OB += ' ';
531 Child->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000532 }
533};
534
535struct AbiTagAttr : Node {
536 Node *Base;
537 StringView Tag;
538
539 AbiTagAttr(Node* Base_, StringView Tag_)
540 : Node(KAbiTagAttr, Base_->RHSComponentCache,
541 Base_->ArrayCache, Base_->FunctionCache),
542 Base(Base_), Tag(Tag_) {}
543
544 template<typename Fn> void match(Fn F) const { F(Base, Tag); }
545
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700546 void printLeft(OutputBuffer &OB) const override {
547 Base->printLeft(OB);
548 OB += "[abi:";
549 OB += Tag;
550 OB += "]";
Richard Smithc20d1442018-08-20 20:14:49 +0000551 }
552};
553
554class EnableIfAttr : public Node {
555 NodeArray Conditions;
556public:
557 EnableIfAttr(NodeArray Conditions_)
558 : Node(KEnableIfAttr), Conditions(Conditions_) {}
559
560 template<typename Fn> void match(Fn F) const { F(Conditions); }
561
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700562 void printLeft(OutputBuffer &OB) const override {
563 OB += " [enable_if:";
564 Conditions.printWithComma(OB);
565 OB += ']';
Richard Smithc20d1442018-08-20 20:14:49 +0000566 }
567};
568
569class ObjCProtoName : public Node {
570 const Node *Ty;
571 StringView Protocol;
572
573 friend class PointerType;
574
575public:
576 ObjCProtoName(const Node *Ty_, StringView Protocol_)
577 : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
578
579 template<typename Fn> void match(Fn F) const { F(Ty, Protocol); }
580
581 bool isObjCObject() const {
582 return Ty->getKind() == KNameType &&
583 static_cast<const NameType *>(Ty)->getName() == "objc_object";
584 }
585
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700586 void printLeft(OutputBuffer &OB) const override {
587 Ty->print(OB);
588 OB += "<";
589 OB += Protocol;
590 OB += ">";
Richard Smithc20d1442018-08-20 20:14:49 +0000591 }
592};
593
594class PointerType final : public Node {
595 const Node *Pointee;
596
597public:
598 PointerType(const Node *Pointee_)
599 : Node(KPointerType, Pointee_->RHSComponentCache),
600 Pointee(Pointee_) {}
601
602 template<typename Fn> void match(Fn F) const { F(Pointee); }
603
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700604 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
605 return Pointee->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000606 }
607
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700608 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +0000609 // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
610 if (Pointee->getKind() != KObjCProtoName ||
611 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700612 Pointee->printLeft(OB);
613 if (Pointee->hasArray(OB))
614 OB += " ";
615 if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
616 OB += "(";
617 OB += "*";
Richard Smithc20d1442018-08-20 20:14:49 +0000618 } else {
619 const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700620 OB += "id<";
621 OB += objcProto->Protocol;
622 OB += ">";
Richard Smithc20d1442018-08-20 20:14:49 +0000623 }
624 }
625
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700626 void printRight(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +0000627 if (Pointee->getKind() != KObjCProtoName ||
628 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700629 if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
630 OB += ")";
631 Pointee->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000632 }
633 }
634};
635
636enum class ReferenceKind {
637 LValue,
638 RValue,
639};
640
641// Represents either a LValue or an RValue reference type.
642class ReferenceType : public Node {
643 const Node *Pointee;
644 ReferenceKind RK;
645
646 mutable bool Printing = false;
647
648 // Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
649 // rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
650 // other combination collapses to a lvalue ref.
Mikhail Borisov05f77222021-08-17 18:10:57 -0400651 //
652 // A combination of a TemplateForwardReference and a back-ref Substitution
653 // from an ill-formed string may have created a cycle; use cycle detection to
654 // avoid looping forever.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700655 std::pair<ReferenceKind, const Node *> collapse(OutputBuffer &OB) const {
Richard Smithc20d1442018-08-20 20:14:49 +0000656 auto SoFar = std::make_pair(RK, Pointee);
Mikhail Borisov05f77222021-08-17 18:10:57 -0400657 // Track the chain of nodes for the Floyd's 'tortoise and hare'
658 // cycle-detection algorithm, since getSyntaxNode(S) is impure
659 PODSmallVector<const Node *, 8> Prev;
Richard Smithc20d1442018-08-20 20:14:49 +0000660 for (;;) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700661 const Node *SN = SoFar.second->getSyntaxNode(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000662 if (SN->getKind() != KReferenceType)
663 break;
664 auto *RT = static_cast<const ReferenceType *>(SN);
665 SoFar.second = RT->Pointee;
666 SoFar.first = std::min(SoFar.first, RT->RK);
Mikhail Borisov05f77222021-08-17 18:10:57 -0400667
668 // The middle of Prev is the 'slow' pointer moving at half speed
669 Prev.push_back(SoFar.second);
670 if (Prev.size() > 1 && SoFar.second == Prev[(Prev.size() - 1) / 2]) {
671 // Cycle detected
672 SoFar.second = nullptr;
673 break;
674 }
Richard Smithc20d1442018-08-20 20:14:49 +0000675 }
676 return SoFar;
677 }
678
679public:
680 ReferenceType(const Node *Pointee_, ReferenceKind RK_)
681 : Node(KReferenceType, Pointee_->RHSComponentCache),
682 Pointee(Pointee_), RK(RK_) {}
683
684 template<typename Fn> void match(Fn F) const { F(Pointee, RK); }
685
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700686 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
687 return Pointee->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000688 }
689
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700690 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +0000691 if (Printing)
692 return;
693 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700694 std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
Mikhail Borisov05f77222021-08-17 18:10:57 -0400695 if (!Collapsed.second)
696 return;
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700697 Collapsed.second->printLeft(OB);
698 if (Collapsed.second->hasArray(OB))
699 OB += " ";
700 if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
701 OB += "(";
Richard Smithc20d1442018-08-20 20:14:49 +0000702
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700703 OB += (Collapsed.first == ReferenceKind::LValue ? "&" : "&&");
Richard Smithc20d1442018-08-20 20:14:49 +0000704 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700705 void printRight(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +0000706 if (Printing)
707 return;
708 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700709 std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
Mikhail Borisov05f77222021-08-17 18:10:57 -0400710 if (!Collapsed.second)
711 return;
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700712 if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
713 OB += ")";
714 Collapsed.second->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000715 }
716};
717
718class PointerToMemberType final : public Node {
719 const Node *ClassType;
720 const Node *MemberType;
721
722public:
723 PointerToMemberType(const Node *ClassType_, const Node *MemberType_)
724 : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
725 ClassType(ClassType_), MemberType(MemberType_) {}
726
727 template<typename Fn> void match(Fn F) const { F(ClassType, MemberType); }
728
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700729 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
730 return MemberType->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000731 }
732
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700733 void printLeft(OutputBuffer &OB) const override {
734 MemberType->printLeft(OB);
735 if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
736 OB += "(";
Richard Smithc20d1442018-08-20 20:14:49 +0000737 else
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700738 OB += " ";
739 ClassType->print(OB);
740 OB += "::*";
Richard Smithc20d1442018-08-20 20:14:49 +0000741 }
742
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700743 void printRight(OutputBuffer &OB) const override {
744 if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
745 OB += ")";
746 MemberType->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000747 }
748};
749
Richard Smithc20d1442018-08-20 20:14:49 +0000750class ArrayType final : public Node {
751 const Node *Base;
Erik Pilkingtond7555e32019-11-04 10:47:44 -0800752 Node *Dimension;
Richard Smithc20d1442018-08-20 20:14:49 +0000753
754public:
Erik Pilkingtond7555e32019-11-04 10:47:44 -0800755 ArrayType(const Node *Base_, Node *Dimension_)
Richard Smithc20d1442018-08-20 20:14:49 +0000756 : Node(KArrayType,
757 /*RHSComponentCache=*/Cache::Yes,
758 /*ArrayCache=*/Cache::Yes),
759 Base(Base_), Dimension(Dimension_) {}
760
761 template<typename Fn> void match(Fn F) const { F(Base, Dimension); }
762
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700763 bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
764 bool hasArraySlow(OutputBuffer &) const override { return true; }
Richard Smithc20d1442018-08-20 20:14:49 +0000765
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700766 void printLeft(OutputBuffer &OB) const override { Base->printLeft(OB); }
Richard Smithc20d1442018-08-20 20:14:49 +0000767
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700768 void printRight(OutputBuffer &OB) const override {
769 if (OB.back() != ']')
770 OB += " ";
771 OB += "[";
Erik Pilkingtond7555e32019-11-04 10:47:44 -0800772 if (Dimension)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700773 Dimension->print(OB);
774 OB += "]";
775 Base->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000776 }
777};
778
779class FunctionType final : public Node {
780 const Node *Ret;
781 NodeArray Params;
782 Qualifiers CVQuals;
783 FunctionRefQual RefQual;
784 const Node *ExceptionSpec;
785
786public:
787 FunctionType(const Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
788 FunctionRefQual RefQual_, const Node *ExceptionSpec_)
789 : Node(KFunctionType,
790 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
791 /*FunctionCache=*/Cache::Yes),
792 Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
793 ExceptionSpec(ExceptionSpec_) {}
794
795 template<typename Fn> void match(Fn F) const {
796 F(Ret, Params, CVQuals, RefQual, ExceptionSpec);
797 }
798
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700799 bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
800 bool hasFunctionSlow(OutputBuffer &) const override { return true; }
Richard Smithc20d1442018-08-20 20:14:49 +0000801
802 // Handle C++'s ... quirky decl grammar by using the left & right
803 // distinction. Consider:
804 // int (*f(float))(char) {}
805 // f is a function that takes a float and returns a pointer to a function
806 // that takes a char and returns an int. If we're trying to print f, start
807 // by printing out the return types's left, then print our parameters, then
808 // finally print right of the return type.
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700809 void printLeft(OutputBuffer &OB) const override {
810 Ret->printLeft(OB);
811 OB += " ";
Richard Smithc20d1442018-08-20 20:14:49 +0000812 }
813
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700814 void printRight(OutputBuffer &OB) const override {
815 OB += "(";
816 Params.printWithComma(OB);
817 OB += ")";
818 Ret->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000819
820 if (CVQuals & QualConst)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700821 OB += " const";
Richard Smithc20d1442018-08-20 20:14:49 +0000822 if (CVQuals & QualVolatile)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700823 OB += " volatile";
Richard Smithc20d1442018-08-20 20:14:49 +0000824 if (CVQuals & QualRestrict)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700825 OB += " restrict";
Richard Smithc20d1442018-08-20 20:14:49 +0000826
827 if (RefQual == FrefQualLValue)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700828 OB += " &";
Richard Smithc20d1442018-08-20 20:14:49 +0000829 else if (RefQual == FrefQualRValue)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700830 OB += " &&";
Richard Smithc20d1442018-08-20 20:14:49 +0000831
832 if (ExceptionSpec != nullptr) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700833 OB += ' ';
834 ExceptionSpec->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000835 }
836 }
837};
838
839class NoexceptSpec : public Node {
840 const Node *E;
841public:
842 NoexceptSpec(const Node *E_) : Node(KNoexceptSpec), E(E_) {}
843
844 template<typename Fn> void match(Fn F) const { F(E); }
845
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700846 void printLeft(OutputBuffer &OB) const override {
847 OB += "noexcept(";
848 E->print(OB);
849 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +0000850 }
851};
852
853class DynamicExceptionSpec : public Node {
854 NodeArray Types;
855public:
856 DynamicExceptionSpec(NodeArray Types_)
857 : Node(KDynamicExceptionSpec), Types(Types_) {}
858
859 template<typename Fn> void match(Fn F) const { F(Types); }
860
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700861 void printLeft(OutputBuffer &OB) const override {
862 OB += "throw(";
863 Types.printWithComma(OB);
864 OB += ')';
Richard Smithc20d1442018-08-20 20:14:49 +0000865 }
866};
867
868class FunctionEncoding final : public Node {
869 const Node *Ret;
870 const Node *Name;
871 NodeArray Params;
872 const Node *Attrs;
873 Qualifiers CVQuals;
874 FunctionRefQual RefQual;
875
876public:
877 FunctionEncoding(const Node *Ret_, const Node *Name_, NodeArray Params_,
878 const Node *Attrs_, Qualifiers CVQuals_,
879 FunctionRefQual RefQual_)
880 : Node(KFunctionEncoding,
881 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
882 /*FunctionCache=*/Cache::Yes),
883 Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
884 CVQuals(CVQuals_), RefQual(RefQual_) {}
885
886 template<typename Fn> void match(Fn F) const {
887 F(Ret, Name, Params, Attrs, CVQuals, RefQual);
888 }
889
890 Qualifiers getCVQuals() const { return CVQuals; }
891 FunctionRefQual getRefQual() const { return RefQual; }
892 NodeArray getParams() const { return Params; }
893 const Node *getReturnType() const { return Ret; }
894
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700895 bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
896 bool hasFunctionSlow(OutputBuffer &) const override { return true; }
Richard Smithc20d1442018-08-20 20:14:49 +0000897
898 const Node *getName() const { return Name; }
899
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700900 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +0000901 if (Ret) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700902 Ret->printLeft(OB);
903 if (!Ret->hasRHSComponent(OB))
904 OB += " ";
Richard Smithc20d1442018-08-20 20:14:49 +0000905 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700906 Name->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000907 }
908
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700909 void printRight(OutputBuffer &OB) const override {
910 OB += "(";
911 Params.printWithComma(OB);
912 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +0000913 if (Ret)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700914 Ret->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000915
916 if (CVQuals & QualConst)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700917 OB += " const";
Richard Smithc20d1442018-08-20 20:14:49 +0000918 if (CVQuals & QualVolatile)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700919 OB += " volatile";
Richard Smithc20d1442018-08-20 20:14:49 +0000920 if (CVQuals & QualRestrict)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700921 OB += " restrict";
Richard Smithc20d1442018-08-20 20:14:49 +0000922
923 if (RefQual == FrefQualLValue)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700924 OB += " &";
Richard Smithc20d1442018-08-20 20:14:49 +0000925 else if (RefQual == FrefQualRValue)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700926 OB += " &&";
Richard Smithc20d1442018-08-20 20:14:49 +0000927
928 if (Attrs != nullptr)
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700929 Attrs->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000930 }
931};
932
933class LiteralOperator : public Node {
934 const Node *OpName;
935
936public:
937 LiteralOperator(const Node *OpName_)
938 : Node(KLiteralOperator), OpName(OpName_) {}
939
940 template<typename Fn> void match(Fn F) const { F(OpName); }
941
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700942 void printLeft(OutputBuffer &OB) const override {
943 OB += "operator\"\" ";
944 OpName->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000945 }
946};
947
948class SpecialName final : public Node {
949 const StringView Special;
950 const Node *Child;
951
952public:
953 SpecialName(StringView Special_, const Node *Child_)
954 : Node(KSpecialName), Special(Special_), Child(Child_) {}
955
956 template<typename Fn> void match(Fn F) const { F(Special, Child); }
957
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700958 void printLeft(OutputBuffer &OB) const override {
959 OB += Special;
960 Child->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000961 }
962};
963
964class CtorVtableSpecialName final : public Node {
965 const Node *FirstType;
966 const Node *SecondType;
967
968public:
969 CtorVtableSpecialName(const Node *FirstType_, const Node *SecondType_)
970 : Node(KCtorVtableSpecialName),
971 FirstType(FirstType_), SecondType(SecondType_) {}
972
973 template<typename Fn> void match(Fn F) const { F(FirstType, SecondType); }
974
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700975 void printLeft(OutputBuffer &OB) const override {
976 OB += "construction vtable for ";
977 FirstType->print(OB);
978 OB += "-in-";
979 SecondType->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000980 }
981};
982
983struct NestedName : Node {
984 Node *Qual;
985 Node *Name;
986
987 NestedName(Node *Qual_, Node *Name_)
988 : Node(KNestedName), Qual(Qual_), Name(Name_) {}
989
990 template<typename Fn> void match(Fn F) const { F(Qual, Name); }
991
992 StringView getBaseName() const override { return Name->getBaseName(); }
993
Luís Ferreiraa4380e22021-10-21 17:31:53 -0700994 void printLeft(OutputBuffer &OB) const override {
995 Qual->print(OB);
996 OB += "::";
997 Name->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +0000998 }
999};
1000
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08001001struct ModuleName : Node {
1002 ModuleName *Parent;
1003 Node *Name;
1004 bool IsPartition;
1005
1006 ModuleName(ModuleName *Parent_, Node *Name_, bool IsPartition_ = false)
1007 : Node(KModuleName), Parent(Parent_), Name(Name_),
1008 IsPartition(IsPartition_) {}
1009
1010 template <typename Fn> void match(Fn F) const { F(Parent, Name); }
1011
1012 void printLeft(OutputBuffer &OB) const override {
1013 if (Parent)
1014 Parent->print(OB);
1015 if (Parent || IsPartition)
1016 OB += IsPartition ? ':' : '.';
1017 Name->print(OB);
1018 }
1019};
1020
1021struct ModuleEntity : Node {
1022 ModuleName *Module;
1023 Node *Name;
1024
1025 ModuleEntity(ModuleName *Module_, Node *Name_)
1026 : Node(KModuleEntity), Module(Module_), Name(Name_) {}
1027
1028 template <typename Fn> void match(Fn F) const { F(Module, Name); }
1029
1030 StringView getBaseName() const override { return Name->getBaseName(); }
1031
1032 void printLeft(OutputBuffer &OB) const override {
1033 Name->print(OB);
1034 OB += '@';
1035 Module->print(OB);
1036 }
1037};
1038
Richard Smithc20d1442018-08-20 20:14:49 +00001039struct LocalName : Node {
1040 Node *Encoding;
1041 Node *Entity;
1042
1043 LocalName(Node *Encoding_, Node *Entity_)
1044 : Node(KLocalName), Encoding(Encoding_), Entity(Entity_) {}
1045
1046 template<typename Fn> void match(Fn F) const { F(Encoding, Entity); }
1047
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001048 void printLeft(OutputBuffer &OB) const override {
1049 Encoding->print(OB);
1050 OB += "::";
1051 Entity->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001052 }
1053};
1054
1055class QualifiedName final : public Node {
1056 // qualifier::name
1057 const Node *Qualifier;
1058 const Node *Name;
1059
1060public:
1061 QualifiedName(const Node *Qualifier_, const Node *Name_)
1062 : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
1063
1064 template<typename Fn> void match(Fn F) const { F(Qualifier, Name); }
1065
1066 StringView getBaseName() const override { return Name->getBaseName(); }
1067
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001068 void printLeft(OutputBuffer &OB) const override {
1069 Qualifier->print(OB);
1070 OB += "::";
1071 Name->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001072 }
1073};
1074
1075class VectorType final : public Node {
1076 const Node *BaseType;
Erik Pilkingtond7555e32019-11-04 10:47:44 -08001077 const Node *Dimension;
Richard Smithc20d1442018-08-20 20:14:49 +00001078
1079public:
Erik Pilkingtond7555e32019-11-04 10:47:44 -08001080 VectorType(const Node *BaseType_, Node *Dimension_)
Richard Smithc20d1442018-08-20 20:14:49 +00001081 : Node(KVectorType), BaseType(BaseType_),
1082 Dimension(Dimension_) {}
1083
1084 template<typename Fn> void match(Fn F) const { F(BaseType, Dimension); }
1085
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001086 void printLeft(OutputBuffer &OB) const override {
1087 BaseType->print(OB);
1088 OB += " vector[";
Erik Pilkingtond7555e32019-11-04 10:47:44 -08001089 if (Dimension)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001090 Dimension->print(OB);
1091 OB += "]";
Richard Smithc20d1442018-08-20 20:14:49 +00001092 }
1093};
1094
1095class PixelVectorType final : public Node {
Erik Pilkingtond7555e32019-11-04 10:47:44 -08001096 const Node *Dimension;
Richard Smithc20d1442018-08-20 20:14:49 +00001097
1098public:
Erik Pilkingtond7555e32019-11-04 10:47:44 -08001099 PixelVectorType(const Node *Dimension_)
Richard Smithc20d1442018-08-20 20:14:49 +00001100 : Node(KPixelVectorType), Dimension(Dimension_) {}
1101
1102 template<typename Fn> void match(Fn F) const { F(Dimension); }
1103
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001104 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001105 // FIXME: This should demangle as "vector pixel".
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001106 OB += "pixel vector[";
1107 Dimension->print(OB);
1108 OB += "]";
Richard Smithc20d1442018-08-20 20:14:49 +00001109 }
1110};
1111
Pengfei Wang50e90b82021-09-23 11:02:25 +08001112class BinaryFPType final : public Node {
1113 const Node *Dimension;
1114
1115public:
1116 BinaryFPType(const Node *Dimension_)
1117 : Node(KBinaryFPType), Dimension(Dimension_) {}
1118
1119 template<typename Fn> void match(Fn F) const { F(Dimension); }
1120
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001121 void printLeft(OutputBuffer &OB) const override {
1122 OB += "_Float";
1123 Dimension->print(OB);
Pengfei Wang50e90b82021-09-23 11:02:25 +08001124 }
1125};
1126
Richard Smithdf1c14c2019-09-06 23:53:21 +00001127enum class TemplateParamKind { Type, NonType, Template };
1128
1129/// An invented name for a template parameter for which we don't have a
1130/// corresponding template argument.
1131///
1132/// This node is created when parsing the <lambda-sig> for a lambda with
1133/// explicit template arguments, which might be referenced in the parameter
1134/// types appearing later in the <lambda-sig>.
1135class SyntheticTemplateParamName final : public Node {
1136 TemplateParamKind Kind;
1137 unsigned Index;
1138
1139public:
1140 SyntheticTemplateParamName(TemplateParamKind Kind_, unsigned Index_)
1141 : Node(KSyntheticTemplateParamName), Kind(Kind_), Index(Index_) {}
1142
1143 template<typename Fn> void match(Fn F) const { F(Kind, Index); }
1144
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001145 void printLeft(OutputBuffer &OB) const override {
Richard Smithdf1c14c2019-09-06 23:53:21 +00001146 switch (Kind) {
1147 case TemplateParamKind::Type:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001148 OB += "$T";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001149 break;
1150 case TemplateParamKind::NonType:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001151 OB += "$N";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001152 break;
1153 case TemplateParamKind::Template:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001154 OB += "$TT";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001155 break;
1156 }
1157 if (Index > 0)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001158 OB << Index - 1;
Richard Smithdf1c14c2019-09-06 23:53:21 +00001159 }
1160};
1161
1162/// A template type parameter declaration, 'typename T'.
1163class TypeTemplateParamDecl final : public Node {
1164 Node *Name;
1165
1166public:
1167 TypeTemplateParamDecl(Node *Name_)
1168 : Node(KTypeTemplateParamDecl, Cache::Yes), Name(Name_) {}
1169
1170 template<typename Fn> void match(Fn F) const { F(Name); }
1171
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001172 void printLeft(OutputBuffer &OB) const override { OB += "typename "; }
Richard Smithdf1c14c2019-09-06 23:53:21 +00001173
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001174 void printRight(OutputBuffer &OB) const override { Name->print(OB); }
Richard Smithdf1c14c2019-09-06 23:53:21 +00001175};
1176
1177/// A non-type template parameter declaration, 'int N'.
1178class NonTypeTemplateParamDecl final : public Node {
1179 Node *Name;
1180 Node *Type;
1181
1182public:
1183 NonTypeTemplateParamDecl(Node *Name_, Node *Type_)
1184 : Node(KNonTypeTemplateParamDecl, Cache::Yes), Name(Name_), Type(Type_) {}
1185
1186 template<typename Fn> void match(Fn F) const { F(Name, Type); }
1187
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001188 void printLeft(OutputBuffer &OB) const override {
1189 Type->printLeft(OB);
1190 if (!Type->hasRHSComponent(OB))
1191 OB += " ";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001192 }
1193
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001194 void printRight(OutputBuffer &OB) const override {
1195 Name->print(OB);
1196 Type->printRight(OB);
Richard Smithdf1c14c2019-09-06 23:53:21 +00001197 }
1198};
1199
1200/// A template template parameter declaration,
1201/// 'template<typename T> typename N'.
1202class TemplateTemplateParamDecl final : public Node {
1203 Node *Name;
1204 NodeArray Params;
1205
1206public:
1207 TemplateTemplateParamDecl(Node *Name_, NodeArray Params_)
1208 : Node(KTemplateTemplateParamDecl, Cache::Yes), Name(Name_),
1209 Params(Params_) {}
1210
1211 template<typename Fn> void match(Fn F) const { F(Name, Params); }
1212
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001213 void printLeft(OutputBuffer &OB) const override {
1214 OB += "template<";
1215 Params.printWithComma(OB);
1216 OB += "> typename ";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001217 }
1218
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001219 void printRight(OutputBuffer &OB) const override { Name->print(OB); }
Richard Smithdf1c14c2019-09-06 23:53:21 +00001220};
1221
1222/// A template parameter pack declaration, 'typename ...T'.
1223class TemplateParamPackDecl final : public Node {
1224 Node *Param;
1225
1226public:
1227 TemplateParamPackDecl(Node *Param_)
1228 : Node(KTemplateParamPackDecl, Cache::Yes), Param(Param_) {}
1229
1230 template<typename Fn> void match(Fn F) const { F(Param); }
1231
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001232 void printLeft(OutputBuffer &OB) const override {
1233 Param->printLeft(OB);
1234 OB += "...";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001235 }
1236
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001237 void printRight(OutputBuffer &OB) const override { Param->printRight(OB); }
Richard Smithdf1c14c2019-09-06 23:53:21 +00001238};
1239
Richard Smithc20d1442018-08-20 20:14:49 +00001240/// An unexpanded parameter pack (either in the expression or type context). If
1241/// this AST is correct, this node will have a ParameterPackExpansion node above
1242/// it.
1243///
1244/// This node is created when some <template-args> are found that apply to an
1245/// <encoding>, and is stored in the TemplateParams table. In order for this to
1246/// appear in the final AST, it has to referenced via a <template-param> (ie,
1247/// T_).
1248class ParameterPack final : public Node {
1249 NodeArray Data;
1250
Nathan Sidwellfd0ef6d2022-01-20 07:40:12 -08001251 // Setup OutputBuffer for a pack expansion, unless we're already expanding
1252 // one.
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001253 void initializePackExpansion(OutputBuffer &OB) const {
1254 if (OB.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
1255 OB.CurrentPackMax = static_cast<unsigned>(Data.size());
1256 OB.CurrentPackIndex = 0;
Richard Smithc20d1442018-08-20 20:14:49 +00001257 }
1258 }
1259
1260public:
1261 ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
1262 ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
1263 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1264 return P->ArrayCache == Cache::No;
1265 }))
1266 ArrayCache = Cache::No;
1267 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1268 return P->FunctionCache == Cache::No;
1269 }))
1270 FunctionCache = Cache::No;
1271 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
1272 return P->RHSComponentCache == Cache::No;
1273 }))
1274 RHSComponentCache = Cache::No;
1275 }
1276
1277 template<typename Fn> void match(Fn F) const { F(Data); }
1278
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001279 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
1280 initializePackExpansion(OB);
1281 size_t Idx = OB.CurrentPackIndex;
1282 return Idx < Data.size() && Data[Idx]->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001283 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001284 bool hasArraySlow(OutputBuffer &OB) const override {
1285 initializePackExpansion(OB);
1286 size_t Idx = OB.CurrentPackIndex;
1287 return Idx < Data.size() && Data[Idx]->hasArray(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001288 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001289 bool hasFunctionSlow(OutputBuffer &OB) const override {
1290 initializePackExpansion(OB);
1291 size_t Idx = OB.CurrentPackIndex;
1292 return Idx < Data.size() && Data[Idx]->hasFunction(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001293 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001294 const Node *getSyntaxNode(OutputBuffer &OB) const override {
1295 initializePackExpansion(OB);
1296 size_t Idx = OB.CurrentPackIndex;
1297 return Idx < Data.size() ? Data[Idx]->getSyntaxNode(OB) : this;
Richard Smithc20d1442018-08-20 20:14:49 +00001298 }
1299
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001300 void printLeft(OutputBuffer &OB) const override {
1301 initializePackExpansion(OB);
1302 size_t Idx = OB.CurrentPackIndex;
Richard Smithc20d1442018-08-20 20:14:49 +00001303 if (Idx < Data.size())
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001304 Data[Idx]->printLeft(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001305 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001306 void printRight(OutputBuffer &OB) const override {
1307 initializePackExpansion(OB);
1308 size_t Idx = OB.CurrentPackIndex;
Richard Smithc20d1442018-08-20 20:14:49 +00001309 if (Idx < Data.size())
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001310 Data[Idx]->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001311 }
1312};
1313
1314/// A variadic template argument. This node represents an occurrence of
1315/// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1316/// one of it's Elements is. The parser inserts a ParameterPack into the
1317/// TemplateParams table if the <template-args> this pack belongs to apply to an
1318/// <encoding>.
1319class TemplateArgumentPack final : public Node {
1320 NodeArray Elements;
1321public:
1322 TemplateArgumentPack(NodeArray Elements_)
1323 : Node(KTemplateArgumentPack), Elements(Elements_) {}
1324
1325 template<typename Fn> void match(Fn F) const { F(Elements); }
1326
1327 NodeArray getElements() const { return Elements; }
1328
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001329 void printLeft(OutputBuffer &OB) const override {
1330 Elements.printWithComma(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001331 }
1332};
1333
1334/// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1335/// which each have Child->ParameterPackSize elements.
1336class ParameterPackExpansion final : public Node {
1337 const Node *Child;
1338
1339public:
1340 ParameterPackExpansion(const Node *Child_)
1341 : Node(KParameterPackExpansion), Child(Child_) {}
1342
1343 template<typename Fn> void match(Fn F) const { F(Child); }
1344
1345 const Node *getChild() const { return Child; }
1346
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001347 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001348 constexpr unsigned Max = std::numeric_limits<unsigned>::max();
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001349 SwapAndRestore<unsigned> SavePackIdx(OB.CurrentPackIndex, Max);
1350 SwapAndRestore<unsigned> SavePackMax(OB.CurrentPackMax, Max);
1351 size_t StreamPos = OB.getCurrentPosition();
Richard Smithc20d1442018-08-20 20:14:49 +00001352
1353 // Print the first element in the pack. If Child contains a ParameterPack,
1354 // it will set up S.CurrentPackMax and print the first element.
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001355 Child->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001356
1357 // No ParameterPack was found in Child. This can occur if we've found a pack
1358 // expansion on a <function-param>.
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001359 if (OB.CurrentPackMax == Max) {
1360 OB += "...";
Richard Smithc20d1442018-08-20 20:14:49 +00001361 return;
1362 }
1363
1364 // We found a ParameterPack, but it has no elements. Erase whatever we may
1365 // of printed.
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001366 if (OB.CurrentPackMax == 0) {
1367 OB.setCurrentPosition(StreamPos);
Richard Smithc20d1442018-08-20 20:14:49 +00001368 return;
1369 }
1370
1371 // Else, iterate through the rest of the elements in the pack.
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001372 for (unsigned I = 1, E = OB.CurrentPackMax; I < E; ++I) {
1373 OB += ", ";
1374 OB.CurrentPackIndex = I;
1375 Child->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001376 }
1377 }
1378};
1379
1380class TemplateArgs final : public Node {
1381 NodeArray Params;
1382
1383public:
1384 TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
1385
1386 template<typename Fn> void match(Fn F) const { F(Params); }
1387
1388 NodeArray getParams() { return Params; }
1389
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001390 void printLeft(OutputBuffer &OB) const override {
1391 OB += "<";
1392 Params.printWithComma(OB);
1393 if (OB.back() == '>')
1394 OB += " ";
1395 OB += ">";
Richard Smithc20d1442018-08-20 20:14:49 +00001396 }
1397};
1398
Richard Smithb485b352018-08-24 23:30:26 +00001399/// A forward-reference to a template argument that was not known at the point
1400/// where the template parameter name was parsed in a mangling.
1401///
1402/// This is created when demangling the name of a specialization of a
1403/// conversion function template:
1404///
1405/// \code
1406/// struct A {
1407/// template<typename T> operator T*();
1408/// };
1409/// \endcode
1410///
1411/// When demangling a specialization of the conversion function template, we
1412/// encounter the name of the template (including the \c T) before we reach
1413/// the template argument list, so we cannot substitute the parameter name
1414/// for the corresponding argument while parsing. Instead, we create a
1415/// \c ForwardTemplateReference node that is resolved after we parse the
1416/// template arguments.
Richard Smithc20d1442018-08-20 20:14:49 +00001417struct ForwardTemplateReference : Node {
1418 size_t Index;
1419 Node *Ref = nullptr;
1420
1421 // If we're currently printing this node. It is possible (though invalid) for
1422 // a forward template reference to refer to itself via a substitution. This
1423 // creates a cyclic AST, which will stack overflow printing. To fix this, bail
1424 // out if more than one print* function is active.
1425 mutable bool Printing = false;
1426
1427 ForwardTemplateReference(size_t Index_)
1428 : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
1429 Cache::Unknown),
1430 Index(Index_) {}
1431
1432 // We don't provide a matcher for these, because the value of the node is
1433 // not determined by its construction parameters, and it generally needs
1434 // special handling.
1435 template<typename Fn> void match(Fn F) const = delete;
1436
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001437 bool hasRHSComponentSlow(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001438 if (Printing)
1439 return false;
1440 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001441 return Ref->hasRHSComponent(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001442 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001443 bool hasArraySlow(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001444 if (Printing)
1445 return false;
1446 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001447 return Ref->hasArray(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001448 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001449 bool hasFunctionSlow(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001450 if (Printing)
1451 return false;
1452 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001453 return Ref->hasFunction(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001454 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001455 const Node *getSyntaxNode(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001456 if (Printing)
1457 return this;
1458 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001459 return Ref->getSyntaxNode(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001460 }
1461
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001462 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001463 if (Printing)
1464 return;
1465 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001466 Ref->printLeft(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001467 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001468 void printRight(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001469 if (Printing)
1470 return;
1471 SwapAndRestore<bool> SavePrinting(Printing, true);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001472 Ref->printRight(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001473 }
1474};
1475
1476struct NameWithTemplateArgs : Node {
1477 // name<template_args>
1478 Node *Name;
1479 Node *TemplateArgs;
1480
1481 NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
1482 : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
1483
1484 template<typename Fn> void match(Fn F) const { F(Name, TemplateArgs); }
1485
1486 StringView getBaseName() const override { return Name->getBaseName(); }
1487
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001488 void printLeft(OutputBuffer &OB) const override {
1489 Name->print(OB);
1490 TemplateArgs->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001491 }
1492};
1493
1494class GlobalQualifiedName final : public Node {
1495 Node *Child;
1496
1497public:
1498 GlobalQualifiedName(Node* Child_)
1499 : Node(KGlobalQualifiedName), Child(Child_) {}
1500
1501 template<typename Fn> void match(Fn F) const { F(Child); }
1502
1503 StringView getBaseName() const override { return Child->getBaseName(); }
1504
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001505 void printLeft(OutputBuffer &OB) const override {
1506 OB += "::";
1507 Child->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001508 }
1509};
1510
Richard Smithc20d1442018-08-20 20:14:49 +00001511enum class SpecialSubKind {
1512 allocator,
1513 basic_string,
1514 string,
1515 istream,
1516 ostream,
1517 iostream,
1518};
1519
1520class ExpandedSpecialSubstitution final : public Node {
1521 SpecialSubKind SSK;
1522
1523public:
1524 ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1525 : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
1526
1527 template<typename Fn> void match(Fn F) const { F(SSK); }
1528
1529 StringView getBaseName() const override {
1530 switch (SSK) {
1531 case SpecialSubKind::allocator:
1532 return StringView("allocator");
1533 case SpecialSubKind::basic_string:
1534 return StringView("basic_string");
1535 case SpecialSubKind::string:
1536 return StringView("basic_string");
1537 case SpecialSubKind::istream:
1538 return StringView("basic_istream");
1539 case SpecialSubKind::ostream:
1540 return StringView("basic_ostream");
1541 case SpecialSubKind::iostream:
1542 return StringView("basic_iostream");
1543 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00001544 DEMANGLE_UNREACHABLE;
Richard Smithc20d1442018-08-20 20:14:49 +00001545 }
1546
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001547 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001548 switch (SSK) {
1549 case SpecialSubKind::allocator:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001550 OB += "std::allocator";
Richard Smithc20d1442018-08-20 20:14:49 +00001551 break;
1552 case SpecialSubKind::basic_string:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001553 OB += "std::basic_string";
Richard Smithb485b352018-08-24 23:30:26 +00001554 break;
Richard Smithc20d1442018-08-20 20:14:49 +00001555 case SpecialSubKind::string:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001556 OB += "std::basic_string<char, std::char_traits<char>, "
1557 "std::allocator<char> >";
Richard Smithc20d1442018-08-20 20:14:49 +00001558 break;
1559 case SpecialSubKind::istream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001560 OB += "std::basic_istream<char, std::char_traits<char> >";
Richard Smithc20d1442018-08-20 20:14:49 +00001561 break;
1562 case SpecialSubKind::ostream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001563 OB += "std::basic_ostream<char, std::char_traits<char> >";
Richard Smithc20d1442018-08-20 20:14:49 +00001564 break;
1565 case SpecialSubKind::iostream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001566 OB += "std::basic_iostream<char, std::char_traits<char> >";
Richard Smithc20d1442018-08-20 20:14:49 +00001567 break;
1568 }
1569 }
1570};
1571
1572class SpecialSubstitution final : public Node {
1573public:
1574 SpecialSubKind SSK;
1575
1576 SpecialSubstitution(SpecialSubKind SSK_)
1577 : Node(KSpecialSubstitution), SSK(SSK_) {}
1578
1579 template<typename Fn> void match(Fn F) const { F(SSK); }
1580
1581 StringView getBaseName() const override {
1582 switch (SSK) {
1583 case SpecialSubKind::allocator:
1584 return StringView("allocator");
1585 case SpecialSubKind::basic_string:
1586 return StringView("basic_string");
1587 case SpecialSubKind::string:
1588 return StringView("string");
1589 case SpecialSubKind::istream:
1590 return StringView("istream");
1591 case SpecialSubKind::ostream:
1592 return StringView("ostream");
1593 case SpecialSubKind::iostream:
1594 return StringView("iostream");
1595 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00001596 DEMANGLE_UNREACHABLE;
Richard Smithc20d1442018-08-20 20:14:49 +00001597 }
1598
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001599 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001600 switch (SSK) {
1601 case SpecialSubKind::allocator:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001602 OB += "std::allocator";
Richard Smithc20d1442018-08-20 20:14:49 +00001603 break;
1604 case SpecialSubKind::basic_string:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001605 OB += "std::basic_string";
Richard Smithc20d1442018-08-20 20:14:49 +00001606 break;
1607 case SpecialSubKind::string:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001608 OB += "std::string";
Richard Smithc20d1442018-08-20 20:14:49 +00001609 break;
1610 case SpecialSubKind::istream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001611 OB += "std::istream";
Richard Smithc20d1442018-08-20 20:14:49 +00001612 break;
1613 case SpecialSubKind::ostream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001614 OB += "std::ostream";
Richard Smithc20d1442018-08-20 20:14:49 +00001615 break;
1616 case SpecialSubKind::iostream:
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001617 OB += "std::iostream";
Richard Smithc20d1442018-08-20 20:14:49 +00001618 break;
1619 }
1620 }
1621};
1622
1623class CtorDtorName final : public Node {
1624 const Node *Basename;
1625 const bool IsDtor;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001626 const int Variant;
Richard Smithc20d1442018-08-20 20:14:49 +00001627
1628public:
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001629 CtorDtorName(const Node *Basename_, bool IsDtor_, int Variant_)
1630 : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_),
1631 Variant(Variant_) {}
Richard Smithc20d1442018-08-20 20:14:49 +00001632
Pavel Labathf4e67eb2018-10-10 08:39:16 +00001633 template<typename Fn> void match(Fn F) const { F(Basename, IsDtor, Variant); }
Richard Smithc20d1442018-08-20 20:14:49 +00001634
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001635 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001636 if (IsDtor)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001637 OB += "~";
1638 OB += Basename->getBaseName();
Richard Smithc20d1442018-08-20 20:14:49 +00001639 }
1640};
1641
1642class DtorName : public Node {
1643 const Node *Base;
1644
1645public:
1646 DtorName(const Node *Base_) : Node(KDtorName), Base(Base_) {}
1647
1648 template<typename Fn> void match(Fn F) const { F(Base); }
1649
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001650 void printLeft(OutputBuffer &OB) const override {
1651 OB += "~";
1652 Base->printLeft(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001653 }
1654};
1655
1656class UnnamedTypeName : public Node {
1657 const StringView Count;
1658
1659public:
1660 UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
1661
1662 template<typename Fn> void match(Fn F) const { F(Count); }
1663
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001664 void printLeft(OutputBuffer &OB) const override {
1665 OB += "'unnamed";
1666 OB += Count;
1667 OB += "\'";
Richard Smithc20d1442018-08-20 20:14:49 +00001668 }
1669};
1670
1671class ClosureTypeName : public Node {
Richard Smithdf1c14c2019-09-06 23:53:21 +00001672 NodeArray TemplateParams;
Richard Smithc20d1442018-08-20 20:14:49 +00001673 NodeArray Params;
1674 StringView Count;
1675
1676public:
Richard Smithdf1c14c2019-09-06 23:53:21 +00001677 ClosureTypeName(NodeArray TemplateParams_, NodeArray Params_,
1678 StringView Count_)
1679 : Node(KClosureTypeName), TemplateParams(TemplateParams_),
1680 Params(Params_), Count(Count_) {}
Richard Smithc20d1442018-08-20 20:14:49 +00001681
Richard Smithdf1c14c2019-09-06 23:53:21 +00001682 template<typename Fn> void match(Fn F) const {
1683 F(TemplateParams, Params, Count);
1684 }
1685
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001686 void printDeclarator(OutputBuffer &OB) const {
Richard Smithdf1c14c2019-09-06 23:53:21 +00001687 if (!TemplateParams.empty()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001688 OB += "<";
1689 TemplateParams.printWithComma(OB);
1690 OB += ">";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001691 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001692 OB += "(";
1693 Params.printWithComma(OB);
1694 OB += ")";
Richard Smithdf1c14c2019-09-06 23:53:21 +00001695 }
Richard Smithc20d1442018-08-20 20:14:49 +00001696
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001697 void printLeft(OutputBuffer &OB) const override {
1698 OB += "\'lambda";
1699 OB += Count;
1700 OB += "\'";
1701 printDeclarator(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001702 }
1703};
1704
1705class StructuredBindingName : public Node {
1706 NodeArray Bindings;
1707public:
1708 StructuredBindingName(NodeArray Bindings_)
1709 : Node(KStructuredBindingName), Bindings(Bindings_) {}
1710
1711 template<typename Fn> void match(Fn F) const { F(Bindings); }
1712
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001713 void printLeft(OutputBuffer &OB) const override {
1714 OB += '[';
1715 Bindings.printWithComma(OB);
1716 OB += ']';
Richard Smithc20d1442018-08-20 20:14:49 +00001717 }
1718};
1719
1720// -- Expression Nodes --
1721
1722class BinaryExpr : public Node {
1723 const Node *LHS;
1724 const StringView InfixOperator;
1725 const Node *RHS;
1726
1727public:
1728 BinaryExpr(const Node *LHS_, StringView InfixOperator_, const Node *RHS_)
1729 : Node(KBinaryExpr), LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {
1730 }
1731
1732 template<typename Fn> void match(Fn F) const { F(LHS, InfixOperator, RHS); }
1733
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001734 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001735 // might be a template argument expression, then we need to disambiguate
1736 // with parens.
1737 if (InfixOperator == ">")
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001738 OB += "(";
Richard Smithc20d1442018-08-20 20:14:49 +00001739
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001740 OB += "(";
1741 LHS->print(OB);
1742 OB += ") ";
1743 OB += InfixOperator;
1744 OB += " (";
1745 RHS->print(OB);
1746 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001747
1748 if (InfixOperator == ">")
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001749 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001750 }
1751};
1752
1753class ArraySubscriptExpr : public Node {
1754 const Node *Op1;
1755 const Node *Op2;
1756
1757public:
1758 ArraySubscriptExpr(const Node *Op1_, const Node *Op2_)
1759 : Node(KArraySubscriptExpr), Op1(Op1_), Op2(Op2_) {}
1760
1761 template<typename Fn> void match(Fn F) const { F(Op1, Op2); }
1762
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001763 void printLeft(OutputBuffer &OB) const override {
1764 OB += "(";
1765 Op1->print(OB);
1766 OB += ")[";
1767 Op2->print(OB);
1768 OB += "]";
Richard Smithc20d1442018-08-20 20:14:49 +00001769 }
1770};
1771
1772class PostfixExpr : public Node {
1773 const Node *Child;
1774 const StringView Operator;
1775
1776public:
1777 PostfixExpr(const Node *Child_, StringView Operator_)
1778 : Node(KPostfixExpr), Child(Child_), Operator(Operator_) {}
1779
1780 template<typename Fn> void match(Fn F) const { F(Child, Operator); }
1781
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001782 void printLeft(OutputBuffer &OB) const override {
1783 OB += "(";
1784 Child->print(OB);
1785 OB += ")";
1786 OB += Operator;
Richard Smithc20d1442018-08-20 20:14:49 +00001787 }
1788};
1789
1790class ConditionalExpr : public Node {
1791 const Node *Cond;
1792 const Node *Then;
1793 const Node *Else;
1794
1795public:
1796 ConditionalExpr(const Node *Cond_, const Node *Then_, const Node *Else_)
1797 : Node(KConditionalExpr), Cond(Cond_), Then(Then_), Else(Else_) {}
1798
1799 template<typename Fn> void match(Fn F) const { F(Cond, Then, Else); }
1800
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001801 void printLeft(OutputBuffer &OB) const override {
1802 OB += "(";
1803 Cond->print(OB);
1804 OB += ") ? (";
1805 Then->print(OB);
1806 OB += ") : (";
1807 Else->print(OB);
1808 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001809 }
1810};
1811
1812class MemberExpr : public Node {
1813 const Node *LHS;
1814 const StringView Kind;
1815 const Node *RHS;
1816
1817public:
1818 MemberExpr(const Node *LHS_, StringView Kind_, const Node *RHS_)
1819 : Node(KMemberExpr), LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
1820
1821 template<typename Fn> void match(Fn F) const { F(LHS, Kind, RHS); }
1822
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001823 void printLeft(OutputBuffer &OB) const override {
1824 LHS->print(OB);
1825 OB += Kind;
Nathan Sidwellc6483042022-01-28 09:27:28 -08001826 // Parenthesize pointer-to-member deference argument.
1827 bool IsPtr = Kind.back() == '*';
1828 if (IsPtr)
1829 OB += '(';
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001830 RHS->print(OB);
Nathan Sidwellc6483042022-01-28 09:27:28 -08001831 if (IsPtr)
1832 OB += ')';
Richard Smithc20d1442018-08-20 20:14:49 +00001833 }
1834};
1835
Richard Smith1865d2f2020-10-22 19:29:36 -07001836class SubobjectExpr : public Node {
1837 const Node *Type;
1838 const Node *SubExpr;
1839 StringView Offset;
1840 NodeArray UnionSelectors;
1841 bool OnePastTheEnd;
1842
1843public:
1844 SubobjectExpr(const Node *Type_, const Node *SubExpr_, StringView Offset_,
1845 NodeArray UnionSelectors_, bool OnePastTheEnd_)
1846 : Node(KSubobjectExpr), Type(Type_), SubExpr(SubExpr_), Offset(Offset_),
1847 UnionSelectors(UnionSelectors_), OnePastTheEnd(OnePastTheEnd_) {}
1848
1849 template<typename Fn> void match(Fn F) const {
1850 F(Type, SubExpr, Offset, UnionSelectors, OnePastTheEnd);
1851 }
1852
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001853 void printLeft(OutputBuffer &OB) const override {
1854 SubExpr->print(OB);
1855 OB += ".<";
1856 Type->print(OB);
1857 OB += " at offset ";
Richard Smith1865d2f2020-10-22 19:29:36 -07001858 if (Offset.empty()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001859 OB += "0";
Richard Smith1865d2f2020-10-22 19:29:36 -07001860 } else if (Offset[0] == 'n') {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001861 OB += "-";
1862 OB += Offset.dropFront();
Richard Smith1865d2f2020-10-22 19:29:36 -07001863 } else {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001864 OB += Offset;
Richard Smith1865d2f2020-10-22 19:29:36 -07001865 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001866 OB += ">";
Richard Smith1865d2f2020-10-22 19:29:36 -07001867 }
1868};
1869
Richard Smithc20d1442018-08-20 20:14:49 +00001870class EnclosingExpr : public Node {
1871 const StringView Prefix;
1872 const Node *Infix;
1873 const StringView Postfix;
1874
1875public:
1876 EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
1877 : Node(KEnclosingExpr), Prefix(Prefix_), Infix(Infix_),
1878 Postfix(Postfix_) {}
1879
1880 template<typename Fn> void match(Fn F) const { F(Prefix, Infix, Postfix); }
1881
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001882 void printLeft(OutputBuffer &OB) const override {
1883 OB += Prefix;
1884 Infix->print(OB);
1885 OB += Postfix;
Richard Smithc20d1442018-08-20 20:14:49 +00001886 }
1887};
1888
1889class CastExpr : public Node {
1890 // cast_kind<to>(from)
1891 const StringView CastKind;
1892 const Node *To;
1893 const Node *From;
1894
1895public:
1896 CastExpr(StringView CastKind_, const Node *To_, const Node *From_)
1897 : Node(KCastExpr), CastKind(CastKind_), To(To_), From(From_) {}
1898
1899 template<typename Fn> void match(Fn F) const { F(CastKind, To, From); }
1900
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001901 void printLeft(OutputBuffer &OB) const override {
1902 OB += CastKind;
1903 OB += "<";
1904 To->printLeft(OB);
1905 OB += ">(";
1906 From->printLeft(OB);
1907 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001908 }
1909};
1910
1911class SizeofParamPackExpr : public Node {
1912 const Node *Pack;
1913
1914public:
1915 SizeofParamPackExpr(const Node *Pack_)
1916 : Node(KSizeofParamPackExpr), Pack(Pack_) {}
1917
1918 template<typename Fn> void match(Fn F) const { F(Pack); }
1919
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001920 void printLeft(OutputBuffer &OB) const override {
1921 OB += "sizeof...(";
Richard Smithc20d1442018-08-20 20:14:49 +00001922 ParameterPackExpansion PPE(Pack);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001923 PPE.printLeft(OB);
1924 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001925 }
1926};
1927
1928class CallExpr : public Node {
1929 const Node *Callee;
1930 NodeArray Args;
1931
1932public:
1933 CallExpr(const Node *Callee_, NodeArray Args_)
1934 : Node(KCallExpr), Callee(Callee_), Args(Args_) {}
1935
1936 template<typename Fn> void match(Fn F) const { F(Callee, Args); }
1937
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001938 void printLeft(OutputBuffer &OB) const override {
1939 Callee->print(OB);
1940 OB += "(";
1941 Args.printWithComma(OB);
1942 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001943 }
1944};
1945
1946class NewExpr : public Node {
1947 // new (expr_list) type(init_list)
1948 NodeArray ExprList;
1949 Node *Type;
1950 NodeArray InitList;
1951 bool IsGlobal; // ::operator new ?
1952 bool IsArray; // new[] ?
1953public:
1954 NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1955 bool IsArray_)
1956 : Node(KNewExpr), ExprList(ExprList_), Type(Type_), InitList(InitList_),
1957 IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1958
1959 template<typename Fn> void match(Fn F) const {
1960 F(ExprList, Type, InitList, IsGlobal, IsArray);
1961 }
1962
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001963 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001964 if (IsGlobal)
Nathan Sidwellc69bde22022-01-28 07:09:38 -08001965 OB += "::";
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001966 OB += "new";
Richard Smithc20d1442018-08-20 20:14:49 +00001967 if (IsArray)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001968 OB += "[]";
Richard Smithc20d1442018-08-20 20:14:49 +00001969 if (!ExprList.empty()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001970 OB += "(";
1971 ExprList.printWithComma(OB);
1972 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001973 }
Nathan Sidwellc69bde22022-01-28 07:09:38 -08001974 OB += ' ';
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001975 Type->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00001976 if (!InitList.empty()) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001977 OB += "(";
1978 InitList.printWithComma(OB);
1979 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00001980 }
Richard Smithc20d1442018-08-20 20:14:49 +00001981 }
1982};
1983
1984class DeleteExpr : public Node {
1985 Node *Op;
1986 bool IsGlobal;
1987 bool IsArray;
1988
1989public:
1990 DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
1991 : Node(KDeleteExpr), Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
1992
1993 template<typename Fn> void match(Fn F) const { F(Op, IsGlobal, IsArray); }
1994
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001995 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00001996 if (IsGlobal)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07001997 OB += "::";
1998 OB += "delete";
Richard Smithc20d1442018-08-20 20:14:49 +00001999 if (IsArray)
Nathan Sidwellc69bde22022-01-28 07:09:38 -08002000 OB += "[]";
2001 OB += ' ';
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002002 Op->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002003 }
2004};
2005
2006class PrefixExpr : public Node {
2007 StringView Prefix;
2008 Node *Child;
2009
2010public:
2011 PrefixExpr(StringView Prefix_, Node *Child_)
2012 : Node(KPrefixExpr), Prefix(Prefix_), Child(Child_) {}
2013
2014 template<typename Fn> void match(Fn F) const { F(Prefix, Child); }
2015
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002016 void printLeft(OutputBuffer &OB) const override {
2017 OB += Prefix;
2018 OB += "(";
2019 Child->print(OB);
2020 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00002021 }
2022};
2023
2024class FunctionParam : public Node {
2025 StringView Number;
2026
2027public:
2028 FunctionParam(StringView Number_) : Node(KFunctionParam), Number(Number_) {}
2029
2030 template<typename Fn> void match(Fn F) const { F(Number); }
2031
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002032 void printLeft(OutputBuffer &OB) const override {
2033 OB += "fp";
2034 OB += Number;
Richard Smithc20d1442018-08-20 20:14:49 +00002035 }
2036};
2037
2038class ConversionExpr : public Node {
2039 const Node *Type;
2040 NodeArray Expressions;
2041
2042public:
2043 ConversionExpr(const Node *Type_, NodeArray Expressions_)
2044 : Node(KConversionExpr), Type(Type_), Expressions(Expressions_) {}
2045
2046 template<typename Fn> void match(Fn F) const { F(Type, Expressions); }
2047
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002048 void printLeft(OutputBuffer &OB) const override {
2049 OB += "(";
2050 Type->print(OB);
2051 OB += ")(";
2052 Expressions.printWithComma(OB);
2053 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00002054 }
2055};
2056
Richard Smith1865d2f2020-10-22 19:29:36 -07002057class PointerToMemberConversionExpr : public Node {
2058 const Node *Type;
2059 const Node *SubExpr;
2060 StringView Offset;
2061
2062public:
2063 PointerToMemberConversionExpr(const Node *Type_, const Node *SubExpr_,
2064 StringView Offset_)
2065 : Node(KPointerToMemberConversionExpr), Type(Type_), SubExpr(SubExpr_),
2066 Offset(Offset_) {}
2067
2068 template<typename Fn> void match(Fn F) const { F(Type, SubExpr, Offset); }
2069
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002070 void printLeft(OutputBuffer &OB) const override {
2071 OB += "(";
2072 Type->print(OB);
2073 OB += ")(";
2074 SubExpr->print(OB);
2075 OB += ")";
Richard Smith1865d2f2020-10-22 19:29:36 -07002076 }
2077};
2078
Richard Smithc20d1442018-08-20 20:14:49 +00002079class InitListExpr : public Node {
2080 const Node *Ty;
2081 NodeArray Inits;
2082public:
2083 InitListExpr(const Node *Ty_, NodeArray Inits_)
2084 : Node(KInitListExpr), Ty(Ty_), Inits(Inits_) {}
2085
2086 template<typename Fn> void match(Fn F) const { F(Ty, Inits); }
2087
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002088 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00002089 if (Ty)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002090 Ty->print(OB);
2091 OB += '{';
2092 Inits.printWithComma(OB);
2093 OB += '}';
Richard Smithc20d1442018-08-20 20:14:49 +00002094 }
2095};
2096
2097class BracedExpr : public Node {
2098 const Node *Elem;
2099 const Node *Init;
2100 bool IsArray;
2101public:
2102 BracedExpr(const Node *Elem_, const Node *Init_, bool IsArray_)
2103 : Node(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
2104
2105 template<typename Fn> void match(Fn F) const { F(Elem, Init, IsArray); }
2106
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002107 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00002108 if (IsArray) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002109 OB += '[';
2110 Elem->print(OB);
2111 OB += ']';
Richard Smithc20d1442018-08-20 20:14:49 +00002112 } else {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002113 OB += '.';
2114 Elem->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002115 }
2116 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002117 OB += " = ";
2118 Init->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002119 }
2120};
2121
2122class BracedRangeExpr : public Node {
2123 const Node *First;
2124 const Node *Last;
2125 const Node *Init;
2126public:
2127 BracedRangeExpr(const Node *First_, const Node *Last_, const Node *Init_)
2128 : Node(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
2129
2130 template<typename Fn> void match(Fn F) const { F(First, Last, Init); }
2131
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002132 void printLeft(OutputBuffer &OB) const override {
2133 OB += '[';
2134 First->print(OB);
2135 OB += " ... ";
2136 Last->print(OB);
2137 OB += ']';
Richard Smithc20d1442018-08-20 20:14:49 +00002138 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002139 OB += " = ";
2140 Init->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002141 }
2142};
2143
2144class FoldExpr : public Node {
2145 const Node *Pack, *Init;
2146 StringView OperatorName;
2147 bool IsLeftFold;
2148
2149public:
2150 FoldExpr(bool IsLeftFold_, StringView OperatorName_, const Node *Pack_,
2151 const Node *Init_)
2152 : Node(KFoldExpr), Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
2153 IsLeftFold(IsLeftFold_) {}
2154
2155 template<typename Fn> void match(Fn F) const {
2156 F(IsLeftFold, OperatorName, Pack, Init);
2157 }
2158
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002159 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00002160 auto PrintPack = [&] {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002161 OB += '(';
2162 ParameterPackExpansion(Pack).print(OB);
2163 OB += ')';
Richard Smithc20d1442018-08-20 20:14:49 +00002164 };
2165
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002166 OB += '(';
Richard Smithc20d1442018-08-20 20:14:49 +00002167
2168 if (IsLeftFold) {
2169 // init op ... op pack
2170 if (Init != nullptr) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002171 Init->print(OB);
2172 OB += ' ';
2173 OB += OperatorName;
2174 OB += ' ';
Richard Smithc20d1442018-08-20 20:14:49 +00002175 }
2176 // ... op pack
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002177 OB += "... ";
2178 OB += OperatorName;
2179 OB += ' ';
Richard Smithc20d1442018-08-20 20:14:49 +00002180 PrintPack();
2181 } else { // !IsLeftFold
2182 // pack op ...
2183 PrintPack();
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002184 OB += ' ';
2185 OB += OperatorName;
2186 OB += " ...";
Richard Smithc20d1442018-08-20 20:14:49 +00002187 // pack op ... op init
2188 if (Init != nullptr) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002189 OB += ' ';
2190 OB += OperatorName;
2191 OB += ' ';
2192 Init->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002193 }
2194 }
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002195 OB += ')';
Richard Smithc20d1442018-08-20 20:14:49 +00002196 }
2197};
2198
2199class ThrowExpr : public Node {
2200 const Node *Op;
2201
2202public:
2203 ThrowExpr(const Node *Op_) : Node(KThrowExpr), Op(Op_) {}
2204
2205 template<typename Fn> void match(Fn F) const { F(Op); }
2206
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002207 void printLeft(OutputBuffer &OB) const override {
2208 OB += "throw ";
2209 Op->print(OB);
Richard Smithc20d1442018-08-20 20:14:49 +00002210 }
2211};
2212
2213class BoolExpr : public Node {
2214 bool Value;
2215
2216public:
2217 BoolExpr(bool Value_) : Node(KBoolExpr), Value(Value_) {}
2218
2219 template<typename Fn> void match(Fn F) const { F(Value); }
2220
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002221 void printLeft(OutputBuffer &OB) const override {
2222 OB += Value ? StringView("true") : StringView("false");
Richard Smithc20d1442018-08-20 20:14:49 +00002223 }
2224};
2225
Richard Smithdf1c14c2019-09-06 23:53:21 +00002226class StringLiteral : public Node {
2227 const Node *Type;
2228
2229public:
2230 StringLiteral(const Node *Type_) : Node(KStringLiteral), Type(Type_) {}
2231
2232 template<typename Fn> void match(Fn F) const { F(Type); }
2233
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002234 void printLeft(OutputBuffer &OB) const override {
2235 OB += "\"<";
2236 Type->print(OB);
2237 OB += ">\"";
Richard Smithdf1c14c2019-09-06 23:53:21 +00002238 }
2239};
2240
2241class LambdaExpr : public Node {
2242 const Node *Type;
2243
Richard Smithdf1c14c2019-09-06 23:53:21 +00002244public:
2245 LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
2246
2247 template<typename Fn> void match(Fn F) const { F(Type); }
2248
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002249 void printLeft(OutputBuffer &OB) const override {
2250 OB += "[]";
Richard Smithfb917462019-09-09 22:26:04 +00002251 if (Type->getKind() == KClosureTypeName)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002252 static_cast<const ClosureTypeName *>(Type)->printDeclarator(OB);
2253 OB += "{...}";
Richard Smithdf1c14c2019-09-06 23:53:21 +00002254 }
2255};
2256
Erik Pilkington0a170f12020-05-13 14:13:37 -04002257class EnumLiteral : public Node {
Richard Smithc20d1442018-08-20 20:14:49 +00002258 // ty(integer)
2259 const Node *Ty;
2260 StringView Integer;
2261
2262public:
Erik Pilkington0a170f12020-05-13 14:13:37 -04002263 EnumLiteral(const Node *Ty_, StringView Integer_)
2264 : Node(KEnumLiteral), Ty(Ty_), Integer(Integer_) {}
Richard Smithc20d1442018-08-20 20:14:49 +00002265
2266 template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
2267
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002268 void printLeft(OutputBuffer &OB) const override {
2269 OB << "(";
2270 Ty->print(OB);
2271 OB << ")";
Erik Pilkington0a170f12020-05-13 14:13:37 -04002272
2273 if (Integer[0] == 'n')
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002274 OB << "-" << Integer.dropFront(1);
Erik Pilkington0a170f12020-05-13 14:13:37 -04002275 else
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002276 OB << Integer;
Richard Smithc20d1442018-08-20 20:14:49 +00002277 }
2278};
2279
2280class IntegerLiteral : public Node {
2281 StringView Type;
2282 StringView Value;
2283
2284public:
2285 IntegerLiteral(StringView Type_, StringView Value_)
2286 : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
2287
2288 template<typename Fn> void match(Fn F) const { F(Type, Value); }
2289
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002290 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00002291 if (Type.size() > 3) {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002292 OB += "(";
2293 OB += Type;
2294 OB += ")";
Richard Smithc20d1442018-08-20 20:14:49 +00002295 }
2296
2297 if (Value[0] == 'n') {
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002298 OB += "-";
2299 OB += Value.dropFront(1);
Richard Smithc20d1442018-08-20 20:14:49 +00002300 } else
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002301 OB += Value;
Richard Smithc20d1442018-08-20 20:14:49 +00002302
2303 if (Type.size() <= 3)
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002304 OB += Type;
Richard Smithc20d1442018-08-20 20:14:49 +00002305 }
2306};
2307
2308template <class Float> struct FloatData;
2309
2310namespace float_literal_impl {
2311constexpr Node::Kind getFloatLiteralKind(float *) {
2312 return Node::KFloatLiteral;
2313}
2314constexpr Node::Kind getFloatLiteralKind(double *) {
2315 return Node::KDoubleLiteral;
2316}
2317constexpr Node::Kind getFloatLiteralKind(long double *) {
2318 return Node::KLongDoubleLiteral;
2319}
2320}
2321
2322template <class Float> class FloatLiteralImpl : public Node {
2323 const StringView Contents;
2324
2325 static constexpr Kind KindForClass =
2326 float_literal_impl::getFloatLiteralKind((Float *)nullptr);
2327
2328public:
2329 FloatLiteralImpl(StringView Contents_)
2330 : Node(KindForClass), Contents(Contents_) {}
2331
2332 template<typename Fn> void match(Fn F) const { F(Contents); }
2333
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002334 void printLeft(OutputBuffer &OB) const override {
Richard Smithc20d1442018-08-20 20:14:49 +00002335 const char *first = Contents.begin();
2336 const char *last = Contents.end() + 1;
2337
2338 const size_t N = FloatData<Float>::mangled_size;
2339 if (static_cast<std::size_t>(last - first) > N) {
2340 last = first + N;
2341 union {
2342 Float value;
2343 char buf[sizeof(Float)];
2344 };
2345 const char *t = first;
2346 char *e = buf;
2347 for (; t != last; ++t, ++e) {
2348 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2349 : static_cast<unsigned>(*t - 'a' + 10);
2350 ++t;
2351 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
2352 : static_cast<unsigned>(*t - 'a' + 10);
2353 *e = static_cast<char>((d1 << 4) + d0);
2354 }
2355#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
2356 std::reverse(buf, e);
2357#endif
2358 char num[FloatData<Float>::max_demangled_size] = {0};
2359 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
Luís Ferreiraa4380e22021-10-21 17:31:53 -07002360 OB += StringView(num, num + n);
Richard Smithc20d1442018-08-20 20:14:49 +00002361 }
2362 }
2363};
2364
2365using FloatLiteral = FloatLiteralImpl<float>;
2366using DoubleLiteral = FloatLiteralImpl<double>;
2367using LongDoubleLiteral = FloatLiteralImpl<long double>;
2368
2369/// Visit the node. Calls \c F(P), where \c P is the node cast to the
2370/// appropriate derived class.
2371template<typename Fn>
2372void Node::visit(Fn F) const {
2373 switch (K) {
2374#define CASE(X) case K ## X: return F(static_cast<const X*>(this));
2375 FOR_EACH_NODE_KIND(CASE)
2376#undef CASE
2377 }
2378 assert(0 && "unknown mangling node kind");
2379}
2380
2381/// Determine the kind of a node from its type.
2382template<typename NodeT> struct NodeKind;
2383#define SPECIALIZATION(X) \
2384 template<> struct NodeKind<X> { \
2385 static constexpr Node::Kind Kind = Node::K##X; \
2386 static constexpr const char *name() { return #X; } \
2387 };
2388FOR_EACH_NODE_KIND(SPECIALIZATION)
2389#undef SPECIALIZATION
2390
2391#undef FOR_EACH_NODE_KIND
2392
Pavel Labathba825192018-10-16 14:29:14 +00002393template <typename Derived, typename Alloc> struct AbstractManglingParser {
Richard Smithc20d1442018-08-20 20:14:49 +00002394 const char *First;
2395 const char *Last;
2396
2397 // Name stack, this is used by the parser to hold temporary names that were
2398 // parsed. The parser collapses multiple names into new nodes to construct
2399 // the AST. Once the parser is finished, names.size() == 1.
2400 PODSmallVector<Node *, 32> Names;
2401
2402 // Substitution table. Itanium supports name substitutions as a means of
2403 // compression. The string "S42_" refers to the 44nd entry (base-36) in this
2404 // table.
2405 PODSmallVector<Node *, 32> Subs;
2406
Richard Smithdf1c14c2019-09-06 23:53:21 +00002407 using TemplateParamList = PODSmallVector<Node *, 8>;
2408
2409 class ScopedTemplateParamList {
2410 AbstractManglingParser *Parser;
2411 size_t OldNumTemplateParamLists;
2412 TemplateParamList Params;
2413
2414 public:
Louis Dionnec1fe8672020-10-30 17:33:02 -04002415 ScopedTemplateParamList(AbstractManglingParser *TheParser)
2416 : Parser(TheParser),
2417 OldNumTemplateParamLists(TheParser->TemplateParams.size()) {
Richard Smithdf1c14c2019-09-06 23:53:21 +00002418 Parser->TemplateParams.push_back(&Params);
2419 }
2420 ~ScopedTemplateParamList() {
2421 assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
2422 Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
2423 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00002424 };
2425
Richard Smithc20d1442018-08-20 20:14:49 +00002426 // Template parameter table. Like the above, but referenced like "T42_".
2427 // This has a smaller size compared to Subs and Names because it can be
2428 // stored on the stack.
Richard Smithdf1c14c2019-09-06 23:53:21 +00002429 TemplateParamList OuterTemplateParams;
2430
2431 // Lists of template parameters indexed by template parameter depth,
2432 // referenced like "TL2_4_". If nonempty, element 0 is always
2433 // OuterTemplateParams; inner elements are always template parameter lists of
2434 // lambda expressions. For a generic lambda with no explicit template
2435 // parameter list, the corresponding parameter list pointer will be null.
2436 PODSmallVector<TemplateParamList *, 4> TemplateParams;
Richard Smithc20d1442018-08-20 20:14:49 +00002437
2438 // Set of unresolved forward <template-param> references. These can occur in a
2439 // conversion operator's type, and are resolved in the enclosing <encoding>.
2440 PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
2441
Richard Smithc20d1442018-08-20 20:14:49 +00002442 bool TryToParseTemplateArgs = true;
2443 bool PermitForwardTemplateReferences = false;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002444 size_t ParsingLambdaParamsAtLevel = (size_t)-1;
2445
2446 unsigned NumSyntheticTemplateParameters[3] = {};
Richard Smithc20d1442018-08-20 20:14:49 +00002447
2448 Alloc ASTAllocator;
2449
Pavel Labathba825192018-10-16 14:29:14 +00002450 AbstractManglingParser(const char *First_, const char *Last_)
2451 : First(First_), Last(Last_) {}
2452
2453 Derived &getDerived() { return static_cast<Derived &>(*this); }
Richard Smithc20d1442018-08-20 20:14:49 +00002454
2455 void reset(const char *First_, const char *Last_) {
2456 First = First_;
2457 Last = Last_;
2458 Names.clear();
2459 Subs.clear();
2460 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002461 ParsingLambdaParamsAtLevel = (size_t)-1;
Richard Smithc20d1442018-08-20 20:14:49 +00002462 TryToParseTemplateArgs = true;
2463 PermitForwardTemplateReferences = false;
Richard Smith9a2307a2019-09-07 00:11:53 +00002464 for (int I = 0; I != 3; ++I)
2465 NumSyntheticTemplateParameters[I] = 0;
Richard Smithc20d1442018-08-20 20:14:49 +00002466 ASTAllocator.reset();
2467 }
2468
Richard Smithb485b352018-08-24 23:30:26 +00002469 template <class T, class... Args> Node *make(Args &&... args) {
Richard Smithc20d1442018-08-20 20:14:49 +00002470 return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
2471 }
2472
2473 template <class It> NodeArray makeNodeArray(It begin, It end) {
2474 size_t sz = static_cast<size_t>(end - begin);
2475 void *mem = ASTAllocator.allocateNodeArray(sz);
2476 Node **data = new (mem) Node *[sz];
2477 std::copy(begin, end, data);
2478 return NodeArray(data, sz);
2479 }
2480
2481 NodeArray popTrailingNodeArray(size_t FromPosition) {
2482 assert(FromPosition <= Names.size());
2483 NodeArray res =
2484 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2485 Names.dropBack(FromPosition);
2486 return res;
2487 }
2488
2489 bool consumeIf(StringView S) {
2490 if (StringView(First, Last).startsWith(S)) {
2491 First += S.size();
2492 return true;
2493 }
2494 return false;
2495 }
2496
2497 bool consumeIf(char C) {
2498 if (First != Last && *First == C) {
2499 ++First;
2500 return true;
2501 }
2502 return false;
2503 }
2504
2505 char consume() { return First != Last ? *First++ : '\0'; }
2506
Nathan Sidwellfd0ef6d2022-01-20 07:40:12 -08002507 char look(unsigned Lookahead = 0) const {
Richard Smithc20d1442018-08-20 20:14:49 +00002508 if (static_cast<size_t>(Last - First) <= Lookahead)
2509 return '\0';
2510 return First[Lookahead];
2511 }
2512
2513 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2514
2515 StringView parseNumber(bool AllowNegative = false);
2516 Qualifiers parseCVQualifiers();
2517 bool parsePositiveInteger(size_t *Out);
2518 StringView parseBareSourceName();
2519
2520 bool parseSeqId(size_t *Out);
2521 Node *parseSubstitution();
2522 Node *parseTemplateParam();
Richard Smithdf1c14c2019-09-06 23:53:21 +00002523 Node *parseTemplateParamDecl();
Richard Smithc20d1442018-08-20 20:14:49 +00002524 Node *parseTemplateArgs(bool TagTemplates = false);
2525 Node *parseTemplateArg();
2526
2527 /// Parse the <expr> production.
2528 Node *parseExpr();
2529 Node *parsePrefixExpr(StringView Kind);
2530 Node *parseBinaryExpr(StringView Kind);
2531 Node *parseIntegerLiteral(StringView Lit);
2532 Node *parseExprPrimary();
2533 template <class Float> Node *parseFloatingLiteral();
2534 Node *parseFunctionParam();
Richard Smithc20d1442018-08-20 20:14:49 +00002535 Node *parseConversionExpr();
2536 Node *parseBracedExpr();
2537 Node *parseFoldExpr();
Richard Smith1865d2f2020-10-22 19:29:36 -07002538 Node *parsePointerToMemberConversionExpr();
2539 Node *parseSubobjectExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00002540
2541 /// Parse the <type> production.
2542 Node *parseType();
2543 Node *parseFunctionType();
2544 Node *parseVectorType();
2545 Node *parseDecltype();
2546 Node *parseArrayType();
2547 Node *parsePointerToMemberType();
2548 Node *parseClassEnumType();
2549 Node *parseQualifiedType();
2550
2551 Node *parseEncoding();
2552 bool parseCallOffset();
2553 Node *parseSpecialName();
2554
2555 /// Holds some extra information about a <name> that is being parsed. This
2556 /// information is only pertinent if the <name> refers to an <encoding>.
2557 struct NameState {
2558 bool CtorDtorConversion = false;
2559 bool EndsWithTemplateArgs = false;
2560 Qualifiers CVQualifiers = QualNone;
2561 FunctionRefQual ReferenceQualifier = FrefQualNone;
2562 size_t ForwardTemplateRefsBegin;
2563
Pavel Labathba825192018-10-16 14:29:14 +00002564 NameState(AbstractManglingParser *Enclosing)
Richard Smithc20d1442018-08-20 20:14:49 +00002565 : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
2566 };
2567
2568 bool resolveForwardTemplateRefs(NameState &State) {
2569 size_t I = State.ForwardTemplateRefsBegin;
2570 size_t E = ForwardTemplateRefs.size();
2571 for (; I < E; ++I) {
2572 size_t Idx = ForwardTemplateRefs[I]->Index;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002573 if (TemplateParams.empty() || !TemplateParams[0] ||
2574 Idx >= TemplateParams[0]->size())
Richard Smithc20d1442018-08-20 20:14:49 +00002575 return true;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002576 ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
Richard Smithc20d1442018-08-20 20:14:49 +00002577 }
2578 ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
2579 return false;
2580 }
2581
2582 /// Parse the <name> production>
2583 Node *parseName(NameState *State = nullptr);
2584 Node *parseLocalName(NameState *State);
2585 Node *parseOperatorName(NameState *State);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002586 bool parseModuleNameOpt(ModuleName *&Module);
2587 Node *parseUnqualifiedName(NameState *State, Node *Scope, ModuleName *Module);
Richard Smithc20d1442018-08-20 20:14:49 +00002588 Node *parseUnnamedTypeName(NameState *State);
2589 Node *parseSourceName(NameState *State);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002590 Node *parseUnscopedName(NameState *State, bool *isSubstName);
Richard Smithc20d1442018-08-20 20:14:49 +00002591 Node *parseNestedName(NameState *State);
2592 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2593
2594 Node *parseAbiTags(Node *N);
2595
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08002596 struct OperatorInfo {
2597 enum OIKind : unsigned char {
2598 Prefix, // Prefix unary: @ expr
2599 Postfix, // Postfix unary: expr @
2600 Binary, // Binary: lhs @ rhs
2601 Array, // Array index: lhs [ rhs ]
2602 Member, // Member access: lhs @ rhs
2603 New, // New
2604 Del, // Delete
2605 Call, // Function call: expr (expr*)
2606 CCast, // C cast: (type)expr
2607 Conditional, // Conditional: expr ? expr : expr
Nathan Sidwell0dda3d42022-02-18 09:51:24 -08002608 NameOnly, // Overload only, not allowed in expression.
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08002609 // Below do not have operator names
2610 NamedCast, // Named cast, @<type>(expr)
2611 OfIdOp, // alignof, sizeof, typeid
2612
2613 Unnameable = NamedCast,
2614 };
2615 char Enc[2]; // Encoding
2616 OIKind Kind; // Kind of operator
2617 bool Flag : 1; // Entry-specific flag
2618 const char *Name; // Spelling
2619
2620 public:
2621 constexpr OperatorInfo(const char (&E)[3], OIKind K, bool F, const char *N)
2622 : Enc{E[0], E[1]}, Kind{K}, Flag{F}, Name{N} {}
2623
2624 public:
2625 bool operator<(const OperatorInfo &Other) const {
2626 return *this < Other.Enc;
2627 }
2628 bool operator<(const char *Peek) const {
2629 return Enc[0] < Peek[0] || (Enc[0] == Peek[0] && Enc[1] < Peek[1]);
2630 }
2631 bool operator==(const char *Peek) const {
2632 return Enc[0] == Peek[0] && Enc[1] == Peek[1];
2633 }
2634 bool operator!=(const char *Peek) const { return !this->operator==(Peek); }
2635
2636 public:
2637 StringView getSymbol() const {
2638 StringView Res = Name;
2639 if (Kind < Unnameable) {
2640 assert(Res.startsWith("operator") &&
2641 "operator name does not start with 'operator'");
2642 Res = Res.dropFront(sizeof("operator") - 1);
2643 Res.consumeFront(' ');
2644 }
2645 return Res;
2646 }
2647 StringView getName() const { return Name; }
2648 OIKind getKind() const { return Kind; }
2649 bool getFlag() const { return Flag; }
2650 };
2651 const OperatorInfo *parseOperatorEncoding();
2652
Richard Smithc20d1442018-08-20 20:14:49 +00002653 /// Parse the <unresolved-name> production.
Nathan Sidwell77c52e22022-01-28 11:59:03 -08002654 Node *parseUnresolvedName(bool Global);
Richard Smithc20d1442018-08-20 20:14:49 +00002655 Node *parseSimpleId();
2656 Node *parseBaseUnresolvedName();
2657 Node *parseUnresolvedType();
2658 Node *parseDestructorName();
2659
2660 /// Top-level entry point into the parser.
2661 Node *parse();
2662};
2663
2664const char* parse_discriminator(const char* first, const char* last);
2665
2666// <name> ::= <nested-name> // N
2667// ::= <local-name> # See Scope Encoding below // Z
2668// ::= <unscoped-template-name> <template-args>
2669// ::= <unscoped-name>
2670//
2671// <unscoped-template-name> ::= <unscoped-name>
2672// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00002673template <typename Derived, typename Alloc>
2674Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002675 if (look() == 'N')
Pavel Labathba825192018-10-16 14:29:14 +00002676 return getDerived().parseNestedName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002677 if (look() == 'Z')
Pavel Labathba825192018-10-16 14:29:14 +00002678 return getDerived().parseLocalName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002679
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08002680 Node *Result = nullptr;
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002681 bool IsSubst = false;
2682
2683 Result = getDerived().parseUnscopedName(State, &IsSubst);
2684 if (!Result)
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08002685 return nullptr;
2686
2687 if (look() == 'I') {
2688 // ::= <unscoped-template-name> <template-args>
2689 if (!IsSubst)
2690 // An unscoped-template-name is substitutable.
2691 Subs.push_back(Result);
Pavel Labathba825192018-10-16 14:29:14 +00002692 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00002693 if (TA == nullptr)
2694 return nullptr;
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08002695 if (State)
2696 State->EndsWithTemplateArgs = true;
2697 Result = make<NameWithTemplateArgs>(Result, TA);
2698 } else if (IsSubst) {
2699 // The substitution case must be followed by <template-args>.
2700 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00002701 }
2702
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08002703 return Result;
Richard Smithc20d1442018-08-20 20:14:49 +00002704}
2705
2706// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2707// := Z <function encoding> E s [<discriminator>]
2708// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
Pavel Labathba825192018-10-16 14:29:14 +00002709template <typename Derived, typename Alloc>
2710Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00002711 if (!consumeIf('Z'))
2712 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002713 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00002714 if (Encoding == nullptr || !consumeIf('E'))
2715 return nullptr;
2716
2717 if (consumeIf('s')) {
2718 First = parse_discriminator(First, Last);
Richard Smithb485b352018-08-24 23:30:26 +00002719 auto *StringLitName = make<NameType>("string literal");
2720 if (!StringLitName)
2721 return nullptr;
2722 return make<LocalName>(Encoding, StringLitName);
Richard Smithc20d1442018-08-20 20:14:49 +00002723 }
2724
2725 if (consumeIf('d')) {
2726 parseNumber(true);
2727 if (!consumeIf('_'))
2728 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00002729 Node *N = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002730 if (N == nullptr)
2731 return nullptr;
2732 return make<LocalName>(Encoding, N);
2733 }
2734
Pavel Labathba825192018-10-16 14:29:14 +00002735 Node *Entity = getDerived().parseName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002736 if (Entity == nullptr)
2737 return nullptr;
2738 First = parse_discriminator(First, Last);
2739 return make<LocalName>(Encoding, Entity);
2740}
2741
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08002742// <unscoped-name> ::= [L]* <unqualified-name>
2743// ::= St [L]* <unqualified-name> # ::std::
2744// [*] extension
Pavel Labathba825192018-10-16 14:29:14 +00002745template <typename Derived, typename Alloc>
2746Node *
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002747AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State,
2748 bool *IsSubst) {
2749
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002750 Node *Std = nullptr;
2751 if (consumeIf("St")) {
2752 Std = make<NameType>("std");
2753 if (Std == nullptr)
Nathan Sidwell200e97c2022-01-21 11:37:01 -08002754 return nullptr;
2755 }
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002756 consumeIf('L');
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08002757
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002758 Node *Res = nullptr;
2759 ModuleName *Module = nullptr;
2760 if (look() == 'S') {
2761 Node *S = getDerived().parseSubstitution();
2762 if (!S)
2763 return nullptr;
2764 if (S->getKind() == Node::KModuleName)
2765 Module = static_cast<ModuleName *>(S);
2766 else if (IsSubst && Std == nullptr) {
2767 Res = S;
2768 *IsSubst = true;
2769 } else {
2770 return nullptr;
2771 }
2772 }
2773
2774 if (Res == nullptr)
2775 Res = getDerived().parseUnqualifiedName(State, Std, Module);
2776
2777 return Res;
Richard Smithc20d1442018-08-20 20:14:49 +00002778}
2779
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002780// <unqualified-name> ::= [<module-name>] <operator-name> [<abi-tags>]
2781// ::= [<module-name>] <ctor-dtor-name> [<abi-tags>]
2782// ::= [<module-name>] <source-name> [<abi-tags>]
2783// ::= [<module-name>] <unnamed-type-name> [<abi-tags>]
2784// # structured binding declaration
2785// ::= [<module-name>] DC <source-name>+ E
Pavel Labathba825192018-10-16 14:29:14 +00002786template <typename Derived, typename Alloc>
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002787Node *AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(
2788 NameState *State, Node *Scope, ModuleName *Module) {
2789 if (getDerived().parseModuleNameOpt(Module))
2790 return nullptr;
2791
Richard Smithc20d1442018-08-20 20:14:49 +00002792 Node *Result;
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002793 if (look() == 'U') {
Pavel Labathba825192018-10-16 14:29:14 +00002794 Result = getDerived().parseUnnamedTypeName(State);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002795 } else if (look() >= '1' && look() <= '9') {
Pavel Labathba825192018-10-16 14:29:14 +00002796 Result = getDerived().parseSourceName(State);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002797 } else if (consumeIf("DC")) {
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002798 // Structured binding
Richard Smithc20d1442018-08-20 20:14:49 +00002799 size_t BindingsBegin = Names.size();
2800 do {
Pavel Labathba825192018-10-16 14:29:14 +00002801 Node *Binding = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00002802 if (Binding == nullptr)
2803 return nullptr;
2804 Names.push_back(Binding);
2805 } while (!consumeIf('E'));
2806 Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002807 } else if (look() == 'C' || look() == 'D') {
2808 // A <ctor-dtor-name>.
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002809 if (Scope == nullptr || Module != nullptr)
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002810 return nullptr;
2811 Result = getDerived().parseCtorDtorName(Scope, State);
2812 } else {
Pavel Labathba825192018-10-16 14:29:14 +00002813 Result = getDerived().parseOperatorName(State);
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002814 }
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002815
2816 if (Module)
2817 Result = make<ModuleEntity>(Module, Result);
Richard Smithc20d1442018-08-20 20:14:49 +00002818 if (Result != nullptr)
Pavel Labathba825192018-10-16 14:29:14 +00002819 Result = getDerived().parseAbiTags(Result);
Nathan Sidwell9a29c972022-01-25 12:23:31 -08002820 if (Result != nullptr && Scope != nullptr)
2821 Result = make<NestedName>(Scope, Result);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002822
Richard Smithc20d1442018-08-20 20:14:49 +00002823 return Result;
2824}
2825
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08002826// <module-name> ::= <module-subname>
2827// ::= <module-name> <module-subname>
2828// ::= <substitution> # passed in by caller
2829// <module-subname> ::= W <source-name>
2830// ::= W P <source-name>
2831template <typename Derived, typename Alloc>
2832bool AbstractManglingParser<Derived, Alloc>::parseModuleNameOpt(
2833 ModuleName *&Module) {
2834 while (consumeIf('W')) {
2835 bool IsPartition = consumeIf('P');
2836 Node *Sub = getDerived().parseSourceName(nullptr);
2837 if (!Sub)
2838 return true;
2839 Module =
2840 static_cast<ModuleName *>(make<ModuleName>(Module, Sub, IsPartition));
2841 Subs.push_back(Module);
2842 }
2843
2844 return false;
2845}
2846
Richard Smithc20d1442018-08-20 20:14:49 +00002847// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2848// ::= <closure-type-name>
2849//
2850// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2851//
2852// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
Pavel Labathba825192018-10-16 14:29:14 +00002853template <typename Derived, typename Alloc>
2854Node *
Richard Smithdf1c14c2019-09-06 23:53:21 +00002855AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
2856 // <template-params> refer to the innermost <template-args>. Clear out any
2857 // outer args that we may have inserted into TemplateParams.
2858 if (State != nullptr)
2859 TemplateParams.clear();
2860
Richard Smithc20d1442018-08-20 20:14:49 +00002861 if (consumeIf("Ut")) {
2862 StringView Count = parseNumber();
2863 if (!consumeIf('_'))
2864 return nullptr;
2865 return make<UnnamedTypeName>(Count);
2866 }
2867 if (consumeIf("Ul")) {
Richard Smithdf1c14c2019-09-06 23:53:21 +00002868 SwapAndRestore<size_t> SwapParams(ParsingLambdaParamsAtLevel,
2869 TemplateParams.size());
2870 ScopedTemplateParamList LambdaTemplateParams(this);
2871
2872 size_t ParamsBegin = Names.size();
2873 while (look() == 'T' &&
2874 StringView("yptn").find(look(1)) != StringView::npos) {
2875 Node *T = parseTemplateParamDecl();
2876 if (!T)
2877 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002878 Names.push_back(T);
2879 }
2880 NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
2881
2882 // FIXME: If TempParams is empty and none of the function parameters
2883 // includes 'auto', we should remove LambdaTemplateParams from the
2884 // TemplateParams list. Unfortunately, we don't find out whether there are
2885 // any 'auto' parameters until too late in an example such as:
2886 //
2887 // template<typename T> void f(
2888 // decltype([](decltype([]<typename T>(T v) {}),
2889 // auto) {})) {}
2890 // template<typename T> void f(
2891 // decltype([](decltype([]<typename T>(T w) {}),
2892 // int) {})) {}
2893 //
2894 // Here, the type of v is at level 2 but the type of w is at level 1. We
2895 // don't find this out until we encounter the type of the next parameter.
2896 //
2897 // However, compilers can't actually cope with the former example in
2898 // practice, and it's likely to be made ill-formed in future, so we don't
2899 // need to support it here.
2900 //
2901 // If we encounter an 'auto' in the function parameter types, we will
2902 // recreate a template parameter scope for it, but any intervening lambdas
2903 // will be parsed in the 'wrong' template parameter depth.
2904 if (TempParams.empty())
2905 TemplateParams.pop_back();
2906
Richard Smithc20d1442018-08-20 20:14:49 +00002907 if (!consumeIf("vE")) {
Richard Smithc20d1442018-08-20 20:14:49 +00002908 do {
Pavel Labathba825192018-10-16 14:29:14 +00002909 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00002910 if (P == nullptr)
2911 return nullptr;
2912 Names.push_back(P);
2913 } while (!consumeIf('E'));
Richard Smithc20d1442018-08-20 20:14:49 +00002914 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00002915 NodeArray Params = popTrailingNodeArray(ParamsBegin);
2916
Richard Smithc20d1442018-08-20 20:14:49 +00002917 StringView Count = parseNumber();
2918 if (!consumeIf('_'))
2919 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00002920 return make<ClosureTypeName>(TempParams, Params, Count);
Richard Smithc20d1442018-08-20 20:14:49 +00002921 }
Erik Pilkington974b6542019-01-17 21:37:51 +00002922 if (consumeIf("Ub")) {
2923 (void)parseNumber();
2924 if (!consumeIf('_'))
2925 return nullptr;
2926 return make<NameType>("'block-literal'");
2927 }
Richard Smithc20d1442018-08-20 20:14:49 +00002928 return nullptr;
2929}
2930
2931// <source-name> ::= <positive length number> <identifier>
Pavel Labathba825192018-10-16 14:29:14 +00002932template <typename Derived, typename Alloc>
2933Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
Richard Smithc20d1442018-08-20 20:14:49 +00002934 size_t Length = 0;
2935 if (parsePositiveInteger(&Length))
2936 return nullptr;
2937 if (numLeft() < Length || Length == 0)
2938 return nullptr;
2939 StringView Name(First, First + Length);
2940 First += Length;
2941 if (Name.startsWith("_GLOBAL__N"))
2942 return make<NameType>("(anonymous namespace)");
2943 return make<NameType>(Name);
2944}
2945
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08002946// If the next 2 chars are an operator encoding, consume them and return their
2947// OperatorInfo. Otherwise return nullptr.
2948template <typename Derived, typename Alloc>
2949const typename AbstractManglingParser<Derived, Alloc>::OperatorInfo *
2950AbstractManglingParser<Derived, Alloc>::parseOperatorEncoding() {
2951 static const OperatorInfo Ops[] = {
2952 // Keep ordered by encoding
2953 {"aN", OperatorInfo::Binary, false, "operator&="},
2954 {"aS", OperatorInfo::Binary, false, "operator="},
2955 {"aa", OperatorInfo::Binary, false, "operator&&"},
2956 {"ad", OperatorInfo::Prefix, false, "operator&"},
2957 {"an", OperatorInfo::Binary, false, "operator&"},
2958 {"at", OperatorInfo::OfIdOp, /*Type*/ true, "alignof ("},
Nathan Sidwell0dda3d42022-02-18 09:51:24 -08002959 {"aw", OperatorInfo::NameOnly, false, "operator co_await"},
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08002960 {"az", OperatorInfo::OfIdOp, /*Type*/ false, "alignof ("},
2961 {"cc", OperatorInfo::NamedCast, false, "const_cast"},
2962 {"cl", OperatorInfo::Call, false, "operator()"},
2963 {"cm", OperatorInfo::Binary, false, "operator,"},
2964 {"co", OperatorInfo::Prefix, false, "operator~"},
2965 {"cv", OperatorInfo::CCast, false, "operator"}, // C Cast
2966 {"dV", OperatorInfo::Binary, false, "operator/="},
2967 {"da", OperatorInfo::Del, /*Ary*/ true, "operator delete[]"},
2968 {"dc", OperatorInfo::NamedCast, false, "dynamic_cast"},
2969 {"de", OperatorInfo::Prefix, false, "operator*"},
2970 {"dl", OperatorInfo::Del, /*Ary*/ false, "operator delete"},
2971 {"ds", OperatorInfo::Member, /*Named*/ false, "operator.*"},
2972 {"dt", OperatorInfo::Member, /*Named*/ false, "operator."},
2973 {"dv", OperatorInfo::Binary, false, "operator/"},
2974 {"eO", OperatorInfo::Binary, false, "operator^="},
2975 {"eo", OperatorInfo::Binary, false, "operator^"},
2976 {"eq", OperatorInfo::Binary, false, "operator=="},
2977 {"ge", OperatorInfo::Binary, false, "operator>="},
2978 {"gt", OperatorInfo::Binary, false, "operator>"},
2979 {"ix", OperatorInfo::Array, false, "operator[]"},
2980 {"lS", OperatorInfo::Binary, false, "operator<<="},
2981 {"le", OperatorInfo::Binary, false, "operator<="},
2982 {"ls", OperatorInfo::Binary, false, "operator<<"},
2983 {"lt", OperatorInfo::Binary, false, "operator<"},
2984 {"mI", OperatorInfo::Binary, false, "operator-="},
2985 {"mL", OperatorInfo::Binary, false, "operator*="},
2986 {"mi", OperatorInfo::Binary, false, "operator-"},
2987 {"ml", OperatorInfo::Binary, false, "operator*"},
2988 {"mm", OperatorInfo::Postfix, false, "operator--"},
2989 {"na", OperatorInfo::New, /*Ary*/ true, "operator new[]"},
2990 {"ne", OperatorInfo::Binary, false, "operator!="},
2991 {"ng", OperatorInfo::Prefix, false, "operator-"},
2992 {"nt", OperatorInfo::Prefix, false, "operator!"},
2993 {"nw", OperatorInfo::New, /*Ary*/ false, "operator new"},
2994 {"oR", OperatorInfo::Binary, false, "operator|="},
2995 {"oo", OperatorInfo::Binary, false, "operator||"},
2996 {"or", OperatorInfo::Binary, false, "operator|"},
2997 {"pL", OperatorInfo::Binary, false, "operator+="},
2998 {"pl", OperatorInfo::Binary, false, "operator+"},
2999 {"pm", OperatorInfo::Member, /*Named*/ false, "operator->*"},
3000 {"pp", OperatorInfo::Postfix, false, "operator++"},
3001 {"ps", OperatorInfo::Prefix, false, "operator+"},
3002 {"pt", OperatorInfo::Member, /*Named*/ true, "operator->"},
3003 {"qu", OperatorInfo::Conditional, false, "operator?"},
3004 {"rM", OperatorInfo::Binary, false, "operator%="},
3005 {"rS", OperatorInfo::Binary, false, "operator>>="},
3006 {"rc", OperatorInfo::NamedCast, false, "reinterpret_cast"},
3007 {"rm", OperatorInfo::Binary, false, "operator%"},
3008 {"rs", OperatorInfo::Binary, false, "operator>>"},
3009 {"sc", OperatorInfo::NamedCast, false, "static_cast"},
3010 {"ss", OperatorInfo::Binary, false, "operator<=>"},
3011 {"st", OperatorInfo::OfIdOp, /*Type*/ true, "sizeof ("},
3012 {"sz", OperatorInfo::OfIdOp, /*Type*/ false, "sizeof ("},
3013 {"te", OperatorInfo::OfIdOp, /*Type*/ false, "typeid ("},
3014 {"ti", OperatorInfo::OfIdOp, /*Type*/ true, "typeid ("},
3015 };
3016 const auto NumOps = sizeof(Ops) / sizeof(Ops[0]);
3017
3018#ifndef NDEBUG
3019 {
3020 // Verify table order.
3021 static bool Done;
3022 if (!Done) {
3023 Done = true;
3024 for (const auto *Op = &Ops[0]; Op != &Ops[NumOps - 1]; Op++)
3025 assert(Op[0] < Op[1] && "Operator table is not ordered");
3026 }
3027 }
3028#endif
3029
3030 if (numLeft() < 2)
3031 return nullptr;
3032
3033 auto Op = std::lower_bound(
3034 &Ops[0], &Ops[NumOps], First,
3035 [](const OperatorInfo &Op_, const char *Enc_) { return Op_ < Enc_; });
3036 if (Op == &Ops[NumOps] || *Op != First)
3037 return nullptr;
3038
3039 First += 2;
3040 return Op;
3041}
3042
3043// <operator-name> ::= See parseOperatorEncoding()
Richard Smithc20d1442018-08-20 20:14:49 +00003044// ::= li <source-name> # operator ""
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08003045// ::= v <digit> <source-name> # vendor extended operator
Pavel Labathba825192018-10-16 14:29:14 +00003046template <typename Derived, typename Alloc>
3047Node *
3048AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08003049 if (const auto *Op = parseOperatorEncoding()) {
3050 if (Op->getKind() == OperatorInfo::CCast) {
3051 // ::= cv <type> # (cast)
Richard Smithc20d1442018-08-20 20:14:49 +00003052 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
3053 // If we're parsing an encoding, State != nullptr and the conversion
3054 // operators' <type> could have a <template-param> that refers to some
3055 // <template-arg>s further ahead in the mangled name.
3056 SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences,
3057 PermitForwardTemplateReferences ||
3058 State != nullptr);
Pavel Labathba825192018-10-16 14:29:14 +00003059 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003060 if (Ty == nullptr)
3061 return nullptr;
3062 if (State) State->CtorDtorConversion = true;
3063 return make<ConversionOperatorType>(Ty);
3064 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08003065
3066 if (Op->getKind() >= OperatorInfo::Unnameable)
3067 /* Not a nameable operator. */
3068 return nullptr;
3069 if (Op->getKind() == OperatorInfo::Member && !Op->getFlag())
3070 /* Not a nameable MemberExpr */
3071 return nullptr;
3072
3073 return make<NameType>(Op->getName());
3074 }
3075
3076 if (consumeIf("li")) {
Richard Smithc20d1442018-08-20 20:14:49 +00003077 // ::= li <source-name> # operator ""
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08003078 Node *SN = getDerived().parseSourceName(State);
3079 if (SN == nullptr)
3080 return nullptr;
3081 return make<LiteralOperator>(SN);
3082 }
3083
3084 if (consumeIf('v')) {
3085 // ::= v <digit> <source-name> # vendor extended operator
3086 if (look() >= '0' && look() <= '9') {
3087 First++;
Pavel Labathba825192018-10-16 14:29:14 +00003088 Node *SN = getDerived().parseSourceName(State);
Richard Smithc20d1442018-08-20 20:14:49 +00003089 if (SN == nullptr)
3090 return nullptr;
3091 return make<ConversionOperatorType>(SN);
3092 }
3093 return nullptr;
3094 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08003095
Richard Smithc20d1442018-08-20 20:14:49 +00003096 return nullptr;
3097}
3098
3099// <ctor-dtor-name> ::= C1 # complete object constructor
3100// ::= C2 # base object constructor
3101// ::= C3 # complete object allocating constructor
Nico Weber29294792019-04-03 23:14:33 +00003102// extension ::= C4 # gcc old-style "[unified]" constructor
3103// extension ::= C5 # the COMDAT used for ctors
Richard Smithc20d1442018-08-20 20:14:49 +00003104// ::= D0 # deleting destructor
3105// ::= D1 # complete object destructor
3106// ::= D2 # base object destructor
Nico Weber29294792019-04-03 23:14:33 +00003107// extension ::= D4 # gcc old-style "[unified]" destructor
3108// extension ::= D5 # the COMDAT used for dtors
Pavel Labathba825192018-10-16 14:29:14 +00003109template <typename Derived, typename Alloc>
3110Node *
3111AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
3112 NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003113 if (SoFar->getKind() == Node::KSpecialSubstitution) {
3114 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
3115 switch (SSK) {
3116 case SpecialSubKind::string:
3117 case SpecialSubKind::istream:
3118 case SpecialSubKind::ostream:
3119 case SpecialSubKind::iostream:
3120 SoFar = make<ExpandedSpecialSubstitution>(SSK);
Richard Smithb485b352018-08-24 23:30:26 +00003121 if (!SoFar)
3122 return nullptr;
Reid Klecknere76aabe2018-11-01 18:24:03 +00003123 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003124 default:
3125 break;
3126 }
3127 }
3128
3129 if (consumeIf('C')) {
3130 bool IsInherited = consumeIf('I');
Nico Weber29294792019-04-03 23:14:33 +00003131 if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
3132 look() != '5')
Richard Smithc20d1442018-08-20 20:14:49 +00003133 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003134 int Variant = look() - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003135 ++First;
3136 if (State) State->CtorDtorConversion = true;
3137 if (IsInherited) {
Pavel Labathba825192018-10-16 14:29:14 +00003138 if (getDerived().parseName(State) == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00003139 return nullptr;
3140 }
Nico Weber29294792019-04-03 23:14:33 +00003141 return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003142 }
3143
Nico Weber29294792019-04-03 23:14:33 +00003144 if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
3145 look(1) == '4' || look(1) == '5')) {
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003146 int Variant = look(1) - '0';
Richard Smithc20d1442018-08-20 20:14:49 +00003147 First += 2;
3148 if (State) State->CtorDtorConversion = true;
Nico Weber29294792019-04-03 23:14:33 +00003149 return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
Richard Smithc20d1442018-08-20 20:14:49 +00003150 }
3151
3152 return nullptr;
3153}
3154
3155// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
3156// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
3157//
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003158// <prefix> ::= <prefix> [L]* <unqualified-name>
Richard Smithc20d1442018-08-20 20:14:49 +00003159// ::= <template-prefix> <template-args>
3160// ::= <template-param>
3161// ::= <decltype>
3162// ::= # empty
3163// ::= <substitution>
3164// ::= <prefix> <data-member-prefix>
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003165// [*] extension
Richard Smithc20d1442018-08-20 20:14:49 +00003166//
3167// <data-member-prefix> := <member source-name> [<template-args>] M
3168//
3169// <template-prefix> ::= <prefix> <template unqualified-name>
3170// ::= <template-param>
3171// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003172template <typename Derived, typename Alloc>
3173Node *
3174AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
Richard Smithc20d1442018-08-20 20:14:49 +00003175 if (!consumeIf('N'))
3176 return nullptr;
3177
3178 Qualifiers CVTmp = parseCVQualifiers();
3179 if (State) State->CVQualifiers = CVTmp;
3180
3181 if (consumeIf('O')) {
3182 if (State) State->ReferenceQualifier = FrefQualRValue;
3183 } else if (consumeIf('R')) {
3184 if (State) State->ReferenceQualifier = FrefQualLValue;
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003185 } else {
Richard Smithc20d1442018-08-20 20:14:49 +00003186 if (State) State->ReferenceQualifier = FrefQualNone;
Richard Smithb485b352018-08-24 23:30:26 +00003187 }
Richard Smithc20d1442018-08-20 20:14:49 +00003188
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003189 Node *SoFar = nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003190 while (!consumeIf('E')) {
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003191 if (State)
3192 // Only set end-with-template on the case that does that.
3193 State->EndsWithTemplateArgs = false;
3194
Richard Smithc20d1442018-08-20 20:14:49 +00003195 if (look() == 'T') {
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003196 // ::= <template-param>
3197 if (SoFar != nullptr)
3198 return nullptr; // Cannot have a prefix.
3199 SoFar = getDerived().parseTemplateParam();
3200 } else if (look() == 'I') {
3201 // ::= <template-prefix> <template-args>
3202 if (SoFar == nullptr)
3203 return nullptr; // Must have a prefix.
Pavel Labathba825192018-10-16 14:29:14 +00003204 Node *TA = getDerived().parseTemplateArgs(State != nullptr);
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003205 if (TA == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00003206 return nullptr;
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003207 if (SoFar->getKind() == Node::KNameWithTemplateArgs)
3208 // Semantically <template-args> <template-args> cannot be generated by a
3209 // C++ entity. There will always be [something like] a name between
3210 // them.
3211 return nullptr;
3212 if (State)
3213 State->EndsWithTemplateArgs = true;
Richard Smithc20d1442018-08-20 20:14:49 +00003214 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003215 } else if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
3216 // ::= <decltype>
3217 if (SoFar != nullptr)
3218 return nullptr; // Cannot have a prefix.
3219 SoFar = getDerived().parseDecltype();
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003220 } else {
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08003221 ModuleName *Module = nullptr;
3222 bool IsLocal = consumeIf('L'); // extension
3223
3224 if (look() == 'S') {
3225 // ::= <substitution>
3226 Node *S = nullptr;
3227 if (look(1) == 't') {
3228 First += 2;
3229 S = make<NameType>("std");
3230 } else {
3231 S = getDerived().parseSubstitution();
3232 }
3233 if (!S)
3234 return nullptr;
3235 if (S->getKind() == Node::KModuleName) {
3236 Module = static_cast<ModuleName *>(S);
3237 } else if (SoFar != nullptr || IsLocal) {
3238 return nullptr; // Cannot have a prefix.
3239 } else {
3240 SoFar = S;
3241 continue; // Do not push a new substitution.
3242 }
3243 }
3244
Nathan Sidwell9a29c972022-01-25 12:23:31 -08003245 // ::= [<prefix>] <unqualified-name>
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08003246 SoFar = getDerived().parseUnqualifiedName(State, SoFar, Module);
Richard Smithc20d1442018-08-20 20:14:49 +00003247 }
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08003248
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08003249 if (SoFar == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00003250 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003251 Subs.push_back(SoFar);
Nathan Sidwelle6545292022-01-25 12:31:01 -08003252
3253 // No longer used.
3254 // <data-member-prefix> := <member source-name> [<template-args>] M
3255 consumeIf('M');
Richard Smithc20d1442018-08-20 20:14:49 +00003256 }
3257
3258 if (SoFar == nullptr || Subs.empty())
3259 return nullptr;
3260
3261 Subs.pop_back();
3262 return SoFar;
3263}
3264
3265// <simple-id> ::= <source-name> [ <template-args> ]
Pavel Labathba825192018-10-16 14:29:14 +00003266template <typename Derived, typename Alloc>
3267Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
3268 Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003269 if (SN == nullptr)
3270 return nullptr;
3271 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003272 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003273 if (TA == nullptr)
3274 return nullptr;
3275 return make<NameWithTemplateArgs>(SN, TA);
3276 }
3277 return SN;
3278}
3279
3280// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
3281// ::= <simple-id> # e.g., ~A<2*N>
Pavel Labathba825192018-10-16 14:29:14 +00003282template <typename Derived, typename Alloc>
3283Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003284 Node *Result;
3285 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003286 Result = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003287 else
Pavel Labathba825192018-10-16 14:29:14 +00003288 Result = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003289 if (Result == nullptr)
3290 return nullptr;
3291 return make<DtorName>(Result);
3292}
3293
3294// <unresolved-type> ::= <template-param>
3295// ::= <decltype>
3296// ::= <substitution>
Pavel Labathba825192018-10-16 14:29:14 +00003297template <typename Derived, typename Alloc>
3298Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003299 if (look() == 'T') {
Pavel Labathba825192018-10-16 14:29:14 +00003300 Node *TP = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003301 if (TP == nullptr)
3302 return nullptr;
3303 Subs.push_back(TP);
3304 return TP;
3305 }
3306 if (look() == 'D') {
Pavel Labathba825192018-10-16 14:29:14 +00003307 Node *DT = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003308 if (DT == nullptr)
3309 return nullptr;
3310 Subs.push_back(DT);
3311 return DT;
3312 }
Pavel Labathba825192018-10-16 14:29:14 +00003313 return getDerived().parseSubstitution();
Richard Smithc20d1442018-08-20 20:14:49 +00003314}
3315
3316// <base-unresolved-name> ::= <simple-id> # unresolved name
3317// extension ::= <operator-name> # unresolved operator-function-id
3318// extension ::= <operator-name> <template-args> # unresolved operator template-id
3319// ::= on <operator-name> # unresolved operator-function-id
3320// ::= on <operator-name> <template-args> # unresolved operator template-id
3321// ::= dn <destructor-name> # destructor or pseudo-destructor;
3322// # e.g. ~X or ~X<N-1>
Pavel Labathba825192018-10-16 14:29:14 +00003323template <typename Derived, typename Alloc>
3324Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003325 if (std::isdigit(look()))
Pavel Labathba825192018-10-16 14:29:14 +00003326 return getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003327
3328 if (consumeIf("dn"))
Pavel Labathba825192018-10-16 14:29:14 +00003329 return getDerived().parseDestructorName();
Richard Smithc20d1442018-08-20 20:14:49 +00003330
3331 consumeIf("on");
3332
Pavel Labathba825192018-10-16 14:29:14 +00003333 Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003334 if (Oper == nullptr)
3335 return nullptr;
3336 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003337 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003338 if (TA == nullptr)
3339 return nullptr;
3340 return make<NameWithTemplateArgs>(Oper, TA);
3341 }
3342 return Oper;
3343}
3344
3345// <unresolved-name>
3346// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3347// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
3348// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3349// # A::x, N::y, A<T>::z; "gs" means leading "::"
Nathan Sidwell77c52e22022-01-28 11:59:03 -08003350// [gs] has been parsed by caller.
Richard Smithc20d1442018-08-20 20:14:49 +00003351// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
3352// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
3353// # T::N::x /decltype(p)::N::x
3354// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3355//
3356// <unresolved-qualifier-level> ::= <simple-id>
Pavel Labathba825192018-10-16 14:29:14 +00003357template <typename Derived, typename Alloc>
Nathan Sidwell77c52e22022-01-28 11:59:03 -08003358Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName(bool Global) {
Richard Smithc20d1442018-08-20 20:14:49 +00003359 Node *SoFar = nullptr;
3360
3361 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
3362 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
3363 if (consumeIf("srN")) {
Pavel Labathba825192018-10-16 14:29:14 +00003364 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003365 if (SoFar == nullptr)
3366 return nullptr;
3367
3368 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003369 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003370 if (TA == nullptr)
3371 return nullptr;
3372 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003373 if (!SoFar)
3374 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003375 }
3376
3377 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003378 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003379 if (Qual == nullptr)
3380 return nullptr;
3381 SoFar = make<QualifiedName>(SoFar, Qual);
Richard Smithb485b352018-08-24 23:30:26 +00003382 if (!SoFar)
3383 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003384 }
3385
Pavel Labathba825192018-10-16 14:29:14 +00003386 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003387 if (Base == nullptr)
3388 return nullptr;
3389 return make<QualifiedName>(SoFar, Base);
3390 }
3391
Richard Smithc20d1442018-08-20 20:14:49 +00003392 // [gs] <base-unresolved-name> # x or (with "gs") ::x
3393 if (!consumeIf("sr")) {
Pavel Labathba825192018-10-16 14:29:14 +00003394 SoFar = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003395 if (SoFar == nullptr)
3396 return nullptr;
3397 if (Global)
3398 SoFar = make<GlobalQualifiedName>(SoFar);
3399 return SoFar;
3400 }
3401
3402 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
3403 if (std::isdigit(look())) {
3404 do {
Pavel Labathba825192018-10-16 14:29:14 +00003405 Node *Qual = getDerived().parseSimpleId();
Richard Smithc20d1442018-08-20 20:14:49 +00003406 if (Qual == nullptr)
3407 return nullptr;
3408 if (SoFar)
3409 SoFar = make<QualifiedName>(SoFar, Qual);
3410 else if (Global)
3411 SoFar = make<GlobalQualifiedName>(Qual);
3412 else
3413 SoFar = Qual;
Richard Smithb485b352018-08-24 23:30:26 +00003414 if (!SoFar)
3415 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003416 } while (!consumeIf('E'));
3417 }
3418 // sr <unresolved-type> <base-unresolved-name>
3419 // sr <unresolved-type> <template-args> <base-unresolved-name>
3420 else {
Pavel Labathba825192018-10-16 14:29:14 +00003421 SoFar = getDerived().parseUnresolvedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003422 if (SoFar == nullptr)
3423 return nullptr;
3424
3425 if (look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00003426 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00003427 if (TA == nullptr)
3428 return nullptr;
3429 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Richard Smithb485b352018-08-24 23:30:26 +00003430 if (!SoFar)
3431 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003432 }
3433 }
3434
3435 assert(SoFar != nullptr);
3436
Pavel Labathba825192018-10-16 14:29:14 +00003437 Node *Base = getDerived().parseBaseUnresolvedName();
Richard Smithc20d1442018-08-20 20:14:49 +00003438 if (Base == nullptr)
3439 return nullptr;
3440 return make<QualifiedName>(SoFar, Base);
3441}
3442
3443// <abi-tags> ::= <abi-tag> [<abi-tags>]
3444// <abi-tag> ::= B <source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003445template <typename Derived, typename Alloc>
3446Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
Richard Smithc20d1442018-08-20 20:14:49 +00003447 while (consumeIf('B')) {
3448 StringView SN = parseBareSourceName();
3449 if (SN.empty())
3450 return nullptr;
3451 N = make<AbiTagAttr>(N, SN);
Richard Smithb485b352018-08-24 23:30:26 +00003452 if (!N)
3453 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003454 }
3455 return N;
3456}
3457
3458// <number> ::= [n] <non-negative decimal integer>
Pavel Labathba825192018-10-16 14:29:14 +00003459template <typename Alloc, typename Derived>
3460StringView
3461AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
Richard Smithc20d1442018-08-20 20:14:49 +00003462 const char *Tmp = First;
3463 if (AllowNegative)
3464 consumeIf('n');
3465 if (numLeft() == 0 || !std::isdigit(*First))
3466 return StringView();
3467 while (numLeft() != 0 && std::isdigit(*First))
3468 ++First;
3469 return StringView(Tmp, First);
3470}
3471
3472// <positive length number> ::= [0-9]*
Pavel Labathba825192018-10-16 14:29:14 +00003473template <typename Alloc, typename Derived>
3474bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00003475 *Out = 0;
3476 if (look() < '0' || look() > '9')
3477 return true;
3478 while (look() >= '0' && look() <= '9') {
3479 *Out *= 10;
3480 *Out += static_cast<size_t>(consume() - '0');
3481 }
3482 return false;
3483}
3484
Pavel Labathba825192018-10-16 14:29:14 +00003485template <typename Alloc, typename Derived>
3486StringView AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
Richard Smithc20d1442018-08-20 20:14:49 +00003487 size_t Int = 0;
3488 if (parsePositiveInteger(&Int) || numLeft() < Int)
3489 return StringView();
3490 StringView R(First, First + Int);
3491 First += Int;
3492 return R;
3493}
3494
3495// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
3496//
3497// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
3498// ::= DO <expression> E # computed (instantiation-dependent) noexcept
3499// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
3500//
3501// <ref-qualifier> ::= R # & ref-qualifier
3502// <ref-qualifier> ::= O # && ref-qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003503template <typename Derived, typename Alloc>
3504Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003505 Qualifiers CVQuals = parseCVQualifiers();
3506
3507 Node *ExceptionSpec = nullptr;
3508 if (consumeIf("Do")) {
3509 ExceptionSpec = make<NameType>("noexcept");
Richard Smithb485b352018-08-24 23:30:26 +00003510 if (!ExceptionSpec)
3511 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003512 } else if (consumeIf("DO")) {
Pavel Labathba825192018-10-16 14:29:14 +00003513 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003514 if (E == nullptr || !consumeIf('E'))
3515 return nullptr;
3516 ExceptionSpec = make<NoexceptSpec>(E);
Richard Smithb485b352018-08-24 23:30:26 +00003517 if (!ExceptionSpec)
3518 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003519 } else if (consumeIf("Dw")) {
3520 size_t SpecsBegin = Names.size();
3521 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00003522 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003523 if (T == nullptr)
3524 return nullptr;
3525 Names.push_back(T);
3526 }
3527 ExceptionSpec =
3528 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
Richard Smithb485b352018-08-24 23:30:26 +00003529 if (!ExceptionSpec)
3530 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003531 }
3532
3533 consumeIf("Dx"); // transaction safe
3534
3535 if (!consumeIf('F'))
3536 return nullptr;
3537 consumeIf('Y'); // extern "C"
Pavel Labathba825192018-10-16 14:29:14 +00003538 Node *ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003539 if (ReturnType == nullptr)
3540 return nullptr;
3541
3542 FunctionRefQual ReferenceQualifier = FrefQualNone;
3543 size_t ParamsBegin = Names.size();
3544 while (true) {
3545 if (consumeIf('E'))
3546 break;
3547 if (consumeIf('v'))
3548 continue;
3549 if (consumeIf("RE")) {
3550 ReferenceQualifier = FrefQualLValue;
3551 break;
3552 }
3553 if (consumeIf("OE")) {
3554 ReferenceQualifier = FrefQualRValue;
3555 break;
3556 }
Pavel Labathba825192018-10-16 14:29:14 +00003557 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003558 if (T == nullptr)
3559 return nullptr;
3560 Names.push_back(T);
3561 }
3562
3563 NodeArray Params = popTrailingNodeArray(ParamsBegin);
3564 return make<FunctionType>(ReturnType, Params, CVQuals,
3565 ReferenceQualifier, ExceptionSpec);
3566}
3567
3568// extension:
3569// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3570// ::= Dv [<dimension expression>] _ <element type>
3571// <extended element type> ::= <element type>
3572// ::= p # AltiVec vector pixel
Pavel Labathba825192018-10-16 14:29:14 +00003573template <typename Derived, typename Alloc>
3574Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003575 if (!consumeIf("Dv"))
3576 return nullptr;
3577 if (look() >= '1' && look() <= '9') {
Erik Pilkingtond7555e32019-11-04 10:47:44 -08003578 Node *DimensionNumber = make<NameType>(parseNumber());
3579 if (!DimensionNumber)
3580 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003581 if (!consumeIf('_'))
3582 return nullptr;
3583 if (consumeIf('p'))
3584 return make<PixelVectorType>(DimensionNumber);
Pavel Labathba825192018-10-16 14:29:14 +00003585 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003586 if (ElemType == nullptr)
3587 return nullptr;
3588 return make<VectorType>(ElemType, DimensionNumber);
3589 }
3590
3591 if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003592 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003593 if (!DimExpr)
3594 return nullptr;
3595 if (!consumeIf('_'))
3596 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003597 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003598 if (!ElemType)
3599 return nullptr;
3600 return make<VectorType>(ElemType, DimExpr);
3601 }
Pavel Labathba825192018-10-16 14:29:14 +00003602 Node *ElemType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003603 if (!ElemType)
3604 return nullptr;
Erik Pilkingtond7555e32019-11-04 10:47:44 -08003605 return make<VectorType>(ElemType, /*Dimension=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00003606}
3607
3608// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3609// ::= DT <expression> E # decltype of an expression (C++0x)
Pavel Labathba825192018-10-16 14:29:14 +00003610template <typename Derived, typename Alloc>
3611Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
Richard Smithc20d1442018-08-20 20:14:49 +00003612 if (!consumeIf('D'))
3613 return nullptr;
3614 if (!consumeIf('t') && !consumeIf('T'))
3615 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003616 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003617 if (E == nullptr)
3618 return nullptr;
3619 if (!consumeIf('E'))
3620 return nullptr;
3621 return make<EnclosingExpr>("decltype(", E, ")");
3622}
3623
3624// <array-type> ::= A <positive dimension number> _ <element type>
3625// ::= A [<dimension expression>] _ <element type>
Pavel Labathba825192018-10-16 14:29:14 +00003626template <typename Derived, typename Alloc>
3627Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003628 if (!consumeIf('A'))
3629 return nullptr;
3630
Erik Pilkingtond7555e32019-11-04 10:47:44 -08003631 Node *Dimension = nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003632
Richard Smithc20d1442018-08-20 20:14:49 +00003633 if (std::isdigit(look())) {
Erik Pilkingtond7555e32019-11-04 10:47:44 -08003634 Dimension = make<NameType>(parseNumber());
3635 if (!Dimension)
3636 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00003637 if (!consumeIf('_'))
3638 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003639 } else if (!consumeIf('_')) {
Pavel Labathba825192018-10-16 14:29:14 +00003640 Node *DimExpr = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00003641 if (DimExpr == nullptr)
3642 return nullptr;
3643 if (!consumeIf('_'))
3644 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003645 Dimension = DimExpr;
Richard Smithc20d1442018-08-20 20:14:49 +00003646 }
3647
Pavel Labathba825192018-10-16 14:29:14 +00003648 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003649 if (Ty == nullptr)
3650 return nullptr;
Pavel Labathf4e67eb2018-10-10 08:39:16 +00003651 return make<ArrayType>(Ty, Dimension);
Richard Smithc20d1442018-08-20 20:14:49 +00003652}
3653
3654// <pointer-to-member-type> ::= M <class type> <member type>
Pavel Labathba825192018-10-16 14:29:14 +00003655template <typename Derived, typename Alloc>
3656Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003657 if (!consumeIf('M'))
3658 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003659 Node *ClassType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003660 if (ClassType == nullptr)
3661 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003662 Node *MemberType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003663 if (MemberType == nullptr)
3664 return nullptr;
3665 return make<PointerToMemberType>(ClassType, MemberType);
3666}
3667
3668// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3669// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3670// ::= Tu <name> # dependent elaborated type specifier using 'union'
3671// ::= Te <name> # dependent elaborated type specifier using 'enum'
Pavel Labathba825192018-10-16 14:29:14 +00003672template <typename Derived, typename Alloc>
3673Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003674 StringView ElabSpef;
3675 if (consumeIf("Ts"))
3676 ElabSpef = "struct";
3677 else if (consumeIf("Tu"))
3678 ElabSpef = "union";
3679 else if (consumeIf("Te"))
3680 ElabSpef = "enum";
3681
Pavel Labathba825192018-10-16 14:29:14 +00003682 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00003683 if (Name == nullptr)
3684 return nullptr;
3685
3686 if (!ElabSpef.empty())
3687 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3688
3689 return Name;
3690}
3691
3692// <qualified-type> ::= <qualifiers> <type>
3693// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3694// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Pavel Labathba825192018-10-16 14:29:14 +00003695template <typename Derived, typename Alloc>
3696Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003697 if (consumeIf('U')) {
3698 StringView Qual = parseBareSourceName();
3699 if (Qual.empty())
3700 return nullptr;
3701
Richard Smithc20d1442018-08-20 20:14:49 +00003702 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3703 if (Qual.startsWith("objcproto")) {
3704 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3705 StringView Proto;
3706 {
3707 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3708 SaveLast(Last, ProtoSourceName.end());
3709 Proto = parseBareSourceName();
3710 }
3711 if (Proto.empty())
3712 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00003713 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003714 if (Child == nullptr)
3715 return nullptr;
3716 return make<ObjCProtoName>(Child, Proto);
3717 }
3718
Alex Orlovf50df922021-03-24 10:21:32 +04003719 Node *TA = nullptr;
3720 if (look() == 'I') {
3721 TA = getDerived().parseTemplateArgs();
3722 if (TA == nullptr)
3723 return nullptr;
3724 }
3725
Pavel Labathba825192018-10-16 14:29:14 +00003726 Node *Child = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003727 if (Child == nullptr)
3728 return nullptr;
Alex Orlovf50df922021-03-24 10:21:32 +04003729 return make<VendorExtQualType>(Child, Qual, TA);
Richard Smithc20d1442018-08-20 20:14:49 +00003730 }
3731
3732 Qualifiers Quals = parseCVQualifiers();
Pavel Labathba825192018-10-16 14:29:14 +00003733 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003734 if (Ty == nullptr)
3735 return nullptr;
3736 if (Quals != QualNone)
3737 Ty = make<QualType>(Ty, Quals);
3738 return Ty;
3739}
3740
3741// <type> ::= <builtin-type>
3742// ::= <qualified-type>
3743// ::= <function-type>
3744// ::= <class-enum-type>
3745// ::= <array-type>
3746// ::= <pointer-to-member-type>
3747// ::= <template-param>
3748// ::= <template-template-param> <template-args>
3749// ::= <decltype>
3750// ::= P <type> # pointer
3751// ::= R <type> # l-value reference
3752// ::= O <type> # r-value reference (C++11)
3753// ::= C <type> # complex pair (C99)
3754// ::= G <type> # imaginary (C99)
3755// ::= <substitution> # See Compression below
3756// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3757// extension ::= <vector-type> # <vector-type> starts with Dv
3758//
3759// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3760// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
Pavel Labathba825192018-10-16 14:29:14 +00003761template <typename Derived, typename Alloc>
3762Node *AbstractManglingParser<Derived, Alloc>::parseType() {
Richard Smithc20d1442018-08-20 20:14:49 +00003763 Node *Result = nullptr;
3764
Richard Smithc20d1442018-08-20 20:14:49 +00003765 switch (look()) {
3766 // ::= <qualified-type>
3767 case 'r':
3768 case 'V':
3769 case 'K': {
3770 unsigned AfterQuals = 0;
3771 if (look(AfterQuals) == 'r') ++AfterQuals;
3772 if (look(AfterQuals) == 'V') ++AfterQuals;
3773 if (look(AfterQuals) == 'K') ++AfterQuals;
3774
3775 if (look(AfterQuals) == 'F' ||
3776 (look(AfterQuals) == 'D' &&
3777 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3778 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Pavel Labathba825192018-10-16 14:29:14 +00003779 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003780 break;
3781 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00003782 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00003783 }
3784 case 'U': {
Pavel Labathba825192018-10-16 14:29:14 +00003785 Result = getDerived().parseQualifiedType();
Richard Smithc20d1442018-08-20 20:14:49 +00003786 break;
3787 }
3788 // <builtin-type> ::= v # void
3789 case 'v':
3790 ++First;
3791 return make<NameType>("void");
3792 // ::= w # wchar_t
3793 case 'w':
3794 ++First;
3795 return make<NameType>("wchar_t");
3796 // ::= b # bool
3797 case 'b':
3798 ++First;
3799 return make<NameType>("bool");
3800 // ::= c # char
3801 case 'c':
3802 ++First;
3803 return make<NameType>("char");
3804 // ::= a # signed char
3805 case 'a':
3806 ++First;
3807 return make<NameType>("signed char");
3808 // ::= h # unsigned char
3809 case 'h':
3810 ++First;
3811 return make<NameType>("unsigned char");
3812 // ::= s # short
3813 case 's':
3814 ++First;
3815 return make<NameType>("short");
3816 // ::= t # unsigned short
3817 case 't':
3818 ++First;
3819 return make<NameType>("unsigned short");
3820 // ::= i # int
3821 case 'i':
3822 ++First;
3823 return make<NameType>("int");
3824 // ::= j # unsigned int
3825 case 'j':
3826 ++First;
3827 return make<NameType>("unsigned int");
3828 // ::= l # long
3829 case 'l':
3830 ++First;
3831 return make<NameType>("long");
3832 // ::= m # unsigned long
3833 case 'm':
3834 ++First;
3835 return make<NameType>("unsigned long");
3836 // ::= x # long long, __int64
3837 case 'x':
3838 ++First;
3839 return make<NameType>("long long");
3840 // ::= y # unsigned long long, __int64
3841 case 'y':
3842 ++First;
3843 return make<NameType>("unsigned long long");
3844 // ::= n # __int128
3845 case 'n':
3846 ++First;
3847 return make<NameType>("__int128");
3848 // ::= o # unsigned __int128
3849 case 'o':
3850 ++First;
3851 return make<NameType>("unsigned __int128");
3852 // ::= f # float
3853 case 'f':
3854 ++First;
3855 return make<NameType>("float");
3856 // ::= d # double
3857 case 'd':
3858 ++First;
3859 return make<NameType>("double");
3860 // ::= e # long double, __float80
3861 case 'e':
3862 ++First;
3863 return make<NameType>("long double");
3864 // ::= g # __float128
3865 case 'g':
3866 ++First;
3867 return make<NameType>("__float128");
3868 // ::= z # ellipsis
3869 case 'z':
3870 ++First;
3871 return make<NameType>("...");
3872
3873 // <builtin-type> ::= u <source-name> # vendor extended type
3874 case 'u': {
3875 ++First;
3876 StringView Res = parseBareSourceName();
3877 if (Res.empty())
3878 return nullptr;
Erik Pilkingtonb94a1f42019-06-10 21:02:39 +00003879 // Typically, <builtin-type>s are not considered substitution candidates,
3880 // but the exception to that exception is vendor extended types (Itanium C++
3881 // ABI 5.9.1).
3882 Result = make<NameType>(Res);
3883 break;
Richard Smithc20d1442018-08-20 20:14:49 +00003884 }
3885 case 'D':
3886 switch (look(1)) {
3887 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3888 case 'd':
3889 First += 2;
3890 return make<NameType>("decimal64");
3891 // ::= De # IEEE 754r decimal floating point (128 bits)
3892 case 'e':
3893 First += 2;
3894 return make<NameType>("decimal128");
3895 // ::= Df # IEEE 754r decimal floating point (32 bits)
3896 case 'f':
3897 First += 2;
3898 return make<NameType>("decimal32");
3899 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3900 case 'h':
3901 First += 2;
Stuart Bradye8bf5772021-06-07 16:30:22 +01003902 return make<NameType>("half");
Pengfei Wang50e90b82021-09-23 11:02:25 +08003903 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point (N bits)
3904 case 'F': {
3905 First += 2;
3906 Node *DimensionNumber = make<NameType>(parseNumber());
3907 if (!DimensionNumber)
3908 return nullptr;
3909 if (!consumeIf('_'))
3910 return nullptr;
3911 return make<BinaryFPType>(DimensionNumber);
3912 }
Richard Smithc20d1442018-08-20 20:14:49 +00003913 // ::= Di # char32_t
3914 case 'i':
3915 First += 2;
3916 return make<NameType>("char32_t");
3917 // ::= Ds # char16_t
3918 case 's':
3919 First += 2;
3920 return make<NameType>("char16_t");
Erik Pilkingtonc3780e82019-06-28 19:54:19 +00003921 // ::= Du # char8_t (C++2a, not yet in the Itanium spec)
3922 case 'u':
3923 First += 2;
3924 return make<NameType>("char8_t");
Richard Smithc20d1442018-08-20 20:14:49 +00003925 // ::= Da # auto (in dependent new-expressions)
3926 case 'a':
3927 First += 2;
3928 return make<NameType>("auto");
3929 // ::= Dc # decltype(auto)
3930 case 'c':
3931 First += 2;
3932 return make<NameType>("decltype(auto)");
3933 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3934 case 'n':
3935 First += 2;
3936 return make<NameType>("std::nullptr_t");
3937
3938 // ::= <decltype>
3939 case 't':
3940 case 'T': {
Pavel Labathba825192018-10-16 14:29:14 +00003941 Result = getDerived().parseDecltype();
Richard Smithc20d1442018-08-20 20:14:49 +00003942 break;
3943 }
3944 // extension ::= <vector-type> # <vector-type> starts with Dv
3945 case 'v': {
Pavel Labathba825192018-10-16 14:29:14 +00003946 Result = getDerived().parseVectorType();
Richard Smithc20d1442018-08-20 20:14:49 +00003947 break;
3948 }
3949 // ::= Dp <type> # pack expansion (C++0x)
3950 case 'p': {
3951 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00003952 Node *Child = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00003953 if (!Child)
3954 return nullptr;
3955 Result = make<ParameterPackExpansion>(Child);
3956 break;
3957 }
3958 // Exception specifier on a function type.
3959 case 'o':
3960 case 'O':
3961 case 'w':
3962 // Transaction safe function type.
3963 case 'x':
Pavel Labathba825192018-10-16 14:29:14 +00003964 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003965 break;
3966 }
3967 break;
3968 // ::= <function-type>
3969 case 'F': {
Pavel Labathba825192018-10-16 14:29:14 +00003970 Result = getDerived().parseFunctionType();
Richard Smithc20d1442018-08-20 20:14:49 +00003971 break;
3972 }
3973 // ::= <array-type>
3974 case 'A': {
Pavel Labathba825192018-10-16 14:29:14 +00003975 Result = getDerived().parseArrayType();
Richard Smithc20d1442018-08-20 20:14:49 +00003976 break;
3977 }
3978 // ::= <pointer-to-member-type>
3979 case 'M': {
Pavel Labathba825192018-10-16 14:29:14 +00003980 Result = getDerived().parsePointerToMemberType();
Richard Smithc20d1442018-08-20 20:14:49 +00003981 break;
3982 }
3983 // ::= <template-param>
3984 case 'T': {
3985 // This could be an elaborate type specifier on a <class-enum-type>.
3986 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
Pavel Labathba825192018-10-16 14:29:14 +00003987 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00003988 break;
3989 }
3990
Pavel Labathba825192018-10-16 14:29:14 +00003991 Result = getDerived().parseTemplateParam();
Richard Smithc20d1442018-08-20 20:14:49 +00003992 if (Result == nullptr)
3993 return nullptr;
3994
3995 // Result could be either of:
3996 // <type> ::= <template-param>
3997 // <type> ::= <template-template-param> <template-args>
3998 //
3999 // <template-template-param> ::= <template-param>
4000 // ::= <substitution>
4001 //
4002 // If this is followed by some <template-args>, and we're permitted to
4003 // parse them, take the second production.
4004
4005 if (TryToParseTemplateArgs && look() == 'I') {
Pavel Labathba825192018-10-16 14:29:14 +00004006 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00004007 if (TA == nullptr)
4008 return nullptr;
4009 Result = make<NameWithTemplateArgs>(Result, TA);
4010 }
4011 break;
4012 }
4013 // ::= P <type> # pointer
4014 case 'P': {
4015 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004016 Node *Ptr = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004017 if (Ptr == nullptr)
4018 return nullptr;
4019 Result = make<PointerType>(Ptr);
4020 break;
4021 }
4022 // ::= R <type> # l-value reference
4023 case 'R': {
4024 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004025 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004026 if (Ref == nullptr)
4027 return nullptr;
4028 Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
4029 break;
4030 }
4031 // ::= O <type> # r-value reference (C++11)
4032 case 'O': {
4033 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004034 Node *Ref = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004035 if (Ref == nullptr)
4036 return nullptr;
4037 Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
4038 break;
4039 }
4040 // ::= C <type> # complex pair (C99)
4041 case 'C': {
4042 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004043 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004044 if (P == nullptr)
4045 return nullptr;
4046 Result = make<PostfixQualifiedType>(P, " complex");
4047 break;
4048 }
4049 // ::= G <type> # imaginary (C99)
4050 case 'G': {
4051 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004052 Node *P = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004053 if (P == nullptr)
4054 return P;
4055 Result = make<PostfixQualifiedType>(P, " imaginary");
4056 break;
4057 }
4058 // ::= <substitution> # See Compression below
4059 case 'S': {
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08004060 if (look(1) != 't') {
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004061 bool IsSubst = false;
4062 Result = getDerived().parseUnscopedName(nullptr, &IsSubst);
4063 if (!Result)
Richard Smithc20d1442018-08-20 20:14:49 +00004064 return nullptr;
4065
4066 // Sub could be either of:
4067 // <type> ::= <substitution>
4068 // <type> ::= <template-template-param> <template-args>
4069 //
4070 // <template-template-param> ::= <template-param>
4071 // ::= <substitution>
4072 //
4073 // If this is followed by some <template-args>, and we're permitted to
4074 // parse them, take the second production.
4075
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004076 if (look() == 'I' && (!IsSubst || TryToParseTemplateArgs)) {
4077 if (!IsSubst)
4078 Subs.push_back(Result);
Pavel Labathba825192018-10-16 14:29:14 +00004079 Node *TA = getDerived().parseTemplateArgs();
Richard Smithc20d1442018-08-20 20:14:49 +00004080 if (TA == nullptr)
4081 return nullptr;
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08004082 Result = make<NameWithTemplateArgs>(Result, TA);
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004083 } else if (IsSubst) {
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08004084 // If all we parsed was a substitution, don't re-insert into the
4085 // substitution table.
4086 return Result;
Richard Smithc20d1442018-08-20 20:14:49 +00004087 }
Nathan Sidwelle4cc3532022-01-24 04:28:09 -08004088 break;
Richard Smithc20d1442018-08-20 20:14:49 +00004089 }
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00004090 DEMANGLE_FALLTHROUGH;
Richard Smithc20d1442018-08-20 20:14:49 +00004091 }
4092 // ::= <class-enum-type>
4093 default: {
Pavel Labathba825192018-10-16 14:29:14 +00004094 Result = getDerived().parseClassEnumType();
Richard Smithc20d1442018-08-20 20:14:49 +00004095 break;
4096 }
4097 }
4098
4099 // If we parsed a type, insert it into the substitution table. Note that all
4100 // <builtin-type>s and <substitution>s have already bailed out, because they
4101 // don't get substitutions.
4102 if (Result != nullptr)
4103 Subs.push_back(Result);
4104 return Result;
4105}
4106
Pavel Labathba825192018-10-16 14:29:14 +00004107template <typename Derived, typename Alloc>
4108Node *AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(StringView Kind) {
4109 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004110 if (E == nullptr)
4111 return nullptr;
4112 return make<PrefixExpr>(Kind, E);
4113}
4114
Pavel Labathba825192018-10-16 14:29:14 +00004115template <typename Derived, typename Alloc>
4116Node *AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(StringView Kind) {
4117 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004118 if (LHS == nullptr)
4119 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004120 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004121 if (RHS == nullptr)
4122 return nullptr;
4123 return make<BinaryExpr>(LHS, Kind, RHS);
4124}
4125
Pavel Labathba825192018-10-16 14:29:14 +00004126template <typename Derived, typename Alloc>
4127Node *
4128AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(StringView Lit) {
Richard Smithc20d1442018-08-20 20:14:49 +00004129 StringView Tmp = parseNumber(true);
4130 if (!Tmp.empty() && consumeIf('E'))
4131 return make<IntegerLiteral>(Lit, Tmp);
4132 return nullptr;
4133}
4134
4135// <CV-Qualifiers> ::= [r] [V] [K]
Pavel Labathba825192018-10-16 14:29:14 +00004136template <typename Alloc, typename Derived>
4137Qualifiers AbstractManglingParser<Alloc, Derived>::parseCVQualifiers() {
Richard Smithc20d1442018-08-20 20:14:49 +00004138 Qualifiers CVR = QualNone;
4139 if (consumeIf('r'))
4140 CVR |= QualRestrict;
4141 if (consumeIf('V'))
4142 CVR |= QualVolatile;
4143 if (consumeIf('K'))
4144 CVR |= QualConst;
4145 return CVR;
4146}
4147
4148// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
4149// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
4150// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
4151// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
Erik Pilkington91c24af2020-05-13 22:19:45 -04004152// ::= fpT # 'this' expression (not part of standard?)
Pavel Labathba825192018-10-16 14:29:14 +00004153template <typename Derived, typename Alloc>
4154Node *AbstractManglingParser<Derived, Alloc>::parseFunctionParam() {
Erik Pilkington91c24af2020-05-13 22:19:45 -04004155 if (consumeIf("fpT"))
4156 return make<NameType>("this");
Richard Smithc20d1442018-08-20 20:14:49 +00004157 if (consumeIf("fp")) {
4158 parseCVQualifiers();
4159 StringView Num = parseNumber();
4160 if (!consumeIf('_'))
4161 return nullptr;
4162 return make<FunctionParam>(Num);
4163 }
4164 if (consumeIf("fL")) {
4165 if (parseNumber().empty())
4166 return nullptr;
4167 if (!consumeIf('p'))
4168 return nullptr;
4169 parseCVQualifiers();
4170 StringView Num = parseNumber();
4171 if (!consumeIf('_'))
4172 return nullptr;
4173 return make<FunctionParam>(Num);
4174 }
4175 return nullptr;
4176}
4177
Richard Smithc20d1442018-08-20 20:14:49 +00004178// cv <type> <expression> # conversion with one argument
4179// cv <type> _ <expression>* E # conversion with a different number of arguments
Pavel Labathba825192018-10-16 14:29:14 +00004180template <typename Derived, typename Alloc>
4181Node *AbstractManglingParser<Derived, Alloc>::parseConversionExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004182 if (!consumeIf("cv"))
4183 return nullptr;
4184 Node *Ty;
4185 {
4186 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Pavel Labathba825192018-10-16 14:29:14 +00004187 Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004188 }
4189
4190 if (Ty == nullptr)
4191 return nullptr;
4192
4193 if (consumeIf('_')) {
4194 size_t ExprsBegin = Names.size();
4195 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00004196 Node *E = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004197 if (E == nullptr)
4198 return E;
4199 Names.push_back(E);
4200 }
4201 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
4202 return make<ConversionExpr>(Ty, Exprs);
4203 }
4204
Pavel Labathba825192018-10-16 14:29:14 +00004205 Node *E[1] = {getDerived().parseExpr()};
Richard Smithc20d1442018-08-20 20:14:49 +00004206 if (E[0] == nullptr)
4207 return nullptr;
4208 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
4209}
4210
4211// <expr-primary> ::= L <type> <value number> E # integer literal
4212// ::= L <type> <value float> E # floating literal
4213// ::= L <string type> E # string literal
4214// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
Richard Smithdf1c14c2019-09-06 23:53:21 +00004215// ::= L <lambda type> E # lambda expression
Richard Smithc20d1442018-08-20 20:14:49 +00004216// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
4217// ::= L <mangled-name> E # external name
Pavel Labathba825192018-10-16 14:29:14 +00004218template <typename Derived, typename Alloc>
4219Node *AbstractManglingParser<Derived, Alloc>::parseExprPrimary() {
Richard Smithc20d1442018-08-20 20:14:49 +00004220 if (!consumeIf('L'))
4221 return nullptr;
4222 switch (look()) {
4223 case 'w':
4224 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004225 return getDerived().parseIntegerLiteral("wchar_t");
Richard Smithc20d1442018-08-20 20:14:49 +00004226 case 'b':
4227 if (consumeIf("b0E"))
4228 return make<BoolExpr>(0);
4229 if (consumeIf("b1E"))
4230 return make<BoolExpr>(1);
4231 return nullptr;
4232 case 'c':
4233 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004234 return getDerived().parseIntegerLiteral("char");
Richard Smithc20d1442018-08-20 20:14:49 +00004235 case 'a':
4236 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004237 return getDerived().parseIntegerLiteral("signed char");
Richard Smithc20d1442018-08-20 20:14:49 +00004238 case 'h':
4239 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004240 return getDerived().parseIntegerLiteral("unsigned char");
Richard Smithc20d1442018-08-20 20:14:49 +00004241 case 's':
4242 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004243 return getDerived().parseIntegerLiteral("short");
Richard Smithc20d1442018-08-20 20:14:49 +00004244 case 't':
4245 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004246 return getDerived().parseIntegerLiteral("unsigned short");
Richard Smithc20d1442018-08-20 20:14:49 +00004247 case 'i':
4248 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004249 return getDerived().parseIntegerLiteral("");
Richard Smithc20d1442018-08-20 20:14:49 +00004250 case 'j':
4251 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004252 return getDerived().parseIntegerLiteral("u");
Richard Smithc20d1442018-08-20 20:14:49 +00004253 case 'l':
4254 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004255 return getDerived().parseIntegerLiteral("l");
Richard Smithc20d1442018-08-20 20:14:49 +00004256 case 'm':
4257 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004258 return getDerived().parseIntegerLiteral("ul");
Richard Smithc20d1442018-08-20 20:14:49 +00004259 case 'x':
4260 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004261 return getDerived().parseIntegerLiteral("ll");
Richard Smithc20d1442018-08-20 20:14:49 +00004262 case 'y':
4263 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004264 return getDerived().parseIntegerLiteral("ull");
Richard Smithc20d1442018-08-20 20:14:49 +00004265 case 'n':
4266 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004267 return getDerived().parseIntegerLiteral("__int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004268 case 'o':
4269 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004270 return getDerived().parseIntegerLiteral("unsigned __int128");
Richard Smithc20d1442018-08-20 20:14:49 +00004271 case 'f':
4272 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004273 return getDerived().template parseFloatingLiteral<float>();
Richard Smithc20d1442018-08-20 20:14:49 +00004274 case 'd':
4275 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00004276 return getDerived().template parseFloatingLiteral<double>();
Richard Smithc20d1442018-08-20 20:14:49 +00004277 case 'e':
4278 ++First;
Xing Xue3dc5e082020-04-15 09:59:06 -04004279#if defined(__powerpc__) || defined(__s390__)
4280 // Handle cases where long doubles encoded with e have the same size
4281 // and representation as doubles.
4282 return getDerived().template parseFloatingLiteral<double>();
4283#else
Pavel Labathba825192018-10-16 14:29:14 +00004284 return getDerived().template parseFloatingLiteral<long double>();
Xing Xue3dc5e082020-04-15 09:59:06 -04004285#endif
Richard Smithc20d1442018-08-20 20:14:49 +00004286 case '_':
4287 if (consumeIf("_Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00004288 Node *R = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00004289 if (R != nullptr && consumeIf('E'))
4290 return R;
4291 }
4292 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00004293 case 'A': {
4294 Node *T = getDerived().parseType();
4295 if (T == nullptr)
4296 return nullptr;
4297 // FIXME: We need to include the string contents in the mangling.
4298 if (consumeIf('E'))
4299 return make<StringLiteral>(T);
4300 return nullptr;
4301 }
4302 case 'D':
4303 if (consumeIf("DnE"))
4304 return make<NameType>("nullptr");
4305 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004306 case 'T':
4307 // Invalid mangled name per
4308 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
4309 return nullptr;
Richard Smithfb917462019-09-09 22:26:04 +00004310 case 'U': {
4311 // FIXME: Should we support LUb... for block literals?
4312 if (look(1) != 'l')
4313 return nullptr;
4314 Node *T = parseUnnamedTypeName(nullptr);
4315 if (!T || !consumeIf('E'))
4316 return nullptr;
4317 return make<LambdaExpr>(T);
4318 }
Richard Smithc20d1442018-08-20 20:14:49 +00004319 default: {
4320 // might be named type
Pavel Labathba825192018-10-16 14:29:14 +00004321 Node *T = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004322 if (T == nullptr)
4323 return nullptr;
Erik Pilkington0a170f12020-05-13 14:13:37 -04004324 StringView N = parseNumber(/*AllowNegative=*/true);
Richard Smithfb917462019-09-09 22:26:04 +00004325 if (N.empty())
4326 return nullptr;
4327 if (!consumeIf('E'))
4328 return nullptr;
Erik Pilkington0a170f12020-05-13 14:13:37 -04004329 return make<EnumLiteral>(T, N);
Richard Smithc20d1442018-08-20 20:14:49 +00004330 }
4331 }
4332}
4333
4334// <braced-expression> ::= <expression>
4335// ::= di <field source-name> <braced-expression> # .name = expr
4336// ::= dx <index expression> <braced-expression> # [expr] = expr
4337// ::= dX <range begin expression> <range end expression> <braced-expression>
Pavel Labathba825192018-10-16 14:29:14 +00004338template <typename Derived, typename Alloc>
4339Node *AbstractManglingParser<Derived, Alloc>::parseBracedExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004340 if (look() == 'd') {
4341 switch (look(1)) {
4342 case 'i': {
4343 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004344 Node *Field = getDerived().parseSourceName(/*NameState=*/nullptr);
Richard Smithc20d1442018-08-20 20:14:49 +00004345 if (Field == nullptr)
4346 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004347 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004348 if (Init == nullptr)
4349 return nullptr;
4350 return make<BracedExpr>(Field, Init, /*isArray=*/false);
4351 }
4352 case 'x': {
4353 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004354 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004355 if (Index == nullptr)
4356 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004357 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004358 if (Init == nullptr)
4359 return nullptr;
4360 return make<BracedExpr>(Index, Init, /*isArray=*/true);
4361 }
4362 case 'X': {
4363 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004364 Node *RangeBegin = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004365 if (RangeBegin == nullptr)
4366 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004367 Node *RangeEnd = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004368 if (RangeEnd == nullptr)
4369 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004370 Node *Init = getDerived().parseBracedExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004371 if (Init == nullptr)
4372 return nullptr;
4373 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
4374 }
4375 }
4376 }
Pavel Labathba825192018-10-16 14:29:14 +00004377 return getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004378}
4379
4380// (not yet in the spec)
4381// <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
4382// ::= fR <binary-operator-name> <expression> <expression>
4383// ::= fl <binary-operator-name> <expression>
4384// ::= fr <binary-operator-name> <expression>
Pavel Labathba825192018-10-16 14:29:14 +00004385template <typename Derived, typename Alloc>
4386Node *AbstractManglingParser<Derived, Alloc>::parseFoldExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004387 if (!consumeIf('f'))
4388 return nullptr;
4389
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004390 bool IsLeftFold = false, HasInitializer = false;
4391 switch (look()) {
4392 default:
Richard Smithc20d1442018-08-20 20:14:49 +00004393 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004394 case 'L':
4395 IsLeftFold = true;
4396 HasInitializer = true;
4397 break;
4398 case 'R':
4399 HasInitializer = true;
4400 break;
4401 case 'l':
4402 IsLeftFold = true;
4403 break;
4404 case 'r':
4405 break;
4406 }
Richard Smithc20d1442018-08-20 20:14:49 +00004407 ++First;
4408
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004409 const auto *Op = parseOperatorEncoding();
4410 if (!Op || Op->getKind() != OperatorInfo::Binary)
4411 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004412
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004413 Node *Pack = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004414 if (Pack == nullptr)
4415 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004416
4417 Node *Init = nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004418 if (HasInitializer) {
Pavel Labathba825192018-10-16 14:29:14 +00004419 Init = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004420 if (Init == nullptr)
4421 return nullptr;
4422 }
4423
4424 if (IsLeftFold && Init)
4425 std::swap(Pack, Init);
4426
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004427 return make<FoldExpr>(IsLeftFold, Op->getSymbol(), Pack, Init);
Richard Smithc20d1442018-08-20 20:14:49 +00004428}
4429
Richard Smith1865d2f2020-10-22 19:29:36 -07004430// <expression> ::= mc <parameter type> <expr> [<offset number>] E
4431//
4432// Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/47
4433template <typename Derived, typename Alloc>
4434Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberConversionExpr() {
4435 Node *Ty = getDerived().parseType();
4436 if (!Ty)
4437 return nullptr;
4438 Node *Expr = getDerived().parseExpr();
4439 if (!Expr)
4440 return nullptr;
4441 StringView Offset = getDerived().parseNumber(true);
4442 if (!consumeIf('E'))
4443 return nullptr;
4444 return make<PointerToMemberConversionExpr>(Ty, Expr, Offset);
4445}
4446
4447// <expression> ::= so <referent type> <expr> [<offset number>] <union-selector>* [p] E
4448// <union-selector> ::= _ [<number>]
4449//
4450// Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/47
4451template <typename Derived, typename Alloc>
4452Node *AbstractManglingParser<Derived, Alloc>::parseSubobjectExpr() {
4453 Node *Ty = getDerived().parseType();
4454 if (!Ty)
4455 return nullptr;
4456 Node *Expr = getDerived().parseExpr();
4457 if (!Expr)
4458 return nullptr;
4459 StringView Offset = getDerived().parseNumber(true);
4460 size_t SelectorsBegin = Names.size();
4461 while (consumeIf('_')) {
4462 Node *Selector = make<NameType>(parseNumber());
4463 if (!Selector)
4464 return nullptr;
4465 Names.push_back(Selector);
4466 }
4467 bool OnePastTheEnd = consumeIf('p');
4468 if (!consumeIf('E'))
4469 return nullptr;
4470 return make<SubobjectExpr>(
4471 Ty, Expr, Offset, popTrailingNodeArray(SelectorsBegin), OnePastTheEnd);
4472}
4473
Richard Smithc20d1442018-08-20 20:14:49 +00004474// <expression> ::= <unary operator-name> <expression>
4475// ::= <binary operator-name> <expression> <expression>
4476// ::= <ternary operator-name> <expression> <expression> <expression>
4477// ::= cl <expression>+ E # call
4478// ::= cv <type> <expression> # conversion with one argument
4479// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4480// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
4481// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
4482// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
4483// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
4484// ::= [gs] dl <expression> # delete expression
4485// ::= [gs] da <expression> # delete[] expression
4486// ::= pp_ <expression> # prefix ++
4487// ::= mm_ <expression> # prefix --
4488// ::= ti <type> # typeid (type)
4489// ::= te <expression> # typeid (expression)
4490// ::= dc <type> <expression> # dynamic_cast<type> (expression)
4491// ::= sc <type> <expression> # static_cast<type> (expression)
4492// ::= cc <type> <expression> # const_cast<type> (expression)
4493// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4494// ::= st <type> # sizeof (a type)
4495// ::= sz <expression> # sizeof (an expression)
4496// ::= at <type> # alignof (a type)
4497// ::= az <expression> # alignof (an expression)
4498// ::= nx <expression> # noexcept (expression)
4499// ::= <template-param>
4500// ::= <function-param>
4501// ::= dt <expression> <unresolved-name> # expr.name
4502// ::= pt <expression> <unresolved-name> # expr->name
4503// ::= ds <expression> <expression> # expr.*expr
4504// ::= sZ <template-param> # size of a parameter pack
4505// ::= sZ <function-param> # size of a function parameter pack
4506// ::= sP <template-arg>* E # sizeof...(T), size of a captured template parameter pack from an alias template
4507// ::= sp <expression> # pack expansion
4508// ::= tw <expression> # throw expression
4509// ::= tr # throw with no operand (rethrow)
4510// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
4511// # freestanding dependent name (e.g., T::x),
4512// # objectless nonstatic member reference
4513// ::= fL <binary-operator-name> <expression> <expression>
4514// ::= fR <binary-operator-name> <expression> <expression>
4515// ::= fl <binary-operator-name> <expression>
4516// ::= fr <binary-operator-name> <expression>
4517// ::= <expr-primary>
Pavel Labathba825192018-10-16 14:29:14 +00004518template <typename Derived, typename Alloc>
4519Node *AbstractManglingParser<Derived, Alloc>::parseExpr() {
Richard Smithc20d1442018-08-20 20:14:49 +00004520 bool Global = consumeIf("gs");
Richard Smithc20d1442018-08-20 20:14:49 +00004521
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004522 const auto *Op = parseOperatorEncoding();
4523 if (Op) {
4524 auto Sym = Op->getSymbol();
4525 switch (Op->getKind()) {
4526 case OperatorInfo::Binary:
4527 // Binary operator: lhs @ rhs
4528 return getDerived().parseBinaryExpr(Sym);
4529 case OperatorInfo::Prefix:
4530 // Prefix unary operator: @ expr
4531 return getDerived().parsePrefixExpr(Sym);
4532 case OperatorInfo::Postfix: {
4533 // Postfix unary operator: expr @
4534 if (consumeIf('_'))
4535 return getDerived().parsePrefixExpr(Sym);
Pavel Labathba825192018-10-16 14:29:14 +00004536 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004537 if (Ex == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004538 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004539 return make<PostfixExpr>(Ex, Sym);
Richard Smithc20d1442018-08-20 20:14:49 +00004540 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004541 case OperatorInfo::Array: {
4542 // Array Index: lhs [ rhs ]
Pavel Labathba825192018-10-16 14:29:14 +00004543 Node *Base = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004544 if (Base == nullptr)
4545 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004546 Node *Index = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004547 if (Index == nullptr)
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004548 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00004549 return make<ArraySubscriptExpr>(Base, Index);
4550 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004551 case OperatorInfo::Member: {
4552 // Member access lhs @ rhs
4553 Node *LHS = getDerived().parseExpr();
4554 if (LHS == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004555 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004556 Node *RHS = getDerived().parseExpr();
4557 if (RHS == nullptr)
4558 return nullptr;
4559 return make<MemberExpr>(LHS, Sym, RHS);
Richard Smithc20d1442018-08-20 20:14:49 +00004560 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004561 case OperatorInfo::New: {
4562 // New
4563 // # new (expr-list) type [(init)]
4564 // [gs] nw <expression>* _ <type> [pi <expression>*] E
4565 // # new[] (expr-list) type [(init)]
4566 // [gs] na <expression>* _ <type> [pi <expression>*] E
Nathan Sidwellc69bde22022-01-28 07:09:38 -08004567 size_t Exprs = Names.size();
4568 while (!consumeIf('_')) {
4569 Node *Ex = getDerived().parseExpr();
4570 if (Ex == nullptr)
4571 return nullptr;
4572 Names.push_back(Ex);
4573 }
4574 NodeArray ExprList = popTrailingNodeArray(Exprs);
4575 Node *Ty = getDerived().parseType();
4576 if (Ty == nullptr)
4577 return nullptr;
4578 bool HaveInits = consumeIf("pi");
4579 size_t InitsBegin = Names.size();
4580 while (!consumeIf('E')) {
4581 if (!HaveInits)
4582 return nullptr;
4583 Node *Init = getDerived().parseExpr();
4584 if (Init == nullptr)
4585 return Init;
4586 Names.push_back(Init);
4587 }
4588 NodeArray Inits = popTrailingNodeArray(InitsBegin);
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004589 return make<NewExpr>(ExprList, Ty, Inits, Global,
4590 /*IsArray=*/Op->getFlag());
Nathan Sidwellc69bde22022-01-28 07:09:38 -08004591 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004592 case OperatorInfo::Del: {
4593 // Delete
Pavel Labathba825192018-10-16 14:29:14 +00004594 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004595 if (Ex == nullptr)
Nathan Sidwellc6483042022-01-28 09:27:28 -08004596 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004597 return make<DeleteExpr>(Ex, Global, /*IsArray=*/Op->getFlag());
Nathan Sidwellc6483042022-01-28 09:27:28 -08004598 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004599 case OperatorInfo::Call: {
4600 // Function Call
4601 Node *Callee = getDerived().parseExpr();
4602 if (Callee == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004603 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004604 size_t ExprsBegin = Names.size();
4605 while (!consumeIf('E')) {
4606 Node *E = getDerived().parseExpr();
4607 if (E == nullptr)
4608 return nullptr;
4609 Names.push_back(E);
4610 }
4611 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
4612 }
4613 case OperatorInfo::CCast: {
4614 // C Cast: (type)expr
4615 Node *Ty;
4616 {
4617 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
4618 Ty = getDerived().parseType();
4619 }
4620 if (Ty == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004621 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004622
4623 size_t ExprsBegin = Names.size();
4624 bool IsMany = consumeIf('_');
4625 while (!consumeIf('E')) {
4626 Node *E = getDerived().parseExpr();
4627 if (E == nullptr)
4628 return E;
4629 Names.push_back(E);
4630 if (!IsMany)
4631 break;
4632 }
4633 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
4634 if (!IsMany && Exprs.size() != 1)
4635 return nullptr;
4636 return make<ConversionExpr>(Ty, Exprs);
Richard Smithc20d1442018-08-20 20:14:49 +00004637 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004638 case OperatorInfo::Conditional: {
4639 // Conditional operator: expr ? expr : expr
Pavel Labathba825192018-10-16 14:29:14 +00004640 Node *Cond = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004641 if (Cond == nullptr)
4642 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004643 Node *LHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004644 if (LHS == nullptr)
4645 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004646 Node *RHS = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004647 if (RHS == nullptr)
4648 return nullptr;
4649 return make<ConditionalExpr>(Cond, LHS, RHS);
4650 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004651 case OperatorInfo::NamedCast: {
4652 // Named cast operation, @<type>(expr)
Pavel Labathba825192018-10-16 14:29:14 +00004653 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004654 if (Ty == nullptr)
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004655 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004656 Node *Ex = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00004657 if (Ex == nullptr)
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004658 return nullptr;
4659 return make<CastExpr>(Sym, Ty, Ex);
Richard Smithc20d1442018-08-20 20:14:49 +00004660 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004661 case OperatorInfo::OfIdOp: {
4662 // [sizeof/alignof/typeid] ( <type>|<expr> )
4663 Node *Arg =
4664 Op->getFlag() ? getDerived().parseType() : getDerived().parseExpr();
4665 if (!Arg)
4666 return nullptr;
4667 return make<EnclosingExpr>(Sym, Arg, ")");
4668 }
Nathan Sidwell0dda3d42022-02-18 09:51:24 -08004669 case OperatorInfo::NameOnly: {
4670 // Not valid as an expression operand.
4671 return nullptr;
4672 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004673 }
4674 DEMANGLE_UNREACHABLE;
4675 }
4676
4677 if (numLeft() < 2)
4678 return nullptr;
4679
4680 if (look() == 'L')
4681 return getDerived().parseExprPrimary();
4682 if (look() == 'T')
4683 return getDerived().parseTemplateParam();
4684 if (look() == 'f') {
4685 // Disambiguate a fold expression from a <function-param>.
4686 if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
4687 return getDerived().parseFunctionParam();
4688 return getDerived().parseFoldExpr();
4689 }
4690 if (consumeIf("il")) {
4691 size_t InitsBegin = Names.size();
4692 while (!consumeIf('E')) {
4693 Node *E = getDerived().parseBracedExpr();
4694 if (E == nullptr)
4695 return nullptr;
4696 Names.push_back(E);
4697 }
4698 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4699 }
4700 if (consumeIf("mc"))
4701 return parsePointerToMemberConversionExpr();
4702 if (consumeIf("nx")) {
4703 Node *Ex = getDerived().parseExpr();
4704 if (Ex == nullptr)
4705 return Ex;
4706 return make<EnclosingExpr>("noexcept (", Ex, ")");
4707 }
4708 if (consumeIf("so"))
4709 return parseSubobjectExpr();
4710 if (consumeIf("sp")) {
4711 Node *Child = getDerived().parseExpr();
4712 if (Child == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004713 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004714 return make<ParameterPackExpansion>(Child);
4715 }
4716 if (consumeIf("sZ")) {
4717 if (look() == 'T') {
4718 Node *R = getDerived().parseTemplateParam();
4719 if (R == nullptr)
Richard Smithb485b352018-08-24 23:30:26 +00004720 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004721 return make<SizeofParamPackExpr>(R);
Richard Smithc20d1442018-08-20 20:14:49 +00004722 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004723 Node *FP = getDerived().parseFunctionParam();
4724 if (FP == nullptr)
4725 return nullptr;
4726 return make<EnclosingExpr>("sizeof... (", FP, ")");
4727 }
4728 if (consumeIf("sP")) {
4729 size_t ArgsBegin = Names.size();
4730 while (!consumeIf('E')) {
4731 Node *Arg = getDerived().parseTemplateArg();
4732 if (Arg == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004733 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004734 Names.push_back(Arg);
Richard Smithc20d1442018-08-20 20:14:49 +00004735 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004736 auto *Pack = make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin));
4737 if (!Pack)
4738 return nullptr;
4739 return make<EnclosingExpr>("sizeof... (", Pack, ")");
4740 }
4741 if (consumeIf("tl")) {
4742 Node *Ty = getDerived().parseType();
4743 if (Ty == nullptr)
4744 return nullptr;
4745 size_t InitsBegin = Names.size();
4746 while (!consumeIf('E')) {
4747 Node *E = getDerived().parseBracedExpr();
4748 if (E == nullptr)
Richard Smithc20d1442018-08-20 20:14:49 +00004749 return nullptr;
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004750 Names.push_back(E);
Richard Smithc20d1442018-08-20 20:14:49 +00004751 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004752 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4753 }
4754 if (consumeIf("tr"))
4755 return make<NameType>("throw");
4756 if (consumeIf("tw")) {
4757 Node *Ex = getDerived().parseExpr();
4758 if (Ex == nullptr)
4759 return nullptr;
4760 return make<ThrowExpr>(Ex);
4761 }
4762 if (consumeIf('u')) {
James Y Knight4a60efc2020-12-07 10:26:49 -05004763 Node *Name = getDerived().parseSourceName(/*NameState=*/nullptr);
4764 if (!Name)
4765 return nullptr;
4766 // Special case legacy __uuidof mangling. The 't' and 'z' appear where the
4767 // standard encoding expects a <template-arg>, and would be otherwise be
4768 // interpreted as <type> node 'short' or 'ellipsis'. However, neither
4769 // __uuidof(short) nor __uuidof(...) can actually appear, so there is no
4770 // actual conflict here.
Nathan Sidwella3b59002022-02-11 05:54:40 -08004771 bool IsUUID = false;
4772 Node *UUID = nullptr;
James Y Knight4a60efc2020-12-07 10:26:49 -05004773 if (Name->getBaseName() == "__uuidof") {
Nathan Sidwella3b59002022-02-11 05:54:40 -08004774 if (consumeIf('t')) {
4775 UUID = getDerived().parseType();
4776 IsUUID = true;
4777 } else if (consumeIf('z')) {
4778 UUID = getDerived().parseExpr();
4779 IsUUID = true;
James Y Knight4a60efc2020-12-07 10:26:49 -05004780 }
4781 }
4782 size_t ExprsBegin = Names.size();
Nathan Sidwella3b59002022-02-11 05:54:40 -08004783 if (IsUUID) {
4784 if (UUID == nullptr)
4785 return nullptr;
4786 Names.push_back(UUID);
4787 } else {
4788 while (!consumeIf('E')) {
4789 Node *E = getDerived().parseTemplateArg();
4790 if (E == nullptr)
4791 return E;
4792 Names.push_back(E);
4793 }
James Y Knight4a60efc2020-12-07 10:26:49 -05004794 }
4795 return make<CallExpr>(Name, popTrailingNodeArray(ExprsBegin));
4796 }
Nathan Sidwell12b2ce72022-01-27 13:23:16 -08004797
4798 // Only unresolved names remain.
4799 return getDerived().parseUnresolvedName(Global);
Richard Smithc20d1442018-08-20 20:14:49 +00004800}
4801
4802// <call-offset> ::= h <nv-offset> _
4803// ::= v <v-offset> _
4804//
4805// <nv-offset> ::= <offset number>
4806// # non-virtual base override
4807//
4808// <v-offset> ::= <offset number> _ <virtual offset number>
4809// # virtual base override, with vcall offset
Pavel Labathba825192018-10-16 14:29:14 +00004810template <typename Alloc, typename Derived>
4811bool AbstractManglingParser<Alloc, Derived>::parseCallOffset() {
Richard Smithc20d1442018-08-20 20:14:49 +00004812 // Just scan through the call offset, we never add this information into the
4813 // output.
4814 if (consumeIf('h'))
4815 return parseNumber(true).empty() || !consumeIf('_');
4816 if (consumeIf('v'))
4817 return parseNumber(true).empty() || !consumeIf('_') ||
4818 parseNumber(true).empty() || !consumeIf('_');
4819 return true;
4820}
4821
4822// <special-name> ::= TV <type> # virtual table
4823// ::= TT <type> # VTT structure (construction vtable index)
4824// ::= TI <type> # typeinfo structure
4825// ::= TS <type> # typeinfo name (null-terminated byte string)
4826// ::= Tc <call-offset> <call-offset> <base encoding>
4827// # base is the nominal target function of thunk
4828// # first call-offset is 'this' adjustment
4829// # second call-offset is result adjustment
4830// ::= T <call-offset> <base encoding>
4831// # base is the nominal target function of thunk
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004832// # Guard variable for one-time initialization
4833// ::= GV <object name>
Richard Smithc20d1442018-08-20 20:14:49 +00004834// # No <type>
4835// ::= TW <object name> # Thread-local wrapper
4836// ::= TH <object name> # Thread-local initialization
4837// ::= GR <object name> _ # First temporary
4838// ::= GR <object name> <seq-id> _ # Subsequent temporaries
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004839// # construction vtable for second-in-first
4840// extension ::= TC <first type> <number> _ <second type>
Richard Smithc20d1442018-08-20 20:14:49 +00004841// extension ::= GR <object name> # reference temporary for object
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004842// extension ::= GI <module name> # module global initializer
Pavel Labathba825192018-10-16 14:29:14 +00004843template <typename Derived, typename Alloc>
4844Node *AbstractManglingParser<Derived, Alloc>::parseSpecialName() {
Richard Smithc20d1442018-08-20 20:14:49 +00004845 switch (look()) {
4846 case 'T':
4847 switch (look(1)) {
Richard Smith1865d2f2020-10-22 19:29:36 -07004848 // TA <template-arg> # template parameter object
4849 //
4850 // Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/63
4851 case 'A': {
4852 First += 2;
4853 Node *Arg = getDerived().parseTemplateArg();
4854 if (Arg == nullptr)
4855 return nullptr;
4856 return make<SpecialName>("template parameter object for ", Arg);
4857 }
Richard Smithc20d1442018-08-20 20:14:49 +00004858 // TV <type> # virtual table
4859 case 'V': {
4860 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004861 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004862 if (Ty == nullptr)
4863 return nullptr;
4864 return make<SpecialName>("vtable for ", Ty);
4865 }
4866 // TT <type> # VTT structure (construction vtable index)
4867 case 'T': {
4868 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004869 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004870 if (Ty == nullptr)
4871 return nullptr;
4872 return make<SpecialName>("VTT for ", Ty);
4873 }
4874 // TI <type> # typeinfo structure
4875 case 'I': {
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 nullptr;
4880 return make<SpecialName>("typeinfo for ", Ty);
4881 }
4882 // TS <type> # typeinfo name (null-terminated byte string)
4883 case 'S': {
4884 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004885 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004886 if (Ty == nullptr)
4887 return nullptr;
4888 return make<SpecialName>("typeinfo name for ", Ty);
4889 }
4890 // Tc <call-offset> <call-offset> <base encoding>
4891 case 'c': {
4892 First += 2;
4893 if (parseCallOffset() || parseCallOffset())
4894 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004895 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00004896 if (Encoding == nullptr)
4897 return nullptr;
4898 return make<SpecialName>("covariant return thunk to ", Encoding);
4899 }
4900 // extension ::= TC <first type> <number> _ <second type>
4901 // # construction vtable for second-in-first
4902 case 'C': {
4903 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004904 Node *FirstType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004905 if (FirstType == nullptr)
4906 return nullptr;
4907 if (parseNumber(true).empty() || !consumeIf('_'))
4908 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004909 Node *SecondType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00004910 if (SecondType == nullptr)
4911 return nullptr;
4912 return make<CtorVtableSpecialName>(SecondType, FirstType);
4913 }
4914 // TW <object name> # Thread-local wrapper
4915 case 'W': {
4916 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004917 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00004918 if (Name == nullptr)
4919 return nullptr;
4920 return make<SpecialName>("thread-local wrapper routine for ", Name);
4921 }
4922 // TH <object name> # Thread-local initialization
4923 case 'H': {
4924 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004925 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00004926 if (Name == nullptr)
4927 return nullptr;
4928 return make<SpecialName>("thread-local initialization routine for ", Name);
4929 }
4930 // T <call-offset> <base encoding>
4931 default: {
4932 ++First;
4933 bool IsVirt = look() == 'v';
4934 if (parseCallOffset())
4935 return nullptr;
Pavel Labathba825192018-10-16 14:29:14 +00004936 Node *BaseEncoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00004937 if (BaseEncoding == nullptr)
4938 return nullptr;
4939 if (IsVirt)
4940 return make<SpecialName>("virtual thunk to ", BaseEncoding);
4941 else
4942 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
4943 }
4944 }
4945 case 'G':
4946 switch (look(1)) {
4947 // GV <object name> # Guard variable for one-time initialization
4948 case 'V': {
4949 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004950 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00004951 if (Name == nullptr)
4952 return nullptr;
4953 return make<SpecialName>("guard variable for ", Name);
4954 }
4955 // GR <object name> # reference temporary for object
4956 // GR <object name> _ # First temporary
4957 // GR <object name> <seq-id> _ # Subsequent temporaries
4958 case 'R': {
4959 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00004960 Node *Name = getDerived().parseName();
Richard Smithc20d1442018-08-20 20:14:49 +00004961 if (Name == nullptr)
4962 return nullptr;
4963 size_t Count;
4964 bool ParsedSeqId = !parseSeqId(&Count);
4965 if (!consumeIf('_') && ParsedSeqId)
4966 return nullptr;
4967 return make<SpecialName>("reference temporary for ", Name);
4968 }
Nathan Sidwelledde7bb2022-01-26 07:22:04 -08004969 // GI <module-name> v
4970 case 'I': {
4971 First += 2;
4972 ModuleName *Module = nullptr;
4973 if (getDerived().parseModuleNameOpt(Module))
4974 return nullptr;
4975 if (Module == nullptr)
4976 return nullptr;
4977 return make<SpecialName>("initializer for module ", Module);
4978 }
Richard Smithc20d1442018-08-20 20:14:49 +00004979 }
4980 }
4981 return nullptr;
4982}
4983
4984// <encoding> ::= <function name> <bare-function-type>
4985// ::= <data name>
4986// ::= <special-name>
Pavel Labathba825192018-10-16 14:29:14 +00004987template <typename Derived, typename Alloc>
4988Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
Richard Smithfac39712020-07-09 21:08:39 -07004989 // The template parameters of an encoding are unrelated to those of the
4990 // enclosing context.
4991 class SaveTemplateParams {
4992 AbstractManglingParser *Parser;
4993 decltype(TemplateParams) OldParams;
Justin Lebar2c536232021-06-09 16:57:22 -07004994 decltype(OuterTemplateParams) OldOuterParams;
Richard Smithfac39712020-07-09 21:08:39 -07004995
4996 public:
Louis Dionnec1fe8672020-10-30 17:33:02 -04004997 SaveTemplateParams(AbstractManglingParser *TheParser) : Parser(TheParser) {
Richard Smithfac39712020-07-09 21:08:39 -07004998 OldParams = std::move(Parser->TemplateParams);
Justin Lebar2c536232021-06-09 16:57:22 -07004999 OldOuterParams = std::move(Parser->OuterTemplateParams);
Richard Smithfac39712020-07-09 21:08:39 -07005000 Parser->TemplateParams.clear();
Justin Lebar2c536232021-06-09 16:57:22 -07005001 Parser->OuterTemplateParams.clear();
Richard Smithfac39712020-07-09 21:08:39 -07005002 }
5003 ~SaveTemplateParams() {
5004 Parser->TemplateParams = std::move(OldParams);
Justin Lebar2c536232021-06-09 16:57:22 -07005005 Parser->OuterTemplateParams = std::move(OldOuterParams);
Richard Smithfac39712020-07-09 21:08:39 -07005006 }
5007 } SaveTemplateParams(this);
Richard Smithfd434322020-07-09 20:36:04 -07005008
Richard Smithc20d1442018-08-20 20:14:49 +00005009 if (look() == 'G' || look() == 'T')
Pavel Labathba825192018-10-16 14:29:14 +00005010 return getDerived().parseSpecialName();
Richard Smithc20d1442018-08-20 20:14:49 +00005011
5012 auto IsEndOfEncoding = [&] {
5013 // The set of chars that can potentially follow an <encoding> (none of which
5014 // can start a <type>). Enumerating these allows us to avoid speculative
5015 // parsing.
5016 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
5017 };
5018
5019 NameState NameInfo(this);
Pavel Labathba825192018-10-16 14:29:14 +00005020 Node *Name = getDerived().parseName(&NameInfo);
Richard Smithc20d1442018-08-20 20:14:49 +00005021 if (Name == nullptr)
5022 return nullptr;
5023
5024 if (resolveForwardTemplateRefs(NameInfo))
5025 return nullptr;
5026
5027 if (IsEndOfEncoding())
5028 return Name;
5029
5030 Node *Attrs = nullptr;
5031 if (consumeIf("Ua9enable_ifI")) {
5032 size_t BeforeArgs = Names.size();
5033 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005034 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005035 if (Arg == nullptr)
5036 return nullptr;
5037 Names.push_back(Arg);
5038 }
5039 Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
Richard Smithb485b352018-08-24 23:30:26 +00005040 if (!Attrs)
5041 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005042 }
5043
5044 Node *ReturnType = nullptr;
5045 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
Pavel Labathba825192018-10-16 14:29:14 +00005046 ReturnType = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005047 if (ReturnType == nullptr)
5048 return nullptr;
5049 }
5050
5051 if (consumeIf('v'))
5052 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
5053 Attrs, NameInfo.CVQualifiers,
5054 NameInfo.ReferenceQualifier);
5055
5056 size_t ParamsBegin = Names.size();
5057 do {
Pavel Labathba825192018-10-16 14:29:14 +00005058 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005059 if (Ty == nullptr)
5060 return nullptr;
5061 Names.push_back(Ty);
5062 } while (!IsEndOfEncoding());
5063
5064 return make<FunctionEncoding>(ReturnType, Name,
5065 popTrailingNodeArray(ParamsBegin),
5066 Attrs, NameInfo.CVQualifiers,
5067 NameInfo.ReferenceQualifier);
5068}
5069
5070template <class Float>
5071struct FloatData;
5072
5073template <>
5074struct FloatData<float>
5075{
5076 static const size_t mangled_size = 8;
5077 static const size_t max_demangled_size = 24;
5078 static constexpr const char* spec = "%af";
5079};
5080
5081template <>
5082struct FloatData<double>
5083{
5084 static const size_t mangled_size = 16;
5085 static const size_t max_demangled_size = 32;
5086 static constexpr const char* spec = "%a";
5087};
5088
5089template <>
5090struct FloatData<long double>
5091{
5092#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
5093 defined(__wasm__)
5094 static const size_t mangled_size = 32;
5095#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
5096 static const size_t mangled_size = 16;
5097#else
5098 static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms
5099#endif
Elliott Hughes5a360ea2020-04-10 17:42:00 -07005100 // `-0x1.ffffffffffffffffffffffffffffp+16383` + 'L' + '\0' == 42 bytes.
5101 // 28 'f's * 4 bits == 112 bits, which is the number of mantissa bits.
5102 // Negatives are one character longer than positives.
5103 // `0x1.` and `p` are constant, and exponents `+16383` and `-16382` are the
5104 // same length. 1 sign bit, 112 mantissa bits, and 15 exponent bits == 128.
5105 static const size_t max_demangled_size = 42;
Richard Smithc20d1442018-08-20 20:14:49 +00005106 static constexpr const char *spec = "%LaL";
5107};
5108
Pavel Labathba825192018-10-16 14:29:14 +00005109template <typename Alloc, typename Derived>
5110template <class Float>
5111Node *AbstractManglingParser<Alloc, Derived>::parseFloatingLiteral() {
Richard Smithc20d1442018-08-20 20:14:49 +00005112 const size_t N = FloatData<Float>::mangled_size;
5113 if (numLeft() <= N)
5114 return nullptr;
5115 StringView Data(First, First + N);
5116 for (char C : Data)
5117 if (!std::isxdigit(C))
5118 return nullptr;
5119 First += N;
5120 if (!consumeIf('E'))
5121 return nullptr;
5122 return make<FloatLiteralImpl<Float>>(Data);
5123}
5124
5125// <seq-id> ::= <0-9A-Z>+
Pavel Labathba825192018-10-16 14:29:14 +00005126template <typename Alloc, typename Derived>
5127bool AbstractManglingParser<Alloc, Derived>::parseSeqId(size_t *Out) {
Richard Smithc20d1442018-08-20 20:14:49 +00005128 if (!(look() >= '0' && look() <= '9') &&
5129 !(look() >= 'A' && look() <= 'Z'))
5130 return true;
5131
5132 size_t Id = 0;
5133 while (true) {
5134 if (look() >= '0' && look() <= '9') {
5135 Id *= 36;
5136 Id += static_cast<size_t>(look() - '0');
5137 } else if (look() >= 'A' && look() <= 'Z') {
5138 Id *= 36;
5139 Id += static_cast<size_t>(look() - 'A') + 10;
5140 } else {
5141 *Out = Id;
5142 return false;
5143 }
5144 ++First;
5145 }
5146}
5147
5148// <substitution> ::= S <seq-id> _
5149// ::= S_
5150// <substitution> ::= Sa # ::std::allocator
5151// <substitution> ::= Sb # ::std::basic_string
5152// <substitution> ::= Ss # ::std::basic_string < char,
5153// ::std::char_traits<char>,
5154// ::std::allocator<char> >
5155// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
5156// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
5157// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
Nathan Sidwelle12f7bd2022-01-21 11:00:56 -08005158// The St case is handled specially in parseNestedName.
Pavel Labathba825192018-10-16 14:29:14 +00005159template <typename Derived, typename Alloc>
5160Node *AbstractManglingParser<Derived, Alloc>::parseSubstitution() {
Richard Smithc20d1442018-08-20 20:14:49 +00005161 if (!consumeIf('S'))
5162 return nullptr;
5163
Nathan Sidwellfd0ef6d2022-01-20 07:40:12 -08005164 if (look() >= 'a' && look() <= 'z') {
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005165 SpecialSubKind Kind;
Richard Smithc20d1442018-08-20 20:14:49 +00005166 switch (look()) {
5167 case 'a':
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005168 Kind = SpecialSubKind::allocator;
Richard Smithc20d1442018-08-20 20:14:49 +00005169 break;
5170 case 'b':
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005171 Kind = SpecialSubKind::basic_string;
Richard Smithc20d1442018-08-20 20:14:49 +00005172 break;
5173 case 'd':
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005174 Kind = SpecialSubKind::iostream;
5175 break;
5176 case 'i':
5177 Kind = SpecialSubKind::istream;
5178 break;
5179 case 'o':
5180 Kind = SpecialSubKind::ostream;
5181 break;
5182 case 's':
5183 Kind = SpecialSubKind::string;
Richard Smithc20d1442018-08-20 20:14:49 +00005184 break;
5185 default:
5186 return nullptr;
5187 }
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005188 ++First;
5189 auto *SpecialSub = make<SpecialSubstitution>(Kind);
Richard Smithb485b352018-08-24 23:30:26 +00005190 if (!SpecialSub)
5191 return nullptr;
Nathan Sidwelldf43e1b2022-01-24 07:59:57 -08005192
Richard Smithc20d1442018-08-20 20:14:49 +00005193 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
5194 // has ABI tags, the tags are appended to the substitution; the result is a
5195 // substitutable component.
Pavel Labathba825192018-10-16 14:29:14 +00005196 Node *WithTags = getDerived().parseAbiTags(SpecialSub);
Richard Smithc20d1442018-08-20 20:14:49 +00005197 if (WithTags != SpecialSub) {
5198 Subs.push_back(WithTags);
5199 SpecialSub = WithTags;
5200 }
5201 return SpecialSub;
5202 }
5203
5204 // ::= S_
5205 if (consumeIf('_')) {
5206 if (Subs.empty())
5207 return nullptr;
5208 return Subs[0];
5209 }
5210
5211 // ::= S <seq-id> _
5212 size_t Index = 0;
5213 if (parseSeqId(&Index))
5214 return nullptr;
5215 ++Index;
5216 if (!consumeIf('_') || Index >= Subs.size())
5217 return nullptr;
5218 return Subs[Index];
5219}
5220
5221// <template-param> ::= T_ # first template parameter
5222// ::= T <parameter-2 non-negative number> _
Richard Smithdf1c14c2019-09-06 23:53:21 +00005223// ::= TL <level-1> __
5224// ::= TL <level-1> _ <parameter-2 non-negative number> _
Pavel Labathba825192018-10-16 14:29:14 +00005225template <typename Derived, typename Alloc>
5226Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParam() {
Richard Smithc20d1442018-08-20 20:14:49 +00005227 if (!consumeIf('T'))
5228 return nullptr;
5229
Richard Smithdf1c14c2019-09-06 23:53:21 +00005230 size_t Level = 0;
5231 if (consumeIf('L')) {
5232 if (parsePositiveInteger(&Level))
5233 return nullptr;
5234 ++Level;
5235 if (!consumeIf('_'))
5236 return nullptr;
5237 }
5238
Richard Smithc20d1442018-08-20 20:14:49 +00005239 size_t Index = 0;
5240 if (!consumeIf('_')) {
5241 if (parsePositiveInteger(&Index))
5242 return nullptr;
5243 ++Index;
5244 if (!consumeIf('_'))
5245 return nullptr;
5246 }
5247
Richard Smithc20d1442018-08-20 20:14:49 +00005248 // If we're in a context where this <template-param> refers to a
5249 // <template-arg> further ahead in the mangled name (currently just conversion
5250 // operator types), then we should only look it up in the right context.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005251 // This can only happen at the outermost level.
5252 if (PermitForwardTemplateReferences && Level == 0) {
Richard Smithb485b352018-08-24 23:30:26 +00005253 Node *ForwardRef = make<ForwardTemplateReference>(Index);
5254 if (!ForwardRef)
5255 return nullptr;
5256 assert(ForwardRef->getKind() == Node::KForwardTemplateReference);
5257 ForwardTemplateRefs.push_back(
5258 static_cast<ForwardTemplateReference *>(ForwardRef));
5259 return ForwardRef;
Richard Smithc20d1442018-08-20 20:14:49 +00005260 }
5261
Richard Smithdf1c14c2019-09-06 23:53:21 +00005262 if (Level >= TemplateParams.size() || !TemplateParams[Level] ||
5263 Index >= TemplateParams[Level]->size()) {
5264 // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter
5265 // list are mangled as the corresponding artificial template type parameter.
5266 if (ParsingLambdaParamsAtLevel == Level && Level <= TemplateParams.size()) {
5267 // This will be popped by the ScopedTemplateParamList in
5268 // parseUnnamedTypeName.
5269 if (Level == TemplateParams.size())
5270 TemplateParams.push_back(nullptr);
5271 return make<NameType>("auto");
5272 }
5273
Richard Smithc20d1442018-08-20 20:14:49 +00005274 return nullptr;
Richard Smithdf1c14c2019-09-06 23:53:21 +00005275 }
5276
5277 return (*TemplateParams[Level])[Index];
5278}
5279
5280// <template-param-decl> ::= Ty # type parameter
5281// ::= Tn <type> # non-type parameter
5282// ::= Tt <template-param-decl>* E # template parameter
5283// ::= Tp <template-param-decl> # parameter pack
5284template <typename Derived, typename Alloc>
5285Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParamDecl() {
5286 auto InventTemplateParamName = [&](TemplateParamKind Kind) {
5287 unsigned Index = NumSyntheticTemplateParameters[(int)Kind]++;
5288 Node *N = make<SyntheticTemplateParamName>(Kind, Index);
5289 if (N) TemplateParams.back()->push_back(N);
5290 return N;
5291 };
5292
5293 if (consumeIf("Ty")) {
5294 Node *Name = InventTemplateParamName(TemplateParamKind::Type);
5295 if (!Name)
5296 return nullptr;
5297 return make<TypeTemplateParamDecl>(Name);
5298 }
5299
5300 if (consumeIf("Tn")) {
5301 Node *Name = InventTemplateParamName(TemplateParamKind::NonType);
5302 if (!Name)
5303 return nullptr;
5304 Node *Type = parseType();
5305 if (!Type)
5306 return nullptr;
5307 return make<NonTypeTemplateParamDecl>(Name, Type);
5308 }
5309
5310 if (consumeIf("Tt")) {
5311 Node *Name = InventTemplateParamName(TemplateParamKind::Template);
5312 if (!Name)
5313 return nullptr;
5314 size_t ParamsBegin = Names.size();
5315 ScopedTemplateParamList TemplateTemplateParamParams(this);
5316 while (!consumeIf("E")) {
5317 Node *P = parseTemplateParamDecl();
5318 if (!P)
5319 return nullptr;
5320 Names.push_back(P);
5321 }
5322 NodeArray Params = popTrailingNodeArray(ParamsBegin);
5323 return make<TemplateTemplateParamDecl>(Name, Params);
5324 }
5325
5326 if (consumeIf("Tp")) {
5327 Node *P = parseTemplateParamDecl();
5328 if (!P)
5329 return nullptr;
5330 return make<TemplateParamPackDecl>(P);
5331 }
5332
5333 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005334}
5335
5336// <template-arg> ::= <type> # type or template
5337// ::= X <expression> E # expression
5338// ::= <expr-primary> # simple expressions
5339// ::= J <template-arg>* E # argument pack
5340// ::= LZ <encoding> E # extension
Pavel Labathba825192018-10-16 14:29:14 +00005341template <typename Derived, typename Alloc>
5342Node *AbstractManglingParser<Derived, Alloc>::parseTemplateArg() {
Richard Smithc20d1442018-08-20 20:14:49 +00005343 switch (look()) {
5344 case 'X': {
5345 ++First;
Pavel Labathba825192018-10-16 14:29:14 +00005346 Node *Arg = getDerived().parseExpr();
Richard Smithc20d1442018-08-20 20:14:49 +00005347 if (Arg == nullptr || !consumeIf('E'))
5348 return nullptr;
5349 return Arg;
5350 }
5351 case 'J': {
5352 ++First;
5353 size_t ArgsBegin = Names.size();
5354 while (!consumeIf('E')) {
Pavel Labathba825192018-10-16 14:29:14 +00005355 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005356 if (Arg == nullptr)
5357 return nullptr;
5358 Names.push_back(Arg);
5359 }
5360 NodeArray Args = popTrailingNodeArray(ArgsBegin);
5361 return make<TemplateArgumentPack>(Args);
5362 }
5363 case 'L': {
5364 // ::= LZ <encoding> E # extension
5365 if (look(1) == 'Z') {
5366 First += 2;
Pavel Labathba825192018-10-16 14:29:14 +00005367 Node *Arg = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005368 if (Arg == nullptr || !consumeIf('E'))
5369 return nullptr;
5370 return Arg;
5371 }
5372 // ::= <expr-primary> # simple expressions
Pavel Labathba825192018-10-16 14:29:14 +00005373 return getDerived().parseExprPrimary();
Richard Smithc20d1442018-08-20 20:14:49 +00005374 }
5375 default:
Pavel Labathba825192018-10-16 14:29:14 +00005376 return getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005377 }
5378}
5379
5380// <template-args> ::= I <template-arg>* E
5381// extension, the abi says <template-arg>+
Pavel Labathba825192018-10-16 14:29:14 +00005382template <typename Derived, typename Alloc>
5383Node *
5384AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005385 if (!consumeIf('I'))
5386 return nullptr;
5387
5388 // <template-params> refer to the innermost <template-args>. Clear out any
5389 // outer args that we may have inserted into TemplateParams.
Richard Smithdf1c14c2019-09-06 23:53:21 +00005390 if (TagTemplates) {
Richard Smithc20d1442018-08-20 20:14:49 +00005391 TemplateParams.clear();
Richard Smithdf1c14c2019-09-06 23:53:21 +00005392 TemplateParams.push_back(&OuterTemplateParams);
5393 OuterTemplateParams.clear();
5394 }
Richard Smithc20d1442018-08-20 20:14:49 +00005395
5396 size_t ArgsBegin = Names.size();
5397 while (!consumeIf('E')) {
5398 if (TagTemplates) {
5399 auto OldParams = std::move(TemplateParams);
Pavel Labathba825192018-10-16 14:29:14 +00005400 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005401 TemplateParams = std::move(OldParams);
5402 if (Arg == nullptr)
5403 return nullptr;
5404 Names.push_back(Arg);
5405 Node *TableEntry = Arg;
5406 if (Arg->getKind() == Node::KTemplateArgumentPack) {
5407 TableEntry = make<ParameterPack>(
5408 static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
Richard Smithb485b352018-08-24 23:30:26 +00005409 if (!TableEntry)
5410 return nullptr;
Richard Smithc20d1442018-08-20 20:14:49 +00005411 }
Richard Smithdf1c14c2019-09-06 23:53:21 +00005412 TemplateParams.back()->push_back(TableEntry);
Richard Smithc20d1442018-08-20 20:14:49 +00005413 } else {
Pavel Labathba825192018-10-16 14:29:14 +00005414 Node *Arg = getDerived().parseTemplateArg();
Richard Smithc20d1442018-08-20 20:14:49 +00005415 if (Arg == nullptr)
5416 return nullptr;
5417 Names.push_back(Arg);
5418 }
5419 }
5420 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
5421}
5422
5423// <mangled-name> ::= _Z <encoding>
5424// ::= <type>
5425// extension ::= ___Z <encoding> _block_invoke
5426// extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
5427// extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
Pavel Labathba825192018-10-16 14:29:14 +00005428template <typename Derived, typename Alloc>
5429Node *AbstractManglingParser<Derived, Alloc>::parse() {
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005430 if (consumeIf("_Z") || consumeIf("__Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005431 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005432 if (Encoding == nullptr)
5433 return nullptr;
5434 if (look() == '.') {
5435 Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
5436 First = Last;
5437 }
5438 if (numLeft() != 0)
5439 return nullptr;
5440 return Encoding;
5441 }
5442
Erik Pilkingtonc0df1582019-01-17 21:37:36 +00005443 if (consumeIf("___Z") || consumeIf("____Z")) {
Pavel Labathba825192018-10-16 14:29:14 +00005444 Node *Encoding = getDerived().parseEncoding();
Richard Smithc20d1442018-08-20 20:14:49 +00005445 if (Encoding == nullptr || !consumeIf("_block_invoke"))
5446 return nullptr;
5447 bool RequireNumber = consumeIf('_');
5448 if (parseNumber().empty() && RequireNumber)
5449 return nullptr;
5450 if (look() == '.')
5451 First = Last;
5452 if (numLeft() != 0)
5453 return nullptr;
5454 return make<SpecialName>("invocation function for block in ", Encoding);
5455 }
5456
Pavel Labathba825192018-10-16 14:29:14 +00005457 Node *Ty = getDerived().parseType();
Richard Smithc20d1442018-08-20 20:14:49 +00005458 if (numLeft() != 0)
5459 return nullptr;
5460 return Ty;
5461}
5462
Pavel Labathba825192018-10-16 14:29:14 +00005463template <typename Alloc>
5464struct ManglingParser : AbstractManglingParser<ManglingParser<Alloc>, Alloc> {
5465 using AbstractManglingParser<ManglingParser<Alloc>,
5466 Alloc>::AbstractManglingParser;
5467};
5468
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005469DEMANGLE_NAMESPACE_END
Richard Smithc20d1442018-08-20 20:14:49 +00005470
Erik Pilkingtonf70e4d82019-01-17 20:37:51 +00005471#endif // DEMANGLE_ITANIUMDEMANGLE_H