blob: 1348b104d2d774762446247746717845200bc39c [file] [log] [blame]
Howard Hinnantd213ffd2011-05-05 15:27:28 +00001//===-------------------------- cxa_demangle.cpp --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Erik Pilkington1c300b92017-11-21 15:04:08 +000010// FIXME: (possibly) incomplete list of features that clang mangles that this
11// file does not yet support:
Erik Pilkington1c300b92017-11-21 15:04:08 +000012// - C++ modules TS
13
Howard Hinnant6c33e762013-06-17 18:10:34 +000014#define _LIBCPP_NO_EXCEPTIONS
Howard Hinnantd213ffd2011-05-05 15:27:28 +000015
Saleem Abdulrasoolb4ec5792015-12-04 02:14:58 +000016#include "__cxxabi_config.h"
17
Howard Hinnant6c33e762013-06-17 18:10:34 +000018#include <vector>
Howard Hinnantd213ffd2011-05-05 15:27:28 +000019#include <algorithm>
Howard Hinnant6c33e762013-06-17 18:10:34 +000020#include <numeric>
Erik Pilkington761e6b02018-01-31 20:17:06 +000021#include <cassert>
Erik Pilkington77101542017-07-28 00:53:30 +000022#include <cstdio>
Howard Hinnant6c33e762013-06-17 18:10:34 +000023#include <cstdlib>
24#include <cstring>
25#include <cctype>
Howard Hinnantd213ffd2011-05-05 15:27:28 +000026
Nico Weberb4c998b2015-09-20 18:10:46 +000027#ifdef _MSC_VER
28// snprintf is implemented in VS 2015
29#if _MSC_VER < 1900
30#define snprintf _snprintf_s
31#endif
32#endif
33
Erik Pilkington761e6b02018-01-31 20:17:06 +000034#ifndef NDEBUG
35#if __has_attribute(noinline) && __has_attribute(used)
36#define DUMP_METHOD __attribute__((noinline,used))
37#else
38#define DUMP_METHOD
39#endif
40#endif
Howard Hinnantd213ffd2011-05-05 15:27:28 +000041
Erik Pilkington761e6b02018-01-31 20:17:06 +000042namespace {
Howard Hinnantd213ffd2011-05-05 15:27:28 +000043
Erik Pilkington0024acd2017-07-28 00:43:49 +000044class StringView {
45 const char *First;
46 const char *Last;
47
48public:
49 template <size_t N>
50 StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {}
Erik Pilkington7de232a2017-08-10 02:48:13 +000051 StringView(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +000052 StringView() : First(nullptr), Last(nullptr) {}
53
54 StringView substr(size_t From, size_t To) {
55 if (To >= size())
56 To = size() - 1;
57 if (From >= size())
58 From = size() - 1;
59 return StringView(First + From, First + To);
60 }
61
62 StringView dropFront(size_t N) const {
63 if (N >= size())
64 N = size() - 1;
65 return StringView(First + N, Last);
66 }
67
68 bool startsWith(StringView Str) const {
69 if (Str.size() > size())
70 return false;
71 return std::equal(Str.begin(), Str.end(), begin());
72 }
73
74 const char &operator[](size_t Idx) const { return *(begin() + Idx); }
75
76 const char *begin() const { return First; }
77 const char *end() const { return Last; }
78 size_t size() const { return static_cast<size_t>(Last - First); }
Erik Pilkington761e6b02018-01-31 20:17:06 +000079 bool empty() const { return First == Last; }
Erik Pilkington0024acd2017-07-28 00:43:49 +000080};
81
82bool operator==(const StringView &LHS, const StringView &RHS) {
83 return LHS.size() == RHS.size() &&
84 std::equal(LHS.begin(), LHS.end(), RHS.begin());
85}
86
87// Stream that AST nodes write their string representation into after the AST
88// has been parsed.
89class OutputStream {
90 char *Buffer;
91 size_t CurrentPosition;
92 size_t BufferCapacity;
93
94 // Ensure there is at least n more positions in buffer.
95 void grow(size_t N) {
96 if (N + CurrentPosition >= BufferCapacity) {
97 BufferCapacity *= 2;
98 if (BufferCapacity < N + CurrentPosition)
99 BufferCapacity = N + CurrentPosition;
100 Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
101 }
102 }
103
104public:
105 OutputStream(char *StartBuf, size_t Size)
106 : Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {}
107
Erik Pilkington761e6b02018-01-31 20:17:06 +0000108 /// If a ParameterPackExpansion (or similar type) is encountered, the offset
109 /// into the pack that we're currently printing.
110 unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max();
Erik Pilkington85619f52018-03-25 22:49:57 +0000111 unsigned CurrentPackMax = std::numeric_limits<unsigned>::max();
Erik Pilkington761e6b02018-01-31 20:17:06 +0000112
Erik Pilkington0024acd2017-07-28 00:43:49 +0000113 OutputStream &operator+=(StringView R) {
114 size_t Size = R.size();
115 if (Size == 0)
116 return *this;
117 grow(Size);
118 memmove(Buffer + CurrentPosition, R.begin(), Size);
119 CurrentPosition += Size;
120 return *this;
121 }
122
123 OutputStream &operator+=(char C) {
124 grow(1);
125 Buffer[CurrentPosition++] = C;
126 return *this;
127 }
128
Erik Pilkington85619f52018-03-25 22:49:57 +0000129 size_t getCurrentPosition() const { return CurrentPosition; }
130 void setCurrentPosition(size_t NewPos) { CurrentPosition = NewPos; }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000131
132 char back() const {
133 return CurrentPosition ? Buffer[CurrentPosition - 1] : '\0';
134 }
135
136 bool empty() const { return CurrentPosition == 0; }
137
138 char *getBuffer() { return Buffer; }
139 char *getBufferEnd() { return Buffer + CurrentPosition - 1; }
140 size_t getBufferCapacity() { return BufferCapacity; }
141};
142
Erik Pilkington761e6b02018-01-31 20:17:06 +0000143template <class T>
144class SwapAndRestore {
145 T &Restore;
146 T OriginalValue;
147public:
148 SwapAndRestore(T& Restore_, T NewVal)
149 : Restore(Restore_), OriginalValue(Restore) {
150 Restore = std::move(NewVal);
151 }
152 ~SwapAndRestore() { Restore = std::move(OriginalValue); }
153
154 SwapAndRestore(const SwapAndRestore &) = delete;
155 SwapAndRestore &operator=(const SwapAndRestore &) = delete;
156};
157
Erik Pilkington0024acd2017-07-28 00:43:49 +0000158// Base class of all AST nodes. The AST is built by the parser, then is
159// traversed by the printLeft/Right functions to produce a demangled string.
160class Node {
161public:
162 enum Kind : unsigned char {
Erik Pilkington6a4e62b2018-04-09 18:31:50 +0000163 KNodeArrayNode,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000164 KDotSuffix,
165 KVendorExtQualType,
166 KQualType,
167 KConversionOperatorType,
168 KPostfixQualifiedType,
Erik Pilkington13fb7dc2018-02-13 00:15:53 +0000169 KElaboratedTypeSpefType,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000170 KNameType,
Erik Pilkington5bff4122017-11-22 20:38:22 +0000171 KAbiTagAttr,
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000172 KEnableIfAttr,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000173 KObjCProtoName,
174 KPointerType,
175 KLValueReferenceType,
176 KRValueReferenceType,
177 KPointerToMemberType,
178 KArrayType,
179 KFunctionType,
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000180 KNoexceptSpec,
181 KDynamicExceptionSpec,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000182 KFunctionEncoding,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000183 KLiteralOperator,
184 KSpecialName,
185 KCtorVtableSpecialName,
186 KQualifiedName,
187 KEmptyName,
188 KVectorType,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000189 KParameterPack,
190 KTemplateArgumentPack,
191 KParameterPackExpansion,
192 KTemplateArgs,
Erik Pilkington04f39852018-03-25 22:50:33 +0000193 KForwardTemplateReference,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000194 KNameWithTemplateArgs,
195 KGlobalQualifiedName,
196 KStdQualifiedName,
197 KExpandedSpecialSubstitution,
198 KSpecialSubstitution,
199 KCtorDtorName,
200 KDtorName,
201 KUnnamedTypeName,
Erik Pilkingtone1d61622018-03-05 16:35:06 +0000202 KClosureTypeName,
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +0000203 KStructuredBindingName,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000204 KExpr,
Erik Pilkington88a1cf62018-02-13 00:15:56 +0000205 KBracedExpr,
206 KBracedRangeExpr,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000207 };
208
Erik Pilkington761e6b02018-01-31 20:17:06 +0000209 Kind K;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000210
Erik Pilkington761e6b02018-01-31 20:17:06 +0000211 /// Three-way bool to track a cached value. Unknown is possible if this node
212 /// has an unexpanded parameter pack below it that may affect this cache.
213 enum class Cache : unsigned char { Yes, No, Unknown, };
Erik Pilkington0024acd2017-07-28 00:43:49 +0000214
Erik Pilkington761e6b02018-01-31 20:17:06 +0000215 /// Tracks if this node has a component on its right side, in which case we
216 /// need to call printRight.
217 Cache RHSComponentCache;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000218
Erik Pilkington761e6b02018-01-31 20:17:06 +0000219 /// Track if this node is a (possibly qualified) array type. This can affect
220 /// how we format the output string.
221 Cache ArrayCache;
222
223 /// Track if this node is a (possibly qualified) function type. This can
224 /// affect how we format the output string.
225 Cache FunctionCache;
226
Erik Pilkington85619f52018-03-25 22:49:57 +0000227 Node(Kind K_, Cache RHSComponentCache_ = Cache::No,
228 Cache ArrayCache_ = Cache::No, Cache FunctionCache_ = Cache::No)
229 : K(K_), RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
Erik Pilkington761e6b02018-01-31 20:17:06 +0000230 FunctionCache(FunctionCache_) {}
231
Erik Pilkington761e6b02018-01-31 20:17:06 +0000232 bool hasRHSComponent(OutputStream &S) const {
233 if (RHSComponentCache != Cache::Unknown)
234 return RHSComponentCache == Cache::Yes;
235 return hasRHSComponentSlow(S);
236 }
237
238 bool hasArray(OutputStream &S) const {
239 if (ArrayCache != Cache::Unknown)
240 return ArrayCache == Cache::Yes;
241 return hasArraySlow(S);
242 }
243
244 bool hasFunction(OutputStream &S) const {
245 if (FunctionCache != Cache::Unknown)
246 return FunctionCache == Cache::Yes;
247 return hasFunctionSlow(S);
248 }
249
250 Kind getKind() const { return K; }
251
252 virtual bool hasRHSComponentSlow(OutputStream &) const { return false; }
253 virtual bool hasArraySlow(OutputStream &) const { return false; }
254 virtual bool hasFunctionSlow(OutputStream &) const { return false; }
255
Erik Pilkington761e6b02018-01-31 20:17:06 +0000256 void print(OutputStream &S) const {
257 printLeft(S);
258 if (RHSComponentCache != Cache::No)
259 printRight(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000260 }
261
262 // Print the "left" side of this Node into OutputStream.
263 virtual void printLeft(OutputStream &) const = 0;
264
265 // Print the "right". This distinction is necessary to represent C++ types
266 // that appear on the RHS of their subtype, such as arrays or functions.
267 // Since most types don't have such a component, provide a default
268 // implemenation.
269 virtual void printRight(OutputStream &) const {}
270
271 virtual StringView getBaseName() const { return StringView(); }
272
273 // Silence compiler warnings, this dtor will never be called.
274 virtual ~Node() = default;
Erik Pilkington761e6b02018-01-31 20:17:06 +0000275
276#ifndef NDEBUG
277 DUMP_METHOD void dump() const {
278 char *Buffer = static_cast<char*>(std::malloc(1024));
279 OutputStream S(Buffer, 1024);
280 print(S);
281 S += '\0';
282 printf("Symbol dump for %p: %s\n", (const void*)this, S.getBuffer());
283 std::free(S.getBuffer());
284 }
285#endif
Erik Pilkington0024acd2017-07-28 00:43:49 +0000286};
287
288class NodeArray {
289 Node **Elements;
290 size_t NumElements;
291
292public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000293 NodeArray() : Elements(nullptr), NumElements(0) {}
Erik Pilkington414f1a52017-08-09 22:45:35 +0000294 NodeArray(Node **Elements_, size_t NumElements_)
295 : Elements(Elements_), NumElements(NumElements_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000296
297 bool empty() const { return NumElements == 0; }
298 size_t size() const { return NumElements; }
299
Erik Pilkington761e6b02018-01-31 20:17:06 +0000300 Node **begin() const { return Elements; }
301 Node **end() const { return Elements + NumElements; }
302
303 Node *operator[](size_t Idx) const { return Elements[Idx]; }
304
305 void printWithComma(OutputStream &S) const {
306 bool FirstElement = true;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000307 for (size_t Idx = 0; Idx != NumElements; ++Idx) {
Erik Pilkington85619f52018-03-25 22:49:57 +0000308 size_t BeforeComma = S.getCurrentPosition();
Erik Pilkington761e6b02018-01-31 20:17:06 +0000309 if (!FirstElement)
310 S += ", ";
Erik Pilkington85619f52018-03-25 22:49:57 +0000311 size_t AfterComma = S.getCurrentPosition();
Erik Pilkington0024acd2017-07-28 00:43:49 +0000312 Elements[Idx]->print(S);
Erik Pilkington85619f52018-03-25 22:49:57 +0000313
314 // Elements[Idx] is an empty parameter pack expansion, we should erase the
315 // comma we just printed.
316 if (AfterComma == S.getCurrentPosition()) {
317 S.setCurrentPosition(BeforeComma);
318 continue;
319 }
320
321 FirstElement = false;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000322 }
323 }
324};
325
Erik Pilkington6a4e62b2018-04-09 18:31:50 +0000326struct NodeArrayNode : Node {
327 NodeArray Array;
328 NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
329 void printLeft(OutputStream &S) const override {
330 Array.printWithComma(S);
331 }
332};
333
Erik Pilkington0024acd2017-07-28 00:43:49 +0000334class DotSuffix final : public Node {
335 const Node *Prefix;
336 const StringView Suffix;
337
338public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000339 DotSuffix(Node *Prefix_, StringView Suffix_)
340 : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000341
342 void printLeft(OutputStream &s) const override {
343 Prefix->print(s);
344 s += " (";
345 s += Suffix;
346 s += ")";
347 }
348};
349
350class VendorExtQualType final : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +0000351 const Node *Ty;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000352 StringView Ext;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000353
354public:
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000355 VendorExtQualType(Node *Ty_, StringView Ext_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000356 : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_) {}
Erik Pilkington761e6b02018-01-31 20:17:06 +0000357
Erik Pilkington0024acd2017-07-28 00:43:49 +0000358 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000359 Ty->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000360 S += " ";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000361 S += Ext;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000362 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000363};
364
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000365enum FunctionRefQual : unsigned char {
366 FrefQualNone,
367 FrefQualLValue,
368 FrefQualRValue,
369};
370
Erik Pilkington0024acd2017-07-28 00:43:49 +0000371enum Qualifiers {
372 QualNone = 0,
373 QualConst = 0x1,
374 QualVolatile = 0x2,
375 QualRestrict = 0x4,
376};
377
378void addQualifiers(Qualifiers &Q1, Qualifiers Q2) {
379 Q1 = static_cast<Qualifiers>(Q1 | Q2);
380}
381
382class QualType : public Node {
383protected:
384 const Qualifiers Quals;
385 const Node *Child;
386
387 void printQuals(OutputStream &S) const {
388 if (Quals & QualConst)
389 S += " const";
390 if (Quals & QualVolatile)
391 S += " volatile";
392 if (Quals & QualRestrict)
393 S += " restrict";
394 }
395
396public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000397 QualType(Node *Child_, Qualifiers Quals_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000398 : Node(KQualType, Child_->RHSComponentCache,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000399 Child_->ArrayCache, Child_->FunctionCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000400 Quals(Quals_), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000401
Erik Pilkington761e6b02018-01-31 20:17:06 +0000402 bool hasRHSComponentSlow(OutputStream &S) const override {
403 return Child->hasRHSComponent(S);
404 }
405 bool hasArraySlow(OutputStream &S) const override {
406 return Child->hasArray(S);
407 }
408 bool hasFunctionSlow(OutputStream &S) const override {
409 return Child->hasFunction(S);
410 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000411
412 void printLeft(OutputStream &S) const override {
413 Child->printLeft(S);
414 printQuals(S);
415 }
416
417 void printRight(OutputStream &S) const override { Child->printRight(S); }
418};
419
420class ConversionOperatorType final : public Node {
421 const Node *Ty;
422
423public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000424 ConversionOperatorType(Node *Ty_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000425 : Node(KConversionOperatorType), Ty(Ty_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000426
427 void printLeft(OutputStream &S) const override {
428 S += "operator ";
429 Ty->print(S);
430 }
431};
432
433class PostfixQualifiedType final : public Node {
434 const Node *Ty;
435 const StringView Postfix;
436
437public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000438 PostfixQualifiedType(Node *Ty_, StringView Postfix_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000439 : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000440
441 void printLeft(OutputStream &s) const override {
442 Ty->printLeft(s);
443 s += Postfix;
444 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000445};
446
447class NameType final : public Node {
448 const StringView Name;
449
450public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000451 NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000452
453 StringView getName() const { return Name; }
454 StringView getBaseName() const override { return Name; }
455
456 void printLeft(OutputStream &s) const override { s += Name; }
457};
458
Erik Pilkington13fb7dc2018-02-13 00:15:53 +0000459class ElaboratedTypeSpefType : public Node {
460 StringView Kind;
461 Node *Child;
462public:
463 ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000464 : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
Erik Pilkington13fb7dc2018-02-13 00:15:53 +0000465
466 void printLeft(OutputStream &S) const override {
467 S += Kind;
468 S += ' ';
469 Child->print(S);
470 }
471};
472
Erik Pilkington5bff4122017-11-22 20:38:22 +0000473class AbiTagAttr final : public Node {
474 const Node* Base;
475 StringView Tag;
476public:
477 AbiTagAttr(const Node* Base_, StringView Tag_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000478 : Node(KAbiTagAttr, Base_->RHSComponentCache,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000479 Base_->ArrayCache, Base_->FunctionCache),
480 Base(Base_), Tag(Tag_) {}
Erik Pilkington5bff4122017-11-22 20:38:22 +0000481
482 void printLeft(OutputStream &S) const override {
483 Base->printLeft(S);
484 S += "[abi:";
485 S += Tag;
486 S += "]";
487 }
488};
489
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000490class EnableIfAttr : public Node {
491 NodeArray Conditions;
492public:
493 EnableIfAttr(NodeArray Conditions_)
494 : Node(KEnableIfAttr), Conditions(Conditions_) {}
495
496 void printLeft(OutputStream &S) const override {
497 S += " [enable_if:";
498 Conditions.printWithComma(S);
499 S += ']';
500 }
501};
502
Erik Pilkington0024acd2017-07-28 00:43:49 +0000503class ObjCProtoName : public Node {
504 Node *Ty;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000505 StringView Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000506
507 friend class PointerType;
508
509public:
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000510 ObjCProtoName(Node *Ty_, StringView Protocol_)
Erik Pilkington414f1a52017-08-09 22:45:35 +0000511 : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000512
513 bool isObjCObject() const {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000514 return Ty->getKind() == KNameType &&
Erik Pilkington0024acd2017-07-28 00:43:49 +0000515 static_cast<NameType *>(Ty)->getName() == "objc_object";
516 }
517
518 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000519 Ty->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000520 S += "<";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000521 S += Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000522 S += ">";
523 }
524};
525
526class PointerType final : public Node {
527 const Node *Pointee;
528
529public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000530 PointerType(Node *Pointee_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000531 : Node(KPointerType, Pointee_->RHSComponentCache),
Erik Pilkington761e6b02018-01-31 20:17:06 +0000532 Pointee(Pointee_) {}
533
534 bool hasRHSComponentSlow(OutputStream &S) const override {
535 return Pointee->hasRHSComponent(S);
536 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000537
538 void printLeft(OutputStream &s) const override {
539 // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
Erik Pilkington761e6b02018-01-31 20:17:06 +0000540 if (Pointee->getKind() != KObjCProtoName ||
Erik Pilkington0024acd2017-07-28 00:43:49 +0000541 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
542 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000543 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000544 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000545 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000546 s += "(";
547 s += "*";
548 } else {
549 const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
550 s += "id<";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000551 s += objcProto->Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000552 s += ">";
553 }
554 }
555
556 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000557 if (Pointee->getKind() != KObjCProtoName ||
Erik Pilkington0024acd2017-07-28 00:43:49 +0000558 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000559 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000560 s += ")";
561 Pointee->printRight(s);
562 }
563 }
564};
565
566class LValueReferenceType final : public Node {
567 const Node *Pointee;
568
569public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000570 LValueReferenceType(Node *Pointee_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000571 : Node(KLValueReferenceType, Pointee_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000572 Pointee(Pointee_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000573
Erik Pilkington761e6b02018-01-31 20:17:06 +0000574 bool hasRHSComponentSlow(OutputStream &S) const override {
575 return Pointee->hasRHSComponent(S);
576 }
577
Erik Pilkington0024acd2017-07-28 00:43:49 +0000578 void printLeft(OutputStream &s) const override {
579 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000580 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000581 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000582 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000583 s += "(&";
584 else
585 s += "&";
586 }
587 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000588 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000589 s += ")";
590 Pointee->printRight(s);
591 }
592};
593
594class RValueReferenceType final : public Node {
595 const Node *Pointee;
596
597public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000598 RValueReferenceType(Node *Pointee_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000599 : Node(KRValueReferenceType, Pointee_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000600 Pointee(Pointee_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000601
Erik Pilkington761e6b02018-01-31 20:17:06 +0000602 bool hasRHSComponentSlow(OutputStream &S) const override {
603 return Pointee->hasRHSComponent(S);
604 }
605
Erik Pilkington0024acd2017-07-28 00:43:49 +0000606 void printLeft(OutputStream &s) const override {
607 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000608 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000609 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000610 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000611 s += "(&&";
612 else
613 s += "&&";
614 }
615
616 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000617 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000618 s += ")";
619 Pointee->printRight(s);
620 }
621};
622
623class PointerToMemberType final : public Node {
624 const Node *ClassType;
625 const Node *MemberType;
626
627public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000628 PointerToMemberType(Node *ClassType_, Node *MemberType_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000629 : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000630 ClassType(ClassType_), MemberType(MemberType_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000631
Erik Pilkington761e6b02018-01-31 20:17:06 +0000632 bool hasRHSComponentSlow(OutputStream &S) const override {
633 return MemberType->hasRHSComponent(S);
634 }
635
Erik Pilkington0024acd2017-07-28 00:43:49 +0000636 void printLeft(OutputStream &s) const override {
637 MemberType->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000638 if (MemberType->hasArray(s) || MemberType->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000639 s += "(";
640 else
641 s += " ";
642 ClassType->print(s);
643 s += "::*";
644 }
645
646 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000647 if (MemberType->hasArray(s) || MemberType->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000648 s += ")";
649 MemberType->printRight(s);
650 }
651};
652
653class NodeOrString {
654 const void *First;
655 const void *Second;
656
657public:
658 /* implicit */ NodeOrString(StringView Str) {
659 const char *FirstChar = Str.begin();
660 const char *SecondChar = Str.end();
661 if (SecondChar == nullptr) {
662 assert(FirstChar == SecondChar);
663 ++FirstChar, ++SecondChar;
664 }
665 First = static_cast<const void *>(FirstChar);
666 Second = static_cast<const void *>(SecondChar);
667 }
668
669 /* implicit */ NodeOrString(Node *N)
670 : First(static_cast<const void *>(N)), Second(nullptr) {}
671 NodeOrString() : First(nullptr), Second(nullptr) {}
672
673 bool isString() const { return Second && First; }
674 bool isNode() const { return First && !Second; }
675 bool isEmpty() const { return !First && !Second; }
676
677 StringView asString() const {
678 assert(isString());
679 return StringView(static_cast<const char *>(First),
680 static_cast<const char *>(Second));
681 }
682
683 const Node *asNode() const {
684 assert(isNode());
685 return static_cast<const Node *>(First);
686 }
687};
688
689class ArrayType final : public Node {
690 Node *Base;
691 NodeOrString Dimension;
692
693public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000694 ArrayType(Node *Base_, NodeOrString Dimension_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000695 : Node(KArrayType,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000696 /*RHSComponentCache=*/Cache::Yes,
697 /*ArrayCache=*/Cache::Yes),
Erik Pilkington85619f52018-03-25 22:49:57 +0000698 Base(Base_), Dimension(Dimension_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000699
700 // Incomplete array type.
Erik Pilkington761e6b02018-01-31 20:17:06 +0000701 ArrayType(Node *Base_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000702 : Node(KArrayType,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000703 /*RHSComponentCache=*/Cache::Yes,
704 /*ArrayCache=*/Cache::Yes),
705 Base(Base_) {}
706
707 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
708 bool hasArraySlow(OutputStream &) const override { return true; }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000709
710 void printLeft(OutputStream &S) const override { Base->printLeft(S); }
711
712 void printRight(OutputStream &S) const override {
713 if (S.back() != ']')
714 S += " ";
715 S += "[";
716 if (Dimension.isString())
717 S += Dimension.asString();
718 else if (Dimension.isNode())
719 Dimension.asNode()->print(S);
720 S += "]";
721 Base->printRight(S);
722 }
723};
724
725class FunctionType final : public Node {
726 Node *Ret;
727 NodeArray Params;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000728 Qualifiers CVQuals;
729 FunctionRefQual RefQual;
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000730 Node *ExceptionSpec;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000731
732public:
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000733 FunctionType(Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000734 FunctionRefQual RefQual_, Node *ExceptionSpec_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000735 : Node(KFunctionType,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000736 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
737 /*FunctionCache=*/Cache::Yes),
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000738 Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
Erik Pilkington85619f52018-03-25 22:49:57 +0000739 ExceptionSpec(ExceptionSpec_) {}
Erik Pilkington761e6b02018-01-31 20:17:06 +0000740
741 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
742 bool hasFunctionSlow(OutputStream &) const override { return true; }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000743
744 // Handle C++'s ... quirky decl grammer by using the left & right
745 // distinction. Consider:
746 // int (*f(float))(char) {}
747 // f is a function that takes a float and returns a pointer to a function
748 // that takes a char and returns an int. If we're trying to print f, start
749 // by printing out the return types's left, then print our parameters, then
750 // finally print right of the return type.
751 void printLeft(OutputStream &S) const override {
752 Ret->printLeft(S);
753 S += " ";
754 }
755
756 void printRight(OutputStream &S) const override {
757 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000758 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000759 S += ")";
760 Ret->printRight(S);
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000761
762 if (CVQuals & QualConst)
763 S += " const";
764 if (CVQuals & QualVolatile)
765 S += " volatile";
766 if (CVQuals & QualRestrict)
767 S += " restrict";
768
769 if (RefQual == FrefQualLValue)
770 S += " &";
771 else if (RefQual == FrefQualRValue)
772 S += " &&";
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000773
774 if (ExceptionSpec != nullptr) {
775 S += ' ';
776 ExceptionSpec->print(S);
777 }
778 }
779};
780
781class NoexceptSpec : public Node {
782 Node *E;
783public:
Erik Pilkington85619f52018-03-25 22:49:57 +0000784 NoexceptSpec(Node *E_) : Node(KNoexceptSpec), E(E_) {}
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000785
786 void printLeft(OutputStream &S) const override {
787 S += "noexcept(";
788 E->print(S);
789 S += ")";
790 }
791};
792
793class DynamicExceptionSpec : public Node {
794 NodeArray Types;
795public:
796 DynamicExceptionSpec(NodeArray Types_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000797 : Node(KDynamicExceptionSpec), Types(Types_) {}
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000798
799 void printLeft(OutputStream &S) const override {
800 S += "throw(";
801 Types.printWithComma(S);
802 S += ')';
Erik Pilkington0024acd2017-07-28 00:43:49 +0000803 }
804};
805
Erik Pilkington761e6b02018-01-31 20:17:06 +0000806class FunctionEncoding final : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +0000807 const Node *Ret;
808 const Node *Name;
809 NodeArray Params;
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000810 Node *Attrs;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000811 Qualifiers CVQuals;
812 FunctionRefQual RefQual;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000813
814public:
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000815 FunctionEncoding(Node *Ret_, Node *Name_, NodeArray Params_,
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000816 Node *Attrs_, Qualifiers CVQuals_, FunctionRefQual RefQual_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000817 : Node(KFunctionEncoding,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000818 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
819 /*FunctionCache=*/Cache::Yes),
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000820 Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
Erik Pilkington85619f52018-03-25 22:49:57 +0000821 CVQuals(CVQuals_), RefQual(RefQual_) {}
Erik Pilkington761e6b02018-01-31 20:17:06 +0000822
823 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
824 bool hasFunctionSlow(OutputStream &) const override { return true; }
825
826 Node *getName() { return const_cast<Node *>(Name); }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000827
828 void printLeft(OutputStream &S) const override {
829 if (Ret) {
830 Ret->printLeft(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000831 if (!Ret->hasRHSComponent(S))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000832 S += " ";
833 }
834 Name->print(S);
835 }
836
837 void printRight(OutputStream &S) const override {
838 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000839 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000840 S += ")";
841 if (Ret)
842 Ret->printRight(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000843
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000844 if (CVQuals & QualConst)
845 S += " const";
846 if (CVQuals & QualVolatile)
847 S += " volatile";
848 if (CVQuals & QualRestrict)
849 S += " restrict";
Erik Pilkington0024acd2017-07-28 00:43:49 +0000850
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000851 if (RefQual == FrefQualLValue)
Erik Pilkington0024acd2017-07-28 00:43:49 +0000852 S += " &";
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000853 else if (RefQual == FrefQualRValue)
Erik Pilkington0024acd2017-07-28 00:43:49 +0000854 S += " &&";
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +0000855
856 if (Attrs != nullptr)
857 Attrs->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000858 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000859};
860
861class LiteralOperator : public Node {
862 const Node *OpName;
863
864public:
Erik Pilkington85619f52018-03-25 22:49:57 +0000865 LiteralOperator(Node *OpName_) : Node(KLiteralOperator), OpName(OpName_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000866
867 void printLeft(OutputStream &S) const override {
868 S += "operator\"\" ";
869 OpName->print(S);
870 }
871};
872
873class SpecialName final : public Node {
874 const StringView Special;
875 const Node *Child;
876
877public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000878 SpecialName(StringView Special_, Node* Child_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000879 : Node(KSpecialName), Special(Special_), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000880
881 void printLeft(OutputStream &S) const override {
882 S += Special;
883 Child->print(S);
884 }
885};
886
887class CtorVtableSpecialName final : public Node {
888 const Node *FirstType;
889 const Node *SecondType;
890
891public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000892 CtorVtableSpecialName(Node *FirstType_, Node *SecondType_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000893 : Node(KCtorVtableSpecialName),
Erik Pilkington761e6b02018-01-31 20:17:06 +0000894 FirstType(FirstType_), SecondType(SecondType_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000895
896 void printLeft(OutputStream &S) const override {
897 S += "construction vtable for ";
898 FirstType->print(S);
899 S += "-in-";
900 SecondType->print(S);
901 }
902};
903
904class QualifiedName final : public Node {
905 // qualifier::name
906 const Node *Qualifier;
907 const Node *Name;
908
Erik Pilkington0024acd2017-07-28 00:43:49 +0000909public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000910 QualifiedName(Node* Qualifier_, Node* Name_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000911 : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000912
913 StringView getBaseName() const override { return Name->getBaseName(); }
914
915 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000916 Qualifier->print(S);
917 S += "::";
Erik Pilkington0024acd2017-07-28 00:43:49 +0000918 Name->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000919 }
920};
921
922class EmptyName : public Node {
923public:
924 EmptyName() : Node(KEmptyName) {}
925 void printLeft(OutputStream &) const override {}
926};
927
928class VectorType final : public Node {
929 const Node *BaseType;
930 const NodeOrString Dimension;
931 const bool IsPixel;
932
933public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000934 VectorType(NodeOrString Dimension_)
935 : Node(KVectorType), BaseType(nullptr), Dimension(Dimension_),
Erik Pilkington85619f52018-03-25 22:49:57 +0000936 IsPixel(true) {}
Erik Pilkington414f1a52017-08-09 22:45:35 +0000937 VectorType(Node *BaseType_, NodeOrString Dimension_)
Erik Pilkington85619f52018-03-25 22:49:57 +0000938 : Node(KVectorType), BaseType(BaseType_),
939 Dimension(Dimension_), IsPixel(false) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000940
941 void printLeft(OutputStream &S) const override {
942 if (IsPixel) {
943 S += "pixel vector[";
944 S += Dimension.asString();
945 S += "]";
946 } else {
947 BaseType->print(S);
948 S += " vector[";
949 if (Dimension.isNode())
950 Dimension.asNode()->print(S);
951 else if (Dimension.isString())
952 S += Dimension.asString();
953 S += "]";
954 }
955 }
956};
957
Erik Pilkington761e6b02018-01-31 20:17:06 +0000958/// An unexpanded parameter pack (either in the expression or type context). If
959/// this AST is correct, this node will have a ParameterPackExpansion node above
960/// it.
961///
962/// This node is created when some <template-args> are found that apply to an
963/// <encoding>, and is stored in the TemplateParams table. In order for this to
964/// appear in the final AST, it has to referenced via a <template-param> (ie,
965/// T_).
966class ParameterPack final : public Node {
967 NodeArray Data;
Erik Pilkington85619f52018-03-25 22:49:57 +0000968
969 // Setup OutputStream for a pack expansion unless we're already expanding one.
970 void initializePackExpansion(OutputStream &S) const {
971 if (S.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
972 S.CurrentPackMax = static_cast<unsigned>(Data.size());
973 S.CurrentPackIndex = 0;
974 }
975 }
976
Erik Pilkington0024acd2017-07-28 00:43:49 +0000977public:
Erik Pilkington85619f52018-03-25 22:49:57 +0000978 ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000979 ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
980 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
981 return P->ArrayCache == Cache::No;
982 }))
983 ArrayCache = Cache::No;
984 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
985 return P->FunctionCache == Cache::No;
986 }))
987 FunctionCache = Cache::No;
988 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
989 return P->RHSComponentCache == Cache::No;
990 }))
991 RHSComponentCache = Cache::No;
992 }
993
994 bool hasRHSComponentSlow(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +0000995 initializePackExpansion(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000996 size_t Idx = S.CurrentPackIndex;
997 return Idx < Data.size() && Data[Idx]->hasRHSComponent(S);
998 }
999 bool hasArraySlow(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +00001000 initializePackExpansion(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +00001001 size_t Idx = S.CurrentPackIndex;
1002 return Idx < Data.size() && Data[Idx]->hasArray(S);
1003 }
1004 bool hasFunctionSlow(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +00001005 initializePackExpansion(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +00001006 size_t Idx = S.CurrentPackIndex;
1007 return Idx < Data.size() && Data[Idx]->hasFunction(S);
1008 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001009
1010 void printLeft(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +00001011 initializePackExpansion(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +00001012 size_t Idx = S.CurrentPackIndex;
1013 if (Idx < Data.size())
1014 Data[Idx]->printLeft(S);
1015 }
1016 void printRight(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +00001017 initializePackExpansion(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +00001018 size_t Idx = S.CurrentPackIndex;
1019 if (Idx < Data.size())
1020 Data[Idx]->printRight(S);
1021 }
1022};
1023
1024/// A variadic template argument. This node represents an occurance of
1025/// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1026/// one of it's Elements is. The parser inserts a ParameterPack into the
1027/// TemplateParams table if the <template-args> this pack belongs to apply to an
1028/// <encoding>.
1029class TemplateArgumentPack final : public Node {
1030 NodeArray Elements;
1031public:
1032 TemplateArgumentPack(NodeArray Elements_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001033 : Node(KTemplateArgumentPack), Elements(Elements_) {}
Erik Pilkington761e6b02018-01-31 20:17:06 +00001034
1035 NodeArray getElements() const { return Elements; }
1036
1037 void printLeft(OutputStream &S) const override {
1038 Elements.printWithComma(S);
1039 }
1040};
1041
1042/// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1043/// which each have Child->ParameterPackSize elements.
1044class ParameterPackExpansion final : public Node {
1045 const Node *Child;
1046
1047public:
1048 ParameterPackExpansion(Node* Child_)
1049 : Node(KParameterPackExpansion), Child(Child_) {}
1050
1051 const Node *getChild() const { return Child; }
1052
1053 void printLeft(OutputStream &S) const override {
Erik Pilkington85619f52018-03-25 22:49:57 +00001054 constexpr unsigned Max = std::numeric_limits<unsigned>::max();
1055 SwapAndRestore<unsigned> SavePackIdx(S.CurrentPackIndex, Max);
1056 SwapAndRestore<unsigned> SavePackMax(S.CurrentPackMax, Max);
1057 size_t StreamPos = S.getCurrentPosition();
1058
1059 // Print the first element in the pack. If Child contains a ParameterPack,
1060 // it will set up S.CurrentPackMax and print the first element.
1061 Child->print(S);
1062
1063 // No ParameterPack was found in Child. This can occur if we've found a pack
1064 // expansion on a <function-param>.
1065 if (S.CurrentPackMax == Max) {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001066 S += "...";
Erik Pilkington0024acd2017-07-28 00:43:49 +00001067 return;
1068 }
1069
Erik Pilkington85619f52018-03-25 22:49:57 +00001070 // We found a ParameterPack, but it has no elements. Erase whatever we may
1071 // of printed.
1072 if (S.CurrentPackMax == 0) {
1073 S.setCurrentPosition(StreamPos);
1074 return;
1075 }
1076
1077 // Else, iterate through the rest of the elements in the pack.
1078 for (unsigned I = 1, E = S.CurrentPackMax; I < E; ++I) {
1079 S += ", ";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001080 S.CurrentPackIndex = I;
1081 Child->print(S);
1082 }
1083 }
1084};
Erik Pilkington0024acd2017-07-28 00:43:49 +00001085
Erik Pilkington761e6b02018-01-31 20:17:06 +00001086class TemplateArgs final : public Node {
1087 NodeArray Params;
1088
1089public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001090 TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
Erik Pilkington761e6b02018-01-31 20:17:06 +00001091
1092 NodeArray getParams() { return Params; }
1093
1094 void printLeft(OutputStream &S) const override {
Erik Pilkington0024acd2017-07-28 00:43:49 +00001095 S += "<";
Erik Pilkington85619f52018-03-25 22:49:57 +00001096 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001097 if (S.back() == '>')
1098 S += " ";
1099 S += ">";
Erik Pilkington0024acd2017-07-28 00:43:49 +00001100 }
1101};
1102
Erik Pilkington04f39852018-03-25 22:50:33 +00001103struct ForwardTemplateReference : Node {
1104 size_t Index;
1105 Node *Ref = nullptr;
1106
Erik Pilkington565ba042018-03-26 15:34:36 +00001107 // If we're currently printing this node. It is possible (though invalid) for
1108 // a forward template reference to refer to itself via a substitution. This
1109 // creates a cyclic AST, which will stack overflow printing. To fix this, bail
1110 // out if more than one print* function is active.
1111 mutable bool Printing = false;
1112
Erik Pilkington04f39852018-03-25 22:50:33 +00001113 ForwardTemplateReference(size_t Index_)
1114 : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
1115 Cache::Unknown),
1116 Index(Index_) {}
1117
1118 bool hasRHSComponentSlow(OutputStream &S) const override {
Erik Pilkington565ba042018-03-26 15:34:36 +00001119 if (Printing)
1120 return false;
1121 SwapAndRestore<bool> SavePrinting(Printing, true);
Erik Pilkington04f39852018-03-25 22:50:33 +00001122 return Ref->hasRHSComponent(S);
1123 }
1124 bool hasArraySlow(OutputStream &S) const override {
Erik Pilkington565ba042018-03-26 15:34:36 +00001125 if (Printing)
1126 return false;
1127 SwapAndRestore<bool> SavePrinting(Printing, true);
Erik Pilkington04f39852018-03-25 22:50:33 +00001128 return Ref->hasArray(S);
1129 }
1130 bool hasFunctionSlow(OutputStream &S) const override {
Erik Pilkington565ba042018-03-26 15:34:36 +00001131 if (Printing)
1132 return false;
1133 SwapAndRestore<bool> SavePrinting(Printing, true);
Erik Pilkington04f39852018-03-25 22:50:33 +00001134 return Ref->hasFunction(S);
1135 }
1136
Erik Pilkington565ba042018-03-26 15:34:36 +00001137 void printLeft(OutputStream &S) const override {
1138 if (Printing)
1139 return;
1140 SwapAndRestore<bool> SavePrinting(Printing, true);
1141 Ref->printLeft(S);
1142 }
1143 void printRight(OutputStream &S) const override {
1144 if (Printing)
1145 return;
1146 SwapAndRestore<bool> SavePrinting(Printing, true);
1147 Ref->printRight(S);
1148 }
Erik Pilkington04f39852018-03-25 22:50:33 +00001149};
1150
Erik Pilkington0024acd2017-07-28 00:43:49 +00001151class NameWithTemplateArgs final : public Node {
1152 // name<template_args>
1153 Node *Name;
1154 Node *TemplateArgs;
1155
1156public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001157 NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001158 : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001159
1160 StringView getBaseName() const override { return Name->getBaseName(); }
1161
1162 void printLeft(OutputStream &S) const override {
1163 Name->print(S);
1164 TemplateArgs->print(S);
1165 }
1166};
1167
1168class GlobalQualifiedName final : public Node {
1169 Node *Child;
1170
1171public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001172 GlobalQualifiedName(Node* Child_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001173 : Node(KGlobalQualifiedName), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001174
1175 StringView getBaseName() const override { return Child->getBaseName(); }
1176
1177 void printLeft(OutputStream &S) const override {
1178 S += "::";
1179 Child->print(S);
1180 }
1181};
1182
1183class StdQualifiedName final : public Node {
1184 Node *Child;
1185
1186public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001187 StdQualifiedName(Node *Child_) : Node(KStdQualifiedName), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001188
1189 StringView getBaseName() const override { return Child->getBaseName(); }
1190
1191 void printLeft(OutputStream &S) const override {
1192 S += "std::";
1193 Child->print(S);
1194 }
1195};
1196
1197enum class SpecialSubKind {
1198 allocator,
1199 basic_string,
1200 string,
1201 istream,
1202 ostream,
1203 iostream,
1204};
1205
1206class ExpandedSpecialSubstitution final : public Node {
1207 SpecialSubKind SSK;
1208
1209public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001210 ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1211 : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001212
1213 StringView getBaseName() const override {
1214 switch (SSK) {
1215 case SpecialSubKind::allocator:
1216 return StringView("allocator");
1217 case SpecialSubKind::basic_string:
1218 return StringView("basic_string");
1219 case SpecialSubKind::string:
1220 return StringView("basic_string");
1221 case SpecialSubKind::istream:
1222 return StringView("basic_istream");
1223 case SpecialSubKind::ostream:
1224 return StringView("basic_ostream");
1225 case SpecialSubKind::iostream:
1226 return StringView("basic_iostream");
1227 }
Erik Pilkingtond25d9012017-08-01 02:38:40 +00001228 _LIBCPP_UNREACHABLE();
Erik Pilkington0024acd2017-07-28 00:43:49 +00001229 }
1230
1231 void printLeft(OutputStream &S) const override {
1232 switch (SSK) {
1233 case SpecialSubKind::allocator:
1234 S += "std::basic_string<char, std::char_traits<char>, "
1235 "std::allocator<char> >";
1236 break;
1237 case SpecialSubKind::basic_string:
1238 case SpecialSubKind::string:
1239 S += "std::basic_string<char, std::char_traits<char>, "
1240 "std::allocator<char> >";
1241 break;
1242 case SpecialSubKind::istream:
1243 S += "std::basic_istream<char, std::char_traits<char> >";
1244 break;
1245 case SpecialSubKind::ostream:
1246 S += "std::basic_ostream<char, std::char_traits<char> >";
1247 break;
1248 case SpecialSubKind::iostream:
1249 S += "std::basic_iostream<char, std::char_traits<char> >";
1250 break;
1251 }
1252 }
1253};
1254
1255class SpecialSubstitution final : public Node {
1256public:
1257 SpecialSubKind SSK;
1258
Erik Pilkington414f1a52017-08-09 22:45:35 +00001259 SpecialSubstitution(SpecialSubKind SSK_)
1260 : Node(KSpecialSubstitution), SSK(SSK_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001261
1262 StringView getBaseName() const override {
1263 switch (SSK) {
1264 case SpecialSubKind::allocator:
1265 return StringView("allocator");
1266 case SpecialSubKind::basic_string:
1267 return StringView("basic_string");
1268 case SpecialSubKind::string:
1269 return StringView("string");
1270 case SpecialSubKind::istream:
1271 return StringView("istream");
1272 case SpecialSubKind::ostream:
1273 return StringView("ostream");
1274 case SpecialSubKind::iostream:
1275 return StringView("iostream");
1276 }
Erik Pilkingtond25d9012017-08-01 02:38:40 +00001277 _LIBCPP_UNREACHABLE();
Erik Pilkington0024acd2017-07-28 00:43:49 +00001278 }
1279
1280 void printLeft(OutputStream &S) const override {
1281 switch (SSK) {
1282 case SpecialSubKind::allocator:
1283 S += "std::allocator";
1284 break;
1285 case SpecialSubKind::basic_string:
1286 S += "std::basic_string";
1287 break;
1288 case SpecialSubKind::string:
1289 S += "std::string";
1290 break;
1291 case SpecialSubKind::istream:
1292 S += "std::istream";
1293 break;
1294 case SpecialSubKind::ostream:
1295 S += "std::ostream";
1296 break;
1297 case SpecialSubKind::iostream:
1298 S += "std::iostream";
1299 break;
1300 }
1301 }
1302};
1303
1304class CtorDtorName final : public Node {
1305 const Node *Basename;
1306 const bool IsDtor;
1307
1308public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001309 CtorDtorName(Node *Basename_, bool IsDtor_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001310 : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001311
1312 void printLeft(OutputStream &S) const override {
1313 if (IsDtor)
1314 S += "~";
1315 S += Basename->getBaseName();
1316 }
1317};
1318
1319class DtorName : public Node {
1320 const Node *Base;
1321
1322public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001323 DtorName(Node *Base_) : Node(KDtorName), Base(Base_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001324
1325 void printLeft(OutputStream &S) const override {
1326 S += "~";
1327 Base->printLeft(S);
1328 }
1329};
1330
1331class UnnamedTypeName : public Node {
1332 const StringView Count;
1333
1334public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001335 UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001336
1337 void printLeft(OutputStream &S) const override {
1338 S += "'unnamed";
1339 S += Count;
1340 S += "\'";
1341 }
1342};
1343
Erik Pilkingtone1d61622018-03-05 16:35:06 +00001344class ClosureTypeName : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +00001345 NodeArray Params;
1346 StringView Count;
1347
1348public:
Erik Pilkingtone1d61622018-03-05 16:35:06 +00001349 ClosureTypeName(NodeArray Params_, StringView Count_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001350 : Node(KClosureTypeName), Params(Params_), Count(Count_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001351
1352 void printLeft(OutputStream &S) const override {
1353 S += "\'lambda";
1354 S += Count;
1355 S += "\'(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001356 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001357 S += ")";
1358 }
1359};
1360
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +00001361class StructuredBindingName : public Node {
1362 NodeArray Bindings;
1363public:
1364 StructuredBindingName(NodeArray Bindings_)
1365 : Node(KStructuredBindingName), Bindings(Bindings_) {}
1366
1367 void printLeft(OutputStream &S) const override {
Erik Pilkingtonaa209d82018-03-10 22:33:49 +00001368 S += '[';
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +00001369 Bindings.printWithComma(S);
1370 S += ']';
1371 }
1372};
1373
Erik Pilkington0024acd2017-07-28 00:43:49 +00001374// -- Expression Nodes --
1375
1376struct Expr : public Node {
Erik Pilkington88a1cf62018-02-13 00:15:56 +00001377 Expr(Kind K = KExpr) : Node(K) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001378};
1379
1380class BinaryExpr : public Expr {
1381 const Node *LHS;
1382 const StringView InfixOperator;
1383 const Node *RHS;
1384
1385public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001386 BinaryExpr(Node *LHS_, StringView InfixOperator_, Node *RHS_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001387 : LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001388
1389 void printLeft(OutputStream &S) const override {
1390 // might be a template argument expression, then we need to disambiguate
1391 // with parens.
1392 if (InfixOperator == ">")
1393 S += "(";
1394
1395 S += "(";
1396 LHS->print(S);
1397 S += ") ";
1398 S += InfixOperator;
1399 S += " (";
1400 RHS->print(S);
1401 S += ")";
1402
1403 if (InfixOperator == ">")
1404 S += ")";
1405 }
1406};
1407
1408class ArraySubscriptExpr : public Expr {
1409 const Node *Op1;
1410 const Node *Op2;
1411
1412public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001413 ArraySubscriptExpr(Node *Op1_, Node *Op2_) : Op1(Op1_), Op2(Op2_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001414
1415 void printLeft(OutputStream &S) const override {
1416 S += "(";
1417 Op1->print(S);
1418 S += ")[";
1419 Op2->print(S);
1420 S += "]";
1421 }
1422};
1423
1424class PostfixExpr : public Expr {
1425 const Node *Child;
1426 const StringView Operand;
1427
1428public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001429 PostfixExpr(Node *Child_, StringView Operand_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001430 : Child(Child_), Operand(Operand_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001431
1432 void printLeft(OutputStream &S) const override {
1433 S += "(";
1434 Child->print(S);
1435 S += ")";
1436 S += Operand;
1437 }
1438};
1439
1440class ConditionalExpr : public Expr {
1441 const Node *Cond;
1442 const Node *Then;
1443 const Node *Else;
1444
1445public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001446 ConditionalExpr(Node *Cond_, Node *Then_, Node *Else_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001447 : Cond(Cond_), Then(Then_), Else(Else_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001448
1449 void printLeft(OutputStream &S) const override {
1450 S += "(";
1451 Cond->print(S);
1452 S += ") ? (";
1453 Then->print(S);
1454 S += ") : (";
1455 Else->print(S);
1456 S += ")";
1457 }
1458};
1459
1460class MemberExpr : public Expr {
1461 const Node *LHS;
1462 const StringView Kind;
1463 const Node *RHS;
1464
1465public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001466 MemberExpr(Node *LHS_, StringView Kind_, Node *RHS_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001467 : LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001468
1469 void printLeft(OutputStream &S) const override {
1470 LHS->print(S);
1471 S += Kind;
1472 RHS->print(S);
1473 }
1474};
1475
1476class EnclosingExpr : public Expr {
1477 const StringView Prefix;
1478 const Node *Infix;
1479 const StringView Postfix;
1480
1481public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001482 EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001483 : Prefix(Prefix_), Infix(Infix_), Postfix(Postfix_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001484
1485 void printLeft(OutputStream &S) const override {
1486 S += Prefix;
1487 Infix->print(S);
1488 S += Postfix;
1489 }
1490};
1491
1492class CastExpr : public Expr {
1493 // cast_kind<to>(from)
1494 const StringView CastKind;
1495 const Node *To;
1496 const Node *From;
1497
1498public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001499 CastExpr(StringView CastKind_, Node *To_, Node *From_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001500 : CastKind(CastKind_), To(To_), From(From_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001501
1502 void printLeft(OutputStream &S) const override {
1503 S += CastKind;
1504 S += "<";
1505 To->printLeft(S);
1506 S += ">(";
1507 From->printLeft(S);
1508 S += ")";
1509 }
1510};
1511
1512class SizeofParamPackExpr : public Expr {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001513 Node *Pack;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001514
1515public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001516 SizeofParamPackExpr(Node *Pack_) : Pack(Pack_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001517
1518 void printLeft(OutputStream &S) const override {
1519 S += "sizeof...(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001520 ParameterPackExpansion PPE(Pack);
1521 PPE.printLeft(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001522 S += ")";
1523 }
1524};
1525
1526class CallExpr : public Expr {
1527 const Node *Callee;
1528 NodeArray Args;
1529
1530public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001531 CallExpr(Node *Callee_, NodeArray Args_) : Callee(Callee_), Args(Args_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001532
1533 void printLeft(OutputStream &S) const override {
1534 Callee->print(S);
1535 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001536 Args.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001537 S += ")";
1538 }
1539};
1540
1541class NewExpr : public Expr {
1542 // new (expr_list) type(init_list)
1543 NodeArray ExprList;
1544 Node *Type;
1545 NodeArray InitList;
1546 bool IsGlobal; // ::operator new ?
1547 bool IsArray; // new[] ?
1548public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001549 NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1550 bool IsArray_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001551 : ExprList(ExprList_), Type(Type_), InitList(InitList_),
Erik Pilkington85619f52018-03-25 22:49:57 +00001552 IsGlobal(IsGlobal_), IsArray(IsArray_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001553
1554 void printLeft(OutputStream &S) const override {
1555 if (IsGlobal)
1556 S += "::operator ";
1557 S += "new";
1558 if (IsArray)
1559 S += "[]";
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001560 S += ' ';
Erik Pilkington0024acd2017-07-28 00:43:49 +00001561 if (!ExprList.empty()) {
1562 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001563 ExprList.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001564 S += ")";
1565 }
1566 Type->print(S);
1567 if (!InitList.empty()) {
1568 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001569 InitList.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001570 S += ")";
1571 }
Erik Pilkington761e6b02018-01-31 20:17:06 +00001572
Erik Pilkington0024acd2017-07-28 00:43:49 +00001573 }
1574};
1575
1576class DeleteExpr : public Expr {
1577 Node *Op;
1578 bool IsGlobal;
1579 bool IsArray;
1580
1581public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001582 DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001583 : Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001584
1585 void printLeft(OutputStream &S) const override {
1586 if (IsGlobal)
1587 S += "::";
1588 S += "delete";
1589 if (IsArray)
1590 S += "[] ";
1591 Op->print(S);
1592 }
1593};
1594
1595class PrefixExpr : public Expr {
1596 StringView Prefix;
1597 Node *Child;
1598
1599public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001600 PrefixExpr(StringView Prefix_, Node *Child_) : Prefix(Prefix_), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001601
1602 void printLeft(OutputStream &S) const override {
1603 S += Prefix;
1604 S += "(";
1605 Child->print(S);
1606 S += ")";
1607 }
1608};
1609
1610class FunctionParam : public Expr {
1611 StringView Number;
1612
1613public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001614 FunctionParam(StringView Number_) : Number(Number_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001615
1616 void printLeft(OutputStream &S) const override {
1617 S += "fp";
1618 S += Number;
1619 }
1620};
1621
Erik Pilkington0024acd2017-07-28 00:43:49 +00001622class ConversionExpr : public Expr {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001623 const Node *Type;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001624 NodeArray Expressions;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001625
1626public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001627 ConversionExpr(const Node *Type_, NodeArray Expressions_)
Erik Pilkington85619f52018-03-25 22:49:57 +00001628 : Type(Type_), Expressions(Expressions_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001629
1630 void printLeft(OutputStream &S) const override {
1631 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001632 Type->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001633 S += ")(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001634 Expressions.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001635 S += ")";
1636 }
1637};
1638
Erik Pilkington88a1cf62018-02-13 00:15:56 +00001639class InitListExpr : public Expr {
1640 Node *Ty;
1641 NodeArray Inits;
1642public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001643 InitListExpr(Node *Ty_, NodeArray Inits_) : Ty(Ty_), Inits(Inits_) {}
Erik Pilkington88a1cf62018-02-13 00:15:56 +00001644
1645 void printLeft(OutputStream &S) const override {
1646 if (Ty)
1647 Ty->print(S);
1648 S += '{';
1649 Inits.printWithComma(S);
1650 S += '}';
1651 }
1652};
1653
1654class BracedExpr : public Expr {
1655 Node *Elem;
1656 Node *Init;
1657 bool IsArray;
1658public:
1659 BracedExpr(Node *Elem_, Node *Init_, bool IsArray_)
1660 : Expr(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
1661
1662 void printLeft(OutputStream &S) const override {
1663 if (IsArray) {
1664 S += '[';
1665 Elem->print(S);
1666 S += ']';
1667 } else {
1668 S += '.';
1669 Elem->print(S);
1670 }
1671 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1672 S += " = ";
1673 Init->print(S);
1674 }
1675};
1676
1677class BracedRangeExpr : public Expr {
1678 Node *First;
1679 Node *Last;
1680 Node *Init;
1681public:
1682 BracedRangeExpr(Node *First_, Node *Last_, Node *Init_)
1683 : Expr(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
1684
1685 void printLeft(OutputStream &S) const override {
1686 S += '[';
1687 First->print(S);
1688 S += " ... ";
1689 Last->print(S);
1690 S += ']';
1691 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1692 S += " = ";
1693 Init->print(S);
1694 }
1695};
1696
Erik Pilkington967b00e2018-04-09 18:33:01 +00001697struct FoldExpr : Expr {
1698 Node *Pack, *Init;
1699 StringView OperatorName;
1700 bool IsLeftFold;
1701
1702 FoldExpr(bool IsLeftFold_, StringView OperatorName_, Node *Pack_, Node *Init_)
1703 : Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
1704 IsLeftFold(IsLeftFold_) {}
1705
1706 void printLeft(OutputStream &S) const override {
1707 auto PrintPack = [&] {
1708 S += '(';
1709 ParameterPackExpansion(Pack).print(S);
1710 S += ')';
1711 };
1712
1713 S += '(';
1714
1715 if (IsLeftFold) {
1716 // init op ... op pack
1717 if (Init != nullptr) {
1718 Init->print(S);
1719 S += ' ';
1720 S += OperatorName;
1721 S += ' ';
1722 }
1723 // ... op pack
1724 S += "... ";
1725 S += OperatorName;
1726 S += ' ';
1727 PrintPack();
1728 } else { // !IsLeftFold
1729 // pack op ...
1730 PrintPack();
1731 S += ' ';
1732 S += OperatorName;
1733 S += " ...";
1734 // pack op ... op init
1735 if (Init != nullptr) {
1736 S += ' ';
1737 S += OperatorName;
1738 S += ' ';
1739 Init->print(S);
1740 }
1741 }
1742 S += ')';
1743 }
1744};
1745
Erik Pilkington0024acd2017-07-28 00:43:49 +00001746class ThrowExpr : public Expr {
1747 const Node *Op;
1748
1749public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001750 ThrowExpr(Node *Op_) : Op(Op_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001751
1752 void printLeft(OutputStream &S) const override {
1753 S += "throw ";
1754 Op->print(S);
1755 }
1756};
1757
1758class BoolExpr : public Expr {
1759 bool Value;
1760
1761public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001762 BoolExpr(bool Value_) : Value(Value_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001763
1764 void printLeft(OutputStream &S) const override {
1765 S += Value ? StringView("true") : StringView("false");
1766 }
1767};
1768
1769class IntegerCastExpr : public Expr {
1770 // ty(integer)
1771 Node *Ty;
1772 StringView Integer;
1773
1774public:
Erik Pilkington85619f52018-03-25 22:49:57 +00001775 IntegerCastExpr(Node *Ty_, StringView Integer_)
1776 : Ty(Ty_), Integer(Integer_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001777
1778 void printLeft(OutputStream &S) const override {
1779 S += "(";
1780 Ty->print(S);
1781 S += ")";
1782 S += Integer;
1783 }
1784};
1785
1786class IntegerExpr : public Expr {
1787 StringView Type;
1788 StringView Value;
1789
1790public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001791 IntegerExpr(StringView Type_, StringView Value_) : Type(Type_), Value(Value_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001792
1793 void printLeft(OutputStream &S) const override {
1794 if (Type.size() > 3) {
1795 S += "(";
1796 S += Type;
1797 S += ")";
1798 }
1799
1800 if (Value[0] == 'n') {
1801 S += "-";
1802 S += Value.dropFront(1);
1803 } else
1804 S += Value;
1805
1806 if (Type.size() <= 3)
1807 S += Type;
1808 }
1809};
1810
1811template <class Float> struct FloatData;
1812
1813template <class Float> class FloatExpr : public Expr {
1814 const StringView Contents;
1815
1816public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001817 FloatExpr(StringView Contents_) : Contents(Contents_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001818
1819 void printLeft(OutputStream &s) const override {
1820 const char *first = Contents.begin();
1821 const char *last = Contents.end() + 1;
1822
1823 const size_t N = FloatData<Float>::mangled_size;
1824 if (static_cast<std::size_t>(last - first) > N) {
1825 last = first + N;
1826 union {
1827 Float value;
1828 char buf[sizeof(Float)];
1829 };
1830 const char *t = first;
1831 char *e = buf;
1832 for (; t != last; ++t, ++e) {
1833 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1834 : static_cast<unsigned>(*t - 'a' + 10);
1835 ++t;
1836 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1837 : static_cast<unsigned>(*t - 'a' + 10);
1838 *e = static_cast<char>((d1 << 4) + d0);
1839 }
1840#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1841 std::reverse(buf, e);
1842#endif
1843 char num[FloatData<Float>::max_demangled_size] = {0};
1844 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
1845 s += StringView(num, num + n);
1846 }
1847 }
1848};
1849
Erik Pilkington0024acd2017-07-28 00:43:49 +00001850class BumpPointerAllocator {
1851 struct BlockMeta {
1852 BlockMeta* Next;
1853 size_t Current;
1854 };
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001855
Erik Pilkington0024acd2017-07-28 00:43:49 +00001856 static constexpr size_t AllocSize = 4096;
1857 static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001858
Erik Pilkington0024acd2017-07-28 00:43:49 +00001859 alignas(16) char InitialBuffer[AllocSize];
1860 BlockMeta* BlockList = nullptr;
1861
1862 void grow() {
1863 char* NewMeta = new char[AllocSize];
1864 BlockList = new (NewMeta) BlockMeta{BlockList, 0};
1865 }
1866
1867 void* allocateMassive(size_t NBytes) {
1868 NBytes += sizeof(BlockMeta);
1869 BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(new char[NBytes]);
1870 BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
1871 return static_cast<void*>(NewMeta + 1);
1872 }
1873
1874public:
1875 BumpPointerAllocator()
1876 : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
1877
1878 void* allocate(size_t N) {
1879 N = (N + 15u) & ~15u;
1880 if (N + BlockList->Current >= UsableAllocSize) {
1881 if (N > UsableAllocSize)
1882 return allocateMassive(N);
1883 grow();
1884 }
1885 BlockList->Current += N;
1886 return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
1887 BlockList->Current - N);
1888 }
1889
1890 ~BumpPointerAllocator() {
1891 while (BlockList) {
1892 BlockMeta* Tmp = BlockList;
1893 BlockList = BlockList->Next;
1894 if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
1895 delete[] reinterpret_cast<char*>(Tmp);
1896 }
1897 }
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001898};
1899
Erik Pilkingtonba34a242017-08-09 21:30:57 +00001900template <class T, size_t N>
1901class PODSmallVector {
1902 static_assert(std::is_pod<T>::value,
1903 "T is required to be a plain old data type");
1904
1905 T* First;
1906 T* Last;
1907 T* Cap;
1908 T Inline[N];
1909
1910 bool isInline() const { return First == Inline; }
1911
1912 void clearInline() {
1913 First = Inline;
1914 Last = Inline;
1915 Cap = Inline + N;
1916 }
1917
1918 void reserve(size_t NewCap) {
1919 size_t S = size();
1920 if (isInline()) {
1921 auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
1922 std::copy(First, Last, Tmp);
1923 First = Tmp;
1924 } else
1925 First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
1926 Last = First + S;
1927 Cap = First + NewCap;
1928 }
1929
1930public:
1931 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
1932
1933 PODSmallVector(const PODSmallVector&) = delete;
1934 PODSmallVector& operator=(const PODSmallVector&) = delete;
1935
1936 PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
1937 if (Other.isInline()) {
1938 std::copy(Other.begin(), Other.end(), First);
1939 Last = First + Other.size();
1940 Other.clear();
1941 return;
1942 }
1943
1944 First = Other.First;
1945 Last = Other.Last;
1946 Cap = Other.Cap;
1947 Other.clearInline();
1948 }
1949
1950 PODSmallVector& operator=(PODSmallVector&& Other) {
1951 if (Other.isInline()) {
1952 if (!isInline()) {
1953 std::free(First);
1954 clearInline();
1955 }
1956 std::copy(Other.begin(), Other.end(), First);
1957 Last = First + Other.size();
1958 Other.clear();
1959 return *this;
1960 }
1961
1962 if (isInline()) {
1963 First = Other.First;
1964 Last = Other.Last;
1965 Cap = Other.Cap;
1966 Other.clearInline();
1967 return *this;
1968 }
1969
1970 std::swap(First, Other.First);
1971 std::swap(Last, Other.Last);
1972 std::swap(Cap, Other.Cap);
1973 Other.clear();
1974 return *this;
1975 }
1976
1977 void push_back(const T& Elem) {
1978 if (Last == Cap)
1979 reserve(size() * 2);
1980 *Last++ = Elem;
1981 }
1982
1983 void pop_back() {
1984 assert(Last != First && "Popping empty vector!");
1985 --Last;
1986 }
1987
1988 void dropBack(size_t Index) {
1989 assert(Index <= size() && "dropBack() can't expand!");
1990 Last = First + Index;
1991 }
1992
1993 T* begin() { return First; }
1994 T* end() { return Last; }
1995
1996 bool empty() const { return First == Last; }
1997 size_t size() const { return static_cast<size_t>(Last - First); }
1998 T& back() {
1999 assert(Last != First && "Calling back() on empty vector!");
2000 return *(Last - 1);
2001 }
2002 T& operator[](size_t Index) {
2003 assert(Index < size() && "Invalid access!");
2004 return *(begin() + Index);
2005 }
2006 void clear() { Last = First; }
2007
2008 ~PODSmallVector() {
2009 if (!isInline())
2010 std::free(First);
2011 }
2012};
2013
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002014struct Db {
2015 const char *First;
2016 const char *Last;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00002017
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002018 // Name stack, this is used by the parser to hold temporary names that were
2019 // parsed. The parser colapses multiple names into new nodes to construct
2020 // the AST. Once the parser is finished, names.size() == 1.
2021 PODSmallVector<Node *, 32> Names;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00002022
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002023 // Substitution table. Itanium supports name substitutions as a means of
2024 // compression. The string "S42_" refers to the 44nd entry (base-36) in this
2025 // table.
2026 PODSmallVector<Node *, 32> Subs;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00002027
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002028 // Template parameter table. Like the above, but referenced like "T42_".
2029 // This has a smaller size compared to Subs and Names because it can be
2030 // stored on the stack.
2031 PODSmallVector<Node *, 8> TemplateParams;
Erik Pilkington9dd63d22017-07-08 18:54:07 +00002032
Erik Pilkington04f39852018-03-25 22:50:33 +00002033 // Set of unresolved forward <template-param> references. These can occur in a
2034 // conversion operator's type, and are resolved in the enclosing <encoding>.
2035 PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
2036
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002037 bool TryToParseTemplateArgs = true;
Erik Pilkington04f39852018-03-25 22:50:33 +00002038 bool PermitForwardTemplateReferences = false;
Erik Pilkington61966e52018-03-16 03:06:30 +00002039 bool ParsingLambdaParams = false;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002040
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002041 BumpPointerAllocator ASTAllocator;
2042
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002043 Db(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
2044
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002045 template <class T, class... Args> T *make(Args &&... args) {
2046 return new (ASTAllocator.allocate(sizeof(T)))
2047 T(std::forward<Args>(args)...);
2048 }
2049
2050 template <class It> NodeArray makeNodeArray(It begin, It end) {
2051 size_t sz = static_cast<size_t>(end - begin);
2052 void *mem = ASTAllocator.allocate(sizeof(Node *) * sz);
2053 Node **data = new (mem) Node *[sz];
2054 std::copy(begin, end, data);
2055 return NodeArray(data, sz);
2056 }
2057
2058 NodeArray popTrailingNodeArray(size_t FromPosition) {
2059 assert(FromPosition <= Names.size());
2060 NodeArray res =
2061 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2062 Names.dropBack(FromPosition);
2063 return res;
2064 }
2065
2066 bool consumeIf(StringView S) {
2067 if (StringView(First, Last).startsWith(S)) {
2068 First += S.size();
2069 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002070 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002071 return false;
2072 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002073
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002074 bool consumeIf(char C) {
2075 if (First != Last && *First == C) {
2076 ++First;
2077 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002078 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002079 return false;
2080 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002081
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002082 char consume() { return First != Last ? *First++ : '\0'; }
2083
2084 char look(unsigned Lookahead = 0) {
2085 if (static_cast<size_t>(Last - First) <= Lookahead)
2086 return '\0';
2087 return First[Lookahead];
2088 }
2089
2090 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2091
2092 StringView parseNumber(bool AllowNegative = false);
2093 Qualifiers parseCVQualifiers();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002094 bool parsePositiveInteger(size_t *Out);
2095 StringView parseBareSourceName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002096
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002097 bool parseSeqId(size_t *Out);
2098 Node *parseSubstitution();
2099 Node *parseTemplateParam();
Erik Pilkington04f39852018-03-25 22:50:33 +00002100 Node *parseTemplateArgs(bool TagTemplates = false);
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002101 Node *parseTemplateArg();
2102
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002103 /// Parse the <expr> production.
2104 Node *parseExpr();
2105 Node *parsePrefixExpr(StringView Kind);
2106 Node *parseBinaryExpr(StringView Kind);
2107 Node *parseIntegerLiteral(StringView Lit);
2108 Node *parseExprPrimary();
2109 template <class Float> Node *parseFloatingLiteral();
2110 Node *parseFunctionParam();
2111 Node *parseNewExpr();
2112 Node *parseConversionExpr();
Erik Pilkington88a1cf62018-02-13 00:15:56 +00002113 Node *parseBracedExpr();
Erik Pilkington967b00e2018-04-09 18:33:01 +00002114 Node *parseFoldExpr();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002115
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002116 /// Parse the <type> production.
2117 Node *parseType();
2118 Node *parseFunctionType();
2119 Node *parseVectorType();
2120 Node *parseDecltype();
2121 Node *parseArrayType();
2122 Node *parsePointerToMemberType();
2123 Node *parseClassEnumType();
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002124 Node *parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002125
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002126 Node *parseEncoding();
2127 bool parseCallOffset();
2128 Node *parseSpecialName();
2129
2130 /// Holds some extra information about a <name> that is being parsed. This
2131 /// information is only pertinent if the <name> refers to an <encoding>.
2132 struct NameState {
2133 bool CtorDtorConversion = false;
2134 bool EndsWithTemplateArgs = false;
2135 Qualifiers CVQualifiers = QualNone;
2136 FunctionRefQual ReferenceQualifier = FrefQualNone;
Erik Pilkington04f39852018-03-25 22:50:33 +00002137 size_t ForwardTemplateRefsBegin;
2138
2139 NameState(Db *Enclosing)
2140 : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002141 };
2142
Erik Pilkington04f39852018-03-25 22:50:33 +00002143 bool resolveForwardTemplateRefs(NameState &State) {
2144 size_t I = State.ForwardTemplateRefsBegin;
2145 size_t E = ForwardTemplateRefs.size();
2146 for (; I < E; ++I) {
2147 size_t Idx = ForwardTemplateRefs[I]->Index;
2148 if (Idx >= TemplateParams.size())
2149 return true;
2150 ForwardTemplateRefs[I]->Ref = TemplateParams[Idx];
2151 }
2152 ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
2153 return false;
2154 }
2155
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002156 /// Parse the <name> production>
2157 Node *parseName(NameState *State = nullptr);
2158 Node *parseLocalName(NameState *State);
2159 Node *parseOperatorName(NameState *State);
2160 Node *parseUnqualifiedName(NameState *State);
2161 Node *parseUnnamedTypeName(NameState *State);
2162 Node *parseSourceName(NameState *State);
2163 Node *parseUnscopedName(NameState *State);
2164 Node *parseNestedName(NameState *State);
2165 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2166
Erik Pilkington2808f772018-02-13 17:09:03 +00002167 Node *parseAbiTags(Node *N);
2168
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002169 /// Parse the <unresolved-name> production.
2170 Node *parseUnresolvedName();
2171 Node *parseSimpleId();
2172 Node *parseBaseUnresolvedName();
2173 Node *parseUnresolvedType();
2174 Node *parseDestructorName();
2175
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002176 /// Top-level entry point into the parser.
2177 Node *parse();
Erik Pilkington0024acd2017-07-28 00:43:49 +00002178};
Erik Pilkingtonc3926622017-07-08 18:54:08 +00002179
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002180const char* parse_discriminator(const char* first, const char* last);
Erik Pilkington2808f772018-02-13 17:09:03 +00002181
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002182// <name> ::= <nested-name> // N
2183// ::= <local-name> # See Scope Encoding below // Z
2184// ::= <unscoped-template-name> <template-args>
2185// ::= <unscoped-name>
2186//
2187// <unscoped-template-name> ::= <unscoped-name>
2188// ::= <substitution>
2189Node *Db::parseName(NameState *State) {
2190 consumeIf('L'); // extension
2191
2192 if (look() == 'N')
2193 return parseNestedName(State);
2194 if (look() == 'Z')
2195 return parseLocalName(State);
2196
2197 // ::= <unscoped-template-name> <template-args>
2198 if (look() == 'S' && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002199 Node *S = parseSubstitution();
2200 if (S == nullptr)
2201 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002202 if (look() != 'I')
2203 return nullptr;
Erik Pilkington04f39852018-03-25 22:50:33 +00002204 Node *TA = parseTemplateArgs(State != nullptr);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002205 if (TA == nullptr)
2206 return nullptr;
2207 if (State) State->EndsWithTemplateArgs = true;
2208 return make<NameWithTemplateArgs>(S, TA);
2209 }
2210
2211 Node *N = parseUnscopedName(State);
2212 if (N == nullptr)
2213 return nullptr;
2214 // ::= <unscoped-template-name> <template-args>
2215 if (look() == 'I') {
2216 Subs.push_back(N);
Erik Pilkington04f39852018-03-25 22:50:33 +00002217 Node *TA = parseTemplateArgs(State != nullptr);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002218 if (TA == nullptr)
2219 return nullptr;
2220 if (State) State->EndsWithTemplateArgs = true;
2221 return make<NameWithTemplateArgs>(N, TA);
2222 }
2223 // ::= <unscoped-name>
2224 return N;
2225}
2226
2227// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2228// := Z <function encoding> E s [<discriminator>]
2229// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
2230Node *Db::parseLocalName(NameState *State) {
2231 if (!consumeIf('Z'))
2232 return nullptr;
2233 Node *Encoding = parseEncoding();
2234 if (Encoding == nullptr || !consumeIf('E'))
2235 return nullptr;
2236
2237 if (consumeIf('s')) {
2238 First = parse_discriminator(First, Last);
2239 return make<QualifiedName>(Encoding, make<NameType>("string literal"));
2240 }
2241
2242 if (consumeIf('d')) {
2243 parseNumber(true);
2244 if (!consumeIf('_'))
2245 return nullptr;
2246 Node *N = parseName(State);
2247 if (N == nullptr)
2248 return nullptr;
2249 return make<QualifiedName>(Encoding, N);
2250 }
2251
2252 Node *Entity = parseName(State);
2253 if (Entity == nullptr)
2254 return nullptr;
2255 First = parse_discriminator(First, Last);
2256 return make<QualifiedName>(Encoding, Entity);
2257}
2258
2259// <unscoped-name> ::= <unqualified-name>
2260// ::= St <unqualified-name> # ::std::
2261// extension ::= StL<unqualified-name>
2262Node *Db::parseUnscopedName(NameState *State) {
2263 if (consumeIf("StL") || consumeIf("St")) {
2264 Node *R = parseUnqualifiedName(State);
2265 if (R == nullptr)
2266 return nullptr;
2267 return make<StdQualifiedName>(R);
2268 }
2269 return parseUnqualifiedName(State);
2270}
2271
2272// <unqualified-name> ::= <operator-name> [abi-tags]
2273// ::= <ctor-dtor-name>
2274// ::= <source-name>
2275// ::= <unnamed-type-name>
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +00002276// ::= DC <source-name>+ E # structured binding declaration
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002277Node *Db::parseUnqualifiedName(NameState *State) {
2278 // <ctor-dtor-name>s are special-cased in parseNestedName().
2279 Node *Result;
2280 if (look() == 'U')
2281 Result = parseUnnamedTypeName(State);
2282 else if (look() >= '1' && look() <= '9')
2283 Result = parseSourceName(State);
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +00002284 else if (consumeIf("DC")) {
2285 size_t BindingsBegin = Names.size();
2286 do {
2287 Node *Binding = parseSourceName(State);
2288 if (Binding == nullptr)
2289 return nullptr;
2290 Names.push_back(Binding);
2291 } while (!consumeIf('E'));
2292 Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
2293 } else
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002294 Result = parseOperatorName(State);
2295 if (Result != nullptr)
2296 Result = parseAbiTags(Result);
2297 return Result;
2298}
2299
2300// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2301// ::= <closure-type-name>
2302//
2303// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2304//
2305// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
2306Node *Db::parseUnnamedTypeName(NameState *) {
2307 if (consumeIf("Ut")) {
2308 StringView Count = parseNumber();
2309 if (!consumeIf('_'))
2310 return nullptr;
2311 return make<UnnamedTypeName>(Count);
2312 }
2313 if (consumeIf("Ul")) {
2314 NodeArray Params;
Erik Pilkington61966e52018-03-16 03:06:30 +00002315 SwapAndRestore<bool> SwapParams(ParsingLambdaParams, true);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002316 if (!consumeIf("vE")) {
2317 size_t ParamsBegin = Names.size();
2318 do {
2319 Node *P = parseType();
2320 if (P == nullptr)
2321 return nullptr;
2322 Names.push_back(P);
2323 } while (!consumeIf('E'));
2324 Params = popTrailingNodeArray(ParamsBegin);
2325 }
2326 StringView Count = parseNumber();
2327 if (!consumeIf('_'))
2328 return nullptr;
2329 return make<ClosureTypeName>(Params, Count);
2330 }
2331 return nullptr;
2332}
2333
2334// <source-name> ::= <positive length number> <identifier>
2335Node *Db::parseSourceName(NameState *) {
2336 size_t Length = 0;
2337 if (parsePositiveInteger(&Length))
2338 return nullptr;
2339 if (numLeft() < Length || Length == 0)
2340 return nullptr;
2341 StringView Name(First, First + Length);
2342 First += Length;
2343 if (Name.startsWith("_GLOBAL__N"))
2344 return make<NameType>("(anonymous namespace)");
2345 return make<NameType>(Name);
2346}
2347
2348// <operator-name> ::= aa # &&
2349// ::= ad # & (unary)
2350// ::= an # &
2351// ::= aN # &=
2352// ::= aS # =
2353// ::= cl # ()
2354// ::= cm # ,
2355// ::= co # ~
2356// ::= cv <type> # (cast)
2357// ::= da # delete[]
2358// ::= de # * (unary)
2359// ::= dl # delete
2360// ::= dv # /
2361// ::= dV # /=
2362// ::= eo # ^
2363// ::= eO # ^=
2364// ::= eq # ==
2365// ::= ge # >=
2366// ::= gt # >
2367// ::= ix # []
2368// ::= le # <=
2369// ::= li <source-name> # operator ""
2370// ::= ls # <<
2371// ::= lS # <<=
2372// ::= lt # <
2373// ::= mi # -
2374// ::= mI # -=
2375// ::= ml # *
2376// ::= mL # *=
2377// ::= mm # -- (postfix in <expression> context)
2378// ::= na # new[]
2379// ::= ne # !=
2380// ::= ng # - (unary)
2381// ::= nt # !
2382// ::= nw # new
2383// ::= oo # ||
2384// ::= or # |
2385// ::= oR # |=
2386// ::= pm # ->*
2387// ::= pl # +
2388// ::= pL # +=
2389// ::= pp # ++ (postfix in <expression> context)
2390// ::= ps # + (unary)
2391// ::= pt # ->
2392// ::= qu # ?
2393// ::= rm # %
2394// ::= rM # %=
2395// ::= rs # >>
2396// ::= rS # >>=
2397// ::= ss # <=> C++2a
2398// ::= v <digit> <source-name> # vendor extended operator
2399Node *Db::parseOperatorName(NameState *State) {
2400 switch (look()) {
2401 case 'a':
2402 switch (look(1)) {
2403 case 'a':
2404 First += 2;
2405 return make<NameType>("operator&&");
2406 case 'd':
2407 case 'n':
2408 First += 2;
2409 return make<NameType>("operator&");
2410 case 'N':
2411 First += 2;
2412 return make<NameType>("operator&=");
2413 case 'S':
2414 First += 2;
2415 return make<NameType>("operator=");
2416 }
2417 return nullptr;
2418 case 'c':
2419 switch (look(1)) {
2420 case 'l':
2421 First += 2;
2422 return make<NameType>("operator()");
2423 case 'm':
2424 First += 2;
2425 return make<NameType>("operator,");
2426 case 'o':
2427 First += 2;
2428 return make<NameType>("operator~");
2429 // ::= cv <type> # (cast)
2430 case 'v': {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002431 First += 2;
Erik Pilkington04f39852018-03-25 22:50:33 +00002432 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2433 // If we're parsing an encoding, State != nullptr and the conversion
2434 // operators' <type> could have a <template-param> that refers to some
2435 // <template-arg>s further ahead in the mangled name.
2436 SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences,
2437 PermitForwardTemplateReferences ||
2438 State != nullptr);
2439 Node* Ty = parseType();
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002440 if (Ty == nullptr)
2441 return nullptr;
2442 if (State) State->CtorDtorConversion = true;
2443 return make<ConversionOperatorType>(Ty);
2444 }
2445 }
2446 return nullptr;
2447 case 'd':
2448 switch (look(1)) {
2449 case 'a':
2450 First += 2;
2451 return make<NameType>("operator delete[]");
2452 case 'e':
2453 First += 2;
2454 return make<NameType>("operator*");
2455 case 'l':
2456 First += 2;
2457 return make<NameType>("operator delete");
2458 case 'v':
2459 First += 2;
2460 return make<NameType>("operator/");
2461 case 'V':
2462 First += 2;
2463 return make<NameType>("operator/=");
2464 }
2465 return nullptr;
2466 case 'e':
2467 switch (look(1)) {
2468 case 'o':
2469 First += 2;
2470 return make<NameType>("operator^");
2471 case 'O':
2472 First += 2;
2473 return make<NameType>("operator^=");
2474 case 'q':
2475 First += 2;
2476 return make<NameType>("operator==");
2477 }
2478 return nullptr;
2479 case 'g':
2480 switch (look(1)) {
2481 case 'e':
2482 First += 2;
2483 return make<NameType>("operator>=");
2484 case 't':
2485 First += 2;
2486 return make<NameType>("operator>");
2487 }
2488 return nullptr;
2489 case 'i':
2490 if (look(1) == 'x') {
2491 First += 2;
2492 return make<NameType>("operator[]");
2493 }
2494 return nullptr;
2495 case 'l':
2496 switch (look(1)) {
2497 case 'e':
2498 First += 2;
2499 return make<NameType>("operator<=");
2500 // ::= li <source-name> # operator ""
2501 case 'i': {
2502 First += 2;
2503 Node *SN = parseSourceName(State);
2504 if (SN == nullptr)
2505 return nullptr;
2506 return make<LiteralOperator>(SN);
2507 }
2508 case 's':
2509 First += 2;
2510 return make<NameType>("operator<<");
2511 case 'S':
2512 First += 2;
2513 return make<NameType>("operator<<=");
2514 case 't':
2515 First += 2;
2516 return make<NameType>("operator<");
2517 }
2518 return nullptr;
2519 case 'm':
2520 switch (look(1)) {
2521 case 'i':
2522 First += 2;
2523 return make<NameType>("operator-");
2524 case 'I':
2525 First += 2;
2526 return make<NameType>("operator-=");
2527 case 'l':
2528 First += 2;
2529 return make<NameType>("operator*");
2530 case 'L':
2531 First += 2;
2532 return make<NameType>("operator*=");
2533 case 'm':
2534 First += 2;
2535 return make<NameType>("operator--");
2536 }
2537 return nullptr;
2538 case 'n':
2539 switch (look(1)) {
2540 case 'a':
2541 First += 2;
2542 return make<NameType>("operator new[]");
2543 case 'e':
2544 First += 2;
2545 return make<NameType>("operator!=");
2546 case 'g':
2547 First += 2;
2548 return make<NameType>("operator-");
2549 case 't':
2550 First += 2;
2551 return make<NameType>("operator!");
2552 case 'w':
2553 First += 2;
2554 return make<NameType>("operator new");
2555 }
2556 return nullptr;
2557 case 'o':
2558 switch (look(1)) {
2559 case 'o':
2560 First += 2;
2561 return make<NameType>("operator||");
2562 case 'r':
2563 First += 2;
2564 return make<NameType>("operator|");
2565 case 'R':
2566 First += 2;
2567 return make<NameType>("operator|=");
2568 }
2569 return nullptr;
2570 case 'p':
2571 switch (look(1)) {
2572 case 'm':
2573 First += 2;
2574 return make<NameType>("operator->*");
2575 case 'l':
2576 First += 2;
2577 return make<NameType>("operator+");
2578 case 'L':
2579 First += 2;
2580 return make<NameType>("operator+=");
2581 case 'p':
2582 First += 2;
2583 return make<NameType>("operator++");
2584 case 's':
2585 First += 2;
2586 return make<NameType>("operator+");
2587 case 't':
2588 First += 2;
2589 return make<NameType>("operator->");
2590 }
2591 return nullptr;
2592 case 'q':
2593 if (look(1) == 'u') {
2594 First += 2;
2595 return make<NameType>("operator?");
2596 }
2597 return nullptr;
2598 case 'r':
2599 switch (look(1)) {
2600 case 'm':
2601 First += 2;
2602 return make<NameType>("operator%");
2603 case 'M':
2604 First += 2;
2605 return make<NameType>("operator%=");
2606 case 's':
2607 First += 2;
2608 return make<NameType>("operator>>");
2609 case 'S':
2610 First += 2;
2611 return make<NameType>("operator>>=");
2612 }
2613 return nullptr;
2614 case 's':
2615 if (look(1) == 's') {
2616 First += 2;
2617 return make<NameType>("operator<=>");
2618 }
2619 return nullptr;
2620 // ::= v <digit> <source-name> # vendor extended operator
2621 case 'v':
2622 if (std::isdigit(look(1))) {
2623 First += 2;
2624 Node *SN = parseSourceName(State);
2625 if (SN == nullptr)
2626 return nullptr;
2627 return make<ConversionOperatorType>(SN);
2628 }
2629 return nullptr;
2630 }
2631 return nullptr;
2632}
2633
Erik Pilkington2808f772018-02-13 17:09:03 +00002634// <ctor-dtor-name> ::= C1 # complete object constructor
2635// ::= C2 # base object constructor
2636// ::= C3 # complete object allocating constructor
2637// extension ::= C5 # ?
2638// ::= D0 # deleting destructor
2639// ::= D1 # complete object destructor
2640// ::= D2 # base object destructor
2641// extension ::= D5 # ?
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002642Node *Db::parseCtorDtorName(Node *&SoFar, NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002643 if (SoFar->K == Node::KSpecialSubstitution) {
2644 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
2645 switch (SSK) {
2646 case SpecialSubKind::string:
2647 case SpecialSubKind::istream:
2648 case SpecialSubKind::ostream:
2649 case SpecialSubKind::iostream:
2650 SoFar = make<ExpandedSpecialSubstitution>(SSK);
2651 default:
2652 break;
2653 }
2654 }
2655
2656 if (consumeIf('C')) {
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002657 bool IsInherited = consumeIf('I');
Erik Pilkington2808f772018-02-13 17:09:03 +00002658 if (look() != '1' && look() != '2' && look() != '3' && look() != '5')
2659 return nullptr;
2660 ++First;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002661 if (State) State->CtorDtorConversion = true;
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002662 if (IsInherited) {
Erik Pilkington04f39852018-03-25 22:50:33 +00002663 if (parseName(State) == nullptr)
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002664 return nullptr;
2665 }
Erik Pilkington2808f772018-02-13 17:09:03 +00002666 return make<CtorDtorName>(SoFar, false);
2667 }
2668
2669 if (look() == 'D' &&
2670 (look(1) == '0' || look(1) == '1' || look(1) == '2' || look(1) == '5')) {
2671 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002672 if (State) State->CtorDtorConversion = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002673 return make<CtorDtorName>(SoFar, true);
2674 }
2675
2676 return nullptr;
2677}
2678
2679// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
2680// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
2681//
2682// <prefix> ::= <prefix> <unqualified-name>
2683// ::= <template-prefix> <template-args>
2684// ::= <template-param>
2685// ::= <decltype>
2686// ::= # empty
2687// ::= <substitution>
2688// ::= <prefix> <data-member-prefix>
2689// extension ::= L
2690//
Erik Pilkington437202e2018-04-09 18:32:25 +00002691// <data-member-prefix> := <member source-name> [<template-args>] M
2692//
Erik Pilkington2808f772018-02-13 17:09:03 +00002693// <template-prefix> ::= <prefix> <template unqualified-name>
2694// ::= <template-param>
2695// ::= <substitution>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002696Node *Db::parseNestedName(NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002697 if (!consumeIf('N'))
2698 return nullptr;
2699
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002700 Qualifiers CVTmp = parseCVQualifiers();
2701 if (State) State->CVQualifiers = CVTmp;
2702
2703 if (consumeIf('O')) {
2704 if (State) State->ReferenceQualifier = FrefQualRValue;
2705 } else if (consumeIf('R')) {
2706 if (State) State->ReferenceQualifier = FrefQualLValue;
2707 } else
2708 if (State) State->ReferenceQualifier = FrefQualNone;
Erik Pilkington2808f772018-02-13 17:09:03 +00002709
2710 Node *SoFar = nullptr;
2711 auto PushComponent = [&](Node *Comp) {
2712 if (SoFar) SoFar = make<QualifiedName>(SoFar, Comp);
2713 else SoFar = Comp;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002714 if (State) State->EndsWithTemplateArgs = false;
Erik Pilkington2808f772018-02-13 17:09:03 +00002715 };
2716
2717 if (consumeIf("St"))
2718 SoFar = make<NameType>("std");
2719
2720 while (!consumeIf('E')) {
2721 consumeIf('L'); // extension
2722
Erik Pilkington437202e2018-04-09 18:32:25 +00002723 // <data-member-prefix> := <member source-name> [<template-args>] M
2724 if (consumeIf('M')) {
2725 if (SoFar == nullptr)
2726 return nullptr;
2727 continue;
2728 }
2729
Erik Pilkington2808f772018-02-13 17:09:03 +00002730 // ::= <template-param>
2731 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002732 Node *TP = parseTemplateParam();
Erik Pilkington2808f772018-02-13 17:09:03 +00002733 if (TP == nullptr)
2734 return nullptr;
2735 PushComponent(TP);
2736 Subs.push_back(SoFar);
2737 continue;
2738 }
2739
2740 // ::= <template-prefix> <template-args>
2741 if (look() == 'I') {
Erik Pilkington04f39852018-03-25 22:50:33 +00002742 Node *TA = parseTemplateArgs(State != nullptr);
Erik Pilkington2808f772018-02-13 17:09:03 +00002743 if (TA == nullptr || SoFar == nullptr)
2744 return nullptr;
2745 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002746 if (State) State->EndsWithTemplateArgs = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002747 Subs.push_back(SoFar);
2748 continue;
2749 }
2750
2751 // ::= <decltype>
2752 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002753 Node *DT = parseDecltype();
Erik Pilkington2808f772018-02-13 17:09:03 +00002754 if (DT == nullptr)
2755 return nullptr;
2756 PushComponent(DT);
2757 Subs.push_back(SoFar);
2758 continue;
2759 }
2760
2761 // ::= <substitution>
2762 if (look() == 'S' && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002763 Node *S = parseSubstitution();
Erik Pilkington2808f772018-02-13 17:09:03 +00002764 if (S == nullptr)
2765 return nullptr;
2766 PushComponent(S);
2767 if (SoFar != S)
2768 Subs.push_back(S);
2769 continue;
2770 }
2771
2772 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
Erik Pilkingtondee4d0b2018-03-10 21:31:15 +00002773 if (look() == 'C' || (look() == 'D' && look(1) != 'C')) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002774 if (SoFar == nullptr)
2775 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002776 Node *CtorDtor = parseCtorDtorName(SoFar, State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002777 if (CtorDtor == nullptr)
2778 return nullptr;
2779 PushComponent(CtorDtor);
2780 SoFar = parseAbiTags(SoFar);
2781 if (SoFar == nullptr)
2782 return nullptr;
2783 Subs.push_back(SoFar);
2784 continue;
2785 }
2786
2787 // ::= <prefix> <unqualified-name>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002788 Node *N = parseUnqualifiedName(State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002789 if (N == nullptr)
2790 return nullptr;
2791 PushComponent(N);
2792 Subs.push_back(SoFar);
2793 }
2794
2795 if (SoFar == nullptr || Subs.empty())
2796 return nullptr;
2797
2798 Subs.pop_back();
2799 return SoFar;
2800}
2801
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002802// <simple-id> ::= <source-name> [ <template-args> ]
2803Node *Db::parseSimpleId() {
2804 Node *SN = parseSourceName(/*NameState=*/nullptr);
2805 if (SN == nullptr)
2806 return nullptr;
2807 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002808 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002809 if (TA == nullptr)
2810 return nullptr;
2811 return make<NameWithTemplateArgs>(SN, TA);
2812 }
2813 return SN;
2814}
2815
2816// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
2817// ::= <simple-id> # e.g., ~A<2*N>
2818Node *Db::parseDestructorName() {
2819 Node *Result;
2820 if (std::isdigit(look()))
2821 Result = parseSimpleId();
2822 else
2823 Result = parseUnresolvedType();
2824 if (Result == nullptr)
2825 return nullptr;
2826 return make<DtorName>(Result);
2827}
2828
2829// <unresolved-type> ::= <template-param>
2830// ::= <decltype>
2831// ::= <substitution>
2832Node *Db::parseUnresolvedType() {
2833 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002834 Node *TP = parseTemplateParam();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002835 if (TP == nullptr)
2836 return nullptr;
2837 Subs.push_back(TP);
2838 return TP;
2839 }
2840 if (look() == 'D') {
2841 Node *DT = parseDecltype();
2842 if (DT == nullptr)
2843 return nullptr;
2844 Subs.push_back(DT);
2845 return DT;
2846 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002847 return parseSubstitution();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002848}
2849
2850// <base-unresolved-name> ::= <simple-id> # unresolved name
2851// extension ::= <operator-name> # unresolved operator-function-id
2852// extension ::= <operator-name> <template-args> # unresolved operator template-id
2853// ::= on <operator-name> # unresolved operator-function-id
2854// ::= on <operator-name> <template-args> # unresolved operator template-id
2855// ::= dn <destructor-name> # destructor or pseudo-destructor;
2856// # e.g. ~X or ~X<N-1>
2857Node *Db::parseBaseUnresolvedName() {
2858 if (std::isdigit(look()))
2859 return parseSimpleId();
2860
2861 if (consumeIf("dn"))
2862 return parseDestructorName();
2863
2864 consumeIf("on");
2865
2866 Node *Oper = parseOperatorName(/*NameState=*/nullptr);
2867 if (Oper == nullptr)
2868 return nullptr;
2869 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002870 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002871 if (TA == nullptr)
2872 return nullptr;
2873 return make<NameWithTemplateArgs>(Oper, TA);
2874 }
2875 return Oper;
2876}
2877
2878// <unresolved-name>
2879// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2880// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
2881// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2882// # A::x, N::y, A<T>::z; "gs" means leading "::"
2883// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
2884// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
2885// # T::N::x /decltype(p)::N::x
2886// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2887//
2888// <unresolved-qualifier-level> ::= <simple-id>
2889Node *Db::parseUnresolvedName() {
2890 Node *SoFar = nullptr;
2891
2892 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2893 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2894 if (consumeIf("srN")) {
2895 SoFar = parseUnresolvedType();
2896 if (SoFar == nullptr)
2897 return nullptr;
2898
2899 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002900 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002901 if (TA == nullptr)
2902 return nullptr;
2903 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2904 }
2905
2906 while (!consumeIf('E')) {
2907 Node *Qual = parseSimpleId();
2908 if (Qual == nullptr)
2909 return nullptr;
2910 SoFar = make<QualifiedName>(SoFar, Qual);
2911 }
2912
2913 Node *Base = parseBaseUnresolvedName();
2914 if (Base == nullptr)
2915 return nullptr;
2916 return make<QualifiedName>(SoFar, Base);
2917 }
2918
2919 bool Global = consumeIf("gs");
2920
2921 // [gs] <base-unresolved-name> # x or (with "gs") ::x
2922 if (!consumeIf("sr")) {
2923 SoFar = parseBaseUnresolvedName();
2924 if (SoFar == nullptr)
2925 return nullptr;
2926 if (Global)
2927 SoFar = make<GlobalQualifiedName>(SoFar);
2928 return SoFar;
2929 }
2930
2931 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2932 if (std::isdigit(look())) {
2933 do {
2934 Node *Qual = parseSimpleId();
2935 if (Qual == nullptr)
2936 return nullptr;
2937 if (SoFar)
2938 SoFar = make<QualifiedName>(SoFar, Qual);
2939 else if (Global)
2940 SoFar = make<GlobalQualifiedName>(Qual);
2941 else
2942 SoFar = Qual;
2943 } while (!consumeIf('E'));
2944 }
2945 // sr <unresolved-type> <base-unresolved-name>
2946 // sr <unresolved-type> <template-args> <base-unresolved-name>
2947 else {
2948 SoFar = parseUnresolvedType();
2949 if (SoFar == nullptr)
2950 return nullptr;
2951
2952 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002953 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002954 if (TA == nullptr)
2955 return nullptr;
2956 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2957 }
2958 }
2959
2960 assert(SoFar != nullptr);
2961
2962 Node *Base = parseBaseUnresolvedName();
2963 if (Base == nullptr)
2964 return nullptr;
2965 return make<QualifiedName>(SoFar, Base);
2966}
2967
Erik Pilkington2808f772018-02-13 17:09:03 +00002968// <abi-tags> ::= <abi-tag> [<abi-tags>]
2969// <abi-tag> ::= B <source-name>
2970Node *Db::parseAbiTags(Node *N) {
2971 while (consumeIf('B')) {
2972 StringView SN = parseBareSourceName();
2973 if (SN.empty())
2974 return nullptr;
2975 N = make<AbiTagAttr>(N, SN);
2976 }
2977 return N;
2978}
2979
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002980// <number> ::= [n] <non-negative decimal integer>
2981StringView Db::parseNumber(bool AllowNegative) {
2982 const char *Tmp = First;
2983 if (AllowNegative)
2984 consumeIf('n');
2985 if (numLeft() == 0 || !std::isdigit(*First))
2986 return StringView();
2987 while (numLeft() != 0 && std::isdigit(*First))
2988 ++First;
2989 return StringView(Tmp, First);
2990}
2991
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002992// <positive length number> ::= [0-9]*
2993bool Db::parsePositiveInteger(size_t *Out) {
2994 *Out = 0;
2995 if (look() < '0' || look() > '9')
2996 return true;
2997 while (look() >= '0' && look() <= '9') {
2998 *Out *= 10;
2999 *Out += static_cast<size_t>(consume() - '0');
3000 }
3001 return false;
3002}
3003
3004StringView Db::parseBareSourceName() {
3005 size_t Int = 0;
3006 if (parsePositiveInteger(&Int) || numLeft() < Int)
3007 return StringView();
3008 StringView R(First, First + Int);
3009 First += Int;
3010 return R;
3011}
3012
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003013// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003014//
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003015// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
3016// ::= DO <expression> E # computed (instantiation-dependent) noexcept
3017// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
3018//
3019// <ref-qualifier> ::= R # & ref-qualifier
3020// <ref-qualifier> ::= O # && ref-qualifier
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003021Node *Db::parseFunctionType() {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003022 Qualifiers CVQuals = parseCVQualifiers();
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003023
3024 Node *ExceptionSpec = nullptr;
3025 if (consumeIf("Do")) {
3026 ExceptionSpec = make<NameType>("noexcept");
3027 } else if (consumeIf("DO")) {
3028 Node *E = parseExpr();
3029 if (E == nullptr || !consumeIf('E'))
3030 return nullptr;
3031 ExceptionSpec = make<NoexceptSpec>(E);
3032 } else if (consumeIf("Dw")) {
3033 size_t SpecsBegin = Names.size();
3034 while (!consumeIf('E')) {
3035 Node *T = parseType();
3036 if (T == nullptr)
3037 return nullptr;
3038 Names.push_back(T);
3039 }
3040 ExceptionSpec =
3041 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
3042 }
3043
3044 consumeIf("Dx"); // transaction safe
3045
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003046 if (!consumeIf('F'))
3047 return nullptr;
3048 consumeIf('Y'); // extern "C"
3049 Node *ReturnType = parseType();
3050 if (ReturnType == nullptr)
3051 return nullptr;
3052
3053 FunctionRefQual ReferenceQualifier = FrefQualNone;
3054 size_t ParamsBegin = Names.size();
3055 while (true) {
3056 if (consumeIf('E'))
3057 break;
3058 if (consumeIf('v'))
3059 continue;
3060 if (consumeIf("RE")) {
3061 ReferenceQualifier = FrefQualLValue;
3062 break;
3063 }
3064 if (consumeIf("OE")) {
3065 ReferenceQualifier = FrefQualRValue;
3066 break;
3067 }
3068 Node *T = parseType();
3069 if (T == nullptr)
3070 return nullptr;
3071 Names.push_back(T);
3072 }
3073
3074 NodeArray Params = popTrailingNodeArray(ParamsBegin);
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003075 return make<FunctionType>(ReturnType, Params, CVQuals,
3076 ReferenceQualifier, ExceptionSpec);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003077}
3078
3079// extension:
3080// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3081// ::= Dv [<dimension expression>] _ <element type>
3082// <extended element type> ::= <element type>
3083// ::= p # AltiVec vector pixel
3084Node *Db::parseVectorType() {
3085 if (!consumeIf("Dv"))
3086 return nullptr;
3087 if (look() >= '1' && look() <= '9') {
3088 StringView DimensionNumber = parseNumber();
3089 if (!consumeIf('_'))
3090 return nullptr;
3091 if (consumeIf('p'))
3092 return make<VectorType>(DimensionNumber);
3093 Node *ElemType = parseType();
3094 if (ElemType == nullptr)
3095 return nullptr;
3096 return make<VectorType>(ElemType, DimensionNumber);
3097 }
3098
3099 if (!consumeIf('_')) {
3100 Node *DimExpr = parseExpr();
3101 if (!DimExpr)
3102 return nullptr;
3103 if (!consumeIf('_'))
3104 return nullptr;
3105 Node *ElemType = parseType();
3106 if (!ElemType)
3107 return nullptr;
3108 return make<VectorType>(ElemType, DimExpr);
3109 }
3110 Node *ElemType = parseType();
3111 if (!ElemType)
3112 return nullptr;
3113 return make<VectorType>(ElemType, StringView());
3114}
3115
3116// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3117// ::= DT <expression> E # decltype of an expression (C++0x)
3118Node *Db::parseDecltype() {
3119 if (!consumeIf('D'))
3120 return nullptr;
3121 if (!consumeIf('t') && !consumeIf('T'))
3122 return nullptr;
3123 Node *E = parseExpr();
3124 if (E == nullptr)
3125 return nullptr;
3126 if (!consumeIf('E'))
3127 return nullptr;
3128 return make<EnclosingExpr>("decltype(", E, ")");
3129}
3130
3131// <array-type> ::= A <positive dimension number> _ <element type>
3132// ::= A [<dimension expression>] _ <element type>
3133Node *Db::parseArrayType() {
3134 if (!consumeIf('A'))
3135 return nullptr;
3136
3137 if (std::isdigit(look())) {
3138 StringView Dimension = parseNumber();
3139 if (!consumeIf('_'))
3140 return nullptr;
3141 Node *Ty = parseType();
3142 if (Ty == nullptr)
3143 return nullptr;
3144 return make<ArrayType>(Ty, Dimension);
3145 }
3146
3147 if (!consumeIf('_')) {
3148 Node *DimExpr = parseExpr();
3149 if (DimExpr == nullptr)
3150 return nullptr;
3151 if (!consumeIf('_'))
3152 return nullptr;
3153 Node *ElementType = parseType();
3154 if (ElementType == nullptr)
3155 return nullptr;
3156 return make<ArrayType>(ElementType, DimExpr);
3157 }
3158
3159 Node *Ty = parseType();
3160 if (Ty == nullptr)
3161 return nullptr;
3162 return make<ArrayType>(Ty);
3163}
3164
3165// <pointer-to-member-type> ::= M <class type> <member type>
3166Node *Db::parsePointerToMemberType() {
3167 if (!consumeIf('M'))
3168 return nullptr;
3169 Node *ClassType = parseType();
3170 if (ClassType == nullptr)
3171 return nullptr;
3172 Node *MemberType = parseType();
3173 if (MemberType == nullptr)
3174 return nullptr;
3175 return make<PointerToMemberType>(ClassType, MemberType);
3176}
3177
3178// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3179// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3180// ::= Tu <name> # dependent elaborated type specifier using 'union'
3181// ::= Te <name> # dependent elaborated type specifier using 'enum'
3182Node *Db::parseClassEnumType() {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003183 StringView ElabSpef;
3184 if (consumeIf("Ts"))
3185 ElabSpef = "struct";
3186 else if (consumeIf("Tu"))
3187 ElabSpef = "union";
3188 else if (consumeIf("Te"))
3189 ElabSpef = "enum";
3190
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003191 Node *Name = parseName();
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003192 if (Name == nullptr)
3193 return nullptr;
3194
3195 if (!ElabSpef.empty())
3196 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3197
3198 return Name;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003199}
3200
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003201// <qualified-type> ::= <qualifiers> <type>
3202// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3203// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003204Node *Db::parseQualifiedType() {
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003205 if (consumeIf('U')) {
3206 StringView Qual = parseBareSourceName();
3207 if (Qual.empty())
3208 return nullptr;
3209
3210 // FIXME parse the optional <template-args> here!
3211
3212 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3213 if (Qual.startsWith("objcproto")) {
3214 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3215 StringView Proto;
3216 {
3217 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3218 SaveLast(Last, ProtoSourceName.end());
3219 Proto = parseBareSourceName();
3220 }
3221 if (Proto.empty())
3222 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003223 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003224 if (Child == nullptr)
3225 return nullptr;
3226 return make<ObjCProtoName>(Child, Proto);
3227 }
3228
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003229 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003230 if (Child == nullptr)
3231 return nullptr;
3232 return make<VendorExtQualType>(Child, Qual);
3233 }
3234
3235 Qualifiers Quals = parseCVQualifiers();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003236 Node *Ty = parseType();
3237 if (Ty == nullptr)
3238 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003239 if (Quals != QualNone)
3240 Ty = make<QualType>(Ty, Quals);
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003241 return Ty;
3242}
3243
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003244// <type> ::= <builtin-type>
3245// ::= <qualified-type>
3246// ::= <function-type>
3247// ::= <class-enum-type>
3248// ::= <array-type>
3249// ::= <pointer-to-member-type>
3250// ::= <template-param>
3251// ::= <template-template-param> <template-args>
3252// ::= <decltype>
3253// ::= P <type> # pointer
3254// ::= R <type> # l-value reference
3255// ::= O <type> # r-value reference (C++11)
3256// ::= C <type> # complex pair (C99)
3257// ::= G <type> # imaginary (C99)
3258// ::= <substitution> # See Compression below
3259// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3260// extension ::= <vector-type> # <vector-type> starts with Dv
3261//
3262// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3263// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
3264Node *Db::parseType() {
3265 Node *Result = nullptr;
3266
3267 switch (look()) {
3268 // ::= <qualified-type>
3269 case 'r':
3270 case 'V':
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003271 case 'K': {
3272 unsigned AfterQuals = 0;
3273 if (look(AfterQuals) == 'r') ++AfterQuals;
3274 if (look(AfterQuals) == 'V') ++AfterQuals;
3275 if (look(AfterQuals) == 'K') ++AfterQuals;
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003276
3277 if (look(AfterQuals) == 'F' ||
3278 (look(AfterQuals) == 'D' &&
3279 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3280 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003281 Result = parseFunctionType();
3282 break;
3283 }
3284 _LIBCPP_FALLTHROUGH();
3285 }
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003286 case 'U': {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003287 Result = parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003288 break;
3289 }
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003290 // <builtin-type> ::= v # void
3291 case 'v':
3292 ++First;
3293 return make<NameType>("void");
3294 // ::= w # wchar_t
3295 case 'w':
3296 ++First;
3297 return make<NameType>("wchar_t");
3298 // ::= b # bool
3299 case 'b':
3300 ++First;
3301 return make<NameType>("bool");
3302 // ::= c # char
3303 case 'c':
3304 ++First;
3305 return make<NameType>("char");
3306 // ::= a # signed char
3307 case 'a':
3308 ++First;
3309 return make<NameType>("signed char");
3310 // ::= h # unsigned char
3311 case 'h':
3312 ++First;
3313 return make<NameType>("unsigned char");
3314 // ::= s # short
3315 case 's':
3316 ++First;
3317 return make<NameType>("short");
3318 // ::= t # unsigned short
3319 case 't':
3320 ++First;
3321 return make<NameType>("unsigned short");
3322 // ::= i # int
3323 case 'i':
3324 ++First;
3325 return make<NameType>("int");
3326 // ::= j # unsigned int
3327 case 'j':
3328 ++First;
3329 return make<NameType>("unsigned int");
3330 // ::= l # long
3331 case 'l':
3332 ++First;
3333 return make<NameType>("long");
3334 // ::= m # unsigned long
3335 case 'm':
3336 ++First;
3337 return make<NameType>("unsigned long");
3338 // ::= x # long long, __int64
3339 case 'x':
3340 ++First;
3341 return make<NameType>("long long");
3342 // ::= y # unsigned long long, __int64
3343 case 'y':
3344 ++First;
3345 return make<NameType>("unsigned long long");
3346 // ::= n # __int128
3347 case 'n':
3348 ++First;
3349 return make<NameType>("__int128");
3350 // ::= o # unsigned __int128
3351 case 'o':
3352 ++First;
3353 return make<NameType>("unsigned __int128");
3354 // ::= f # float
3355 case 'f':
3356 ++First;
3357 return make<NameType>("float");
3358 // ::= d # double
3359 case 'd':
3360 ++First;
3361 return make<NameType>("double");
3362 // ::= e # long double, __float80
3363 case 'e':
3364 ++First;
3365 return make<NameType>("long double");
3366 // ::= g # __float128
3367 case 'g':
3368 ++First;
3369 return make<NameType>("__float128");
3370 // ::= z # ellipsis
3371 case 'z':
3372 ++First;
3373 return make<NameType>("...");
3374
3375 // <builtin-type> ::= u <source-name> # vendor extended type
3376 case 'u': {
3377 ++First;
3378 StringView Res = parseBareSourceName();
3379 if (Res.empty())
3380 return nullptr;
3381 return make<NameType>(Res);
3382 }
3383 case 'D':
3384 switch (look(1)) {
3385 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3386 case 'd':
3387 First += 2;
3388 return make<NameType>("decimal64");
3389 // ::= De # IEEE 754r decimal floating point (128 bits)
3390 case 'e':
3391 First += 2;
3392 return make<NameType>("decimal128");
3393 // ::= Df # IEEE 754r decimal floating point (32 bits)
3394 case 'f':
3395 First += 2;
3396 return make<NameType>("decimal32");
3397 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3398 case 'h':
3399 First += 2;
3400 return make<NameType>("decimal16");
3401 // ::= Di # char32_t
3402 case 'i':
3403 First += 2;
3404 return make<NameType>("char32_t");
3405 // ::= Ds # char16_t
3406 case 's':
3407 First += 2;
3408 return make<NameType>("char16_t");
3409 // ::= Da # auto (in dependent new-expressions)
3410 case 'a':
3411 First += 2;
3412 return make<NameType>("auto");
3413 // ::= Dc # decltype(auto)
3414 case 'c':
3415 First += 2;
3416 return make<NameType>("decltype(auto)");
3417 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3418 case 'n':
3419 First += 2;
3420 return make<NameType>("std::nullptr_t");
3421
3422 // ::= <decltype>
3423 case 't':
3424 case 'T': {
3425 Result = parseDecltype();
3426 break;
3427 }
3428 // extension ::= <vector-type> # <vector-type> starts with Dv
3429 case 'v': {
3430 Result = parseVectorType();
3431 break;
3432 }
3433 // ::= Dp <type> # pack expansion (C++0x)
3434 case 'p': {
3435 First += 2;
3436 Node *Child = parseType();
3437 if (!Child)
3438 return nullptr;
3439 Result = make<ParameterPackExpansion>(Child);
3440 break;
3441 }
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003442 // Exception specifier on a function type.
3443 case 'o':
3444 case 'O':
3445 case 'w':
3446 // Transaction safe function type.
3447 case 'x':
3448 Result = parseFunctionType();
3449 break;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003450 }
3451 break;
3452 // ::= <function-type>
3453 case 'F': {
3454 Result = parseFunctionType();
3455 break;
3456 }
3457 // ::= <array-type>
3458 case 'A': {
3459 Result = parseArrayType();
3460 break;
3461 }
3462 // ::= <pointer-to-member-type>
3463 case 'M': {
3464 Result = parsePointerToMemberType();
3465 break;
3466 }
3467 // ::= <template-param>
3468 case 'T': {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003469 // This could be an elaborate type specifier on a <class-enum-type>.
3470 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
3471 Result = parseClassEnumType();
3472 break;
3473 }
3474
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003475 Result = parseTemplateParam();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003476 if (Result == nullptr)
3477 return nullptr;
3478
3479 // Result could be either of:
3480 // <type> ::= <template-param>
3481 // <type> ::= <template-template-param> <template-args>
3482 //
3483 // <template-template-param> ::= <template-param>
3484 // ::= <substitution>
3485 //
3486 // If this is followed by some <template-args>, and we're permitted to
3487 // parse them, take the second production.
3488
3489 if (TryToParseTemplateArgs && look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003490 Node *TA = parseTemplateArgs();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003491 if (TA == nullptr)
3492 return nullptr;
3493 Result = make<NameWithTemplateArgs>(Result, TA);
3494 }
3495 break;
3496 }
3497 // ::= P <type> # pointer
3498 case 'P': {
3499 ++First;
3500 Node *Ptr = parseType();
3501 if (Ptr == nullptr)
3502 return nullptr;
3503 Result = make<PointerType>(Ptr);
3504 break;
3505 }
3506 // ::= R <type> # l-value reference
3507 case 'R': {
3508 ++First;
3509 Node *Ref = parseType();
3510 if (Ref == nullptr)
3511 return nullptr;
3512 Result = make<LValueReferenceType>(Ref);
3513 break;
3514 }
3515 // ::= O <type> # r-value reference (C++11)
3516 case 'O': {
3517 ++First;
3518 Node *Ref = parseType();
3519 if (Ref == nullptr)
3520 return nullptr;
3521 Result = make<RValueReferenceType>(Ref);
3522 break;
3523 }
3524 // ::= C <type> # complex pair (C99)
3525 case 'C': {
3526 ++First;
3527 Node *P = parseType();
3528 if (P == nullptr)
3529 return nullptr;
3530 Result = make<PostfixQualifiedType>(P, " complex");
3531 break;
3532 }
3533 // ::= G <type> # imaginary (C99)
3534 case 'G': {
3535 ++First;
3536 Node *P = parseType();
3537 if (P == nullptr)
3538 return P;
3539 Result = make<PostfixQualifiedType>(P, " imaginary");
3540 break;
3541 }
3542 // ::= <substitution> # See Compression below
3543 case 'S': {
3544 if (look(1) && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003545 Node *Sub = parseSubstitution();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003546 if (Sub == nullptr)
3547 return nullptr;
3548
3549 // Sub could be either of:
3550 // <type> ::= <substitution>
3551 // <type> ::= <template-template-param> <template-args>
3552 //
3553 // <template-template-param> ::= <template-param>
3554 // ::= <substitution>
3555 //
3556 // If this is followed by some <template-args>, and we're permitted to
3557 // parse them, take the second production.
3558
3559 if (TryToParseTemplateArgs && look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003560 Node *TA = parseTemplateArgs();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003561 if (TA == nullptr)
3562 return nullptr;
3563 Result = make<NameWithTemplateArgs>(Sub, TA);
3564 break;
3565 }
3566
3567 // If all we parsed was a substitution, don't re-insert into the
3568 // substitution table.
3569 return Sub;
3570 }
3571 _LIBCPP_FALLTHROUGH();
3572 }
3573 // ::= <class-enum-type>
3574 default: {
3575 Result = parseClassEnumType();
3576 break;
3577 }
3578 }
3579
3580 // If we parsed a type, insert it into the substitution table. Note that all
3581 // <builtin-type>s and <substitution>s have already bailed out, because they
3582 // don't get substitutions.
3583 if (Result != nullptr)
3584 Subs.push_back(Result);
3585 return Result;
3586}
3587
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003588Node *Db::parsePrefixExpr(StringView Kind) {
3589 Node *E = parseExpr();
3590 if (E == nullptr)
3591 return nullptr;
3592 return make<PrefixExpr>(Kind, E);
3593}
3594
3595Node *Db::parseBinaryExpr(StringView Kind) {
3596 Node *LHS = parseExpr();
3597 if (LHS == nullptr)
3598 return nullptr;
3599 Node *RHS = parseExpr();
3600 if (RHS == nullptr)
3601 return nullptr;
3602 return make<BinaryExpr>(LHS, Kind, RHS);
3603}
3604
3605Node *Db::parseIntegerLiteral(StringView Lit) {
3606 StringView Tmp = parseNumber(true);
3607 if (!Tmp.empty() && consumeIf('E'))
3608 return make<IntegerExpr>(Lit, Tmp);
3609 return nullptr;
3610}
3611
Erik Pilkington2808f772018-02-13 17:09:03 +00003612// <CV-Qualifiers> ::= [r] [V] [K]
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003613Qualifiers Db::parseCVQualifiers() {
3614 Qualifiers CVR = QualNone;
3615 if (consumeIf('r'))
3616 addQualifiers(CVR, QualRestrict);
3617 if (consumeIf('V'))
3618 addQualifiers(CVR, QualVolatile);
3619 if (consumeIf('K'))
3620 addQualifiers(CVR, QualConst);
3621 return CVR;
3622}
3623
3624// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
3625// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
3626// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
3627// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
3628Node *Db::parseFunctionParam() {
3629 if (consumeIf("fp")) {
3630 parseCVQualifiers();
3631 StringView Num = parseNumber();
3632 if (!consumeIf('_'))
3633 return nullptr;
3634 return make<FunctionParam>(Num);
3635 }
3636 if (consumeIf("fL")) {
3637 if (parseNumber().empty())
3638 return nullptr;
3639 if (!consumeIf('p'))
3640 return nullptr;
3641 parseCVQualifiers();
3642 StringView Num = parseNumber();
3643 if (!consumeIf('_'))
3644 return nullptr;
3645 return make<FunctionParam>(Num);
3646 }
3647 return nullptr;
3648}
3649
3650// [gs] nw <expression>* _ <type> E # new (expr-list) type
3651// [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3652// [gs] na <expression>* _ <type> E # new[] (expr-list) type
3653// [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3654// <initializer> ::= pi <expression>* E # parenthesized initialization
3655Node *Db::parseNewExpr() {
3656 bool Global = consumeIf("gs");
3657 bool IsArray = look(1) == 'a';
3658 if (!consumeIf("nw") && !consumeIf("na"))
3659 return nullptr;
3660 size_t Exprs = Names.size();
3661 while (!consumeIf('_')) {
3662 Node *Ex = parseExpr();
3663 if (Ex == nullptr)
3664 return nullptr;
3665 Names.push_back(Ex);
3666 }
3667 NodeArray ExprList = popTrailingNodeArray(Exprs);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003668 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003669 if (Ty == nullptr)
3670 return Ty;
3671 if (consumeIf("pi")) {
3672 size_t InitsBegin = Names.size();
3673 while (!consumeIf('E')) {
3674 Node *Init = parseExpr();
3675 if (Init == nullptr)
3676 return Init;
3677 Names.push_back(Init);
3678 }
3679 NodeArray Inits = popTrailingNodeArray(InitsBegin);
3680 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
3681 } else if (!consumeIf('E'))
3682 return nullptr;
3683 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
3684}
3685
3686// cv <type> <expression> # conversion with one argument
3687// cv <type> _ <expression>* E # conversion with a different number of arguments
3688Node *Db::parseConversionExpr() {
3689 if (!consumeIf("cv"))
3690 return nullptr;
3691 Node *Ty;
3692 {
3693 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003694 Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003695 }
3696
3697 if (Ty == nullptr)
3698 return nullptr;
3699
3700 if (consumeIf('_')) {
3701 size_t ExprsBegin = Names.size();
3702 while (!consumeIf('E')) {
3703 Node *E = parseExpr();
3704 if (E == nullptr)
3705 return E;
3706 Names.push_back(E);
3707 }
3708 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
3709 return make<ConversionExpr>(Ty, Exprs);
3710 }
3711
3712 Node *E[1] = {parseExpr()};
3713 if (E[0] == nullptr)
3714 return nullptr;
3715 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
3716}
3717
3718// <expr-primary> ::= L <type> <value number> E # integer literal
3719// ::= L <type> <value float> E # floating literal
3720// ::= L <string type> E # string literal
3721// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
3722// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
3723// ::= L <mangled-name> E # external name
3724Node *Db::parseExprPrimary() {
3725 if (!consumeIf('L'))
3726 return nullptr;
3727 switch (look()) {
3728 case 'w':
3729 ++First;
3730 return parseIntegerLiteral("wchar_t");
3731 case 'b':
3732 if (consumeIf("b0E"))
3733 return make<BoolExpr>(0);
3734 if (consumeIf("b1E"))
3735 return make<BoolExpr>(1);
3736 return nullptr;
3737 case 'c':
3738 ++First;
3739 return parseIntegerLiteral("char");
3740 case 'a':
3741 ++First;
3742 return parseIntegerLiteral("signed char");
3743 case 'h':
3744 ++First;
3745 return parseIntegerLiteral("unsigned char");
3746 case 's':
3747 ++First;
3748 return parseIntegerLiteral("short");
3749 case 't':
3750 ++First;
3751 return parseIntegerLiteral("unsigned short");
3752 case 'i':
3753 ++First;
3754 return parseIntegerLiteral("");
3755 case 'j':
3756 ++First;
3757 return parseIntegerLiteral("u");
3758 case 'l':
3759 ++First;
3760 return parseIntegerLiteral("l");
3761 case 'm':
3762 ++First;
3763 return parseIntegerLiteral("ul");
3764 case 'x':
3765 ++First;
3766 return parseIntegerLiteral("ll");
3767 case 'y':
3768 ++First;
3769 return parseIntegerLiteral("ull");
3770 case 'n':
3771 ++First;
3772 return parseIntegerLiteral("__int128");
3773 case 'o':
3774 ++First;
3775 return parseIntegerLiteral("unsigned __int128");
3776 case 'f':
3777 ++First;
3778 return parseFloatingLiteral<float>();
3779 case 'd':
3780 ++First;
3781 return parseFloatingLiteral<double>();
3782 case 'e':
3783 ++First;
3784 return parseFloatingLiteral<long double>();
3785 case '_':
3786 if (consumeIf("_Z")) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003787 Node *R = parseEncoding();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003788 if (R != nullptr && consumeIf('E'))
3789 return R;
3790 }
3791 return nullptr;
3792 case 'T':
3793 // Invalid mangled name per
3794 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
3795 return nullptr;
3796 default: {
3797 // might be named type
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003798 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003799 if (T == nullptr)
3800 return nullptr;
3801 StringView N = parseNumber();
3802 if (!N.empty()) {
3803 if (!consumeIf('E'))
3804 return nullptr;
3805 return make<IntegerCastExpr>(T, N);
3806 }
3807 if (consumeIf('E'))
3808 return T;
3809 return nullptr;
3810 }
3811 }
3812}
3813
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003814// <braced-expression> ::= <expression>
3815// ::= di <field source-name> <braced-expression> # .name = expr
3816// ::= dx <index expression> <braced-expression> # [expr] = expr
3817// ::= dX <range begin expression> <range end expression> <braced-expression>
3818Node *Db::parseBracedExpr() {
3819 if (look() == 'd') {
3820 switch (look(1)) {
3821 case 'i': {
3822 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003823 Node *Field = parseSourceName(/*NameState=*/nullptr);
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003824 if (Field == nullptr)
3825 return nullptr;
3826 Node *Init = parseBracedExpr();
3827 if (Init == nullptr)
3828 return nullptr;
3829 return make<BracedExpr>(Field, Init, /*isArray=*/false);
3830 }
3831 case 'x': {
3832 First += 2;
3833 Node *Index = parseExpr();
3834 if (Index == nullptr)
3835 return nullptr;
3836 Node *Init = parseBracedExpr();
3837 if (Init == nullptr)
3838 return nullptr;
3839 return make<BracedExpr>(Index, Init, /*isArray=*/true);
3840 }
3841 case 'X': {
3842 First += 2;
3843 Node *RangeBegin = parseExpr();
3844 if (RangeBegin == nullptr)
3845 return nullptr;
3846 Node *RangeEnd = parseExpr();
3847 if (RangeEnd == nullptr)
3848 return nullptr;
3849 Node *Init = parseBracedExpr();
3850 if (Init == nullptr)
3851 return nullptr;
3852 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
3853 }
3854 }
3855 }
3856 return parseExpr();
3857}
3858
Erik Pilkington967b00e2018-04-09 18:33:01 +00003859// (not yet in the spec)
3860// <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
3861// ::= fR <binary-operator-name> <expression> <expression>
3862// ::= fl <binary-operator-name> <expression>
3863// ::= fr <binary-operator-name> <expression>
3864Node *Db::parseFoldExpr() {
3865 if (!consumeIf('f'))
3866 return nullptr;
3867
3868 char FoldKind = look();
3869 bool IsLeftFold, HasInitializer;
3870 HasInitializer = FoldKind == 'L' || FoldKind == 'R';
3871 if (FoldKind == 'l' || FoldKind == 'L')
3872 IsLeftFold = true;
3873 else if (FoldKind == 'r' || FoldKind == 'R')
3874 IsLeftFold = false;
3875 else
3876 return nullptr;
3877 ++First;
3878
3879 // FIXME: This map is duplicated in parseOperatorName and parseExpr.
3880 StringView OperatorName;
3881 if (consumeIf("aa")) OperatorName = "&&";
3882 else if (consumeIf("an")) OperatorName = "&";
3883 else if (consumeIf("aN")) OperatorName = "&=";
3884 else if (consumeIf("aS")) OperatorName = "=";
3885 else if (consumeIf("cm")) OperatorName = ",";
3886 else if (consumeIf("ds")) OperatorName = ".*";
3887 else if (consumeIf("dv")) OperatorName = "/";
3888 else if (consumeIf("dV")) OperatorName = "/=";
3889 else if (consumeIf("eo")) OperatorName = "^";
3890 else if (consumeIf("eO")) OperatorName = "^=";
3891 else if (consumeIf("eq")) OperatorName = "==";
3892 else if (consumeIf("ge")) OperatorName = ">=";
3893 else if (consumeIf("gt")) OperatorName = ">";
3894 else if (consumeIf("le")) OperatorName = "<=";
3895 else if (consumeIf("ls")) OperatorName = "<<";
3896 else if (consumeIf("lS")) OperatorName = "<<=";
3897 else if (consumeIf("lt")) OperatorName = "<";
3898 else if (consumeIf("mi")) OperatorName = "-";
3899 else if (consumeIf("mI")) OperatorName = "-=";
3900 else if (consumeIf("ml")) OperatorName = "*";
3901 else if (consumeIf("mL")) OperatorName = "*=";
3902 else if (consumeIf("ne")) OperatorName = "!=";
3903 else if (consumeIf("oo")) OperatorName = "||";
3904 else if (consumeIf("or")) OperatorName = "|";
3905 else if (consumeIf("oR")) OperatorName = "|=";
3906 else if (consumeIf("pl")) OperatorName = "+";
3907 else if (consumeIf("pL")) OperatorName = "+=";
3908 else if (consumeIf("rm")) OperatorName = "%";
3909 else if (consumeIf("rM")) OperatorName = "%=";
3910 else if (consumeIf("rs")) OperatorName = ">>";
3911 else if (consumeIf("rS")) OperatorName = ">>=";
3912 else return nullptr;
3913
3914 Node *Pack = parseExpr(), *Init = nullptr;
3915 if (Pack == nullptr)
3916 return nullptr;
3917 if (HasInitializer) {
3918 Init = parseExpr();
3919 if (Init == nullptr)
3920 return nullptr;
3921 }
3922
3923 if (IsLeftFold && Init)
3924 std::swap(Pack, Init);
3925
3926 return make<FoldExpr>(IsLeftFold, OperatorName, Pack, Init);
3927}
3928
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003929// <expression> ::= <unary operator-name> <expression>
3930// ::= <binary operator-name> <expression> <expression>
3931// ::= <ternary operator-name> <expression> <expression> <expression>
3932// ::= cl <expression>+ E # call
3933// ::= cv <type> <expression> # conversion with one argument
3934// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3935// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
3936// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3937// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
3938// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3939// ::= [gs] dl <expression> # delete expression
3940// ::= [gs] da <expression> # delete[] expression
3941// ::= pp_ <expression> # prefix ++
3942// ::= mm_ <expression> # prefix --
3943// ::= ti <type> # typeid (type)
3944// ::= te <expression> # typeid (expression)
3945// ::= dc <type> <expression> # dynamic_cast<type> (expression)
3946// ::= sc <type> <expression> # static_cast<type> (expression)
3947// ::= cc <type> <expression> # const_cast<type> (expression)
3948// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3949// ::= st <type> # sizeof (a type)
3950// ::= sz <expression> # sizeof (an expression)
3951// ::= at <type> # alignof (a type)
3952// ::= az <expression> # alignof (an expression)
3953// ::= nx <expression> # noexcept (expression)
3954// ::= <template-param>
3955// ::= <function-param>
3956// ::= dt <expression> <unresolved-name> # expr.name
3957// ::= pt <expression> <unresolved-name> # expr->name
3958// ::= ds <expression> <expression> # expr.*expr
3959// ::= sZ <template-param> # size of a parameter pack
3960// ::= sZ <function-param> # size of a function parameter pack
Erik Pilkington6a4e62b2018-04-09 18:31:50 +00003961// ::= sP <template-arg>* E # sizeof...(T), size of a captured template parameter pack from an alias template
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003962// ::= sp <expression> # pack expansion
3963// ::= tw <expression> # throw expression
3964// ::= tr # throw with no operand (rethrow)
3965// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
3966// # freestanding dependent name (e.g., T::x),
3967// # objectless nonstatic member reference
3968// ::= fL <binary-operator-name> <expression> <expression>
3969// ::= fR <binary-operator-name> <expression> <expression>
3970// ::= fl <binary-operator-name> <expression>
3971// ::= fr <binary-operator-name> <expression>
3972// ::= <expr-primary>
3973Node *Db::parseExpr() {
3974 bool Global = consumeIf("gs");
3975 if (numLeft() < 2)
3976 return nullptr;
3977
3978 switch (*First) {
3979 case 'L':
3980 return parseExprPrimary();
3981 case 'T':
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003982 return parseTemplateParam();
Erik Pilkington967b00e2018-04-09 18:33:01 +00003983 case 'f': {
3984 // Disambiguate a fold expression from a <function-param>.
3985 if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
3986 return parseFunctionParam();
3987 return parseFoldExpr();
3988 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003989 case 'a':
3990 switch (First[1]) {
3991 case 'a':
3992 First += 2;
3993 return parseBinaryExpr("&&");
3994 case 'd':
3995 First += 2;
3996 return parsePrefixExpr("&");
3997 case 'n':
3998 First += 2;
3999 return parseBinaryExpr("&");
4000 case 'N':
4001 First += 2;
4002 return parseBinaryExpr("&=");
4003 case 'S':
4004 First += 2;
4005 return parseBinaryExpr("=");
4006 case 't': {
4007 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004008 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004009 if (Ty == nullptr)
4010 return nullptr;
4011 return make<EnclosingExpr>("alignof (", Ty, ")");
4012 }
4013 case 'z': {
4014 First += 2;
4015 Node *Ty = parseExpr();
4016 if (Ty == nullptr)
4017 return nullptr;
4018 return make<EnclosingExpr>("alignof (", Ty, ")");
4019 }
4020 }
4021 return nullptr;
4022 case 'c':
4023 switch (First[1]) {
4024 // cc <type> <expression> # const_cast<type>(expression)
4025 case 'c': {
4026 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004027 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004028 if (Ty == nullptr)
4029 return Ty;
4030 Node *Ex = parseExpr();
4031 if (Ex == nullptr)
4032 return Ex;
4033 return make<CastExpr>("const_cast", Ty, Ex);
4034 }
4035 // cl <expression>+ E # call
4036 case 'l': {
4037 First += 2;
4038 Node *Callee = parseExpr();
4039 if (Callee == nullptr)
4040 return Callee;
4041 size_t ExprsBegin = Names.size();
4042 while (!consumeIf('E')) {
4043 Node *E = parseExpr();
4044 if (E == nullptr)
4045 return E;
4046 Names.push_back(E);
4047 }
4048 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
4049 }
4050 case 'm':
4051 First += 2;
4052 return parseBinaryExpr(",");
4053 case 'o':
4054 First += 2;
4055 return parsePrefixExpr("~");
4056 case 'v':
4057 return parseConversionExpr();
4058 }
4059 return nullptr;
4060 case 'd':
4061 switch (First[1]) {
4062 case 'a': {
4063 First += 2;
4064 Node *Ex = parseExpr();
4065 if (Ex == nullptr)
4066 return Ex;
4067 return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
4068 }
4069 case 'c': {
4070 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004071 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004072 if (T == nullptr)
4073 return T;
4074 Node *Ex = parseExpr();
4075 if (Ex == nullptr)
4076 return Ex;
4077 return make<CastExpr>("dynamic_cast", T, Ex);
4078 }
4079 case 'e':
4080 First += 2;
4081 return parsePrefixExpr("*");
4082 case 'l': {
4083 First += 2;
4084 Node *E = parseExpr();
4085 if (E == nullptr)
4086 return E;
4087 return make<DeleteExpr>(E, Global, /*is_array=*/false);
4088 }
4089 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004090 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004091 case 's': {
4092 First += 2;
4093 Node *LHS = parseExpr();
4094 if (LHS == nullptr)
4095 return nullptr;
4096 Node *RHS = parseExpr();
4097 if (RHS == nullptr)
4098 return nullptr;
4099 return make<MemberExpr>(LHS, ".*", RHS);
4100 }
4101 case 't': {
4102 First += 2;
4103 Node *LHS = parseExpr();
4104 if (LHS == nullptr)
4105 return LHS;
4106 Node *RHS = parseExpr();
4107 if (RHS == nullptr)
4108 return nullptr;
4109 return make<MemberExpr>(LHS, ".", RHS);
4110 }
4111 case 'v':
4112 First += 2;
4113 return parseBinaryExpr("/");
4114 case 'V':
4115 First += 2;
4116 return parseBinaryExpr("/=");
4117 }
4118 return nullptr;
4119 case 'e':
4120 switch (First[1]) {
4121 case 'o':
4122 First += 2;
4123 return parseBinaryExpr("^");
4124 case 'O':
4125 First += 2;
4126 return parseBinaryExpr("^=");
4127 case 'q':
4128 First += 2;
4129 return parseBinaryExpr("==");
4130 }
4131 return nullptr;
4132 case 'g':
4133 switch (First[1]) {
4134 case 'e':
4135 First += 2;
4136 return parseBinaryExpr(">=");
4137 case 't':
4138 First += 2;
4139 return parseBinaryExpr(">");
4140 }
4141 return nullptr;
4142 case 'i':
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004143 switch (First[1]) {
4144 case 'x': {
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004145 First += 2;
4146 Node *Base = parseExpr();
4147 if (Base == nullptr)
4148 return nullptr;
4149 Node *Index = parseExpr();
4150 if (Index == nullptr)
4151 return Index;
4152 return make<ArraySubscriptExpr>(Base, Index);
4153 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004154 case 'l': {
4155 First += 2;
4156 size_t InitsBegin = Names.size();
4157 while (!consumeIf('E')) {
4158 Node *E = parseBracedExpr();
4159 if (E == nullptr)
4160 return nullptr;
4161 Names.push_back(E);
4162 }
4163 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4164 }
4165 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004166 return nullptr;
4167 case 'l':
4168 switch (First[1]) {
4169 case 'e':
4170 First += 2;
4171 return parseBinaryExpr("<=");
4172 case 's':
4173 First += 2;
4174 return parseBinaryExpr("<<");
4175 case 'S':
4176 First += 2;
4177 return parseBinaryExpr("<<=");
4178 case 't':
4179 First += 2;
4180 return parseBinaryExpr("<");
4181 }
4182 return nullptr;
4183 case 'm':
4184 switch (First[1]) {
4185 case 'i':
4186 First += 2;
4187 return parseBinaryExpr("-");
4188 case 'I':
4189 First += 2;
4190 return parseBinaryExpr("-=");
4191 case 'l':
4192 First += 2;
4193 return parseBinaryExpr("*");
4194 case 'L':
4195 First += 2;
4196 return parseBinaryExpr("*=");
4197 case 'm':
4198 First += 2;
4199 if (consumeIf('_'))
4200 return parsePrefixExpr("--");
4201 Node *Ex = parseExpr();
4202 if (Ex == nullptr)
4203 return nullptr;
4204 return make<PostfixExpr>(Ex, "--");
4205 }
4206 return nullptr;
4207 case 'n':
4208 switch (First[1]) {
4209 case 'a':
4210 case 'w':
4211 return parseNewExpr();
4212 case 'e':
4213 First += 2;
4214 return parseBinaryExpr("!=");
4215 case 'g':
4216 First += 2;
4217 return parsePrefixExpr("-");
4218 case 't':
4219 First += 2;
4220 return parsePrefixExpr("!");
4221 case 'x':
4222 First += 2;
4223 Node *Ex = parseExpr();
4224 if (Ex == nullptr)
4225 return Ex;
4226 return make<EnclosingExpr>("noexcept (", Ex, ")");
4227 }
4228 return nullptr;
4229 case 'o':
4230 switch (First[1]) {
4231 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004232 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004233 case 'o':
4234 First += 2;
4235 return parseBinaryExpr("||");
4236 case 'r':
4237 First += 2;
4238 return parseBinaryExpr("|");
4239 case 'R':
4240 First += 2;
4241 return parseBinaryExpr("|=");
4242 }
4243 return nullptr;
4244 case 'p':
4245 switch (First[1]) {
4246 case 'm':
4247 First += 2;
4248 return parseBinaryExpr("->*");
4249 case 'l':
4250 First += 2;
4251 return parseBinaryExpr("+");
4252 case 'L':
4253 First += 2;
4254 return parseBinaryExpr("+=");
4255 case 'p': {
4256 First += 2;
4257 if (consumeIf('_'))
4258 return parsePrefixExpr("++");
4259 Node *Ex = parseExpr();
4260 if (Ex == nullptr)
4261 return Ex;
4262 return make<PostfixExpr>(Ex, "++");
4263 }
4264 case 's':
4265 First += 2;
4266 return parsePrefixExpr("+");
4267 case 't': {
4268 First += 2;
4269 Node *L = parseExpr();
4270 if (L == nullptr)
4271 return nullptr;
4272 Node *R = parseExpr();
4273 if (R == nullptr)
4274 return nullptr;
4275 return make<MemberExpr>(L, "->", R);
4276 }
4277 }
4278 return nullptr;
4279 case 'q':
4280 if (First[1] == 'u') {
4281 First += 2;
4282 Node *Cond = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004283 if (Cond == nullptr)
4284 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004285 Node *LHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004286 if (LHS == nullptr)
4287 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004288 Node *RHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004289 if (RHS == nullptr)
4290 return nullptr;
4291 return make<ConditionalExpr>(Cond, LHS, RHS);
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004292 }
4293 return nullptr;
4294 case 'r':
4295 switch (First[1]) {
4296 case 'c': {
4297 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004298 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004299 if (T == nullptr)
4300 return T;
4301 Node *Ex = parseExpr();
4302 if (Ex == nullptr)
4303 return Ex;
4304 return make<CastExpr>("reinterpret_cast", T, Ex);
4305 }
4306 case 'm':
4307 First += 2;
4308 return parseBinaryExpr("%");
4309 case 'M':
4310 First += 2;
4311 return parseBinaryExpr("%=");
4312 case 's':
4313 First += 2;
4314 return parseBinaryExpr(">>");
4315 case 'S':
4316 First += 2;
4317 return parseBinaryExpr(">>=");
4318 }
4319 return nullptr;
4320 case 's':
4321 switch (First[1]) {
4322 case 'c': {
4323 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004324 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004325 if (T == nullptr)
4326 return T;
4327 Node *Ex = parseExpr();
4328 if (Ex == nullptr)
4329 return Ex;
4330 return make<CastExpr>("static_cast", T, Ex);
4331 }
4332 case 'p': {
4333 First += 2;
4334 Node *Child = parseExpr();
4335 if (Child == nullptr)
4336 return nullptr;
4337 return make<ParameterPackExpansion>(Child);
4338 }
4339 case 'r':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004340 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004341 case 't': {
4342 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004343 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004344 if (Ty == nullptr)
4345 return Ty;
4346 return make<EnclosingExpr>("sizeof (", Ty, ")");
4347 }
4348 case 'z': {
4349 First += 2;
4350 Node *Ex = parseExpr();
4351 if (Ex == nullptr)
4352 return Ex;
4353 return make<EnclosingExpr>("sizeof (", Ex, ")");
4354 }
4355 case 'Z':
4356 First += 2;
4357 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004358 Node *R = parseTemplateParam();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004359 if (R == nullptr)
4360 return nullptr;
4361 return make<SizeofParamPackExpr>(R);
4362 } else if (look() == 'f') {
4363 Node *FP = parseFunctionParam();
4364 if (FP == nullptr)
4365 return nullptr;
Erik Pilkington6a4e62b2018-04-09 18:31:50 +00004366 return make<EnclosingExpr>("sizeof... (", FP, ")");
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004367 }
4368 return nullptr;
Erik Pilkington6a4e62b2018-04-09 18:31:50 +00004369 case 'P': {
4370 First += 2;
4371 size_t ArgsBegin = Names.size();
4372 while (!consumeIf('E')) {
4373 Node *Arg = parseTemplateArg();
4374 if (Arg == nullptr)
4375 return nullptr;
4376 Names.push_back(Arg);
4377 }
4378 return make<EnclosingExpr>(
4379 "sizeof... (", make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin)),
4380 ")");
4381 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004382 }
4383 return nullptr;
4384 case 't':
4385 switch (First[1]) {
4386 case 'e': {
4387 First += 2;
4388 Node *Ex = parseExpr();
4389 if (Ex == nullptr)
4390 return Ex;
4391 return make<EnclosingExpr>("typeid (", Ex, ")");
4392 }
4393 case 'i': {
4394 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004395 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004396 if (Ty == nullptr)
4397 return Ty;
4398 return make<EnclosingExpr>("typeid (", Ty, ")");
4399 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004400 case 'l': {
4401 First += 2;
4402 Node *Ty = parseType();
4403 if (Ty == nullptr)
4404 return nullptr;
4405 size_t InitsBegin = Names.size();
4406 while (!consumeIf('E')) {
4407 Node *E = parseBracedExpr();
4408 if (E == nullptr)
4409 return nullptr;
4410 Names.push_back(E);
4411 }
4412 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4413 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004414 case 'r':
4415 First += 2;
4416 return make<NameType>("throw");
4417 case 'w': {
4418 First += 2;
4419 Node *Ex = parseExpr();
4420 if (Ex == nullptr)
4421 return nullptr;
4422 return make<ThrowExpr>(Ex);
4423 }
4424 }
4425 return nullptr;
4426 case '1':
4427 case '2':
4428 case '3':
4429 case '4':
4430 case '5':
4431 case '6':
4432 case '7':
4433 case '8':
4434 case '9':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004435 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004436 }
4437 return nullptr;
4438}
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004439
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004440// <call-offset> ::= h <nv-offset> _
4441// ::= v <v-offset> _
4442//
4443// <nv-offset> ::= <offset number>
4444// # non-virtual base override
4445//
4446// <v-offset> ::= <offset number> _ <virtual offset number>
4447// # virtual base override, with vcall offset
4448bool Db::parseCallOffset() {
4449 // Just scan through the call offset, we never add this information into the
4450 // output.
4451 if (consumeIf('h'))
4452 return parseNumber(true).empty() || !consumeIf('_');
4453 if (consumeIf('v'))
4454 return parseNumber(true).empty() || !consumeIf('_') ||
4455 parseNumber(true).empty() || !consumeIf('_');
4456 return true;
4457}
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004458
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004459// <special-name> ::= TV <type> # virtual table
4460// ::= TT <type> # VTT structure (construction vtable index)
4461// ::= TI <type> # typeinfo structure
4462// ::= TS <type> # typeinfo name (null-terminated byte string)
4463// ::= Tc <call-offset> <call-offset> <base encoding>
4464// # base is the nominal target function of thunk
4465// # first call-offset is 'this' adjustment
4466// # second call-offset is result adjustment
4467// ::= T <call-offset> <base encoding>
4468// # base is the nominal target function of thunk
4469// ::= GV <object name> # Guard variable for one-time initialization
4470// # No <type>
4471// ::= TW <object name> # Thread-local wrapper
4472// ::= TH <object name> # Thread-local initialization
Erik Pilkingtond145e1f2018-03-10 21:31:22 +00004473// ::= GR <object name> _ # First temporary
4474// ::= GR <object name> <seq-id> _ # Subsequent temporaries
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004475// extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4476// extension ::= GR <object name> # reference temporary for object
4477Node *Db::parseSpecialName() {
4478 switch (look()) {
4479 case 'T':
4480 switch (look(1)) {
4481 // TV <type> # virtual table
4482 case 'V': {
4483 First += 2;
4484 Node *Ty = parseType();
4485 if (Ty == nullptr)
4486 return nullptr;
4487 return make<SpecialName>("vtable for ", Ty);
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004488 }
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004489 // TT <type> # VTT structure (construction vtable index)
4490 case 'T': {
4491 First += 2;
4492 Node *Ty = parseType();
4493 if (Ty == nullptr)
4494 return nullptr;
4495 return make<SpecialName>("VTT for ", Ty);
4496 }
4497 // TI <type> # typeinfo structure
4498 case 'I': {
4499 First += 2;
4500 Node *Ty = parseType();
4501 if (Ty == nullptr)
4502 return nullptr;
4503 return make<SpecialName>("typeinfo for ", Ty);
4504 }
4505 // TS <type> # typeinfo name (null-terminated byte string)
4506 case 'S': {
4507 First += 2;
4508 Node *Ty = parseType();
4509 if (Ty == nullptr)
4510 return nullptr;
4511 return make<SpecialName>("typeinfo name for ", Ty);
4512 }
4513 // Tc <call-offset> <call-offset> <base encoding>
4514 case 'c': {
4515 First += 2;
4516 if (parseCallOffset() || parseCallOffset())
4517 return nullptr;
4518 Node *Encoding = parseEncoding();
4519 if (Encoding == nullptr)
4520 return nullptr;
4521 return make<SpecialName>("covariant return thunk to ", Encoding);
4522 }
4523 // extension ::= TC <first type> <number> _ <second type>
4524 // # construction vtable for second-in-first
4525 case 'C': {
4526 First += 2;
4527 Node *FirstType = parseType();
4528 if (FirstType == nullptr)
4529 return nullptr;
4530 if (parseNumber(true).empty() || !consumeIf('_'))
4531 return nullptr;
4532 Node *SecondType = parseType();
4533 if (SecondType == nullptr)
4534 return nullptr;
4535 return make<CtorVtableSpecialName>(SecondType, FirstType);
4536 }
4537 // TW <object name> # Thread-local wrapper
4538 case 'W': {
4539 First += 2;
4540 Node *Name = parseName();
4541 if (Name == nullptr)
4542 return nullptr;
4543 return make<SpecialName>("thread-local wrapper routine for ", Name);
4544 }
4545 // TH <object name> # Thread-local initialization
4546 case 'H': {
4547 First += 2;
4548 Node *Name = parseName();
4549 if (Name == nullptr)
4550 return nullptr;
4551 return make<SpecialName>("thread-local initialization routine for ", Name);
4552 }
4553 // T <call-offset> <base encoding>
4554 default: {
4555 ++First;
4556 bool IsVirt = look() == 'v';
4557 if (parseCallOffset())
4558 return nullptr;
4559 Node *BaseEncoding = parseEncoding();
4560 if (BaseEncoding == nullptr)
4561 return nullptr;
4562 if (IsVirt)
4563 return make<SpecialName>("virtual thunk to ", BaseEncoding);
4564 else
4565 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
4566 }
4567 }
4568 case 'G':
4569 switch (look(1)) {
4570 // GV <object name> # Guard variable for one-time initialization
4571 case 'V': {
4572 First += 2;
4573 Node *Name = parseName();
4574 if (Name == nullptr)
4575 return nullptr;
4576 return make<SpecialName>("guard variable for ", Name);
4577 }
4578 // GR <object name> # reference temporary for object
Erik Pilkingtond145e1f2018-03-10 21:31:22 +00004579 // GR <object name> _ # First temporary
4580 // GR <object name> <seq-id> _ # Subsequent temporaries
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004581 case 'R': {
4582 First += 2;
4583 Node *Name = parseName();
4584 if (Name == nullptr)
4585 return nullptr;
Erik Pilkingtond145e1f2018-03-10 21:31:22 +00004586 size_t Count;
4587 bool ParsedSeqId = !parseSeqId(&Count);
4588 if (!consumeIf('_') && ParsedSeqId)
4589 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004590 return make<SpecialName>("reference temporary for ", Name);
4591 }
4592 }
4593 }
4594 return nullptr;
4595}
4596
4597// <encoding> ::= <function name> <bare-function-type>
4598// ::= <data name>
4599// ::= <special-name>
4600Node *Db::parseEncoding() {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004601 if (look() == 'G' || look() == 'T')
4602 return parseSpecialName();
4603
4604 auto IsEndOfEncoding = [&] {
4605 // The set of chars that can potentially follow an <encoding> (none of which
4606 // can start a <type>). Enumerating these allows us to avoid speculative
4607 // parsing.
4608 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
4609 };
4610
Erik Pilkington04f39852018-03-25 22:50:33 +00004611 NameState NameInfo(this);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004612 Node *Name = parseName(&NameInfo);
Erik Pilkington04f39852018-03-25 22:50:33 +00004613 if (Name == nullptr)
4614 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004615
Erik Pilkington04f39852018-03-25 22:50:33 +00004616 if (resolveForwardTemplateRefs(NameInfo))
4617 return nullptr;
4618
4619 if (IsEndOfEncoding())
4620 return Name;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004621
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +00004622 Node *Attrs = nullptr;
4623 if (consumeIf("Ua9enable_ifI")) {
4624 size_t BeforeArgs = Names.size();
4625 while (!consumeIf('E')) {
4626 Node *Arg = parseTemplateArg();
4627 if (Arg == nullptr)
4628 return nullptr;
4629 Names.push_back(Arg);
4630 }
4631 Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
4632 }
4633
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004634 Node *ReturnType = nullptr;
4635 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
4636 ReturnType = parseType();
4637 if (ReturnType == nullptr)
4638 return nullptr;
4639 }
4640
4641 if (consumeIf('v'))
4642 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +00004643 Attrs, NameInfo.CVQualifiers,
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004644 NameInfo.ReferenceQualifier);
4645
4646 size_t ParamsBegin = Names.size();
4647 do {
4648 Node *Ty = parseType();
4649 if (Ty == nullptr)
4650 return nullptr;
4651 Names.push_back(Ty);
4652 } while (!IsEndOfEncoding());
4653
4654 return make<FunctionEncoding>(ReturnType, Name,
4655 popTrailingNodeArray(ParamsBegin),
Erik Pilkingtonbb80c5c2018-03-25 22:49:16 +00004656 Attrs, NameInfo.CVQualifiers,
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004657 NameInfo.ReferenceQualifier);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004658}
4659
4660template <class Float>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004661struct FloatData;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004662
4663template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004664struct FloatData<float>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004665{
4666 static const size_t mangled_size = 8;
4667 static const size_t max_demangled_size = 24;
Howard Hinnantc62cbea2013-06-17 20:25:21 +00004668 static constexpr const char* spec = "%af";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004669};
4670
Erik Pilkington0024acd2017-07-28 00:43:49 +00004671constexpr const char* FloatData<float>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004672
4673template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004674struct FloatData<double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004675{
4676 static const size_t mangled_size = 16;
4677 static const size_t max_demangled_size = 32;
4678 static constexpr const char* spec = "%a";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004679};
4680
Erik Pilkington0024acd2017-07-28 00:43:49 +00004681constexpr const char* FloatData<double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004682
4683template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004684struct FloatData<long double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004685{
Dan Gohmand04ecd02016-01-13 16:39:30 +00004686#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
4687 defined(__wasm__)
Daniel Sanders52cf98b2015-07-30 16:11:04 +00004688 static const size_t mangled_size = 32;
Ben Craig9ef2c6e2016-01-20 14:10:23 +00004689#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
Logan Chien05d51bc2014-05-10 00:42:10 +00004690 static const size_t mangled_size = 16;
4691#else
Howard Hinnant6c33e762013-06-17 18:10:34 +00004692 static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms
Logan Chien05d51bc2014-05-10 00:42:10 +00004693#endif
Howard Hinnant6c33e762013-06-17 18:10:34 +00004694 static const size_t max_demangled_size = 40;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004695 static constexpr const char *spec = "%LaL";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004696};
4697
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004698constexpr const char *FloatData<long double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004699
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004700template <class Float> Node *Db::parseFloatingLiteral() {
4701 const size_t N = FloatData<Float>::mangled_size;
4702 if (numLeft() <= N)
4703 return nullptr;
4704 StringView Data(First, First + N);
4705 for (char C : Data)
4706 if (!std::isxdigit(C))
4707 return nullptr;
4708 First += N;
4709 if (!consumeIf('E'))
4710 return nullptr;
4711 return make<FloatExpr<Float>>(Data);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004712}
4713
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004714// <seq-id> ::= <0-9A-Z>+
4715bool Db::parseSeqId(size_t *Out) {
4716 if (!(look() >= '0' && look() <= '9') &&
4717 !(look() >= 'A' && look() <= 'Z'))
4718 return true;
4719
4720 size_t Id = 0;
4721 while (true) {
4722 if (look() >= '0' && look() <= '9') {
4723 Id *= 36;
4724 Id += static_cast<size_t>(look() - '0');
4725 } else if (look() >= 'A' && look() <= 'Z') {
4726 Id *= 36;
4727 Id += static_cast<size_t>(look() - 'A') + 10;
4728 } else {
4729 *Out = Id;
4730 return false;
4731 }
4732 ++First;
4733 }
4734}
4735
Howard Hinnant6c33e762013-06-17 18:10:34 +00004736// <substitution> ::= S <seq-id> _
4737// ::= S_
4738// <substitution> ::= Sa # ::std::allocator
4739// <substitution> ::= Sb # ::std::basic_string
4740// <substitution> ::= Ss # ::std::basic_string < char,
4741// ::std::char_traits<char>,
4742// ::std::allocator<char> >
4743// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
4744// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
4745// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004746Node *Db::parseSubstitution() {
4747 if (!consumeIf('S'))
4748 return nullptr;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004749
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004750 if (std::islower(look())) {
4751 Node *SpecialSub;
4752 switch (look()) {
4753 case 'a':
4754 ++First;
4755 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
4756 break;
4757 case 'b':
4758 ++First;
4759 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
4760 break;
4761 case 's':
4762 ++First;
4763 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
4764 break;
4765 case 'i':
4766 ++First;
4767 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
4768 break;
4769 case 'o':
4770 ++First;
4771 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
4772 break;
4773 case 'd':
4774 ++First;
4775 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
4776 break;
4777 default:
4778 return nullptr;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004779 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004780 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
4781 // has ABI tags, the tags are appended to the substitution; the result is a
4782 // substitutable component.
4783 Node *WithTags = parseAbiTags(SpecialSub);
4784 if (WithTags != SpecialSub) {
4785 Subs.push_back(WithTags);
4786 SpecialSub = WithTags;
4787 }
4788 return SpecialSub;
4789 }
4790
4791 // ::= S_
4792 if (consumeIf('_')) {
4793 if (Subs.empty())
4794 return nullptr;
4795 return Subs[0];
4796 }
4797
4798 // ::= S <seq-id> _
4799 size_t Index = 0;
4800 if (parseSeqId(&Index))
4801 return nullptr;
4802 ++Index;
4803 if (!consumeIf('_') || Index >= Subs.size())
4804 return nullptr;
4805 return Subs[Index];
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004806}
4807
Howard Hinnant6c33e762013-06-17 18:10:34 +00004808// <template-param> ::= T_ # first template parameter
4809// ::= T <parameter-2 non-negative number> _
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004810Node *Db::parseTemplateParam() {
4811 if (!consumeIf('T'))
4812 return nullptr;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004813
Erik Pilkington61966e52018-03-16 03:06:30 +00004814 size_t Index = 0;
4815 if (!consumeIf('_')) {
4816 if (parsePositiveInteger(&Index))
4817 return nullptr;
4818 ++Index;
4819 if (!consumeIf('_'))
4820 return nullptr;
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004821 }
4822
Erik Pilkington61966e52018-03-16 03:06:30 +00004823 // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter list
4824 // are mangled as the corresponding artificial template type parameter.
4825 if (ParsingLambdaParams)
4826 return make<NameType>("auto");
4827
Erik Pilkington04f39852018-03-25 22:50:33 +00004828 // If we're in a context where this <template-param> refers to a
4829 // <template-arg> further ahead in the mangled name (currently just conversion
4830 // operator types), then we should only look it up in the right context.
4831 if (PermitForwardTemplateReferences) {
4832 ForwardTemplateRefs.push_back(make<ForwardTemplateReference>(Index));
4833 return ForwardTemplateRefs.back();
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004834 }
Erik Pilkington04f39852018-03-25 22:50:33 +00004835
4836 if (Index >= TemplateParams.size())
4837 return nullptr;
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004838 return TemplateParams[Index];
Howard Hinnant6c33e762013-06-17 18:10:34 +00004839}
4840
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004841// <template-arg> ::= <type> # type or template
4842// ::= X <expression> E # expression
4843// ::= <expr-primary> # simple expressions
4844// ::= J <template-arg>* E # argument pack
4845// ::= LZ <encoding> E # extension
4846Node *Db::parseTemplateArg() {
4847 switch (look()) {
4848 case 'X': {
4849 ++First;
4850 Node *Arg = parseExpr();
4851 if (Arg == nullptr || !consumeIf('E'))
4852 return nullptr;
4853 return Arg;
4854 }
4855 case 'J': {
4856 ++First;
4857 size_t ArgsBegin = Names.size();
4858 while (!consumeIf('E')) {
4859 Node *Arg = parseTemplateArg();
4860 if (Arg == nullptr)
4861 return nullptr;
4862 Names.push_back(Arg);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004863 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004864 NodeArray Args = popTrailingNodeArray(ArgsBegin);
4865 return make<TemplateArgumentPack>(Args);
4866 }
4867 case 'L': {
4868 // ::= LZ <encoding> E # extension
4869 if (look(1) == 'Z') {
4870 First += 2;
4871 Node *Arg = parseEncoding();
4872 if (Arg == nullptr || !consumeIf('E'))
4873 return nullptr;
4874 return Arg;
4875 }
4876 // ::= <expr-primary> # simple expressions
4877 return parseExprPrimary();
4878 }
4879 default:
4880 return parseType();
4881 }
Howard Hinnant6c33e762013-06-17 18:10:34 +00004882}
4883
4884// <template-args> ::= I <template-arg>* E
4885// extension, the abi says <template-arg>+
Erik Pilkington04f39852018-03-25 22:50:33 +00004886Node *Db::parseTemplateArgs(bool TagTemplates) {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004887 if (!consumeIf('I'))
4888 return nullptr;
4889
4890 // <template-params> refer to the innermost <template-args>. Clear out any
4891 // outer args that we may have inserted into TemplateParams.
4892 if (TagTemplates)
4893 TemplateParams.clear();
4894
4895 size_t ArgsBegin = Names.size();
4896 while (!consumeIf('E')) {
4897 if (TagTemplates) {
4898 auto OldParams = std::move(TemplateParams);
4899 Node *Arg = parseTemplateArg();
4900 TemplateParams = std::move(OldParams);
4901 if (Arg == nullptr)
4902 return nullptr;
4903 Names.push_back(Arg);
4904 Node *TableEntry = Arg;
4905 if (Arg->getKind() == Node::KTemplateArgumentPack) {
4906 TableEntry = make<ParameterPack>(
4907 static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
4908 }
4909 TemplateParams.push_back(TableEntry);
4910 } else {
4911 Node *Arg = parseTemplateArg();
4912 if (Arg == nullptr)
4913 return nullptr;
4914 Names.push_back(Arg);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004915 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004916 }
4917 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004918}
4919
Howard Hinnant6c33e762013-06-17 18:10:34 +00004920// <discriminator> := _ <non-negative number> # when number < 10
4921// := __ <non-negative number> _ # when number >= 10
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004922// extension := decimal-digit+ # at the end of string
Howard Hinnant6c33e762013-06-17 18:10:34 +00004923
4924const char*
4925parse_discriminator(const char* first, const char* last)
4926{
4927 // parse but ignore discriminator
4928 if (first != last)
4929 {
4930 if (*first == '_')
4931 {
4932 const char* t1 = first+1;
4933 if (t1 != last)
4934 {
4935 if (std::isdigit(*t1))
4936 first = t1+1;
4937 else if (*t1 == '_')
4938 {
4939 for (++t1; t1 != last && std::isdigit(*t1); ++t1)
4940 ;
4941 if (t1 != last && *t1 == '_')
4942 first = t1 + 1;
4943 }
4944 }
4945 }
4946 else if (std::isdigit(*first))
4947 {
4948 const char* t1 = first+1;
4949 for (; t1 != last && std::isdigit(*t1); ++t1)
4950 ;
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004951 if (t1 == last)
4952 first = last;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004953 }
4954 }
4955 return first;
4956}
4957
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004958// <mangled-name> ::= _Z <encoding>
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004959// ::= <type>
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004960// extension ::= ___Z <encoding> _block_invoke
4961// extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
4962// extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
4963Node *Db::parse() {
4964 if (consumeIf("_Z")) {
4965 Node *Encoding = parseEncoding();
4966 if (Encoding == nullptr)
4967 return nullptr;
4968 if (look() == '.') {
4969 Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
4970 First = Last;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004971 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004972 if (numLeft() != 0)
4973 return nullptr;
4974 return Encoding;
4975 }
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004976
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004977 if (consumeIf("___Z")) {
4978 Node *Encoding = parseEncoding();
4979 if (Encoding == nullptr || !consumeIf("_block_invoke"))
4980 return nullptr;
Erik Pilkington9eaf30b2018-03-07 04:29:33 +00004981 bool RequireNumber = consumeIf('_');
4982 if (parseNumber().empty() && RequireNumber)
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004983 return nullptr;
4984 if (numLeft() != 0)
4985 return nullptr;
4986 return make<SpecialName>("invocation function for block in ", Encoding);
4987 }
4988
4989 Node *Ty = parseType();
4990 if (numLeft() != 0)
4991 return nullptr;
4992 return Ty;
4993}
Howard Hinnant6c33e762013-06-17 18:10:34 +00004994} // unnamed namespace
4995
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004996enum {
4997 unknown_error = -4,
4998 invalid_args = -3,
4999 invalid_mangled_name = -2,
5000 memory_alloc_failure = -1,
5001 success = 0,
5002};
Erik Pilkington761e6b02018-01-31 20:17:06 +00005003
5004namespace __cxxabiv1 {
Saleem Abdulrasoolb4ec5792015-12-04 02:14:58 +00005005extern "C" _LIBCXXABI_FUNC_VIS char *
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00005006__cxa_demangle(const char *MangledName, char *Buf, size_t *N, int *Status) {
5007 if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
5008 if (Status)
5009 *Status = invalid_args;
5010 return nullptr;
5011 }
5012
5013 size_t BufSize = Buf != nullptr ? *N : 0;
5014 int InternalStatus = success;
5015 size_t MangledNameLength = std::strlen(MangledName);
5016
5017 Db Parser(MangledName, MangledName + MangledNameLength);
5018 Node *AST = Parser.parse();
5019
5020 if (AST == nullptr)
5021 InternalStatus = invalid_mangled_name;
5022
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00005023 if (InternalStatus == success) {
Erik Pilkington04f39852018-03-25 22:50:33 +00005024 assert(Parser.ForwardTemplateRefs.empty());
5025
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00005026 if (Buf == nullptr) {
5027 BufSize = 1024;
5028 Buf = static_cast<char*>(std::malloc(BufSize));
Howard Hinnantd213ffd2011-05-05 15:27:28 +00005029 }
Saleem Abdulrasool8cfa5a32016-11-14 01:55:54 +00005030
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00005031 if (Buf) {
5032 OutputStream Stream(Buf, BufSize);
5033 AST->print(Stream);
5034 Stream += '\0';
5035 if (N != nullptr)
5036 *N = Stream.getCurrentPosition();
5037 Buf = Stream.getBuffer();
5038 } else
5039 InternalStatus = memory_alloc_failure;
5040 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00005041
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00005042 if (Status)
5043 *Status = InternalStatus;
5044 return InternalStatus == success ? Buf : nullptr;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00005045}
Howard Hinnant6c33e762013-06-17 18:10:34 +00005046} // __cxxabiv1