blob: 51952bd01c5d41d018e989ef1916f0dae7f49972 [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:
12// - enable_if attribute
Erik Pilkington1c300b92017-11-21 15:04:08 +000013// - C++ modules TS
Erik Pilkington761e6b02018-01-31 20:17:06 +000014// - All C++14 and C++17 features
Erik Pilkington1c300b92017-11-21 15:04:08 +000015
Howard Hinnant6c33e762013-06-17 18:10:34 +000016#define _LIBCPP_NO_EXCEPTIONS
Howard Hinnantd213ffd2011-05-05 15:27:28 +000017
Saleem Abdulrasoolb4ec5792015-12-04 02:14:58 +000018#include "__cxxabi_config.h"
19
Howard Hinnant6c33e762013-06-17 18:10:34 +000020#include <vector>
Howard Hinnantd213ffd2011-05-05 15:27:28 +000021#include <algorithm>
Howard Hinnant6c33e762013-06-17 18:10:34 +000022#include <numeric>
Erik Pilkington761e6b02018-01-31 20:17:06 +000023#include <cassert>
Erik Pilkington77101542017-07-28 00:53:30 +000024#include <cstdio>
Howard Hinnant6c33e762013-06-17 18:10:34 +000025#include <cstdlib>
26#include <cstring>
27#include <cctype>
Howard Hinnantd213ffd2011-05-05 15:27:28 +000028
Nico Weberb4c998b2015-09-20 18:10:46 +000029#ifdef _MSC_VER
30// snprintf is implemented in VS 2015
31#if _MSC_VER < 1900
32#define snprintf _snprintf_s
33#endif
34#endif
35
Erik Pilkington761e6b02018-01-31 20:17:06 +000036#ifndef NDEBUG
37#if __has_attribute(noinline) && __has_attribute(used)
38#define DUMP_METHOD __attribute__((noinline,used))
39#else
40#define DUMP_METHOD
41#endif
42#endif
Howard Hinnantd213ffd2011-05-05 15:27:28 +000043
Erik Pilkington761e6b02018-01-31 20:17:06 +000044namespace {
Howard Hinnantd213ffd2011-05-05 15:27:28 +000045
Erik Pilkington0024acd2017-07-28 00:43:49 +000046class StringView {
47 const char *First;
48 const char *Last;
49
50public:
51 template <size_t N>
52 StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {}
Erik Pilkington7de232a2017-08-10 02:48:13 +000053 StringView(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +000054 StringView() : First(nullptr), Last(nullptr) {}
55
56 StringView substr(size_t From, size_t To) {
57 if (To >= size())
58 To = size() - 1;
59 if (From >= size())
60 From = size() - 1;
61 return StringView(First + From, First + To);
62 }
63
64 StringView dropFront(size_t N) const {
65 if (N >= size())
66 N = size() - 1;
67 return StringView(First + N, Last);
68 }
69
70 bool startsWith(StringView Str) const {
71 if (Str.size() > size())
72 return false;
73 return std::equal(Str.begin(), Str.end(), begin());
74 }
75
76 const char &operator[](size_t Idx) const { return *(begin() + Idx); }
77
78 const char *begin() const { return First; }
79 const char *end() const { return Last; }
80 size_t size() const { return static_cast<size_t>(Last - First); }
Erik Pilkington761e6b02018-01-31 20:17:06 +000081 bool empty() const { return First == Last; }
Erik Pilkington0024acd2017-07-28 00:43:49 +000082};
83
84bool operator==(const StringView &LHS, const StringView &RHS) {
85 return LHS.size() == RHS.size() &&
86 std::equal(LHS.begin(), LHS.end(), RHS.begin());
87}
88
89// Stream that AST nodes write their string representation into after the AST
90// has been parsed.
91class OutputStream {
92 char *Buffer;
93 size_t CurrentPosition;
94 size_t BufferCapacity;
95
96 // Ensure there is at least n more positions in buffer.
97 void grow(size_t N) {
98 if (N + CurrentPosition >= BufferCapacity) {
99 BufferCapacity *= 2;
100 if (BufferCapacity < N + CurrentPosition)
101 BufferCapacity = N + CurrentPosition;
102 Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity));
103 }
104 }
105
106public:
107 OutputStream(char *StartBuf, size_t Size)
108 : Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {}
109
Erik Pilkington761e6b02018-01-31 20:17:06 +0000110 /// If a ParameterPackExpansion (or similar type) is encountered, the offset
111 /// into the pack that we're currently printing.
112 unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max();
113
Erik Pilkington0024acd2017-07-28 00:43:49 +0000114 OutputStream &operator+=(StringView R) {
115 size_t Size = R.size();
116 if (Size == 0)
117 return *this;
118 grow(Size);
119 memmove(Buffer + CurrentPosition, R.begin(), Size);
120 CurrentPosition += Size;
121 return *this;
122 }
123
124 OutputStream &operator+=(char C) {
125 grow(1);
126 Buffer[CurrentPosition++] = C;
127 return *this;
128 }
129
Erik Pilkington761e6b02018-01-31 20:17:06 +0000130 size_t getCurrentPosition() const { return CurrentPosition; };
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 {
163 KDotSuffix,
164 KVendorExtQualType,
165 KQualType,
166 KConversionOperatorType,
167 KPostfixQualifiedType,
Erik Pilkington13fb7dc2018-02-13 00:15:53 +0000168 KElaboratedTypeSpefType,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000169 KNameType,
Erik Pilkington5bff4122017-11-22 20:38:22 +0000170 KAbiTagAttr,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000171 KObjCProtoName,
172 KPointerType,
173 KLValueReferenceType,
174 KRValueReferenceType,
175 KPointerToMemberType,
176 KArrayType,
177 KFunctionType,
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000178 KNoexceptSpec,
179 KDynamicExceptionSpec,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000180 KFunctionEncoding,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000181 KLiteralOperator,
182 KSpecialName,
183 KCtorVtableSpecialName,
184 KQualifiedName,
185 KEmptyName,
186 KVectorType,
Erik Pilkington761e6b02018-01-31 20:17:06 +0000187 KParameterPack,
188 KTemplateArgumentPack,
189 KParameterPackExpansion,
190 KTemplateArgs,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000191 KNameWithTemplateArgs,
192 KGlobalQualifiedName,
193 KStdQualifiedName,
194 KExpandedSpecialSubstitution,
195 KSpecialSubstitution,
196 KCtorDtorName,
197 KDtorName,
198 KUnnamedTypeName,
Erik Pilkingtone1d61622018-03-05 16:35:06 +0000199 KClosureTypeName,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000200 KExpr,
Erik Pilkington88a1cf62018-02-13 00:15:56 +0000201 KBracedExpr,
202 KBracedRangeExpr,
Erik Pilkington0024acd2017-07-28 00:43:49 +0000203 };
204
Erik Pilkington761e6b02018-01-31 20:17:06 +0000205 static constexpr unsigned NoParameterPack =
206 std::numeric_limits<unsigned>::max();
207 unsigned ParameterPackSize = NoParameterPack;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000208
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
227 Node(Kind K_, unsigned ParameterPackSize_ = NoParameterPack,
228 Cache RHSComponentCache_ = Cache::No, Cache ArrayCache_ = Cache::No,
229 Cache FunctionCache_ = Cache::No)
230 : ParameterPackSize(ParameterPackSize_), K(K_),
231 RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_),
232 FunctionCache(FunctionCache_) {}
233
234 bool containsUnexpandedParameterPack() const {
235 return ParameterPackSize != NoParameterPack;
236 }
237
238 bool hasRHSComponent(OutputStream &S) const {
239 if (RHSComponentCache != Cache::Unknown)
240 return RHSComponentCache == Cache::Yes;
241 return hasRHSComponentSlow(S);
242 }
243
244 bool hasArray(OutputStream &S) const {
245 if (ArrayCache != Cache::Unknown)
246 return ArrayCache == Cache::Yes;
247 return hasArraySlow(S);
248 }
249
250 bool hasFunction(OutputStream &S) const {
251 if (FunctionCache != Cache::Unknown)
252 return FunctionCache == Cache::Yes;
253 return hasFunctionSlow(S);
254 }
255
256 Kind getKind() const { return K; }
257
258 virtual bool hasRHSComponentSlow(OutputStream &) const { return false; }
259 virtual bool hasArraySlow(OutputStream &) const { return false; }
260 virtual bool hasFunctionSlow(OutputStream &) const { return false; }
261
262 /// If this node is a pack expansion that expands to 0 elements. This can have
263 /// an effect on how we should format the output.
264 bool isEmptyPackExpansion() const;
265
266 void print(OutputStream &S) const {
267 printLeft(S);
268 if (RHSComponentCache != Cache::No)
269 printRight(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000270 }
271
272 // Print the "left" side of this Node into OutputStream.
273 virtual void printLeft(OutputStream &) const = 0;
274
275 // Print the "right". This distinction is necessary to represent C++ types
276 // that appear on the RHS of their subtype, such as arrays or functions.
277 // Since most types don't have such a component, provide a default
278 // implemenation.
279 virtual void printRight(OutputStream &) const {}
280
281 virtual StringView getBaseName() const { return StringView(); }
282
283 // Silence compiler warnings, this dtor will never be called.
284 virtual ~Node() = default;
Erik Pilkington761e6b02018-01-31 20:17:06 +0000285
286#ifndef NDEBUG
287 DUMP_METHOD void dump() const {
288 char *Buffer = static_cast<char*>(std::malloc(1024));
289 OutputStream S(Buffer, 1024);
290 print(S);
291 S += '\0';
292 printf("Symbol dump for %p: %s\n", (const void*)this, S.getBuffer());
293 std::free(S.getBuffer());
294 }
295#endif
Erik Pilkington0024acd2017-07-28 00:43:49 +0000296};
297
298class NodeArray {
299 Node **Elements;
300 size_t NumElements;
301
302public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000303 NodeArray() : Elements(nullptr), NumElements(0) {}
Erik Pilkington414f1a52017-08-09 22:45:35 +0000304 NodeArray(Node **Elements_, size_t NumElements_)
305 : Elements(Elements_), NumElements(NumElements_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000306
307 bool empty() const { return NumElements == 0; }
308 size_t size() const { return NumElements; }
309
Erik Pilkington761e6b02018-01-31 20:17:06 +0000310 Node **begin() const { return Elements; }
311 Node **end() const { return Elements + NumElements; }
312
313 Node *operator[](size_t Idx) const { return Elements[Idx]; }
314
315 void printWithComma(OutputStream &S) const {
316 bool FirstElement = true;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000317 for (size_t Idx = 0; Idx != NumElements; ++Idx) {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000318 if (Elements[Idx]->isEmptyPackExpansion())
319 continue;
320 if (!FirstElement)
321 S += ", ";
322 FirstElement = false;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000323 Elements[Idx]->print(S);
324 }
325 }
326};
327
328class DotSuffix final : public Node {
329 const Node *Prefix;
330 const StringView Suffix;
331
332public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000333 DotSuffix(Node *Prefix_, StringView Suffix_)
334 : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000335
336 void printLeft(OutputStream &s) const override {
337 Prefix->print(s);
338 s += " (";
339 s += Suffix;
340 s += ")";
341 }
342};
343
344class VendorExtQualType final : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +0000345 const Node *Ty;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000346 StringView Ext;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000347
348public:
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000349 VendorExtQualType(Node *Ty_, StringView Ext_)
350 : Node(KVendorExtQualType, Ty_->ParameterPackSize),
Erik Pilkington761e6b02018-01-31 20:17:06 +0000351 Ty(Ty_), Ext(Ext_) {}
352
Erik Pilkington0024acd2017-07-28 00:43:49 +0000353 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000354 Ty->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000355 S += " ";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000356 S += Ext;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000357 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000358};
359
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000360enum FunctionRefQual : unsigned char {
361 FrefQualNone,
362 FrefQualLValue,
363 FrefQualRValue,
364};
365
Erik Pilkington0024acd2017-07-28 00:43:49 +0000366enum Qualifiers {
367 QualNone = 0,
368 QualConst = 0x1,
369 QualVolatile = 0x2,
370 QualRestrict = 0x4,
371};
372
373void addQualifiers(Qualifiers &Q1, Qualifiers Q2) {
374 Q1 = static_cast<Qualifiers>(Q1 | Q2);
375}
376
377class QualType : public Node {
378protected:
379 const Qualifiers Quals;
380 const Node *Child;
381
382 void printQuals(OutputStream &S) const {
383 if (Quals & QualConst)
384 S += " const";
385 if (Quals & QualVolatile)
386 S += " volatile";
387 if (Quals & QualRestrict)
388 S += " restrict";
389 }
390
391public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000392 QualType(Node *Child_, Qualifiers Quals_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000393 : Node(KQualType, Child_->ParameterPackSize, Child_->RHSComponentCache,
394 Child_->ArrayCache, Child_->FunctionCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000395 Quals(Quals_), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000396
Erik Pilkington761e6b02018-01-31 20:17:06 +0000397 bool hasRHSComponentSlow(OutputStream &S) const override {
398 return Child->hasRHSComponent(S);
399 }
400 bool hasArraySlow(OutputStream &S) const override {
401 return Child->hasArray(S);
402 }
403 bool hasFunctionSlow(OutputStream &S) const override {
404 return Child->hasFunction(S);
405 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000406
407 void printLeft(OutputStream &S) const override {
408 Child->printLeft(S);
409 printQuals(S);
410 }
411
412 void printRight(OutputStream &S) const override { Child->printRight(S); }
413};
414
415class ConversionOperatorType final : public Node {
416 const Node *Ty;
417
418public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000419 ConversionOperatorType(Node *Ty_)
420 : Node(KConversionOperatorType, Ty_->ParameterPackSize), Ty(Ty_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000421
422 void printLeft(OutputStream &S) const override {
423 S += "operator ";
424 Ty->print(S);
425 }
426};
427
428class PostfixQualifiedType final : public Node {
429 const Node *Ty;
430 const StringView Postfix;
431
432public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000433 PostfixQualifiedType(Node *Ty_, StringView Postfix_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000434 : Node(KPostfixQualifiedType, Ty_->ParameterPackSize),
435 Ty(Ty_), Postfix(Postfix_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000436
437 void printLeft(OutputStream &s) const override {
438 Ty->printLeft(s);
439 s += Postfix;
440 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000441};
442
443class NameType final : public Node {
444 const StringView Name;
445
446public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000447 NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000448
449 StringView getName() const { return Name; }
450 StringView getBaseName() const override { return Name; }
451
452 void printLeft(OutputStream &s) const override { s += Name; }
453};
454
Erik Pilkington13fb7dc2018-02-13 00:15:53 +0000455class ElaboratedTypeSpefType : public Node {
456 StringView Kind;
457 Node *Child;
458public:
459 ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
460 : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {
461 ParameterPackSize = Child->ParameterPackSize;
462 }
463
464 void printLeft(OutputStream &S) const override {
465 S += Kind;
466 S += ' ';
467 Child->print(S);
468 }
469};
470
Erik Pilkington5bff4122017-11-22 20:38:22 +0000471class AbiTagAttr final : public Node {
472 const Node* Base;
473 StringView Tag;
474public:
475 AbiTagAttr(const Node* Base_, StringView Tag_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000476 : Node(KAbiTagAttr, Base_->ParameterPackSize, Base_->RHSComponentCache,
477 Base_->ArrayCache, Base_->FunctionCache),
478 Base(Base_), Tag(Tag_) {}
Erik Pilkington5bff4122017-11-22 20:38:22 +0000479
480 void printLeft(OutputStream &S) const override {
481 Base->printLeft(S);
482 S += "[abi:";
483 S += Tag;
484 S += "]";
485 }
486};
487
Erik Pilkington0024acd2017-07-28 00:43:49 +0000488class ObjCProtoName : public Node {
489 Node *Ty;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000490 StringView Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000491
492 friend class PointerType;
493
494public:
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000495 ObjCProtoName(Node *Ty_, StringView Protocol_)
Erik Pilkington414f1a52017-08-09 22:45:35 +0000496 : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000497
498 bool isObjCObject() const {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000499 return Ty->getKind() == KNameType &&
Erik Pilkington0024acd2017-07-28 00:43:49 +0000500 static_cast<NameType *>(Ty)->getName() == "objc_object";
501 }
502
503 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000504 Ty->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000505 S += "<";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000506 S += Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000507 S += ">";
508 }
509};
510
511class PointerType final : public Node {
512 const Node *Pointee;
513
514public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000515 PointerType(Node *Pointee_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000516 : Node(KPointerType, Pointee_->ParameterPackSize,
517 Pointee_->RHSComponentCache),
518 Pointee(Pointee_) {}
519
520 bool hasRHSComponentSlow(OutputStream &S) const override {
521 return Pointee->hasRHSComponent(S);
522 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000523
524 void printLeft(OutputStream &s) const override {
525 // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
Erik Pilkington761e6b02018-01-31 20:17:06 +0000526 if (Pointee->getKind() != KObjCProtoName ||
Erik Pilkington0024acd2017-07-28 00:43:49 +0000527 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
528 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000529 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000530 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000531 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000532 s += "(";
533 s += "*";
534 } else {
535 const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
536 s += "id<";
Erik Pilkingtonf23deca2018-02-05 22:41:20 +0000537 s += objcProto->Protocol;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000538 s += ">";
539 }
540 }
541
542 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000543 if (Pointee->getKind() != KObjCProtoName ||
Erik Pilkington0024acd2017-07-28 00:43:49 +0000544 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
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 Pointee->printRight(s);
548 }
549 }
550};
551
552class LValueReferenceType final : public Node {
553 const Node *Pointee;
554
555public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000556 LValueReferenceType(Node *Pointee_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000557 : Node(KLValueReferenceType, Pointee_->ParameterPackSize,
558 Pointee_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000559 Pointee(Pointee_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000560
Erik Pilkington761e6b02018-01-31 20:17:06 +0000561 bool hasRHSComponentSlow(OutputStream &S) const override {
562 return Pointee->hasRHSComponent(S);
563 }
564
Erik Pilkington0024acd2017-07-28 00:43:49 +0000565 void printLeft(OutputStream &s) const override {
566 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000567 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000568 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000569 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000570 s += "(&";
571 else
572 s += "&";
573 }
574 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000575 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000576 s += ")";
577 Pointee->printRight(s);
578 }
579};
580
581class RValueReferenceType final : public Node {
582 const Node *Pointee;
583
584public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000585 RValueReferenceType(Node *Pointee_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000586 : Node(KRValueReferenceType, Pointee_->ParameterPackSize,
587 Pointee_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000588 Pointee(Pointee_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000589
Erik Pilkington761e6b02018-01-31 20:17:06 +0000590 bool hasRHSComponentSlow(OutputStream &S) const override {
591 return Pointee->hasRHSComponent(S);
592 }
593
Erik Pilkington0024acd2017-07-28 00:43:49 +0000594 void printLeft(OutputStream &s) const override {
595 Pointee->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000596 if (Pointee->hasArray(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000597 s += " ";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000598 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000599 s += "(&&";
600 else
601 s += "&&";
602 }
603
604 void printRight(OutputStream &s) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000605 if (Pointee->hasArray(s) || Pointee->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000606 s += ")";
607 Pointee->printRight(s);
608 }
609};
610
611class PointerToMemberType final : public Node {
612 const Node *ClassType;
613 const Node *MemberType;
614
615public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000616 PointerToMemberType(Node *ClassType_, Node *MemberType_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000617 : Node(KPointerToMemberType,
618 std::min(MemberType_->ParameterPackSize,
619 ClassType_->ParameterPackSize),
620 MemberType_->RHSComponentCache),
Erik Pilkington414f1a52017-08-09 22:45:35 +0000621 ClassType(ClassType_), MemberType(MemberType_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000622
Erik Pilkington761e6b02018-01-31 20:17:06 +0000623 bool hasRHSComponentSlow(OutputStream &S) const override {
624 return MemberType->hasRHSComponent(S);
625 }
626
Erik Pilkington0024acd2017-07-28 00:43:49 +0000627 void printLeft(OutputStream &s) const override {
628 MemberType->printLeft(s);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000629 if (MemberType->hasArray(s) || MemberType->hasFunction(s))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000630 s += "(";
631 else
632 s += " ";
633 ClassType->print(s);
634 s += "::*";
635 }
636
637 void printRight(OutputStream &s) const override {
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 MemberType->printRight(s);
641 }
642};
643
644class NodeOrString {
645 const void *First;
646 const void *Second;
647
648public:
649 /* implicit */ NodeOrString(StringView Str) {
650 const char *FirstChar = Str.begin();
651 const char *SecondChar = Str.end();
652 if (SecondChar == nullptr) {
653 assert(FirstChar == SecondChar);
654 ++FirstChar, ++SecondChar;
655 }
656 First = static_cast<const void *>(FirstChar);
657 Second = static_cast<const void *>(SecondChar);
658 }
659
660 /* implicit */ NodeOrString(Node *N)
661 : First(static_cast<const void *>(N)), Second(nullptr) {}
662 NodeOrString() : First(nullptr), Second(nullptr) {}
663
664 bool isString() const { return Second && First; }
665 bool isNode() const { return First && !Second; }
666 bool isEmpty() const { return !First && !Second; }
667
668 StringView asString() const {
669 assert(isString());
670 return StringView(static_cast<const char *>(First),
671 static_cast<const char *>(Second));
672 }
673
674 const Node *asNode() const {
675 assert(isNode());
676 return static_cast<const Node *>(First);
677 }
678};
679
680class ArrayType final : public Node {
681 Node *Base;
682 NodeOrString Dimension;
683
684public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000685 ArrayType(Node *Base_, NodeOrString Dimension_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000686 : Node(KArrayType, Base_->ParameterPackSize,
687 /*RHSComponentCache=*/Cache::Yes,
688 /*ArrayCache=*/Cache::Yes),
689 Base(Base_), Dimension(Dimension_) {
690 if (Dimension.isNode())
691 ParameterPackSize =
692 std::min(ParameterPackSize, Dimension.asNode()->ParameterPackSize);
693 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000694
695 // Incomplete array type.
Erik Pilkington761e6b02018-01-31 20:17:06 +0000696 ArrayType(Node *Base_)
697 : Node(KArrayType, Base_->ParameterPackSize,
698 /*RHSComponentCache=*/Cache::Yes,
699 /*ArrayCache=*/Cache::Yes),
700 Base(Base_) {}
701
702 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
703 bool hasArraySlow(OutputStream &) const override { return true; }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000704
705 void printLeft(OutputStream &S) const override { Base->printLeft(S); }
706
707 void printRight(OutputStream &S) const override {
708 if (S.back() != ']')
709 S += " ";
710 S += "[";
711 if (Dimension.isString())
712 S += Dimension.asString();
713 else if (Dimension.isNode())
714 Dimension.asNode()->print(S);
715 S += "]";
716 Base->printRight(S);
717 }
718};
719
720class FunctionType final : public Node {
721 Node *Ret;
722 NodeArray Params;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000723 Qualifiers CVQuals;
724 FunctionRefQual RefQual;
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000725 Node *ExceptionSpec;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000726
727public:
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000728 FunctionType(Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000729 FunctionRefQual RefQual_, Node *ExceptionSpec_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000730 : Node(KFunctionType, Ret_->ParameterPackSize,
731 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
732 /*FunctionCache=*/Cache::Yes),
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000733 Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
734 ExceptionSpec(ExceptionSpec_) {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000735 for (Node *P : Params)
736 ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000737 if (ExceptionSpec != nullptr)
738 ParameterPackSize =
739 std::min(ParameterPackSize, ExceptionSpec->ParameterPackSize);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000740 }
741
742 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
743 bool hasFunctionSlow(OutputStream &) const override { return true; }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000744
745 // Handle C++'s ... quirky decl grammer by using the left & right
746 // distinction. Consider:
747 // int (*f(float))(char) {}
748 // f is a function that takes a float and returns a pointer to a function
749 // that takes a char and returns an int. If we're trying to print f, start
750 // by printing out the return types's left, then print our parameters, then
751 // finally print right of the return type.
752 void printLeft(OutputStream &S) const override {
753 Ret->printLeft(S);
754 S += " ";
755 }
756
757 void printRight(OutputStream &S) const override {
758 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000759 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000760 S += ")";
761 Ret->printRight(S);
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000762
763 if (CVQuals & QualConst)
764 S += " const";
765 if (CVQuals & QualVolatile)
766 S += " volatile";
767 if (CVQuals & QualRestrict)
768 S += " restrict";
769
770 if (RefQual == FrefQualLValue)
771 S += " &";
772 else if (RefQual == FrefQualRValue)
773 S += " &&";
Erik Pilkington7e027ac2018-02-14 01:08:20 +0000774
775 if (ExceptionSpec != nullptr) {
776 S += ' ';
777 ExceptionSpec->print(S);
778 }
779 }
780};
781
782class NoexceptSpec : public Node {
783 Node *E;
784public:
785 NoexceptSpec(Node *E_) : Node(KNoexceptSpec, E_->ParameterPackSize), E(E_) {}
786
787 void printLeft(OutputStream &S) const override {
788 S += "noexcept(";
789 E->print(S);
790 S += ")";
791 }
792};
793
794class DynamicExceptionSpec : public Node {
795 NodeArray Types;
796public:
797 DynamicExceptionSpec(NodeArray Types_)
798 : Node(KDynamicExceptionSpec), Types(Types_) {
799 for (Node *T : Types)
800 ParameterPackSize = std::min(ParameterPackSize, T->ParameterPackSize);
801 }
802
803 void printLeft(OutputStream &S) const override {
804 S += "throw(";
805 Types.printWithComma(S);
806 S += ')';
Erik Pilkington0024acd2017-07-28 00:43:49 +0000807 }
808};
809
Erik Pilkington761e6b02018-01-31 20:17:06 +0000810class FunctionEncoding final : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +0000811 const Node *Ret;
812 const Node *Name;
813 NodeArray Params;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000814 Qualifiers CVQuals;
815 FunctionRefQual RefQual;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000816
817public:
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000818 FunctionEncoding(Node *Ret_, Node *Name_, NodeArray Params_,
819 Qualifiers CVQuals_, FunctionRefQual RefQual_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000820 : Node(KFunctionEncoding, NoParameterPack,
821 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
822 /*FunctionCache=*/Cache::Yes),
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000823 Ret(Ret_), Name(Name_), Params(Params_), CVQuals(CVQuals_),
824 RefQual(RefQual_) {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000825 for (Node *P : Params)
826 ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
827 if (Ret)
828 ParameterPackSize = std::min(ParameterPackSize, Ret->ParameterPackSize);
829 }
830
831 bool hasRHSComponentSlow(OutputStream &) const override { return true; }
832 bool hasFunctionSlow(OutputStream &) const override { return true; }
833
834 Node *getName() { return const_cast<Node *>(Name); }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000835
836 void printLeft(OutputStream &S) const override {
837 if (Ret) {
838 Ret->printLeft(S);
Erik Pilkington761e6b02018-01-31 20:17:06 +0000839 if (!Ret->hasRHSComponent(S))
Erik Pilkington0024acd2017-07-28 00:43:49 +0000840 S += " ";
841 }
842 Name->print(S);
843 }
844
845 void printRight(OutputStream &S) const override {
846 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +0000847 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000848 S += ")";
849 if (Ret)
850 Ret->printRight(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000851
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000852 if (CVQuals & QualConst)
853 S += " const";
854 if (CVQuals & QualVolatile)
855 S += " volatile";
856 if (CVQuals & QualRestrict)
857 S += " restrict";
Erik Pilkington0024acd2017-07-28 00:43:49 +0000858
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000859 if (RefQual == FrefQualLValue)
Erik Pilkington0024acd2017-07-28 00:43:49 +0000860 S += " &";
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +0000861 else if (RefQual == FrefQualRValue)
Erik Pilkington0024acd2017-07-28 00:43:49 +0000862 S += " &&";
863 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000864};
865
866class LiteralOperator : public Node {
867 const Node *OpName;
868
869public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000870 LiteralOperator(Node *OpName_)
871 : Node(KLiteralOperator, OpName_->ParameterPackSize), OpName(OpName_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000872
873 void printLeft(OutputStream &S) const override {
874 S += "operator\"\" ";
875 OpName->print(S);
876 }
877};
878
879class SpecialName final : public Node {
880 const StringView Special;
881 const Node *Child;
882
883public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000884 SpecialName(StringView Special_, Node* Child_)
885 : Node(KSpecialName, Child_->ParameterPackSize), Special(Special_),
886 Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000887
888 void printLeft(OutputStream &S) const override {
889 S += Special;
890 Child->print(S);
891 }
892};
893
894class CtorVtableSpecialName final : public Node {
895 const Node *FirstType;
896 const Node *SecondType;
897
898public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000899 CtorVtableSpecialName(Node *FirstType_, Node *SecondType_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000900 : Node(KCtorVtableSpecialName, std::min(FirstType_->ParameterPackSize,
901 SecondType_->ParameterPackSize)),
902 FirstType(FirstType_), SecondType(SecondType_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000903
904 void printLeft(OutputStream &S) const override {
905 S += "construction vtable for ";
906 FirstType->print(S);
907 S += "-in-";
908 SecondType->print(S);
909 }
910};
911
912class QualifiedName final : public Node {
913 // qualifier::name
914 const Node *Qualifier;
915 const Node *Name;
916
Erik Pilkington0024acd2017-07-28 00:43:49 +0000917public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000918 QualifiedName(Node* Qualifier_, Node* Name_)
919 : Node(KQualifiedName,
920 std::min(Qualifier_->ParameterPackSize, Name_->ParameterPackSize)),
921 Qualifier(Qualifier_), Name(Name_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +0000922
923 StringView getBaseName() const override { return Name->getBaseName(); }
924
925 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +0000926 Qualifier->print(S);
927 S += "::";
Erik Pilkington0024acd2017-07-28 00:43:49 +0000928 Name->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +0000929 }
930};
931
932class EmptyName : public Node {
933public:
934 EmptyName() : Node(KEmptyName) {}
935 void printLeft(OutputStream &) const override {}
936};
937
938class VectorType final : public Node {
939 const Node *BaseType;
940 const NodeOrString Dimension;
941 const bool IsPixel;
942
943public:
Erik Pilkington414f1a52017-08-09 22:45:35 +0000944 VectorType(NodeOrString Dimension_)
945 : Node(KVectorType), BaseType(nullptr), Dimension(Dimension_),
Erik Pilkington761e6b02018-01-31 20:17:06 +0000946 IsPixel(true) {
947 if (Dimension.isNode())
948 ParameterPackSize = Dimension.asNode()->ParameterPackSize;
949 }
Erik Pilkington414f1a52017-08-09 22:45:35 +0000950 VectorType(Node *BaseType_, NodeOrString Dimension_)
Erik Pilkington761e6b02018-01-31 20:17:06 +0000951 : Node(KVectorType, BaseType_->ParameterPackSize), BaseType(BaseType_),
952 Dimension(Dimension_), IsPixel(false) {
953 if (Dimension.isNode())
954 ParameterPackSize =
955 std::min(ParameterPackSize, Dimension.asNode()->ParameterPackSize);
956 }
Erik Pilkington0024acd2017-07-28 00:43:49 +0000957
958 void printLeft(OutputStream &S) const override {
959 if (IsPixel) {
960 S += "pixel vector[";
961 S += Dimension.asString();
962 S += "]";
963 } else {
964 BaseType->print(S);
965 S += " vector[";
966 if (Dimension.isNode())
967 Dimension.asNode()->print(S);
968 else if (Dimension.isString())
969 S += Dimension.asString();
970 S += "]";
971 }
972 }
973};
974
Erik Pilkington761e6b02018-01-31 20:17:06 +0000975/// An unexpanded parameter pack (either in the expression or type context). If
976/// this AST is correct, this node will have a ParameterPackExpansion node above
977/// it.
978///
979/// This node is created when some <template-args> are found that apply to an
980/// <encoding>, and is stored in the TemplateParams table. In order for this to
981/// appear in the final AST, it has to referenced via a <template-param> (ie,
982/// T_).
983class ParameterPack final : public Node {
984 NodeArray Data;
Erik Pilkington0024acd2017-07-28 00:43:49 +0000985public:
Erik Pilkington761e6b02018-01-31 20:17:06 +0000986 ParameterPack(NodeArray Data_)
987 : Node(KParameterPack, static_cast<unsigned>(Data_.size())), Data(Data_) {
988 ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
989 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
990 return P->ArrayCache == Cache::No;
991 }))
992 ArrayCache = Cache::No;
993 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
994 return P->FunctionCache == Cache::No;
995 }))
996 FunctionCache = Cache::No;
997 if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
998 return P->RHSComponentCache == Cache::No;
999 }))
1000 RHSComponentCache = Cache::No;
1001 }
1002
1003 bool hasRHSComponentSlow(OutputStream &S) const override {
1004 size_t Idx = S.CurrentPackIndex;
1005 return Idx < Data.size() && Data[Idx]->hasRHSComponent(S);
1006 }
1007 bool hasArraySlow(OutputStream &S) const override {
1008 size_t Idx = S.CurrentPackIndex;
1009 return Idx < Data.size() && Data[Idx]->hasArray(S);
1010 }
1011 bool hasFunctionSlow(OutputStream &S) const override {
1012 size_t Idx = S.CurrentPackIndex;
1013 return Idx < Data.size() && Data[Idx]->hasFunction(S);
1014 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001015
1016 void printLeft(OutputStream &S) const override {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001017 size_t Idx = S.CurrentPackIndex;
1018 if (Idx < Data.size())
1019 Data[Idx]->printLeft(S);
1020 }
1021 void printRight(OutputStream &S) const override {
1022 size_t Idx = S.CurrentPackIndex;
1023 if (Idx < Data.size())
1024 Data[Idx]->printRight(S);
1025 }
1026};
1027
1028/// A variadic template argument. This node represents an occurance of
1029/// J<something>E in some <template-args>. It isn't itself unexpanded, unless
1030/// one of it's Elements is. The parser inserts a ParameterPack into the
1031/// TemplateParams table if the <template-args> this pack belongs to apply to an
1032/// <encoding>.
1033class TemplateArgumentPack final : public Node {
1034 NodeArray Elements;
1035public:
1036 TemplateArgumentPack(NodeArray Elements_)
1037 : Node(KTemplateArgumentPack), Elements(Elements_) {
1038 for (Node *E : Elements)
1039 ParameterPackSize = std::min(E->ParameterPackSize, ParameterPackSize);
1040 }
1041
1042 NodeArray getElements() const { return Elements; }
1043
1044 void printLeft(OutputStream &S) const override {
1045 Elements.printWithComma(S);
1046 }
1047};
1048
1049/// A pack expansion. Below this node, there are some unexpanded ParameterPacks
1050/// which each have Child->ParameterPackSize elements.
1051class ParameterPackExpansion final : public Node {
1052 const Node *Child;
1053
1054public:
1055 ParameterPackExpansion(Node* Child_)
1056 : Node(KParameterPackExpansion), Child(Child_) {}
1057
1058 const Node *getChild() const { return Child; }
1059
1060 void printLeft(OutputStream &S) const override {
1061 unsigned PackSize = Child->ParameterPackSize;
1062 if (PackSize == NoParameterPack) {
1063 Child->print(S);
1064 S += "...";
Erik Pilkington0024acd2017-07-28 00:43:49 +00001065 return;
1066 }
1067
Erik Pilkington761e6b02018-01-31 20:17:06 +00001068 SwapAndRestore<unsigned> SavePackIndex(S.CurrentPackIndex, 0);
1069 for (unsigned I = 0; I != PackSize; ++I) {
1070 if (I != 0)
1071 S += ", ";
1072 S.CurrentPackIndex = I;
1073 Child->print(S);
1074 }
1075 }
1076};
Erik Pilkington0024acd2017-07-28 00:43:49 +00001077
Erik Pilkington761e6b02018-01-31 20:17:06 +00001078inline bool Node::isEmptyPackExpansion() const {
1079 if (getKind() == KParameterPackExpansion) {
1080 auto *AsPack = static_cast<const ParameterPackExpansion *>(this);
1081 return AsPack->getChild()->isEmptyPackExpansion();
1082 }
1083 if (getKind() == KTemplateArgumentPack) {
1084 auto *AsTemplateArg = static_cast<const TemplateArgumentPack *>(this);
1085 for (Node *E : AsTemplateArg->getElements())
1086 if (!E->isEmptyPackExpansion())
1087 return false;
1088 return true;
1089 }
1090 return ParameterPackSize == 0;
1091}
1092
1093class TemplateArgs final : public Node {
1094 NodeArray Params;
1095
1096public:
1097 TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {
1098 for (Node *P : Params)
1099 ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1100 }
1101
1102 NodeArray getParams() { return Params; }
1103
1104 void printLeft(OutputStream &S) const override {
Erik Pilkington0024acd2017-07-28 00:43:49 +00001105 S += "<";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001106 bool FirstElement = true;
1107 for (size_t Idx = 0, E = Params.size(); Idx != E; ++Idx) {
1108 if (Params[Idx]->isEmptyPackExpansion())
1109 continue;
1110 if (!FirstElement)
1111 S += ", ";
1112 FirstElement = false;
1113 Params[Idx]->print(S);
1114 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001115 if (S.back() == '>')
1116 S += " ";
1117 S += ">";
Erik Pilkington0024acd2017-07-28 00:43:49 +00001118 }
1119};
1120
1121class NameWithTemplateArgs final : public Node {
1122 // name<template_args>
1123 Node *Name;
1124 Node *TemplateArgs;
1125
1126public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001127 NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001128 : Node(KNameWithTemplateArgs, std::min(Name_->ParameterPackSize,
1129 TemplateArgs_->ParameterPackSize)),
1130 Name(Name_), TemplateArgs(TemplateArgs_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001131
1132 StringView getBaseName() const override { return Name->getBaseName(); }
1133
1134 void printLeft(OutputStream &S) const override {
1135 Name->print(S);
1136 TemplateArgs->print(S);
1137 }
1138};
1139
1140class GlobalQualifiedName final : public Node {
1141 Node *Child;
1142
1143public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001144 GlobalQualifiedName(Node* Child_)
1145 : Node(KGlobalQualifiedName, Child_->ParameterPackSize), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001146
1147 StringView getBaseName() const override { return Child->getBaseName(); }
1148
1149 void printLeft(OutputStream &S) const override {
1150 S += "::";
1151 Child->print(S);
1152 }
1153};
1154
1155class StdQualifiedName final : public Node {
1156 Node *Child;
1157
1158public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001159 StdQualifiedName(Node *Child_)
1160 : Node(KStdQualifiedName, Child_->ParameterPackSize), Child(Child_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001161
1162 StringView getBaseName() const override { return Child->getBaseName(); }
1163
1164 void printLeft(OutputStream &S) const override {
1165 S += "std::";
1166 Child->print(S);
1167 }
1168};
1169
1170enum class SpecialSubKind {
1171 allocator,
1172 basic_string,
1173 string,
1174 istream,
1175 ostream,
1176 iostream,
1177};
1178
1179class ExpandedSpecialSubstitution final : public Node {
1180 SpecialSubKind SSK;
1181
1182public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001183 ExpandedSpecialSubstitution(SpecialSubKind SSK_)
1184 : Node(KExpandedSpecialSubstitution), SSK(SSK_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001185
1186 StringView getBaseName() const override {
1187 switch (SSK) {
1188 case SpecialSubKind::allocator:
1189 return StringView("allocator");
1190 case SpecialSubKind::basic_string:
1191 return StringView("basic_string");
1192 case SpecialSubKind::string:
1193 return StringView("basic_string");
1194 case SpecialSubKind::istream:
1195 return StringView("basic_istream");
1196 case SpecialSubKind::ostream:
1197 return StringView("basic_ostream");
1198 case SpecialSubKind::iostream:
1199 return StringView("basic_iostream");
1200 }
Erik Pilkingtond25d9012017-08-01 02:38:40 +00001201 _LIBCPP_UNREACHABLE();
Erik Pilkington0024acd2017-07-28 00:43:49 +00001202 }
1203
1204 void printLeft(OutputStream &S) const override {
1205 switch (SSK) {
1206 case SpecialSubKind::allocator:
1207 S += "std::basic_string<char, std::char_traits<char>, "
1208 "std::allocator<char> >";
1209 break;
1210 case SpecialSubKind::basic_string:
1211 case SpecialSubKind::string:
1212 S += "std::basic_string<char, std::char_traits<char>, "
1213 "std::allocator<char> >";
1214 break;
1215 case SpecialSubKind::istream:
1216 S += "std::basic_istream<char, std::char_traits<char> >";
1217 break;
1218 case SpecialSubKind::ostream:
1219 S += "std::basic_ostream<char, std::char_traits<char> >";
1220 break;
1221 case SpecialSubKind::iostream:
1222 S += "std::basic_iostream<char, std::char_traits<char> >";
1223 break;
1224 }
1225 }
1226};
1227
1228class SpecialSubstitution final : public Node {
1229public:
1230 SpecialSubKind SSK;
1231
Erik Pilkington414f1a52017-08-09 22:45:35 +00001232 SpecialSubstitution(SpecialSubKind SSK_)
1233 : Node(KSpecialSubstitution), SSK(SSK_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001234
1235 StringView getBaseName() const override {
1236 switch (SSK) {
1237 case SpecialSubKind::allocator:
1238 return StringView("allocator");
1239 case SpecialSubKind::basic_string:
1240 return StringView("basic_string");
1241 case SpecialSubKind::string:
1242 return StringView("string");
1243 case SpecialSubKind::istream:
1244 return StringView("istream");
1245 case SpecialSubKind::ostream:
1246 return StringView("ostream");
1247 case SpecialSubKind::iostream:
1248 return StringView("iostream");
1249 }
Erik Pilkingtond25d9012017-08-01 02:38:40 +00001250 _LIBCPP_UNREACHABLE();
Erik Pilkington0024acd2017-07-28 00:43:49 +00001251 }
1252
1253 void printLeft(OutputStream &S) const override {
1254 switch (SSK) {
1255 case SpecialSubKind::allocator:
1256 S += "std::allocator";
1257 break;
1258 case SpecialSubKind::basic_string:
1259 S += "std::basic_string";
1260 break;
1261 case SpecialSubKind::string:
1262 S += "std::string";
1263 break;
1264 case SpecialSubKind::istream:
1265 S += "std::istream";
1266 break;
1267 case SpecialSubKind::ostream:
1268 S += "std::ostream";
1269 break;
1270 case SpecialSubKind::iostream:
1271 S += "std::iostream";
1272 break;
1273 }
1274 }
1275};
1276
1277class CtorDtorName final : public Node {
1278 const Node *Basename;
1279 const bool IsDtor;
1280
1281public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001282 CtorDtorName(Node *Basename_, bool IsDtor_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001283 : Node(KCtorDtorName, Basename_->ParameterPackSize),
1284 Basename(Basename_), IsDtor(IsDtor_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001285
1286 void printLeft(OutputStream &S) const override {
1287 if (IsDtor)
1288 S += "~";
1289 S += Basename->getBaseName();
1290 }
1291};
1292
1293class DtorName : public Node {
1294 const Node *Base;
1295
1296public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001297 DtorName(Node *Base_) : Node(KDtorName), Base(Base_) {
1298 ParameterPackSize = Base->ParameterPackSize;
1299 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001300
1301 void printLeft(OutputStream &S) const override {
1302 S += "~";
1303 Base->printLeft(S);
1304 }
1305};
1306
1307class UnnamedTypeName : public Node {
1308 const StringView Count;
1309
1310public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001311 UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001312
1313 void printLeft(OutputStream &S) const override {
1314 S += "'unnamed";
1315 S += Count;
1316 S += "\'";
1317 }
1318};
1319
Erik Pilkingtone1d61622018-03-05 16:35:06 +00001320class ClosureTypeName : public Node {
Erik Pilkington0024acd2017-07-28 00:43:49 +00001321 NodeArray Params;
1322 StringView Count;
1323
1324public:
Erik Pilkingtone1d61622018-03-05 16:35:06 +00001325 ClosureTypeName(NodeArray Params_, StringView Count_)
1326 : Node(KClosureTypeName), Params(Params_), Count(Count_) {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001327 for (Node *P : Params)
1328 ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1329 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001330
1331 void printLeft(OutputStream &S) const override {
1332 S += "\'lambda";
1333 S += Count;
1334 S += "\'(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001335 Params.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001336 S += ")";
1337 }
1338};
1339
1340// -- Expression Nodes --
1341
1342struct Expr : public Node {
Erik Pilkington88a1cf62018-02-13 00:15:56 +00001343 Expr(Kind K = KExpr) : Node(K) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001344};
1345
1346class BinaryExpr : public Expr {
1347 const Node *LHS;
1348 const StringView InfixOperator;
1349 const Node *RHS;
1350
1351public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001352 BinaryExpr(Node *LHS_, StringView InfixOperator_, Node *RHS_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001353 : LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {
1354 ParameterPackSize =
1355 std::min(LHS->ParameterPackSize, RHS->ParameterPackSize);
1356 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001357
1358 void printLeft(OutputStream &S) const override {
1359 // might be a template argument expression, then we need to disambiguate
1360 // with parens.
1361 if (InfixOperator == ">")
1362 S += "(";
1363
1364 S += "(";
1365 LHS->print(S);
1366 S += ") ";
1367 S += InfixOperator;
1368 S += " (";
1369 RHS->print(S);
1370 S += ")";
1371
1372 if (InfixOperator == ">")
1373 S += ")";
1374 }
1375};
1376
1377class ArraySubscriptExpr : public Expr {
1378 const Node *Op1;
1379 const Node *Op2;
1380
1381public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001382 ArraySubscriptExpr(Node *Op1_, Node *Op2_) : Op1(Op1_), Op2(Op2_) {
1383 ParameterPackSize =
1384 std::min(Op1->ParameterPackSize, Op2->ParameterPackSize);
1385 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001386
1387 void printLeft(OutputStream &S) const override {
1388 S += "(";
1389 Op1->print(S);
1390 S += ")[";
1391 Op2->print(S);
1392 S += "]";
1393 }
1394};
1395
1396class PostfixExpr : public Expr {
1397 const Node *Child;
1398 const StringView Operand;
1399
1400public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001401 PostfixExpr(Node *Child_, StringView Operand_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001402 : Child(Child_), Operand(Operand_) {
1403 ParameterPackSize = Child->ParameterPackSize;
1404 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001405
1406 void printLeft(OutputStream &S) const override {
1407 S += "(";
1408 Child->print(S);
1409 S += ")";
1410 S += Operand;
1411 }
1412};
1413
1414class ConditionalExpr : public Expr {
1415 const Node *Cond;
1416 const Node *Then;
1417 const Node *Else;
1418
1419public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001420 ConditionalExpr(Node *Cond_, Node *Then_, Node *Else_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001421 : Cond(Cond_), Then(Then_), Else(Else_) {
1422 ParameterPackSize =
1423 std::min(Cond->ParameterPackSize,
1424 std::min(Then->ParameterPackSize, Else->ParameterPackSize));
1425 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001426
1427 void printLeft(OutputStream &S) const override {
1428 S += "(";
1429 Cond->print(S);
1430 S += ") ? (";
1431 Then->print(S);
1432 S += ") : (";
1433 Else->print(S);
1434 S += ")";
1435 }
1436};
1437
1438class MemberExpr : public Expr {
1439 const Node *LHS;
1440 const StringView Kind;
1441 const Node *RHS;
1442
1443public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001444 MemberExpr(Node *LHS_, StringView Kind_, Node *RHS_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001445 : LHS(LHS_), Kind(Kind_), RHS(RHS_) {
1446 ParameterPackSize =
1447 std::min(LHS->ParameterPackSize, RHS->ParameterPackSize);
1448 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001449
1450 void printLeft(OutputStream &S) const override {
1451 LHS->print(S);
1452 S += Kind;
1453 RHS->print(S);
1454 }
1455};
1456
1457class EnclosingExpr : public Expr {
1458 const StringView Prefix;
1459 const Node *Infix;
1460 const StringView Postfix;
1461
1462public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001463 EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001464 : Prefix(Prefix_), Infix(Infix_), Postfix(Postfix_) {
1465 ParameterPackSize = Infix->ParameterPackSize;
1466 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001467
1468 void printLeft(OutputStream &S) const override {
1469 S += Prefix;
1470 Infix->print(S);
1471 S += Postfix;
1472 }
1473};
1474
1475class CastExpr : public Expr {
1476 // cast_kind<to>(from)
1477 const StringView CastKind;
1478 const Node *To;
1479 const Node *From;
1480
1481public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001482 CastExpr(StringView CastKind_, Node *To_, Node *From_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001483 : CastKind(CastKind_), To(To_), From(From_) {
1484 ParameterPackSize =
1485 std::min(To->ParameterPackSize, From->ParameterPackSize);
1486 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001487
1488 void printLeft(OutputStream &S) const override {
1489 S += CastKind;
1490 S += "<";
1491 To->printLeft(S);
1492 S += ">(";
1493 From->printLeft(S);
1494 S += ")";
1495 }
1496};
1497
1498class SizeofParamPackExpr : public Expr {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001499 Node *Pack;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001500
1501public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001502 SizeofParamPackExpr(Node *Pack_) : Pack(Pack_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001503
1504 void printLeft(OutputStream &S) const override {
1505 S += "sizeof...(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001506 ParameterPackExpansion PPE(Pack);
1507 PPE.printLeft(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001508 S += ")";
1509 }
1510};
1511
1512class CallExpr : public Expr {
1513 const Node *Callee;
1514 NodeArray Args;
1515
1516public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001517 CallExpr(Node *Callee_, NodeArray Args_) : Callee(Callee_), Args(Args_) {
1518 for (Node *P : Args)
1519 ParameterPackSize = std::min(ParameterPackSize, P->ParameterPackSize);
1520 ParameterPackSize = std::min(ParameterPackSize, Callee->ParameterPackSize);
1521 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001522
1523 void printLeft(OutputStream &S) const override {
1524 Callee->print(S);
1525 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001526 Args.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001527 S += ")";
1528 }
1529};
1530
1531class NewExpr : public Expr {
1532 // new (expr_list) type(init_list)
1533 NodeArray ExprList;
1534 Node *Type;
1535 NodeArray InitList;
1536 bool IsGlobal; // ::operator new ?
1537 bool IsArray; // new[] ?
1538public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001539 NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
1540 bool IsArray_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001541 : ExprList(ExprList_), Type(Type_), InitList(InitList_),
1542 IsGlobal(IsGlobal_), IsArray(IsArray_) {
1543 for (Node *E : ExprList)
1544 ParameterPackSize = std::min(ParameterPackSize, E->ParameterPackSize);
1545 for (Node *I : InitList)
1546 ParameterPackSize = std::min(ParameterPackSize, I->ParameterPackSize);
1547 if (Type)
1548 ParameterPackSize = std::min(ParameterPackSize, Type->ParameterPackSize);
1549 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001550
1551 void printLeft(OutputStream &S) const override {
1552 if (IsGlobal)
1553 S += "::operator ";
1554 S += "new";
1555 if (IsArray)
1556 S += "[]";
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001557 S += ' ';
Erik Pilkington0024acd2017-07-28 00:43:49 +00001558 if (!ExprList.empty()) {
1559 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001560 ExprList.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001561 S += ")";
1562 }
1563 Type->print(S);
1564 if (!InitList.empty()) {
1565 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001566 InitList.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001567 S += ")";
1568 }
Erik Pilkington761e6b02018-01-31 20:17:06 +00001569
Erik Pilkington0024acd2017-07-28 00:43:49 +00001570 }
1571};
1572
1573class DeleteExpr : public Expr {
1574 Node *Op;
1575 bool IsGlobal;
1576 bool IsArray;
1577
1578public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001579 DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_)
Erik Pilkington761e6b02018-01-31 20:17:06 +00001580 : Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {
1581 ParameterPackSize = Op->ParameterPackSize;
1582 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001583
1584 void printLeft(OutputStream &S) const override {
1585 if (IsGlobal)
1586 S += "::";
1587 S += "delete";
1588 if (IsArray)
1589 S += "[] ";
1590 Op->print(S);
1591 }
1592};
1593
1594class PrefixExpr : public Expr {
1595 StringView Prefix;
1596 Node *Child;
1597
1598public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001599 PrefixExpr(StringView Prefix_, Node *Child_) : Prefix(Prefix_), Child(Child_) {
1600 ParameterPackSize = Child->ParameterPackSize;
1601 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001602
1603 void printLeft(OutputStream &S) const override {
1604 S += Prefix;
1605 S += "(";
1606 Child->print(S);
1607 S += ")";
1608 }
1609};
1610
1611class FunctionParam : public Expr {
1612 StringView Number;
1613
1614public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001615 FunctionParam(StringView Number_) : Number(Number_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001616
1617 void printLeft(OutputStream &S) const override {
1618 S += "fp";
1619 S += Number;
1620 }
1621};
1622
Erik Pilkington0024acd2017-07-28 00:43:49 +00001623class ConversionExpr : public Expr {
Erik Pilkington761e6b02018-01-31 20:17:06 +00001624 const Node *Type;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001625 NodeArray Expressions;
Erik Pilkington0024acd2017-07-28 00:43:49 +00001626
1627public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001628 ConversionExpr(const Node *Type_, NodeArray Expressions_)
1629 : Type(Type_), Expressions(Expressions_) {
1630 for (Node *E : Expressions)
1631 ParameterPackSize = std::min(ParameterPackSize, E->ParameterPackSize);
1632 ParameterPackSize = std::min(ParameterPackSize, Type->ParameterPackSize);
1633 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001634
1635 void printLeft(OutputStream &S) const override {
1636 S += "(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001637 Type->print(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001638 S += ")(";
Erik Pilkington761e6b02018-01-31 20:17:06 +00001639 Expressions.printWithComma(S);
Erik Pilkington0024acd2017-07-28 00:43:49 +00001640 S += ")";
1641 }
1642};
1643
Erik Pilkington88a1cf62018-02-13 00:15:56 +00001644class InitListExpr : public Expr {
1645 Node *Ty;
1646 NodeArray Inits;
1647public:
1648 InitListExpr(Node *Ty_, NodeArray Inits_)
1649 : Ty(Ty_), Inits(Inits_) {
1650 if (Ty)
1651 ParameterPackSize = Ty->ParameterPackSize;
1652 for (Node *I : Inits)
1653 ParameterPackSize = std::min(I->ParameterPackSize, ParameterPackSize);
1654 }
1655
1656 void printLeft(OutputStream &S) const override {
1657 if (Ty)
1658 Ty->print(S);
1659 S += '{';
1660 Inits.printWithComma(S);
1661 S += '}';
1662 }
1663};
1664
1665class BracedExpr : public Expr {
1666 Node *Elem;
1667 Node *Init;
1668 bool IsArray;
1669public:
1670 BracedExpr(Node *Elem_, Node *Init_, bool IsArray_)
1671 : Expr(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
1672
1673 void printLeft(OutputStream &S) const override {
1674 if (IsArray) {
1675 S += '[';
1676 Elem->print(S);
1677 S += ']';
1678 } else {
1679 S += '.';
1680 Elem->print(S);
1681 }
1682 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1683 S += " = ";
1684 Init->print(S);
1685 }
1686};
1687
1688class BracedRangeExpr : public Expr {
1689 Node *First;
1690 Node *Last;
1691 Node *Init;
1692public:
1693 BracedRangeExpr(Node *First_, Node *Last_, Node *Init_)
1694 : Expr(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
1695
1696 void printLeft(OutputStream &S) const override {
1697 S += '[';
1698 First->print(S);
1699 S += " ... ";
1700 Last->print(S);
1701 S += ']';
1702 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
1703 S += " = ";
1704 Init->print(S);
1705 }
1706};
1707
Erik Pilkington0024acd2017-07-28 00:43:49 +00001708class ThrowExpr : public Expr {
1709 const Node *Op;
1710
1711public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001712 ThrowExpr(Node *Op_) : Op(Op_) {
1713 ParameterPackSize = Op->ParameterPackSize;
1714 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001715
1716 void printLeft(OutputStream &S) const override {
1717 S += "throw ";
1718 Op->print(S);
1719 }
1720};
1721
1722class BoolExpr : public Expr {
1723 bool Value;
1724
1725public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001726 BoolExpr(bool Value_) : Value(Value_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001727
1728 void printLeft(OutputStream &S) const override {
1729 S += Value ? StringView("true") : StringView("false");
1730 }
1731};
1732
1733class IntegerCastExpr : public Expr {
1734 // ty(integer)
1735 Node *Ty;
1736 StringView Integer;
1737
1738public:
Erik Pilkington761e6b02018-01-31 20:17:06 +00001739 IntegerCastExpr(Node *Ty_, StringView Integer_) : Ty(Ty_), Integer(Integer_) {
1740 ParameterPackSize = Ty->ParameterPackSize;
1741 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00001742
1743 void printLeft(OutputStream &S) const override {
1744 S += "(";
1745 Ty->print(S);
1746 S += ")";
1747 S += Integer;
1748 }
1749};
1750
1751class IntegerExpr : public Expr {
1752 StringView Type;
1753 StringView Value;
1754
1755public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001756 IntegerExpr(StringView Type_, StringView Value_) : Type(Type_), Value(Value_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001757
1758 void printLeft(OutputStream &S) const override {
1759 if (Type.size() > 3) {
1760 S += "(";
1761 S += Type;
1762 S += ")";
1763 }
1764
1765 if (Value[0] == 'n') {
1766 S += "-";
1767 S += Value.dropFront(1);
1768 } else
1769 S += Value;
1770
1771 if (Type.size() <= 3)
1772 S += Type;
1773 }
1774};
1775
1776template <class Float> struct FloatData;
1777
1778template <class Float> class FloatExpr : public Expr {
1779 const StringView Contents;
1780
1781public:
Erik Pilkington414f1a52017-08-09 22:45:35 +00001782 FloatExpr(StringView Contents_) : Contents(Contents_) {}
Erik Pilkington0024acd2017-07-28 00:43:49 +00001783
1784 void printLeft(OutputStream &s) const override {
1785 const char *first = Contents.begin();
1786 const char *last = Contents.end() + 1;
1787
1788 const size_t N = FloatData<Float>::mangled_size;
1789 if (static_cast<std::size_t>(last - first) > N) {
1790 last = first + N;
1791 union {
1792 Float value;
1793 char buf[sizeof(Float)];
1794 };
1795 const char *t = first;
1796 char *e = buf;
1797 for (; t != last; ++t, ++e) {
1798 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1799 : static_cast<unsigned>(*t - 'a' + 10);
1800 ++t;
1801 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
1802 : static_cast<unsigned>(*t - 'a' + 10);
1803 *e = static_cast<char>((d1 << 4) + d0);
1804 }
1805#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1806 std::reverse(buf, e);
1807#endif
1808 char num[FloatData<Float>::max_demangled_size] = {0};
1809 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
1810 s += StringView(num, num + n);
1811 }
1812 }
1813};
1814
Erik Pilkington0024acd2017-07-28 00:43:49 +00001815class BumpPointerAllocator {
1816 struct BlockMeta {
1817 BlockMeta* Next;
1818 size_t Current;
1819 };
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001820
Erik Pilkington0024acd2017-07-28 00:43:49 +00001821 static constexpr size_t AllocSize = 4096;
1822 static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001823
Erik Pilkington0024acd2017-07-28 00:43:49 +00001824 alignas(16) char InitialBuffer[AllocSize];
1825 BlockMeta* BlockList = nullptr;
1826
1827 void grow() {
1828 char* NewMeta = new char[AllocSize];
1829 BlockList = new (NewMeta) BlockMeta{BlockList, 0};
1830 }
1831
1832 void* allocateMassive(size_t NBytes) {
1833 NBytes += sizeof(BlockMeta);
1834 BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(new char[NBytes]);
1835 BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
1836 return static_cast<void*>(NewMeta + 1);
1837 }
1838
1839public:
1840 BumpPointerAllocator()
1841 : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
1842
1843 void* allocate(size_t N) {
1844 N = (N + 15u) & ~15u;
1845 if (N + BlockList->Current >= UsableAllocSize) {
1846 if (N > UsableAllocSize)
1847 return allocateMassive(N);
1848 grow();
1849 }
1850 BlockList->Current += N;
1851 return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
1852 BlockList->Current - N);
1853 }
1854
1855 ~BumpPointerAllocator() {
1856 while (BlockList) {
1857 BlockMeta* Tmp = BlockList;
1858 BlockList = BlockList->Next;
1859 if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
1860 delete[] reinterpret_cast<char*>(Tmp);
1861 }
1862 }
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001863};
1864
Erik Pilkingtonba34a242017-08-09 21:30:57 +00001865template <class T, size_t N>
1866class PODSmallVector {
1867 static_assert(std::is_pod<T>::value,
1868 "T is required to be a plain old data type");
1869
1870 T* First;
1871 T* Last;
1872 T* Cap;
1873 T Inline[N];
1874
1875 bool isInline() const { return First == Inline; }
1876
1877 void clearInline() {
1878 First = Inline;
1879 Last = Inline;
1880 Cap = Inline + N;
1881 }
1882
1883 void reserve(size_t NewCap) {
1884 size_t S = size();
1885 if (isInline()) {
1886 auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T)));
1887 std::copy(First, Last, Tmp);
1888 First = Tmp;
1889 } else
1890 First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T)));
1891 Last = First + S;
1892 Cap = First + NewCap;
1893 }
1894
1895public:
1896 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
1897
1898 PODSmallVector(const PODSmallVector&) = delete;
1899 PODSmallVector& operator=(const PODSmallVector&) = delete;
1900
1901 PODSmallVector(PODSmallVector&& Other) : PODSmallVector() {
1902 if (Other.isInline()) {
1903 std::copy(Other.begin(), Other.end(), First);
1904 Last = First + Other.size();
1905 Other.clear();
1906 return;
1907 }
1908
1909 First = Other.First;
1910 Last = Other.Last;
1911 Cap = Other.Cap;
1912 Other.clearInline();
1913 }
1914
1915 PODSmallVector& operator=(PODSmallVector&& Other) {
1916 if (Other.isInline()) {
1917 if (!isInline()) {
1918 std::free(First);
1919 clearInline();
1920 }
1921 std::copy(Other.begin(), Other.end(), First);
1922 Last = First + Other.size();
1923 Other.clear();
1924 return *this;
1925 }
1926
1927 if (isInline()) {
1928 First = Other.First;
1929 Last = Other.Last;
1930 Cap = Other.Cap;
1931 Other.clearInline();
1932 return *this;
1933 }
1934
1935 std::swap(First, Other.First);
1936 std::swap(Last, Other.Last);
1937 std::swap(Cap, Other.Cap);
1938 Other.clear();
1939 return *this;
1940 }
1941
1942 void push_back(const T& Elem) {
1943 if (Last == Cap)
1944 reserve(size() * 2);
1945 *Last++ = Elem;
1946 }
1947
1948 void pop_back() {
1949 assert(Last != First && "Popping empty vector!");
1950 --Last;
1951 }
1952
1953 void dropBack(size_t Index) {
1954 assert(Index <= size() && "dropBack() can't expand!");
1955 Last = First + Index;
1956 }
1957
1958 T* begin() { return First; }
1959 T* end() { return Last; }
1960
1961 bool empty() const { return First == Last; }
1962 size_t size() const { return static_cast<size_t>(Last - First); }
1963 T& back() {
1964 assert(Last != First && "Calling back() on empty vector!");
1965 return *(Last - 1);
1966 }
1967 T& operator[](size_t Index) {
1968 assert(Index < size() && "Invalid access!");
1969 return *(begin() + Index);
1970 }
1971 void clear() { Last = First; }
1972
1973 ~PODSmallVector() {
1974 if (!isInline())
1975 std::free(First);
1976 }
1977};
1978
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001979struct Db {
1980 const char *First;
1981 const char *Last;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00001982
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001983 // Name stack, this is used by the parser to hold temporary names that were
1984 // parsed. The parser colapses multiple names into new nodes to construct
1985 // the AST. Once the parser is finished, names.size() == 1.
1986 PODSmallVector<Node *, 32> Names;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00001987
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001988 // Substitution table. Itanium supports name substitutions as a means of
1989 // compression. The string "S42_" refers to the 44nd entry (base-36) in this
1990 // table.
1991 PODSmallVector<Node *, 32> Subs;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00001992
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001993 // Template parameter table. Like the above, but referenced like "T42_".
1994 // This has a smaller size compared to Subs and Names because it can be
1995 // stored on the stack.
1996 PODSmallVector<Node *, 8> TemplateParams;
Erik Pilkington9dd63d22017-07-08 18:54:07 +00001997
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001998 unsigned EncodingDepth = 0;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00001999 bool TagTemplates = true;
2000 bool FixForwardReferences = false;
2001 bool TryToParseTemplateArgs = true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002002
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002003 BumpPointerAllocator ASTAllocator;
2004
2005 template <class T, class... Args> T *make(Args &&... args) {
2006 return new (ASTAllocator.allocate(sizeof(T)))
2007 T(std::forward<Args>(args)...);
2008 }
2009
2010 template <class It> NodeArray makeNodeArray(It begin, It end) {
2011 size_t sz = static_cast<size_t>(end - begin);
2012 void *mem = ASTAllocator.allocate(sizeof(Node *) * sz);
2013 Node **data = new (mem) Node *[sz];
2014 std::copy(begin, end, data);
2015 return NodeArray(data, sz);
2016 }
2017
2018 NodeArray popTrailingNodeArray(size_t FromPosition) {
2019 assert(FromPosition <= Names.size());
2020 NodeArray res =
2021 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2022 Names.dropBack(FromPosition);
2023 return res;
2024 }
2025
2026 bool consumeIf(StringView S) {
2027 if (StringView(First, Last).startsWith(S)) {
2028 First += S.size();
2029 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002030 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002031 return false;
2032 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002033
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002034 bool consumeIf(char C) {
2035 if (First != Last && *First == C) {
2036 ++First;
2037 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002038 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002039 return false;
2040 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002041
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002042 char consume() { return First != Last ? *First++ : '\0'; }
2043
2044 char look(unsigned Lookahead = 0) {
2045 if (static_cast<size_t>(Last - First) <= Lookahead)
2046 return '\0';
2047 return First[Lookahead];
2048 }
2049
2050 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2051
2052 StringView parseNumber(bool AllowNegative = false);
2053 Qualifiers parseCVQualifiers();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002054 bool parsePositiveInteger(size_t *Out);
2055 StringView parseBareSourceName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002056
2057 /// Parse the <expr> production.
2058 Node *parseExpr();
2059 Node *parsePrefixExpr(StringView Kind);
2060 Node *parseBinaryExpr(StringView Kind);
2061 Node *parseIntegerLiteral(StringView Lit);
2062 Node *parseExprPrimary();
2063 template <class Float> Node *parseFloatingLiteral();
2064 Node *parseFunctionParam();
2065 Node *parseNewExpr();
2066 Node *parseConversionExpr();
Erik Pilkington88a1cf62018-02-13 00:15:56 +00002067 Node *parseBracedExpr();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002068
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002069 /// Parse the <type> production.
2070 Node *parseType();
2071 Node *parseFunctionType();
2072 Node *parseVectorType();
2073 Node *parseDecltype();
2074 Node *parseArrayType();
2075 Node *parsePointerToMemberType();
2076 Node *parseClassEnumType();
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002077 Node *parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002078
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002079 Node *parseEncoding();
2080 bool parseCallOffset();
2081 Node *parseSpecialName();
2082
2083 /// Holds some extra information about a <name> that is being parsed. This
2084 /// information is only pertinent if the <name> refers to an <encoding>.
2085 struct NameState {
2086 bool CtorDtorConversion = false;
2087 bool EndsWithTemplateArgs = false;
2088 Qualifiers CVQualifiers = QualNone;
2089 FunctionRefQual ReferenceQualifier = FrefQualNone;
2090 };
2091
2092 /// Parse the <name> production>
2093 Node *parseName(NameState *State = nullptr);
2094 Node *parseLocalName(NameState *State);
2095 Node *parseOperatorName(NameState *State);
2096 Node *parseUnqualifiedName(NameState *State);
2097 Node *parseUnnamedTypeName(NameState *State);
2098 Node *parseSourceName(NameState *State);
2099 Node *parseUnscopedName(NameState *State);
2100 Node *parseNestedName(NameState *State);
2101 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2102
Erik Pilkington2808f772018-02-13 17:09:03 +00002103 Node *parseAbiTags(Node *N);
2104
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002105 /// Parse the <unresolved-name> production.
2106 Node *parseUnresolvedName();
2107 Node *parseSimpleId();
2108 Node *parseBaseUnresolvedName();
2109 Node *parseUnresolvedType();
2110 Node *parseDestructorName();
2111
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002112 // FIXME: remove this when all the parse_* functions have been rewritten.
2113 template <const char *(*parse_fn)(const char *, const char *, Db &)>
2114 Node *legacyParse() {
2115 size_t BeforeType = Names.size();
2116 const char *OrigFirst = First;
2117 const char *T = parse_fn(First, Last, *this);
2118 if (T == OrigFirst || BeforeType + 1 != Names.size())
2119 return nullptr;
2120 First = T;
2121 Node *R = Names.back();
2122 Names.pop_back();
2123 return R;
2124 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002125};
Erik Pilkingtonc3926622017-07-08 18:54:08 +00002126
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002127const char *parse_expression(const char *first, const char *last, Db &db) {
2128 db.First = first;
2129 db.Last = last;
2130 Node *R = db.parseExpr();
2131 if (R == nullptr)
2132 return first;
2133 db.Names.push_back(R);
2134 return db.First;
2135}
2136
2137const char *parse_expr_primary(const char *first, const char *last, Db &db) {
2138 db.First = first;
2139 db.Last = last;
2140 Node *R = db.parseExprPrimary();
2141 if (R == nullptr)
2142 return first;
2143 db.Names.push_back(R);
2144 return db.First;
2145}
2146
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002147const char *parse_type(const char *first, const char *last, Db &db) {
2148 db.First = first;
2149 db.Last = last;
2150 Node *R = db.parseType();
2151 if (R == nullptr)
2152 return first;
2153 db.Names.push_back(R);
2154 return db.First;
2155}
2156
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002157const char *parse_encoding(const char *first, const char *last, Db &db) {
2158 db.First = first;
2159 db.Last = last;
2160 Node *R = db.parseEncoding();
2161 if (R == nullptr)
2162 return first;
2163 db.Names.push_back(R);
2164 return db.First;
2165}
2166
2167const char* parse_discriminator(const char* first, const char* last);
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002168const char *parse_template_args(const char *first, const char *last, Db &db);
2169const char *parse_template_param(const char *, const char *, Db &);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002170const char *parse_substitution(const char *, const char *, Db &);
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002171
Erik Pilkington2808f772018-02-13 17:09:03 +00002172
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002173// <name> ::= <nested-name> // N
2174// ::= <local-name> # See Scope Encoding below // Z
2175// ::= <unscoped-template-name> <template-args>
2176// ::= <unscoped-name>
2177//
2178// <unscoped-template-name> ::= <unscoped-name>
2179// ::= <substitution>
2180Node *Db::parseName(NameState *State) {
2181 consumeIf('L'); // extension
2182
2183 if (look() == 'N')
2184 return parseNestedName(State);
2185 if (look() == 'Z')
2186 return parseLocalName(State);
2187
2188 // ::= <unscoped-template-name> <template-args>
2189 if (look() == 'S' && look(1) != 't') {
2190 Node *S = legacyParse<parse_substitution>();
2191 if (look() != 'I')
2192 return nullptr;
2193 Node *TA = legacyParse<parse_template_args>();
2194 if (TA == nullptr)
2195 return nullptr;
2196 if (State) State->EndsWithTemplateArgs = true;
2197 return make<NameWithTemplateArgs>(S, TA);
2198 }
2199
2200 Node *N = parseUnscopedName(State);
2201 if (N == nullptr)
2202 return nullptr;
2203 // ::= <unscoped-template-name> <template-args>
2204 if (look() == 'I') {
2205 Subs.push_back(N);
2206 Node *TA = legacyParse<parse_template_args>();
2207 if (TA == nullptr)
2208 return nullptr;
2209 if (State) State->EndsWithTemplateArgs = true;
2210 return make<NameWithTemplateArgs>(N, TA);
2211 }
2212 // ::= <unscoped-name>
2213 return N;
2214}
2215
2216// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2217// := Z <function encoding> E s [<discriminator>]
2218// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
2219Node *Db::parseLocalName(NameState *State) {
2220 if (!consumeIf('Z'))
2221 return nullptr;
2222 Node *Encoding = parseEncoding();
2223 if (Encoding == nullptr || !consumeIf('E'))
2224 return nullptr;
2225
2226 if (consumeIf('s')) {
2227 First = parse_discriminator(First, Last);
2228 return make<QualifiedName>(Encoding, make<NameType>("string literal"));
2229 }
2230
2231 if (consumeIf('d')) {
2232 parseNumber(true);
2233 if (!consumeIf('_'))
2234 return nullptr;
2235 Node *N = parseName(State);
2236 if (N == nullptr)
2237 return nullptr;
2238 return make<QualifiedName>(Encoding, N);
2239 }
2240
2241 Node *Entity = parseName(State);
2242 if (Entity == nullptr)
2243 return nullptr;
2244 First = parse_discriminator(First, Last);
2245 return make<QualifiedName>(Encoding, Entity);
2246}
2247
2248// <unscoped-name> ::= <unqualified-name>
2249// ::= St <unqualified-name> # ::std::
2250// extension ::= StL<unqualified-name>
2251Node *Db::parseUnscopedName(NameState *State) {
2252 if (consumeIf("StL") || consumeIf("St")) {
2253 Node *R = parseUnqualifiedName(State);
2254 if (R == nullptr)
2255 return nullptr;
2256 return make<StdQualifiedName>(R);
2257 }
2258 return parseUnqualifiedName(State);
2259}
2260
2261// <unqualified-name> ::= <operator-name> [abi-tags]
2262// ::= <ctor-dtor-name>
2263// ::= <source-name>
2264// ::= <unnamed-type-name>
2265// FIXME: ::= DC <source-name>+ E # structured binding declaration
2266Node *Db::parseUnqualifiedName(NameState *State) {
2267 // <ctor-dtor-name>s are special-cased in parseNestedName().
2268 Node *Result;
2269 if (look() == 'U')
2270 Result = parseUnnamedTypeName(State);
2271 else if (look() >= '1' && look() <= '9')
2272 Result = parseSourceName(State);
2273 else
2274 Result = parseOperatorName(State);
2275 if (Result != nullptr)
2276 Result = parseAbiTags(Result);
2277 return Result;
2278}
2279
2280// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2281// ::= <closure-type-name>
2282//
2283// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2284//
2285// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
2286Node *Db::parseUnnamedTypeName(NameState *) {
2287 if (consumeIf("Ut")) {
2288 StringView Count = parseNumber();
2289 if (!consumeIf('_'))
2290 return nullptr;
2291 return make<UnnamedTypeName>(Count);
2292 }
2293 if (consumeIf("Ul")) {
2294 NodeArray Params;
2295 if (!consumeIf("vE")) {
2296 size_t ParamsBegin = Names.size();
2297 do {
2298 Node *P = parseType();
2299 if (P == nullptr)
2300 return nullptr;
2301 Names.push_back(P);
2302 } while (!consumeIf('E'));
2303 Params = popTrailingNodeArray(ParamsBegin);
2304 }
2305 StringView Count = parseNumber();
2306 if (!consumeIf('_'))
2307 return nullptr;
2308 return make<ClosureTypeName>(Params, Count);
2309 }
2310 return nullptr;
2311}
2312
2313// <source-name> ::= <positive length number> <identifier>
2314Node *Db::parseSourceName(NameState *) {
2315 size_t Length = 0;
2316 if (parsePositiveInteger(&Length))
2317 return nullptr;
2318 if (numLeft() < Length || Length == 0)
2319 return nullptr;
2320 StringView Name(First, First + Length);
2321 First += Length;
2322 if (Name.startsWith("_GLOBAL__N"))
2323 return make<NameType>("(anonymous namespace)");
2324 return make<NameType>(Name);
2325}
2326
2327// <operator-name> ::= aa # &&
2328// ::= ad # & (unary)
2329// ::= an # &
2330// ::= aN # &=
2331// ::= aS # =
2332// ::= cl # ()
2333// ::= cm # ,
2334// ::= co # ~
2335// ::= cv <type> # (cast)
2336// ::= da # delete[]
2337// ::= de # * (unary)
2338// ::= dl # delete
2339// ::= dv # /
2340// ::= dV # /=
2341// ::= eo # ^
2342// ::= eO # ^=
2343// ::= eq # ==
2344// ::= ge # >=
2345// ::= gt # >
2346// ::= ix # []
2347// ::= le # <=
2348// ::= li <source-name> # operator ""
2349// ::= ls # <<
2350// ::= lS # <<=
2351// ::= lt # <
2352// ::= mi # -
2353// ::= mI # -=
2354// ::= ml # *
2355// ::= mL # *=
2356// ::= mm # -- (postfix in <expression> context)
2357// ::= na # new[]
2358// ::= ne # !=
2359// ::= ng # - (unary)
2360// ::= nt # !
2361// ::= nw # new
2362// ::= oo # ||
2363// ::= or # |
2364// ::= oR # |=
2365// ::= pm # ->*
2366// ::= pl # +
2367// ::= pL # +=
2368// ::= pp # ++ (postfix in <expression> context)
2369// ::= ps # + (unary)
2370// ::= pt # ->
2371// ::= qu # ?
2372// ::= rm # %
2373// ::= rM # %=
2374// ::= rs # >>
2375// ::= rS # >>=
2376// ::= ss # <=> C++2a
2377// ::= v <digit> <source-name> # vendor extended operator
2378Node *Db::parseOperatorName(NameState *State) {
2379 switch (look()) {
2380 case 'a':
2381 switch (look(1)) {
2382 case 'a':
2383 First += 2;
2384 return make<NameType>("operator&&");
2385 case 'd':
2386 case 'n':
2387 First += 2;
2388 return make<NameType>("operator&");
2389 case 'N':
2390 First += 2;
2391 return make<NameType>("operator&=");
2392 case 'S':
2393 First += 2;
2394 return make<NameType>("operator=");
2395 }
2396 return nullptr;
2397 case 'c':
2398 switch (look(1)) {
2399 case 'l':
2400 First += 2;
2401 return make<NameType>("operator()");
2402 case 'm':
2403 First += 2;
2404 return make<NameType>("operator,");
2405 case 'o':
2406 First += 2;
2407 return make<NameType>("operator~");
2408 // ::= cv <type> # (cast)
2409 case 'v': {
2410 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2411 First += 2;
2412 Node *Ty = parseType();
2413 if (Ty == nullptr)
2414 return nullptr;
2415 if (State) State->CtorDtorConversion = true;
2416 return make<ConversionOperatorType>(Ty);
2417 }
2418 }
2419 return nullptr;
2420 case 'd':
2421 switch (look(1)) {
2422 case 'a':
2423 First += 2;
2424 return make<NameType>("operator delete[]");
2425 case 'e':
2426 First += 2;
2427 return make<NameType>("operator*");
2428 case 'l':
2429 First += 2;
2430 return make<NameType>("operator delete");
2431 case 'v':
2432 First += 2;
2433 return make<NameType>("operator/");
2434 case 'V':
2435 First += 2;
2436 return make<NameType>("operator/=");
2437 }
2438 return nullptr;
2439 case 'e':
2440 switch (look(1)) {
2441 case 'o':
2442 First += 2;
2443 return make<NameType>("operator^");
2444 case 'O':
2445 First += 2;
2446 return make<NameType>("operator^=");
2447 case 'q':
2448 First += 2;
2449 return make<NameType>("operator==");
2450 }
2451 return nullptr;
2452 case 'g':
2453 switch (look(1)) {
2454 case 'e':
2455 First += 2;
2456 return make<NameType>("operator>=");
2457 case 't':
2458 First += 2;
2459 return make<NameType>("operator>");
2460 }
2461 return nullptr;
2462 case 'i':
2463 if (look(1) == 'x') {
2464 First += 2;
2465 return make<NameType>("operator[]");
2466 }
2467 return nullptr;
2468 case 'l':
2469 switch (look(1)) {
2470 case 'e':
2471 First += 2;
2472 return make<NameType>("operator<=");
2473 // ::= li <source-name> # operator ""
2474 case 'i': {
2475 First += 2;
2476 Node *SN = parseSourceName(State);
2477 if (SN == nullptr)
2478 return nullptr;
2479 return make<LiteralOperator>(SN);
2480 }
2481 case 's':
2482 First += 2;
2483 return make<NameType>("operator<<");
2484 case 'S':
2485 First += 2;
2486 return make<NameType>("operator<<=");
2487 case 't':
2488 First += 2;
2489 return make<NameType>("operator<");
2490 }
2491 return nullptr;
2492 case 'm':
2493 switch (look(1)) {
2494 case 'i':
2495 First += 2;
2496 return make<NameType>("operator-");
2497 case 'I':
2498 First += 2;
2499 return make<NameType>("operator-=");
2500 case 'l':
2501 First += 2;
2502 return make<NameType>("operator*");
2503 case 'L':
2504 First += 2;
2505 return make<NameType>("operator*=");
2506 case 'm':
2507 First += 2;
2508 return make<NameType>("operator--");
2509 }
2510 return nullptr;
2511 case 'n':
2512 switch (look(1)) {
2513 case 'a':
2514 First += 2;
2515 return make<NameType>("operator new[]");
2516 case 'e':
2517 First += 2;
2518 return make<NameType>("operator!=");
2519 case 'g':
2520 First += 2;
2521 return make<NameType>("operator-");
2522 case 't':
2523 First += 2;
2524 return make<NameType>("operator!");
2525 case 'w':
2526 First += 2;
2527 return make<NameType>("operator new");
2528 }
2529 return nullptr;
2530 case 'o':
2531 switch (look(1)) {
2532 case 'o':
2533 First += 2;
2534 return make<NameType>("operator||");
2535 case 'r':
2536 First += 2;
2537 return make<NameType>("operator|");
2538 case 'R':
2539 First += 2;
2540 return make<NameType>("operator|=");
2541 }
2542 return nullptr;
2543 case 'p':
2544 switch (look(1)) {
2545 case 'm':
2546 First += 2;
2547 return make<NameType>("operator->*");
2548 case 'l':
2549 First += 2;
2550 return make<NameType>("operator+");
2551 case 'L':
2552 First += 2;
2553 return make<NameType>("operator+=");
2554 case 'p':
2555 First += 2;
2556 return make<NameType>("operator++");
2557 case 's':
2558 First += 2;
2559 return make<NameType>("operator+");
2560 case 't':
2561 First += 2;
2562 return make<NameType>("operator->");
2563 }
2564 return nullptr;
2565 case 'q':
2566 if (look(1) == 'u') {
2567 First += 2;
2568 return make<NameType>("operator?");
2569 }
2570 return nullptr;
2571 case 'r':
2572 switch (look(1)) {
2573 case 'm':
2574 First += 2;
2575 return make<NameType>("operator%");
2576 case 'M':
2577 First += 2;
2578 return make<NameType>("operator%=");
2579 case 's':
2580 First += 2;
2581 return make<NameType>("operator>>");
2582 case 'S':
2583 First += 2;
2584 return make<NameType>("operator>>=");
2585 }
2586 return nullptr;
2587 case 's':
2588 if (look(1) == 's') {
2589 First += 2;
2590 return make<NameType>("operator<=>");
2591 }
2592 return nullptr;
2593 // ::= v <digit> <source-name> # vendor extended operator
2594 case 'v':
2595 if (std::isdigit(look(1))) {
2596 First += 2;
2597 Node *SN = parseSourceName(State);
2598 if (SN == nullptr)
2599 return nullptr;
2600 return make<ConversionOperatorType>(SN);
2601 }
2602 return nullptr;
2603 }
2604 return nullptr;
2605}
2606
Erik Pilkington2808f772018-02-13 17:09:03 +00002607// <ctor-dtor-name> ::= C1 # complete object constructor
2608// ::= C2 # base object constructor
2609// ::= C3 # complete object allocating constructor
2610// extension ::= C5 # ?
2611// ::= D0 # deleting destructor
2612// ::= D1 # complete object destructor
2613// ::= D2 # base object destructor
2614// extension ::= D5 # ?
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002615Node *Db::parseCtorDtorName(Node *&SoFar, NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002616 if (SoFar->K == Node::KSpecialSubstitution) {
2617 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
2618 switch (SSK) {
2619 case SpecialSubKind::string:
2620 case SpecialSubKind::istream:
2621 case SpecialSubKind::ostream:
2622 case SpecialSubKind::iostream:
2623 SoFar = make<ExpandedSpecialSubstitution>(SSK);
2624 default:
2625 break;
2626 }
2627 }
2628
2629 if (consumeIf('C')) {
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002630 bool IsInherited = consumeIf('I');
Erik Pilkington2808f772018-02-13 17:09:03 +00002631 if (look() != '1' && look() != '2' && look() != '3' && look() != '5')
2632 return nullptr;
2633 ++First;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002634 if (State) State->CtorDtorConversion = true;
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002635 if (IsInherited) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002636 if (parseName() == nullptr)
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002637 return nullptr;
2638 }
Erik Pilkington2808f772018-02-13 17:09:03 +00002639 return make<CtorDtorName>(SoFar, false);
2640 }
2641
2642 if (look() == 'D' &&
2643 (look(1) == '0' || look(1) == '1' || look(1) == '2' || look(1) == '5')) {
2644 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002645 if (State) State->CtorDtorConversion = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002646 return make<CtorDtorName>(SoFar, true);
2647 }
2648
2649 return nullptr;
2650}
2651
2652// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
2653// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
2654//
2655// <prefix> ::= <prefix> <unqualified-name>
2656// ::= <template-prefix> <template-args>
2657// ::= <template-param>
2658// ::= <decltype>
2659// ::= # empty
2660// ::= <substitution>
2661// ::= <prefix> <data-member-prefix>
2662// extension ::= L
2663//
2664// <template-prefix> ::= <prefix> <template unqualified-name>
2665// ::= <template-param>
2666// ::= <substitution>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002667Node *Db::parseNestedName(NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002668 if (!consumeIf('N'))
2669 return nullptr;
2670
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002671 Qualifiers CVTmp = parseCVQualifiers();
2672 if (State) State->CVQualifiers = CVTmp;
2673
2674 if (consumeIf('O')) {
2675 if (State) State->ReferenceQualifier = FrefQualRValue;
2676 } else if (consumeIf('R')) {
2677 if (State) State->ReferenceQualifier = FrefQualLValue;
2678 } else
2679 if (State) State->ReferenceQualifier = FrefQualNone;
Erik Pilkington2808f772018-02-13 17:09:03 +00002680
2681 Node *SoFar = nullptr;
2682 auto PushComponent = [&](Node *Comp) {
2683 if (SoFar) SoFar = make<QualifiedName>(SoFar, Comp);
2684 else SoFar = Comp;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002685 if (State) State->EndsWithTemplateArgs = false;
Erik Pilkington2808f772018-02-13 17:09:03 +00002686 };
2687
2688 if (consumeIf("St"))
2689 SoFar = make<NameType>("std");
2690
2691 while (!consumeIf('E')) {
2692 consumeIf('L'); // extension
2693
2694 // ::= <template-param>
2695 if (look() == 'T') {
2696 Node *TP = legacyParse<parse_template_param>();
2697 if (TP == nullptr)
2698 return nullptr;
2699 PushComponent(TP);
2700 Subs.push_back(SoFar);
2701 continue;
2702 }
2703
2704 // ::= <template-prefix> <template-args>
2705 if (look() == 'I') {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002706 Node *TA = legacyParse<parse_template_args>();
Erik Pilkington2808f772018-02-13 17:09:03 +00002707 if (TA == nullptr || SoFar == nullptr)
2708 return nullptr;
2709 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002710 if (State) State->EndsWithTemplateArgs = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002711 Subs.push_back(SoFar);
2712 continue;
2713 }
2714
2715 // ::= <decltype>
2716 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002717 Node *DT = parseDecltype();
Erik Pilkington2808f772018-02-13 17:09:03 +00002718 if (DT == nullptr)
2719 return nullptr;
2720 PushComponent(DT);
2721 Subs.push_back(SoFar);
2722 continue;
2723 }
2724
2725 // ::= <substitution>
2726 if (look() == 'S' && look(1) != 't') {
2727 Node *S = legacyParse<parse_substitution>();
2728 if (S == nullptr)
2729 return nullptr;
2730 PushComponent(S);
2731 if (SoFar != S)
2732 Subs.push_back(S);
2733 continue;
2734 }
2735
2736 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
2737 if (look() == 'C' || look() == 'D') {
2738 if (SoFar == nullptr)
2739 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002740 Node *CtorDtor = parseCtorDtorName(SoFar, State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002741 if (CtorDtor == nullptr)
2742 return nullptr;
2743 PushComponent(CtorDtor);
2744 SoFar = parseAbiTags(SoFar);
2745 if (SoFar == nullptr)
2746 return nullptr;
2747 Subs.push_back(SoFar);
2748 continue;
2749 }
2750
2751 // ::= <prefix> <unqualified-name>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002752 Node *N = parseUnqualifiedName(State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002753 if (N == nullptr)
2754 return nullptr;
2755 PushComponent(N);
2756 Subs.push_back(SoFar);
2757 }
2758
2759 if (SoFar == nullptr || Subs.empty())
2760 return nullptr;
2761
2762 Subs.pop_back();
2763 return SoFar;
2764}
2765
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002766// <simple-id> ::= <source-name> [ <template-args> ]
2767Node *Db::parseSimpleId() {
2768 Node *SN = parseSourceName(/*NameState=*/nullptr);
2769 if (SN == nullptr)
2770 return nullptr;
2771 if (look() == 'I') {
2772 Node *TA = legacyParse<parse_template_args>();
2773 if (TA == nullptr)
2774 return nullptr;
2775 return make<NameWithTemplateArgs>(SN, TA);
2776 }
2777 return SN;
2778}
2779
2780// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
2781// ::= <simple-id> # e.g., ~A<2*N>
2782Node *Db::parseDestructorName() {
2783 Node *Result;
2784 if (std::isdigit(look()))
2785 Result = parseSimpleId();
2786 else
2787 Result = parseUnresolvedType();
2788 if (Result == nullptr)
2789 return nullptr;
2790 return make<DtorName>(Result);
2791}
2792
2793// <unresolved-type> ::= <template-param>
2794// ::= <decltype>
2795// ::= <substitution>
2796Node *Db::parseUnresolvedType() {
2797 if (look() == 'T') {
2798 Node *TP = legacyParse<parse_template_param>();
2799 if (TP == nullptr)
2800 return nullptr;
2801 Subs.push_back(TP);
2802 return TP;
2803 }
2804 if (look() == 'D') {
2805 Node *DT = parseDecltype();
2806 if (DT == nullptr)
2807 return nullptr;
2808 Subs.push_back(DT);
2809 return DT;
2810 }
2811 return legacyParse<parse_substitution>();
2812}
2813
2814// <base-unresolved-name> ::= <simple-id> # unresolved name
2815// extension ::= <operator-name> # unresolved operator-function-id
2816// extension ::= <operator-name> <template-args> # unresolved operator template-id
2817// ::= on <operator-name> # unresolved operator-function-id
2818// ::= on <operator-name> <template-args> # unresolved operator template-id
2819// ::= dn <destructor-name> # destructor or pseudo-destructor;
2820// # e.g. ~X or ~X<N-1>
2821Node *Db::parseBaseUnresolvedName() {
2822 if (std::isdigit(look()))
2823 return parseSimpleId();
2824
2825 if (consumeIf("dn"))
2826 return parseDestructorName();
2827
2828 consumeIf("on");
2829
2830 Node *Oper = parseOperatorName(/*NameState=*/nullptr);
2831 if (Oper == nullptr)
2832 return nullptr;
2833 if (look() == 'I') {
2834 Node *TA = legacyParse<parse_template_args>();
2835 if (TA == nullptr)
2836 return nullptr;
2837 return make<NameWithTemplateArgs>(Oper, TA);
2838 }
2839 return Oper;
2840}
2841
2842// <unresolved-name>
2843// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2844// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
2845// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2846// # A::x, N::y, A<T>::z; "gs" means leading "::"
2847// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
2848// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
2849// # T::N::x /decltype(p)::N::x
2850// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2851//
2852// <unresolved-qualifier-level> ::= <simple-id>
2853Node *Db::parseUnresolvedName() {
2854 Node *SoFar = nullptr;
2855
2856 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2857 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2858 if (consumeIf("srN")) {
2859 SoFar = parseUnresolvedType();
2860 if (SoFar == nullptr)
2861 return nullptr;
2862
2863 if (look() == 'I') {
2864 Node *TA = legacyParse<parse_template_args>();
2865 if (TA == nullptr)
2866 return nullptr;
2867 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2868 }
2869
2870 while (!consumeIf('E')) {
2871 Node *Qual = parseSimpleId();
2872 if (Qual == nullptr)
2873 return nullptr;
2874 SoFar = make<QualifiedName>(SoFar, Qual);
2875 }
2876
2877 Node *Base = parseBaseUnresolvedName();
2878 if (Base == nullptr)
2879 return nullptr;
2880 return make<QualifiedName>(SoFar, Base);
2881 }
2882
2883 bool Global = consumeIf("gs");
2884
2885 // [gs] <base-unresolved-name> # x or (with "gs") ::x
2886 if (!consumeIf("sr")) {
2887 SoFar = parseBaseUnresolvedName();
2888 if (SoFar == nullptr)
2889 return nullptr;
2890 if (Global)
2891 SoFar = make<GlobalQualifiedName>(SoFar);
2892 return SoFar;
2893 }
2894
2895 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2896 if (std::isdigit(look())) {
2897 do {
2898 Node *Qual = parseSimpleId();
2899 if (Qual == nullptr)
2900 return nullptr;
2901 if (SoFar)
2902 SoFar = make<QualifiedName>(SoFar, Qual);
2903 else if (Global)
2904 SoFar = make<GlobalQualifiedName>(Qual);
2905 else
2906 SoFar = Qual;
2907 } while (!consumeIf('E'));
2908 }
2909 // sr <unresolved-type> <base-unresolved-name>
2910 // sr <unresolved-type> <template-args> <base-unresolved-name>
2911 else {
2912 SoFar = parseUnresolvedType();
2913 if (SoFar == nullptr)
2914 return nullptr;
2915
2916 if (look() == 'I') {
2917 Node *TA = legacyParse<parse_template_args>();
2918 if (TA == nullptr)
2919 return nullptr;
2920 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2921 }
2922 }
2923
2924 assert(SoFar != nullptr);
2925
2926 Node *Base = parseBaseUnresolvedName();
2927 if (Base == nullptr)
2928 return nullptr;
2929 return make<QualifiedName>(SoFar, Base);
2930}
2931
Erik Pilkington2808f772018-02-13 17:09:03 +00002932// <abi-tags> ::= <abi-tag> [<abi-tags>]
2933// <abi-tag> ::= B <source-name>
2934Node *Db::parseAbiTags(Node *N) {
2935 while (consumeIf('B')) {
2936 StringView SN = parseBareSourceName();
2937 if (SN.empty())
2938 return nullptr;
2939 N = make<AbiTagAttr>(N, SN);
2940 }
2941 return N;
2942}
2943
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002944// <number> ::= [n] <non-negative decimal integer>
2945StringView Db::parseNumber(bool AllowNegative) {
2946 const char *Tmp = First;
2947 if (AllowNegative)
2948 consumeIf('n');
2949 if (numLeft() == 0 || !std::isdigit(*First))
2950 return StringView();
2951 while (numLeft() != 0 && std::isdigit(*First))
2952 ++First;
2953 return StringView(Tmp, First);
2954}
2955
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002956// <positive length number> ::= [0-9]*
2957bool Db::parsePositiveInteger(size_t *Out) {
2958 *Out = 0;
2959 if (look() < '0' || look() > '9')
2960 return true;
2961 while (look() >= '0' && look() <= '9') {
2962 *Out *= 10;
2963 *Out += static_cast<size_t>(consume() - '0');
2964 }
2965 return false;
2966}
2967
2968StringView Db::parseBareSourceName() {
2969 size_t Int = 0;
2970 if (parsePositiveInteger(&Int) || numLeft() < Int)
2971 return StringView();
2972 StringView R(First, First + Int);
2973 First += Int;
2974 return R;
2975}
2976
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002977// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002978//
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002979// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
2980// ::= DO <expression> E # computed (instantiation-dependent) noexcept
2981// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
2982//
2983// <ref-qualifier> ::= R # & ref-qualifier
2984// <ref-qualifier> ::= O # && ref-qualifier
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002985Node *Db::parseFunctionType() {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002986 Qualifiers CVQuals = parseCVQualifiers();
Erik Pilkington7e027ac2018-02-14 01:08:20 +00002987
2988 Node *ExceptionSpec = nullptr;
2989 if (consumeIf("Do")) {
2990 ExceptionSpec = make<NameType>("noexcept");
2991 } else if (consumeIf("DO")) {
2992 Node *E = parseExpr();
2993 if (E == nullptr || !consumeIf('E'))
2994 return nullptr;
2995 ExceptionSpec = make<NoexceptSpec>(E);
2996 } else if (consumeIf("Dw")) {
2997 size_t SpecsBegin = Names.size();
2998 while (!consumeIf('E')) {
2999 Node *T = parseType();
3000 if (T == nullptr)
3001 return nullptr;
3002 Names.push_back(T);
3003 }
3004 ExceptionSpec =
3005 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
3006 }
3007
3008 consumeIf("Dx"); // transaction safe
3009
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003010 if (!consumeIf('F'))
3011 return nullptr;
3012 consumeIf('Y'); // extern "C"
3013 Node *ReturnType = parseType();
3014 if (ReturnType == nullptr)
3015 return nullptr;
3016
3017 FunctionRefQual ReferenceQualifier = FrefQualNone;
3018 size_t ParamsBegin = Names.size();
3019 while (true) {
3020 if (consumeIf('E'))
3021 break;
3022 if (consumeIf('v'))
3023 continue;
3024 if (consumeIf("RE")) {
3025 ReferenceQualifier = FrefQualLValue;
3026 break;
3027 }
3028 if (consumeIf("OE")) {
3029 ReferenceQualifier = FrefQualRValue;
3030 break;
3031 }
3032 Node *T = parseType();
3033 if (T == nullptr)
3034 return nullptr;
3035 Names.push_back(T);
3036 }
3037
3038 NodeArray Params = popTrailingNodeArray(ParamsBegin);
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003039 return make<FunctionType>(ReturnType, Params, CVQuals,
3040 ReferenceQualifier, ExceptionSpec);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003041}
3042
3043// extension:
3044// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3045// ::= Dv [<dimension expression>] _ <element type>
3046// <extended element type> ::= <element type>
3047// ::= p # AltiVec vector pixel
3048Node *Db::parseVectorType() {
3049 if (!consumeIf("Dv"))
3050 return nullptr;
3051 if (look() >= '1' && look() <= '9') {
3052 StringView DimensionNumber = parseNumber();
3053 if (!consumeIf('_'))
3054 return nullptr;
3055 if (consumeIf('p'))
3056 return make<VectorType>(DimensionNumber);
3057 Node *ElemType = parseType();
3058 if (ElemType == nullptr)
3059 return nullptr;
3060 return make<VectorType>(ElemType, DimensionNumber);
3061 }
3062
3063 if (!consumeIf('_')) {
3064 Node *DimExpr = parseExpr();
3065 if (!DimExpr)
3066 return nullptr;
3067 if (!consumeIf('_'))
3068 return nullptr;
3069 Node *ElemType = parseType();
3070 if (!ElemType)
3071 return nullptr;
3072 return make<VectorType>(ElemType, DimExpr);
3073 }
3074 Node *ElemType = parseType();
3075 if (!ElemType)
3076 return nullptr;
3077 return make<VectorType>(ElemType, StringView());
3078}
3079
3080// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3081// ::= DT <expression> E # decltype of an expression (C++0x)
3082Node *Db::parseDecltype() {
3083 if (!consumeIf('D'))
3084 return nullptr;
3085 if (!consumeIf('t') && !consumeIf('T'))
3086 return nullptr;
3087 Node *E = parseExpr();
3088 if (E == nullptr)
3089 return nullptr;
3090 if (!consumeIf('E'))
3091 return nullptr;
3092 return make<EnclosingExpr>("decltype(", E, ")");
3093}
3094
3095// <array-type> ::= A <positive dimension number> _ <element type>
3096// ::= A [<dimension expression>] _ <element type>
3097Node *Db::parseArrayType() {
3098 if (!consumeIf('A'))
3099 return nullptr;
3100
3101 if (std::isdigit(look())) {
3102 StringView Dimension = parseNumber();
3103 if (!consumeIf('_'))
3104 return nullptr;
3105 Node *Ty = parseType();
3106 if (Ty == nullptr)
3107 return nullptr;
3108 return make<ArrayType>(Ty, Dimension);
3109 }
3110
3111 if (!consumeIf('_')) {
3112 Node *DimExpr = parseExpr();
3113 if (DimExpr == nullptr)
3114 return nullptr;
3115 if (!consumeIf('_'))
3116 return nullptr;
3117 Node *ElementType = parseType();
3118 if (ElementType == nullptr)
3119 return nullptr;
3120 return make<ArrayType>(ElementType, DimExpr);
3121 }
3122
3123 Node *Ty = parseType();
3124 if (Ty == nullptr)
3125 return nullptr;
3126 return make<ArrayType>(Ty);
3127}
3128
3129// <pointer-to-member-type> ::= M <class type> <member type>
3130Node *Db::parsePointerToMemberType() {
3131 if (!consumeIf('M'))
3132 return nullptr;
3133 Node *ClassType = parseType();
3134 if (ClassType == nullptr)
3135 return nullptr;
3136 Node *MemberType = parseType();
3137 if (MemberType == nullptr)
3138 return nullptr;
3139 return make<PointerToMemberType>(ClassType, MemberType);
3140}
3141
3142// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3143// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3144// ::= Tu <name> # dependent elaborated type specifier using 'union'
3145// ::= Te <name> # dependent elaborated type specifier using 'enum'
3146Node *Db::parseClassEnumType() {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003147 StringView ElabSpef;
3148 if (consumeIf("Ts"))
3149 ElabSpef = "struct";
3150 else if (consumeIf("Tu"))
3151 ElabSpef = "union";
3152 else if (consumeIf("Te"))
3153 ElabSpef = "enum";
3154
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003155 Node *Name = parseName();
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003156 if (Name == nullptr)
3157 return nullptr;
3158
3159 if (!ElabSpef.empty())
3160 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3161
3162 return Name;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003163}
3164
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003165// <qualified-type> ::= <qualifiers> <type>
3166// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3167// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003168Node *Db::parseQualifiedType() {
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003169 if (consumeIf('U')) {
3170 StringView Qual = parseBareSourceName();
3171 if (Qual.empty())
3172 return nullptr;
3173
3174 // FIXME parse the optional <template-args> here!
3175
3176 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3177 if (Qual.startsWith("objcproto")) {
3178 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3179 StringView Proto;
3180 {
3181 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3182 SaveLast(Last, ProtoSourceName.end());
3183 Proto = parseBareSourceName();
3184 }
3185 if (Proto.empty())
3186 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003187 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003188 if (Child == nullptr)
3189 return nullptr;
3190 return make<ObjCProtoName>(Child, Proto);
3191 }
3192
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003193 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003194 if (Child == nullptr)
3195 return nullptr;
3196 return make<VendorExtQualType>(Child, Qual);
3197 }
3198
3199 Qualifiers Quals = parseCVQualifiers();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003200 Node *Ty = parseType();
3201 if (Ty == nullptr)
3202 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003203 if (Quals != QualNone)
3204 Ty = make<QualType>(Ty, Quals);
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003205 return Ty;
3206}
3207
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003208// <type> ::= <builtin-type>
3209// ::= <qualified-type>
3210// ::= <function-type>
3211// ::= <class-enum-type>
3212// ::= <array-type>
3213// ::= <pointer-to-member-type>
3214// ::= <template-param>
3215// ::= <template-template-param> <template-args>
3216// ::= <decltype>
3217// ::= P <type> # pointer
3218// ::= R <type> # l-value reference
3219// ::= O <type> # r-value reference (C++11)
3220// ::= C <type> # complex pair (C99)
3221// ::= G <type> # imaginary (C99)
3222// ::= <substitution> # See Compression below
3223// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3224// extension ::= <vector-type> # <vector-type> starts with Dv
3225//
3226// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3227// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
3228Node *Db::parseType() {
3229 Node *Result = nullptr;
3230
3231 switch (look()) {
3232 // ::= <qualified-type>
3233 case 'r':
3234 case 'V':
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003235 case 'K': {
3236 unsigned AfterQuals = 0;
3237 if (look(AfterQuals) == 'r') ++AfterQuals;
3238 if (look(AfterQuals) == 'V') ++AfterQuals;
3239 if (look(AfterQuals) == 'K') ++AfterQuals;
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003240
3241 if (look(AfterQuals) == 'F' ||
3242 (look(AfterQuals) == 'D' &&
3243 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3244 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003245 Result = parseFunctionType();
3246 break;
3247 }
3248 _LIBCPP_FALLTHROUGH();
3249 }
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003250 case 'U': {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003251 Result = parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003252 break;
3253 }
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003254 // <builtin-type> ::= v # void
3255 case 'v':
3256 ++First;
3257 return make<NameType>("void");
3258 // ::= w # wchar_t
3259 case 'w':
3260 ++First;
3261 return make<NameType>("wchar_t");
3262 // ::= b # bool
3263 case 'b':
3264 ++First;
3265 return make<NameType>("bool");
3266 // ::= c # char
3267 case 'c':
3268 ++First;
3269 return make<NameType>("char");
3270 // ::= a # signed char
3271 case 'a':
3272 ++First;
3273 return make<NameType>("signed char");
3274 // ::= h # unsigned char
3275 case 'h':
3276 ++First;
3277 return make<NameType>("unsigned char");
3278 // ::= s # short
3279 case 's':
3280 ++First;
3281 return make<NameType>("short");
3282 // ::= t # unsigned short
3283 case 't':
3284 ++First;
3285 return make<NameType>("unsigned short");
3286 // ::= i # int
3287 case 'i':
3288 ++First;
3289 return make<NameType>("int");
3290 // ::= j # unsigned int
3291 case 'j':
3292 ++First;
3293 return make<NameType>("unsigned int");
3294 // ::= l # long
3295 case 'l':
3296 ++First;
3297 return make<NameType>("long");
3298 // ::= m # unsigned long
3299 case 'm':
3300 ++First;
3301 return make<NameType>("unsigned long");
3302 // ::= x # long long, __int64
3303 case 'x':
3304 ++First;
3305 return make<NameType>("long long");
3306 // ::= y # unsigned long long, __int64
3307 case 'y':
3308 ++First;
3309 return make<NameType>("unsigned long long");
3310 // ::= n # __int128
3311 case 'n':
3312 ++First;
3313 return make<NameType>("__int128");
3314 // ::= o # unsigned __int128
3315 case 'o':
3316 ++First;
3317 return make<NameType>("unsigned __int128");
3318 // ::= f # float
3319 case 'f':
3320 ++First;
3321 return make<NameType>("float");
3322 // ::= d # double
3323 case 'd':
3324 ++First;
3325 return make<NameType>("double");
3326 // ::= e # long double, __float80
3327 case 'e':
3328 ++First;
3329 return make<NameType>("long double");
3330 // ::= g # __float128
3331 case 'g':
3332 ++First;
3333 return make<NameType>("__float128");
3334 // ::= z # ellipsis
3335 case 'z':
3336 ++First;
3337 return make<NameType>("...");
3338
3339 // <builtin-type> ::= u <source-name> # vendor extended type
3340 case 'u': {
3341 ++First;
3342 StringView Res = parseBareSourceName();
3343 if (Res.empty())
3344 return nullptr;
3345 return make<NameType>(Res);
3346 }
3347 case 'D':
3348 switch (look(1)) {
3349 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3350 case 'd':
3351 First += 2;
3352 return make<NameType>("decimal64");
3353 // ::= De # IEEE 754r decimal floating point (128 bits)
3354 case 'e':
3355 First += 2;
3356 return make<NameType>("decimal128");
3357 // ::= Df # IEEE 754r decimal floating point (32 bits)
3358 case 'f':
3359 First += 2;
3360 return make<NameType>("decimal32");
3361 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3362 case 'h':
3363 First += 2;
3364 return make<NameType>("decimal16");
3365 // ::= Di # char32_t
3366 case 'i':
3367 First += 2;
3368 return make<NameType>("char32_t");
3369 // ::= Ds # char16_t
3370 case 's':
3371 First += 2;
3372 return make<NameType>("char16_t");
3373 // ::= Da # auto (in dependent new-expressions)
3374 case 'a':
3375 First += 2;
3376 return make<NameType>("auto");
3377 // ::= Dc # decltype(auto)
3378 case 'c':
3379 First += 2;
3380 return make<NameType>("decltype(auto)");
3381 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3382 case 'n':
3383 First += 2;
3384 return make<NameType>("std::nullptr_t");
3385
3386 // ::= <decltype>
3387 case 't':
3388 case 'T': {
3389 Result = parseDecltype();
3390 break;
3391 }
3392 // extension ::= <vector-type> # <vector-type> starts with Dv
3393 case 'v': {
3394 Result = parseVectorType();
3395 break;
3396 }
3397 // ::= Dp <type> # pack expansion (C++0x)
3398 case 'p': {
3399 First += 2;
3400 Node *Child = parseType();
3401 if (!Child)
3402 return nullptr;
3403 Result = make<ParameterPackExpansion>(Child);
3404 break;
3405 }
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003406 // Exception specifier on a function type.
3407 case 'o':
3408 case 'O':
3409 case 'w':
3410 // Transaction safe function type.
3411 case 'x':
3412 Result = parseFunctionType();
3413 break;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003414 }
3415 break;
3416 // ::= <function-type>
3417 case 'F': {
3418 Result = parseFunctionType();
3419 break;
3420 }
3421 // ::= <array-type>
3422 case 'A': {
3423 Result = parseArrayType();
3424 break;
3425 }
3426 // ::= <pointer-to-member-type>
3427 case 'M': {
3428 Result = parsePointerToMemberType();
3429 break;
3430 }
3431 // ::= <template-param>
3432 case 'T': {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003433 // This could be an elaborate type specifier on a <class-enum-type>.
3434 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
3435 Result = parseClassEnumType();
3436 break;
3437 }
3438
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003439 Result = legacyParse<parse_template_param>();
3440 if (Result == nullptr)
3441 return nullptr;
3442
3443 // Result could be either of:
3444 // <type> ::= <template-param>
3445 // <type> ::= <template-template-param> <template-args>
3446 //
3447 // <template-template-param> ::= <template-param>
3448 // ::= <substitution>
3449 //
3450 // If this is followed by some <template-args>, and we're permitted to
3451 // parse them, take the second production.
3452
3453 if (TryToParseTemplateArgs && look() == 'I') {
3454 Node *TA = legacyParse<parse_template_args>();
3455 if (TA == nullptr)
3456 return nullptr;
3457 Result = make<NameWithTemplateArgs>(Result, TA);
3458 }
3459 break;
3460 }
3461 // ::= P <type> # pointer
3462 case 'P': {
3463 ++First;
3464 Node *Ptr = parseType();
3465 if (Ptr == nullptr)
3466 return nullptr;
3467 Result = make<PointerType>(Ptr);
3468 break;
3469 }
3470 // ::= R <type> # l-value reference
3471 case 'R': {
3472 ++First;
3473 Node *Ref = parseType();
3474 if (Ref == nullptr)
3475 return nullptr;
3476 Result = make<LValueReferenceType>(Ref);
3477 break;
3478 }
3479 // ::= O <type> # r-value reference (C++11)
3480 case 'O': {
3481 ++First;
3482 Node *Ref = parseType();
3483 if (Ref == nullptr)
3484 return nullptr;
3485 Result = make<RValueReferenceType>(Ref);
3486 break;
3487 }
3488 // ::= C <type> # complex pair (C99)
3489 case 'C': {
3490 ++First;
3491 Node *P = parseType();
3492 if (P == nullptr)
3493 return nullptr;
3494 Result = make<PostfixQualifiedType>(P, " complex");
3495 break;
3496 }
3497 // ::= G <type> # imaginary (C99)
3498 case 'G': {
3499 ++First;
3500 Node *P = parseType();
3501 if (P == nullptr)
3502 return P;
3503 Result = make<PostfixQualifiedType>(P, " imaginary");
3504 break;
3505 }
3506 // ::= <substitution> # See Compression below
3507 case 'S': {
3508 if (look(1) && look(1) != 't') {
3509 Node *Sub = legacyParse<parse_substitution>();
3510 if (Sub == nullptr)
3511 return nullptr;
3512
3513 // Sub could be either of:
3514 // <type> ::= <substitution>
3515 // <type> ::= <template-template-param> <template-args>
3516 //
3517 // <template-template-param> ::= <template-param>
3518 // ::= <substitution>
3519 //
3520 // If this is followed by some <template-args>, and we're permitted to
3521 // parse them, take the second production.
3522
3523 if (TryToParseTemplateArgs && look() == 'I') {
3524 Node *TA = legacyParse<parse_template_args>();
3525 if (TA == nullptr)
3526 return nullptr;
3527 Result = make<NameWithTemplateArgs>(Sub, TA);
3528 break;
3529 }
3530
3531 // If all we parsed was a substitution, don't re-insert into the
3532 // substitution table.
3533 return Sub;
3534 }
3535 _LIBCPP_FALLTHROUGH();
3536 }
3537 // ::= <class-enum-type>
3538 default: {
3539 Result = parseClassEnumType();
3540 break;
3541 }
3542 }
3543
3544 // If we parsed a type, insert it into the substitution table. Note that all
3545 // <builtin-type>s and <substitution>s have already bailed out, because they
3546 // don't get substitutions.
3547 if (Result != nullptr)
3548 Subs.push_back(Result);
3549 return Result;
3550}
3551
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003552Node *Db::parsePrefixExpr(StringView Kind) {
3553 Node *E = parseExpr();
3554 if (E == nullptr)
3555 return nullptr;
3556 return make<PrefixExpr>(Kind, E);
3557}
3558
3559Node *Db::parseBinaryExpr(StringView Kind) {
3560 Node *LHS = parseExpr();
3561 if (LHS == nullptr)
3562 return nullptr;
3563 Node *RHS = parseExpr();
3564 if (RHS == nullptr)
3565 return nullptr;
3566 return make<BinaryExpr>(LHS, Kind, RHS);
3567}
3568
3569Node *Db::parseIntegerLiteral(StringView Lit) {
3570 StringView Tmp = parseNumber(true);
3571 if (!Tmp.empty() && consumeIf('E'))
3572 return make<IntegerExpr>(Lit, Tmp);
3573 return nullptr;
3574}
3575
Erik Pilkington2808f772018-02-13 17:09:03 +00003576// <CV-Qualifiers> ::= [r] [V] [K]
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003577Qualifiers Db::parseCVQualifiers() {
3578 Qualifiers CVR = QualNone;
3579 if (consumeIf('r'))
3580 addQualifiers(CVR, QualRestrict);
3581 if (consumeIf('V'))
3582 addQualifiers(CVR, QualVolatile);
3583 if (consumeIf('K'))
3584 addQualifiers(CVR, QualConst);
3585 return CVR;
3586}
3587
3588// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
3589// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
3590// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
3591// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
3592Node *Db::parseFunctionParam() {
3593 if (consumeIf("fp")) {
3594 parseCVQualifiers();
3595 StringView Num = parseNumber();
3596 if (!consumeIf('_'))
3597 return nullptr;
3598 return make<FunctionParam>(Num);
3599 }
3600 if (consumeIf("fL")) {
3601 if (parseNumber().empty())
3602 return nullptr;
3603 if (!consumeIf('p'))
3604 return nullptr;
3605 parseCVQualifiers();
3606 StringView Num = parseNumber();
3607 if (!consumeIf('_'))
3608 return nullptr;
3609 return make<FunctionParam>(Num);
3610 }
3611 return nullptr;
3612}
3613
3614// [gs] nw <expression>* _ <type> E # new (expr-list) type
3615// [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3616// [gs] na <expression>* _ <type> E # new[] (expr-list) type
3617// [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3618// <initializer> ::= pi <expression>* E # parenthesized initialization
3619Node *Db::parseNewExpr() {
3620 bool Global = consumeIf("gs");
3621 bool IsArray = look(1) == 'a';
3622 if (!consumeIf("nw") && !consumeIf("na"))
3623 return nullptr;
3624 size_t Exprs = Names.size();
3625 while (!consumeIf('_')) {
3626 Node *Ex = parseExpr();
3627 if (Ex == nullptr)
3628 return nullptr;
3629 Names.push_back(Ex);
3630 }
3631 NodeArray ExprList = popTrailingNodeArray(Exprs);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003632 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003633 if (Ty == nullptr)
3634 return Ty;
3635 if (consumeIf("pi")) {
3636 size_t InitsBegin = Names.size();
3637 while (!consumeIf('E')) {
3638 Node *Init = parseExpr();
3639 if (Init == nullptr)
3640 return Init;
3641 Names.push_back(Init);
3642 }
3643 NodeArray Inits = popTrailingNodeArray(InitsBegin);
3644 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
3645 } else if (!consumeIf('E'))
3646 return nullptr;
3647 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
3648}
3649
3650// cv <type> <expression> # conversion with one argument
3651// cv <type> _ <expression>* E # conversion with a different number of arguments
3652Node *Db::parseConversionExpr() {
3653 if (!consumeIf("cv"))
3654 return nullptr;
3655 Node *Ty;
3656 {
3657 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003658 Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003659 }
3660
3661 if (Ty == nullptr)
3662 return nullptr;
3663
3664 if (consumeIf('_')) {
3665 size_t ExprsBegin = Names.size();
3666 while (!consumeIf('E')) {
3667 Node *E = parseExpr();
3668 if (E == nullptr)
3669 return E;
3670 Names.push_back(E);
3671 }
3672 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
3673 return make<ConversionExpr>(Ty, Exprs);
3674 }
3675
3676 Node *E[1] = {parseExpr()};
3677 if (E[0] == nullptr)
3678 return nullptr;
3679 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
3680}
3681
3682// <expr-primary> ::= L <type> <value number> E # integer literal
3683// ::= L <type> <value float> E # floating literal
3684// ::= L <string type> E # string literal
3685// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
3686// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
3687// ::= L <mangled-name> E # external name
3688Node *Db::parseExprPrimary() {
3689 if (!consumeIf('L'))
3690 return nullptr;
3691 switch (look()) {
3692 case 'w':
3693 ++First;
3694 return parseIntegerLiteral("wchar_t");
3695 case 'b':
3696 if (consumeIf("b0E"))
3697 return make<BoolExpr>(0);
3698 if (consumeIf("b1E"))
3699 return make<BoolExpr>(1);
3700 return nullptr;
3701 case 'c':
3702 ++First;
3703 return parseIntegerLiteral("char");
3704 case 'a':
3705 ++First;
3706 return parseIntegerLiteral("signed char");
3707 case 'h':
3708 ++First;
3709 return parseIntegerLiteral("unsigned char");
3710 case 's':
3711 ++First;
3712 return parseIntegerLiteral("short");
3713 case 't':
3714 ++First;
3715 return parseIntegerLiteral("unsigned short");
3716 case 'i':
3717 ++First;
3718 return parseIntegerLiteral("");
3719 case 'j':
3720 ++First;
3721 return parseIntegerLiteral("u");
3722 case 'l':
3723 ++First;
3724 return parseIntegerLiteral("l");
3725 case 'm':
3726 ++First;
3727 return parseIntegerLiteral("ul");
3728 case 'x':
3729 ++First;
3730 return parseIntegerLiteral("ll");
3731 case 'y':
3732 ++First;
3733 return parseIntegerLiteral("ull");
3734 case 'n':
3735 ++First;
3736 return parseIntegerLiteral("__int128");
3737 case 'o':
3738 ++First;
3739 return parseIntegerLiteral("unsigned __int128");
3740 case 'f':
3741 ++First;
3742 return parseFloatingLiteral<float>();
3743 case 'd':
3744 ++First;
3745 return parseFloatingLiteral<double>();
3746 case 'e':
3747 ++First;
3748 return parseFloatingLiteral<long double>();
3749 case '_':
3750 if (consumeIf("_Z")) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003751 Node *R = parseEncoding();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003752 if (R != nullptr && consumeIf('E'))
3753 return R;
3754 }
3755 return nullptr;
3756 case 'T':
3757 // Invalid mangled name per
3758 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
3759 return nullptr;
3760 default: {
3761 // might be named type
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003762 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003763 if (T == nullptr)
3764 return nullptr;
3765 StringView N = parseNumber();
3766 if (!N.empty()) {
3767 if (!consumeIf('E'))
3768 return nullptr;
3769 return make<IntegerCastExpr>(T, N);
3770 }
3771 if (consumeIf('E'))
3772 return T;
3773 return nullptr;
3774 }
3775 }
3776}
3777
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003778// <braced-expression> ::= <expression>
3779// ::= di <field source-name> <braced-expression> # .name = expr
3780// ::= dx <index expression> <braced-expression> # [expr] = expr
3781// ::= dX <range begin expression> <range end expression> <braced-expression>
3782Node *Db::parseBracedExpr() {
3783 if (look() == 'd') {
3784 switch (look(1)) {
3785 case 'i': {
3786 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003787 Node *Field = parseSourceName(/*NameState=*/nullptr);
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003788 if (Field == nullptr)
3789 return nullptr;
3790 Node *Init = parseBracedExpr();
3791 if (Init == nullptr)
3792 return nullptr;
3793 return make<BracedExpr>(Field, Init, /*isArray=*/false);
3794 }
3795 case 'x': {
3796 First += 2;
3797 Node *Index = parseExpr();
3798 if (Index == nullptr)
3799 return nullptr;
3800 Node *Init = parseBracedExpr();
3801 if (Init == nullptr)
3802 return nullptr;
3803 return make<BracedExpr>(Index, Init, /*isArray=*/true);
3804 }
3805 case 'X': {
3806 First += 2;
3807 Node *RangeBegin = parseExpr();
3808 if (RangeBegin == nullptr)
3809 return nullptr;
3810 Node *RangeEnd = parseExpr();
3811 if (RangeEnd == nullptr)
3812 return nullptr;
3813 Node *Init = parseBracedExpr();
3814 if (Init == nullptr)
3815 return nullptr;
3816 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
3817 }
3818 }
3819 }
3820 return parseExpr();
3821}
3822
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003823// <expression> ::= <unary operator-name> <expression>
3824// ::= <binary operator-name> <expression> <expression>
3825// ::= <ternary operator-name> <expression> <expression> <expression>
3826// ::= cl <expression>+ E # call
3827// ::= cv <type> <expression> # conversion with one argument
3828// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3829// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
3830// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3831// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
3832// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3833// ::= [gs] dl <expression> # delete expression
3834// ::= [gs] da <expression> # delete[] expression
3835// ::= pp_ <expression> # prefix ++
3836// ::= mm_ <expression> # prefix --
3837// ::= ti <type> # typeid (type)
3838// ::= te <expression> # typeid (expression)
3839// ::= dc <type> <expression> # dynamic_cast<type> (expression)
3840// ::= sc <type> <expression> # static_cast<type> (expression)
3841// ::= cc <type> <expression> # const_cast<type> (expression)
3842// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3843// ::= st <type> # sizeof (a type)
3844// ::= sz <expression> # sizeof (an expression)
3845// ::= at <type> # alignof (a type)
3846// ::= az <expression> # alignof (an expression)
3847// ::= nx <expression> # noexcept (expression)
3848// ::= <template-param>
3849// ::= <function-param>
3850// ::= dt <expression> <unresolved-name> # expr.name
3851// ::= pt <expression> <unresolved-name> # expr->name
3852// ::= ds <expression> <expression> # expr.*expr
3853// ::= sZ <template-param> # size of a parameter pack
3854// ::= sZ <function-param> # size of a function parameter pack
3855// ::= sp <expression> # pack expansion
3856// ::= tw <expression> # throw expression
3857// ::= tr # throw with no operand (rethrow)
3858// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
3859// # freestanding dependent name (e.g., T::x),
3860// # objectless nonstatic member reference
3861// ::= fL <binary-operator-name> <expression> <expression>
3862// ::= fR <binary-operator-name> <expression> <expression>
3863// ::= fl <binary-operator-name> <expression>
3864// ::= fr <binary-operator-name> <expression>
3865// ::= <expr-primary>
3866Node *Db::parseExpr() {
3867 bool Global = consumeIf("gs");
3868 if (numLeft() < 2)
3869 return nullptr;
3870
3871 switch (*First) {
3872 case 'L':
3873 return parseExprPrimary();
3874 case 'T':
3875 return legacyParse<parse_template_param>();
3876 case 'f':
3877 return parseFunctionParam();
3878 case 'a':
3879 switch (First[1]) {
3880 case 'a':
3881 First += 2;
3882 return parseBinaryExpr("&&");
3883 case 'd':
3884 First += 2;
3885 return parsePrefixExpr("&");
3886 case 'n':
3887 First += 2;
3888 return parseBinaryExpr("&");
3889 case 'N':
3890 First += 2;
3891 return parseBinaryExpr("&=");
3892 case 'S':
3893 First += 2;
3894 return parseBinaryExpr("=");
3895 case 't': {
3896 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003897 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003898 if (Ty == nullptr)
3899 return nullptr;
3900 return make<EnclosingExpr>("alignof (", Ty, ")");
3901 }
3902 case 'z': {
3903 First += 2;
3904 Node *Ty = parseExpr();
3905 if (Ty == nullptr)
3906 return nullptr;
3907 return make<EnclosingExpr>("alignof (", Ty, ")");
3908 }
3909 }
3910 return nullptr;
3911 case 'c':
3912 switch (First[1]) {
3913 // cc <type> <expression> # const_cast<type>(expression)
3914 case 'c': {
3915 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003916 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003917 if (Ty == nullptr)
3918 return Ty;
3919 Node *Ex = parseExpr();
3920 if (Ex == nullptr)
3921 return Ex;
3922 return make<CastExpr>("const_cast", Ty, Ex);
3923 }
3924 // cl <expression>+ E # call
3925 case 'l': {
3926 First += 2;
3927 Node *Callee = parseExpr();
3928 if (Callee == nullptr)
3929 return Callee;
3930 size_t ExprsBegin = Names.size();
3931 while (!consumeIf('E')) {
3932 Node *E = parseExpr();
3933 if (E == nullptr)
3934 return E;
3935 Names.push_back(E);
3936 }
3937 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
3938 }
3939 case 'm':
3940 First += 2;
3941 return parseBinaryExpr(",");
3942 case 'o':
3943 First += 2;
3944 return parsePrefixExpr("~");
3945 case 'v':
3946 return parseConversionExpr();
3947 }
3948 return nullptr;
3949 case 'd':
3950 switch (First[1]) {
3951 case 'a': {
3952 First += 2;
3953 Node *Ex = parseExpr();
3954 if (Ex == nullptr)
3955 return Ex;
3956 return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
3957 }
3958 case 'c': {
3959 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003960 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003961 if (T == nullptr)
3962 return T;
3963 Node *Ex = parseExpr();
3964 if (Ex == nullptr)
3965 return Ex;
3966 return make<CastExpr>("dynamic_cast", T, Ex);
3967 }
3968 case 'e':
3969 First += 2;
3970 return parsePrefixExpr("*");
3971 case 'l': {
3972 First += 2;
3973 Node *E = parseExpr();
3974 if (E == nullptr)
3975 return E;
3976 return make<DeleteExpr>(E, Global, /*is_array=*/false);
3977 }
3978 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00003979 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003980 case 's': {
3981 First += 2;
3982 Node *LHS = parseExpr();
3983 if (LHS == nullptr)
3984 return nullptr;
3985 Node *RHS = parseExpr();
3986 if (RHS == nullptr)
3987 return nullptr;
3988 return make<MemberExpr>(LHS, ".*", RHS);
3989 }
3990 case 't': {
3991 First += 2;
3992 Node *LHS = parseExpr();
3993 if (LHS == nullptr)
3994 return LHS;
3995 Node *RHS = parseExpr();
3996 if (RHS == nullptr)
3997 return nullptr;
3998 return make<MemberExpr>(LHS, ".", RHS);
3999 }
4000 case 'v':
4001 First += 2;
4002 return parseBinaryExpr("/");
4003 case 'V':
4004 First += 2;
4005 return parseBinaryExpr("/=");
4006 }
4007 return nullptr;
4008 case 'e':
4009 switch (First[1]) {
4010 case 'o':
4011 First += 2;
4012 return parseBinaryExpr("^");
4013 case 'O':
4014 First += 2;
4015 return parseBinaryExpr("^=");
4016 case 'q':
4017 First += 2;
4018 return parseBinaryExpr("==");
4019 }
4020 return nullptr;
4021 case 'g':
4022 switch (First[1]) {
4023 case 'e':
4024 First += 2;
4025 return parseBinaryExpr(">=");
4026 case 't':
4027 First += 2;
4028 return parseBinaryExpr(">");
4029 }
4030 return nullptr;
4031 case 'i':
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004032 switch (First[1]) {
4033 case 'x': {
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004034 First += 2;
4035 Node *Base = parseExpr();
4036 if (Base == nullptr)
4037 return nullptr;
4038 Node *Index = parseExpr();
4039 if (Index == nullptr)
4040 return Index;
4041 return make<ArraySubscriptExpr>(Base, Index);
4042 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004043 case 'l': {
4044 First += 2;
4045 size_t InitsBegin = Names.size();
4046 while (!consumeIf('E')) {
4047 Node *E = parseBracedExpr();
4048 if (E == nullptr)
4049 return nullptr;
4050 Names.push_back(E);
4051 }
4052 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4053 }
4054 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004055 return nullptr;
4056 case 'l':
4057 switch (First[1]) {
4058 case 'e':
4059 First += 2;
4060 return parseBinaryExpr("<=");
4061 case 's':
4062 First += 2;
4063 return parseBinaryExpr("<<");
4064 case 'S':
4065 First += 2;
4066 return parseBinaryExpr("<<=");
4067 case 't':
4068 First += 2;
4069 return parseBinaryExpr("<");
4070 }
4071 return nullptr;
4072 case 'm':
4073 switch (First[1]) {
4074 case 'i':
4075 First += 2;
4076 return parseBinaryExpr("-");
4077 case 'I':
4078 First += 2;
4079 return parseBinaryExpr("-=");
4080 case 'l':
4081 First += 2;
4082 return parseBinaryExpr("*");
4083 case 'L':
4084 First += 2;
4085 return parseBinaryExpr("*=");
4086 case 'm':
4087 First += 2;
4088 if (consumeIf('_'))
4089 return parsePrefixExpr("--");
4090 Node *Ex = parseExpr();
4091 if (Ex == nullptr)
4092 return nullptr;
4093 return make<PostfixExpr>(Ex, "--");
4094 }
4095 return nullptr;
4096 case 'n':
4097 switch (First[1]) {
4098 case 'a':
4099 case 'w':
4100 return parseNewExpr();
4101 case 'e':
4102 First += 2;
4103 return parseBinaryExpr("!=");
4104 case 'g':
4105 First += 2;
4106 return parsePrefixExpr("-");
4107 case 't':
4108 First += 2;
4109 return parsePrefixExpr("!");
4110 case 'x':
4111 First += 2;
4112 Node *Ex = parseExpr();
4113 if (Ex == nullptr)
4114 return Ex;
4115 return make<EnclosingExpr>("noexcept (", Ex, ")");
4116 }
4117 return nullptr;
4118 case 'o':
4119 switch (First[1]) {
4120 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004121 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004122 case 'o':
4123 First += 2;
4124 return parseBinaryExpr("||");
4125 case 'r':
4126 First += 2;
4127 return parseBinaryExpr("|");
4128 case 'R':
4129 First += 2;
4130 return parseBinaryExpr("|=");
4131 }
4132 return nullptr;
4133 case 'p':
4134 switch (First[1]) {
4135 case 'm':
4136 First += 2;
4137 return parseBinaryExpr("->*");
4138 case 'l':
4139 First += 2;
4140 return parseBinaryExpr("+");
4141 case 'L':
4142 First += 2;
4143 return parseBinaryExpr("+=");
4144 case 'p': {
4145 First += 2;
4146 if (consumeIf('_'))
4147 return parsePrefixExpr("++");
4148 Node *Ex = parseExpr();
4149 if (Ex == nullptr)
4150 return Ex;
4151 return make<PostfixExpr>(Ex, "++");
4152 }
4153 case 's':
4154 First += 2;
4155 return parsePrefixExpr("+");
4156 case 't': {
4157 First += 2;
4158 Node *L = parseExpr();
4159 if (L == nullptr)
4160 return nullptr;
4161 Node *R = parseExpr();
4162 if (R == nullptr)
4163 return nullptr;
4164 return make<MemberExpr>(L, "->", R);
4165 }
4166 }
4167 return nullptr;
4168 case 'q':
4169 if (First[1] == 'u') {
4170 First += 2;
4171 Node *Cond = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004172 if (Cond == nullptr)
4173 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004174 Node *LHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004175 if (LHS == nullptr)
4176 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004177 Node *RHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004178 if (RHS == nullptr)
4179 return nullptr;
4180 return make<ConditionalExpr>(Cond, LHS, RHS);
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004181 }
4182 return nullptr;
4183 case 'r':
4184 switch (First[1]) {
4185 case 'c': {
4186 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004187 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004188 if (T == nullptr)
4189 return T;
4190 Node *Ex = parseExpr();
4191 if (Ex == nullptr)
4192 return Ex;
4193 return make<CastExpr>("reinterpret_cast", T, Ex);
4194 }
4195 case 'm':
4196 First += 2;
4197 return parseBinaryExpr("%");
4198 case 'M':
4199 First += 2;
4200 return parseBinaryExpr("%=");
4201 case 's':
4202 First += 2;
4203 return parseBinaryExpr(">>");
4204 case 'S':
4205 First += 2;
4206 return parseBinaryExpr(">>=");
4207 }
4208 return nullptr;
4209 case 's':
4210 switch (First[1]) {
4211 case 'c': {
4212 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004213 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004214 if (T == nullptr)
4215 return T;
4216 Node *Ex = parseExpr();
4217 if (Ex == nullptr)
4218 return Ex;
4219 return make<CastExpr>("static_cast", T, Ex);
4220 }
4221 case 'p': {
4222 First += 2;
4223 Node *Child = parseExpr();
4224 if (Child == nullptr)
4225 return nullptr;
4226 return make<ParameterPackExpansion>(Child);
4227 }
4228 case 'r':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004229 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004230 case 't': {
4231 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004232 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004233 if (Ty == nullptr)
4234 return Ty;
4235 return make<EnclosingExpr>("sizeof (", Ty, ")");
4236 }
4237 case 'z': {
4238 First += 2;
4239 Node *Ex = parseExpr();
4240 if (Ex == nullptr)
4241 return Ex;
4242 return make<EnclosingExpr>("sizeof (", Ex, ")");
4243 }
4244 case 'Z':
4245 First += 2;
4246 if (look() == 'T') {
4247 Node *R = legacyParse<parse_template_param>();
4248 if (R == nullptr)
4249 return nullptr;
4250 return make<SizeofParamPackExpr>(R);
4251 } else if (look() == 'f') {
4252 Node *FP = parseFunctionParam();
4253 if (FP == nullptr)
4254 return nullptr;
4255 return make<EnclosingExpr>("sizeof...", FP, ")");
4256 }
4257 return nullptr;
4258 }
4259 return nullptr;
4260 case 't':
4261 switch (First[1]) {
4262 case 'e': {
4263 First += 2;
4264 Node *Ex = parseExpr();
4265 if (Ex == nullptr)
4266 return Ex;
4267 return make<EnclosingExpr>("typeid (", Ex, ")");
4268 }
4269 case 'i': {
4270 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004271 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004272 if (Ty == nullptr)
4273 return Ty;
4274 return make<EnclosingExpr>("typeid (", Ty, ")");
4275 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004276 case 'l': {
4277 First += 2;
4278 Node *Ty = parseType();
4279 if (Ty == nullptr)
4280 return nullptr;
4281 size_t InitsBegin = Names.size();
4282 while (!consumeIf('E')) {
4283 Node *E = parseBracedExpr();
4284 if (E == nullptr)
4285 return nullptr;
4286 Names.push_back(E);
4287 }
4288 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4289 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004290 case 'r':
4291 First += 2;
4292 return make<NameType>("throw");
4293 case 'w': {
4294 First += 2;
4295 Node *Ex = parseExpr();
4296 if (Ex == nullptr)
4297 return nullptr;
4298 return make<ThrowExpr>(Ex);
4299 }
4300 }
4301 return nullptr;
4302 case '1':
4303 case '2':
4304 case '3':
4305 case '4':
4306 case '5':
4307 case '6':
4308 case '7':
4309 case '8':
4310 case '9':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004311 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004312 }
4313 return nullptr;
4314}
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004315
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004316// <call-offset> ::= h <nv-offset> _
4317// ::= v <v-offset> _
4318//
4319// <nv-offset> ::= <offset number>
4320// # non-virtual base override
4321//
4322// <v-offset> ::= <offset number> _ <virtual offset number>
4323// # virtual base override, with vcall offset
4324bool Db::parseCallOffset() {
4325 // Just scan through the call offset, we never add this information into the
4326 // output.
4327 if (consumeIf('h'))
4328 return parseNumber(true).empty() || !consumeIf('_');
4329 if (consumeIf('v'))
4330 return parseNumber(true).empty() || !consumeIf('_') ||
4331 parseNumber(true).empty() || !consumeIf('_');
4332 return true;
4333}
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004334
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004335// <special-name> ::= TV <type> # virtual table
4336// ::= TT <type> # VTT structure (construction vtable index)
4337// ::= TI <type> # typeinfo structure
4338// ::= TS <type> # typeinfo name (null-terminated byte string)
4339// ::= Tc <call-offset> <call-offset> <base encoding>
4340// # base is the nominal target function of thunk
4341// # first call-offset is 'this' adjustment
4342// # second call-offset is result adjustment
4343// ::= T <call-offset> <base encoding>
4344// # base is the nominal target function of thunk
4345// ::= GV <object name> # Guard variable for one-time initialization
4346// # No <type>
4347// ::= TW <object name> # Thread-local wrapper
4348// ::= TH <object name> # Thread-local initialization
4349// extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4350// extension ::= GR <object name> # reference temporary for object
4351Node *Db::parseSpecialName() {
4352 switch (look()) {
4353 case 'T':
4354 switch (look(1)) {
4355 // TV <type> # virtual table
4356 case 'V': {
4357 First += 2;
4358 Node *Ty = parseType();
4359 if (Ty == nullptr)
4360 return nullptr;
4361 return make<SpecialName>("vtable for ", Ty);
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004362 }
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004363 // TT <type> # VTT structure (construction vtable index)
4364 case 'T': {
4365 First += 2;
4366 Node *Ty = parseType();
4367 if (Ty == nullptr)
4368 return nullptr;
4369 return make<SpecialName>("VTT for ", Ty);
4370 }
4371 // TI <type> # typeinfo structure
4372 case 'I': {
4373 First += 2;
4374 Node *Ty = parseType();
4375 if (Ty == nullptr)
4376 return nullptr;
4377 return make<SpecialName>("typeinfo for ", Ty);
4378 }
4379 // TS <type> # typeinfo name (null-terminated byte string)
4380 case 'S': {
4381 First += 2;
4382 Node *Ty = parseType();
4383 if (Ty == nullptr)
4384 return nullptr;
4385 return make<SpecialName>("typeinfo name for ", Ty);
4386 }
4387 // Tc <call-offset> <call-offset> <base encoding>
4388 case 'c': {
4389 First += 2;
4390 if (parseCallOffset() || parseCallOffset())
4391 return nullptr;
4392 Node *Encoding = parseEncoding();
4393 if (Encoding == nullptr)
4394 return nullptr;
4395 return make<SpecialName>("covariant return thunk to ", Encoding);
4396 }
4397 // extension ::= TC <first type> <number> _ <second type>
4398 // # construction vtable for second-in-first
4399 case 'C': {
4400 First += 2;
4401 Node *FirstType = parseType();
4402 if (FirstType == nullptr)
4403 return nullptr;
4404 if (parseNumber(true).empty() || !consumeIf('_'))
4405 return nullptr;
4406 Node *SecondType = parseType();
4407 if (SecondType == nullptr)
4408 return nullptr;
4409 return make<CtorVtableSpecialName>(SecondType, FirstType);
4410 }
4411 // TW <object name> # Thread-local wrapper
4412 case 'W': {
4413 First += 2;
4414 Node *Name = parseName();
4415 if (Name == nullptr)
4416 return nullptr;
4417 return make<SpecialName>("thread-local wrapper routine for ", Name);
4418 }
4419 // TH <object name> # Thread-local initialization
4420 case 'H': {
4421 First += 2;
4422 Node *Name = parseName();
4423 if (Name == nullptr)
4424 return nullptr;
4425 return make<SpecialName>("thread-local initialization routine for ", Name);
4426 }
4427 // T <call-offset> <base encoding>
4428 default: {
4429 ++First;
4430 bool IsVirt = look() == 'v';
4431 if (parseCallOffset())
4432 return nullptr;
4433 Node *BaseEncoding = parseEncoding();
4434 if (BaseEncoding == nullptr)
4435 return nullptr;
4436 if (IsVirt)
4437 return make<SpecialName>("virtual thunk to ", BaseEncoding);
4438 else
4439 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
4440 }
4441 }
4442 case 'G':
4443 switch (look(1)) {
4444 // GV <object name> # Guard variable for one-time initialization
4445 case 'V': {
4446 First += 2;
4447 Node *Name = parseName();
4448 if (Name == nullptr)
4449 return nullptr;
4450 return make<SpecialName>("guard variable for ", Name);
4451 }
4452 // GR <object name> # reference temporary for object
4453 case 'R': {
4454 First += 2;
4455 Node *Name = parseName();
4456 if (Name == nullptr)
4457 return nullptr;
4458 return make<SpecialName>("reference temporary for ", Name);
4459 }
4460 }
4461 }
4462 return nullptr;
4463}
4464
4465// <encoding> ::= <function name> <bare-function-type>
4466// ::= <data name>
4467// ::= <special-name>
4468Node *Db::parseEncoding() {
4469 // Always "tag" templates (insert them into Db::TemplateParams) unless we're
4470 // doing a second parse to resolve a forward template reference, in which case
4471 // we only tag templates if EncodingDepth > 1.
4472 // FIXME: This is kinda broken; it would be better to make a forward reference
4473 // and patch it all in one pass.
4474 SwapAndRestore<bool> SaveTagTemplates(TagTemplates,
4475 TagTemplates || EncodingDepth);
4476 SwapAndRestore<unsigned> SaveEncodingDepth(EncodingDepth, EncodingDepth + 1);
4477
4478 if (look() == 'G' || look() == 'T')
4479 return parseSpecialName();
4480
4481 auto IsEndOfEncoding = [&] {
4482 // The set of chars that can potentially follow an <encoding> (none of which
4483 // can start a <type>). Enumerating these allows us to avoid speculative
4484 // parsing.
4485 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
4486 };
4487
4488 NameState NameInfo;
4489 Node *Name = parseName(&NameInfo);
4490 if (Name == nullptr || IsEndOfEncoding())
4491 return Name;
4492
4493 TagTemplates = false;
4494
4495 Node *ReturnType = nullptr;
4496 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
4497 ReturnType = parseType();
4498 if (ReturnType == nullptr)
4499 return nullptr;
4500 }
4501
4502 if (consumeIf('v'))
4503 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
4504 NameInfo.CVQualifiers,
4505 NameInfo.ReferenceQualifier);
4506
4507 size_t ParamsBegin = Names.size();
4508 do {
4509 Node *Ty = parseType();
4510 if (Ty == nullptr)
4511 return nullptr;
4512 Names.push_back(Ty);
4513 } while (!IsEndOfEncoding());
4514
4515 return make<FunctionEncoding>(ReturnType, Name,
4516 popTrailingNodeArray(ParamsBegin),
4517 NameInfo.CVQualifiers,
4518 NameInfo.ReferenceQualifier);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004519}
4520
4521template <class Float>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004522struct FloatData;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004523
4524template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004525struct FloatData<float>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004526{
4527 static const size_t mangled_size = 8;
4528 static const size_t max_demangled_size = 24;
Howard Hinnantc62cbea2013-06-17 20:25:21 +00004529 static constexpr const char* spec = "%af";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004530};
4531
Erik Pilkington0024acd2017-07-28 00:43:49 +00004532constexpr const char* FloatData<float>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004533
4534template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004535struct FloatData<double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004536{
4537 static const size_t mangled_size = 16;
4538 static const size_t max_demangled_size = 32;
4539 static constexpr const char* spec = "%a";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004540};
4541
Erik Pilkington0024acd2017-07-28 00:43:49 +00004542constexpr const char* FloatData<double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004543
4544template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004545struct FloatData<long double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004546{
Dan Gohmand04ecd02016-01-13 16:39:30 +00004547#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
4548 defined(__wasm__)
Daniel Sanders52cf98b2015-07-30 16:11:04 +00004549 static const size_t mangled_size = 32;
Ben Craig9ef2c6e2016-01-20 14:10:23 +00004550#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
Logan Chien05d51bc2014-05-10 00:42:10 +00004551 static const size_t mangled_size = 16;
4552#else
Howard Hinnant6c33e762013-06-17 18:10:34 +00004553 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 +00004554#endif
Howard Hinnant6c33e762013-06-17 18:10:34 +00004555 static const size_t max_demangled_size = 40;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004556 static constexpr const char *spec = "%LaL";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004557};
4558
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004559constexpr const char *FloatData<long double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004560
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004561template <class Float> Node *Db::parseFloatingLiteral() {
4562 const size_t N = FloatData<Float>::mangled_size;
4563 if (numLeft() <= N)
4564 return nullptr;
4565 StringView Data(First, First + N);
4566 for (char C : Data)
4567 if (!std::isxdigit(C))
4568 return nullptr;
4569 First += N;
4570 if (!consumeIf('E'))
4571 return nullptr;
4572 return make<FloatExpr<Float>>(Data);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004573}
4574
Howard Hinnant6c33e762013-06-17 18:10:34 +00004575// <substitution> ::= S <seq-id> _
4576// ::= S_
4577// <substitution> ::= Sa # ::std::allocator
4578// <substitution> ::= Sb # ::std::basic_string
4579// <substitution> ::= Ss # ::std::basic_string < char,
4580// ::std::char_traits<char>,
4581// ::std::allocator<char> >
4582// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
4583// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
4584// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
4585
Howard Hinnant6c33e762013-06-17 18:10:34 +00004586const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004587parse_substitution(const char* first, const char* last, Db& db)
Howard Hinnant6c33e762013-06-17 18:10:34 +00004588{
4589 if (last - first >= 2)
4590 {
4591 if (*first == 'S')
4592 {
4593 switch (first[1])
4594 {
4595 case 'a':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004596 db.Names.push_back(
Erik Pilkington0024acd2017-07-28 00:43:49 +00004597 db.make<SpecialSubstitution>(
4598 SpecialSubKind::allocator));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004599 first += 2;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004600 break;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004601 case 'b':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004602 db.Names.push_back(
Erik Pilkington0024acd2017-07-28 00:43:49 +00004603 db.make<SpecialSubstitution>(SpecialSubKind::basic_string));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004604 first += 2;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004605 break;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004606 case 's':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004607 db.Names.push_back(
Erik Pilkington0024acd2017-07-28 00:43:49 +00004608 db.make<SpecialSubstitution>(
4609 SpecialSubKind::string));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004610 first += 2;
4611 break;
4612 case 'i':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004613 db.Names.push_back(db.make<SpecialSubstitution>(SpecialSubKind::istream));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004614 first += 2;
4615 break;
4616 case 'o':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004617 db.Names.push_back(db.make<SpecialSubstitution>(SpecialSubKind::ostream));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004618 first += 2;
4619 break;
4620 case 'd':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004621 db.Names.push_back(db.make<SpecialSubstitution>(SpecialSubKind::iostream));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004622 first += 2;
4623 break;
4624 case '_':
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004625 if (!db.Subs.empty())
Howard Hinnant6c33e762013-06-17 18:10:34 +00004626 {
Erik Pilkington761e6b02018-01-31 20:17:06 +00004627 db.Names.push_back(db.Subs[0]);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004628 first += 2;
4629 }
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004630 break;
4631 default:
Howard Hinnant6c33e762013-06-17 18:10:34 +00004632 if (std::isdigit(first[1]) || std::isupper(first[1]))
4633 {
4634 size_t sub = 0;
4635 const char* t = first+1;
4636 if (std::isdigit(*t))
4637 sub = static_cast<size_t>(*t - '0');
4638 else
4639 sub = static_cast<size_t>(*t - 'A') + 10;
4640 for (++t; t != last && (std::isdigit(*t) || std::isupper(*t)); ++t)
4641 {
4642 sub *= 36;
4643 if (std::isdigit(*t))
4644 sub += static_cast<size_t>(*t - '0');
4645 else
4646 sub += static_cast<size_t>(*t - 'A') + 10;
4647 }
4648 if (t == last || *t != '_')
4649 return first;
4650 ++sub;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004651 if (sub < db.Subs.size())
Howard Hinnant6c33e762013-06-17 18:10:34 +00004652 {
Erik Pilkington761e6b02018-01-31 20:17:06 +00004653 db.Names.push_back(db.Subs[sub]);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004654 first = t+1;
4655 }
4656 }
4657 break;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004658 }
4659 }
4660 }
4661 return first;
4662}
4663
Howard Hinnant6c33e762013-06-17 18:10:34 +00004664// <template-param> ::= T_ # first template parameter
4665// ::= T <parameter-2 non-negative number> _
4666
Howard Hinnant6c33e762013-06-17 18:10:34 +00004667const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004668parse_template_param(const char* first, const char* last, Db& db)
Howard Hinnant6c33e762013-06-17 18:10:34 +00004669{
4670 if (last - first >= 2)
4671 {
4672 if (*first == 'T')
4673 {
4674 if (first[1] == '_')
4675 {
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004676 if (!db.TemplateParams.empty())
Howard Hinnant6c33e762013-06-17 18:10:34 +00004677 {
Erik Pilkington761e6b02018-01-31 20:17:06 +00004678 db.Names.push_back(db.TemplateParams[0]);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004679 first += 2;
4680 }
4681 else
4682 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004683 db.Names.push_back(db.make<NameType>("T_"));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004684 first += 2;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004685 db.FixForwardReferences = true;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004686 }
4687 }
4688 else if (isdigit(first[1]))
4689 {
4690 const char* t = first+1;
4691 size_t sub = static_cast<size_t>(*t - '0');
4692 for (++t; t != last && isdigit(*t); ++t)
4693 {
4694 sub *= 10;
4695 sub += static_cast<size_t>(*t - '0');
4696 }
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004697 if (t == last || *t != '_')
Howard Hinnant6c33e762013-06-17 18:10:34 +00004698 return first;
4699 ++sub;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004700 if (sub < db.TemplateParams.size())
Howard Hinnant6c33e762013-06-17 18:10:34 +00004701 {
Erik Pilkington761e6b02018-01-31 20:17:06 +00004702 db.Names.push_back(db.TemplateParams[sub]);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004703 first = t+1;
4704 }
4705 else
4706 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004707 db.Names.push_back(
Erik Pilkington0024acd2017-07-28 00:43:49 +00004708 db.make<NameType>(StringView(first, t + 1)));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004709 first = t+1;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004710 db.FixForwardReferences = true;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004711 }
4712 }
4713 }
4714 }
4715 return first;
4716}
4717
Howard Hinnant6c33e762013-06-17 18:10:34 +00004718// <template-arg> ::= <type> # type or template
4719// ::= X <expression> E # expression
4720// ::= <expr-primary> # simple expressions
4721// ::= J <template-arg>* E # argument pack
4722// ::= LZ <encoding> E # extension
Howard Hinnant6c33e762013-06-17 18:10:34 +00004723const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004724parse_template_arg(const char* first, const char* last, Db& db)
Howard Hinnant6c33e762013-06-17 18:10:34 +00004725{
4726 if (first != last)
4727 {
4728 const char* t;
4729 switch (*first)
4730 {
4731 case 'X':
4732 t = parse_expression(first+1, last, db);
4733 if (t != first+1)
4734 {
4735 if (t != last && *t == 'E')
4736 first = t+1;
4737 }
4738 break;
Erik Pilkington761e6b02018-01-31 20:17:06 +00004739 case 'J': {
Howard Hinnant6c33e762013-06-17 18:10:34 +00004740 t = first+1;
4741 if (t == last)
4742 return first;
Erik Pilkington761e6b02018-01-31 20:17:06 +00004743 size_t ArgsBegin = db.Names.size();
Howard Hinnant6c33e762013-06-17 18:10:34 +00004744 while (*t != 'E')
4745 {
4746 const char* t1 = parse_template_arg(t, last, db);
4747 if (t1 == t)
4748 return first;
4749 t = t1;
4750 }
Erik Pilkington761e6b02018-01-31 20:17:06 +00004751 NodeArray Args = db.popTrailingNodeArray(ArgsBegin);
4752 db.Names.push_back(db.make<TemplateArgumentPack>(Args));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004753 first = t+1;
4754 break;
Erik Pilkington761e6b02018-01-31 20:17:06 +00004755 }
Howard Hinnant6c33e762013-06-17 18:10:34 +00004756 case 'L':
4757 // <expr-primary> or LZ <encoding> E
4758 if (first+1 != last && first[1] == 'Z')
4759 {
4760 t = parse_encoding(first+2, last, db);
4761 if (t != first+2 && t != last && *t == 'E')
4762 first = t+1;
4763 }
4764 else
4765 first = parse_expr_primary(first, last, db);
4766 break;
4767 default:
4768 // <type>
4769 first = parse_type(first, last, db);
4770 break;
4771 }
4772 }
4773 return first;
4774}
4775
4776// <template-args> ::= I <template-arg>* E
4777// extension, the abi says <template-arg>+
Howard Hinnant6c33e762013-06-17 18:10:34 +00004778const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004779parse_template_args(const char* first, const char* last, Db& db)
Howard Hinnant6c33e762013-06-17 18:10:34 +00004780{
4781 if (last - first >= 2 && *first == 'I')
4782 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004783 if (db.TagTemplates)
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004784 db.TemplateParams.clear();
Howard Hinnant6c33e762013-06-17 18:10:34 +00004785 const char* t = first+1;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004786 size_t begin_idx = db.Names.size();
Howard Hinnant6c33e762013-06-17 18:10:34 +00004787 while (*t != 'E')
4788 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004789 if (db.TagTemplates)
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004790 {
4791 auto TmpParams = std::move(db.TemplateParams);
4792 size_t k0 = db.Names.size();
4793 const char* t1 = parse_template_arg(t, last, db);
4794 size_t k1 = db.Names.size();
4795 db.TemplateParams = std::move(TmpParams);
Erik Pilkington761e6b02018-01-31 20:17:06 +00004796 if (t1 == t || t1 == last || k0 + 1 != k1)
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004797 return first;
Erik Pilkington761e6b02018-01-31 20:17:06 +00004798 Node *TableEntry = db.Names.back();
4799 if (TableEntry->getKind() == Node::KTemplateArgumentPack)
4800 TableEntry = db.make<ParameterPack>(
4801 static_cast<TemplateArgumentPack*>(TableEntry)
4802 ->getElements());
4803 db.TemplateParams.push_back(TableEntry);
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004804 t = t1;
4805 continue;
4806 }
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004807 size_t k0 = db.Names.size();
Howard Hinnant6c33e762013-06-17 18:10:34 +00004808 const char* t1 = parse_template_arg(t, last, db);
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004809 size_t k1 = db.Names.size();
Erik Pilkington0024acd2017-07-28 00:43:49 +00004810 if (t1 == t || t1 == last || k0 > k1)
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004811 return first;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004812 t = t1;
4813 }
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004814 if (begin_idx > db.Names.size())
Erik Pilkingtonffdace52017-07-30 20:09:55 +00004815 return first;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004816 first = t + 1;
Erik Pilkington761e6b02018-01-31 20:17:06 +00004817 auto *tp = db.make<TemplateArgs>(
Erik Pilkington0024acd2017-07-28 00:43:49 +00004818 db.popTrailingNodeArray(begin_idx));
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004819 db.Names.push_back(tp);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004820 }
4821 return first;
4822}
4823
Howard Hinnant6c33e762013-06-17 18:10:34 +00004824// <discriminator> := _ <non-negative number> # when number < 10
4825// := __ <non-negative number> _ # when number >= 10
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004826// extension := decimal-digit+ # at the end of string
Howard Hinnant6c33e762013-06-17 18:10:34 +00004827
4828const char*
4829parse_discriminator(const char* first, const char* last)
4830{
4831 // parse but ignore discriminator
4832 if (first != last)
4833 {
4834 if (*first == '_')
4835 {
4836 const char* t1 = first+1;
4837 if (t1 != last)
4838 {
4839 if (std::isdigit(*t1))
4840 first = t1+1;
4841 else if (*t1 == '_')
4842 {
4843 for (++t1; t1 != last && std::isdigit(*t1); ++t1)
4844 ;
4845 if (t1 != last && *t1 == '_')
4846 first = t1 + 1;
4847 }
4848 }
4849 }
4850 else if (std::isdigit(*first))
4851 {
4852 const char* t1 = first+1;
4853 for (; t1 != last && std::isdigit(*t1); ++t1)
4854 ;
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004855 if (t1 == last)
4856 first = last;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004857 }
4858 }
4859 return first;
4860}
4861
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004862// _block_invoke
4863// _block_invoke<decimal-digit>+
4864// _block_invoke_<decimal-digit>+
4865
4866const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004867parse_block_invoke(const char* first, const char* last, Db& db)
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004868{
4869 if (last - first >= 13)
4870 {
Erik Pilkington0024acd2017-07-28 00:43:49 +00004871 // FIXME: strcmp?
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004872 const char test[] = "_block_invoke";
4873 const char* t = first;
4874 for (int i = 0; i < 13; ++i, ++t)
4875 {
4876 if (*t != test[i])
4877 return first;
4878 }
4879 if (t != last)
4880 {
4881 if (*t == '_')
4882 {
4883 // must have at least 1 decimal digit
Howard Hinnant6c33e762013-06-17 18:10:34 +00004884 if (++t == last || !std::isdigit(*t))
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004885 return first;
4886 ++t;
4887 }
4888 // parse zero or more digits
4889 while (t != last && isdigit(*t))
4890 ++t;
4891 }
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004892 if (db.Names.empty())
Howard Hinnant753a30d2013-12-11 19:44:25 +00004893 return first;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004894 db.Names.back() =
Erik Pilkington0024acd2017-07-28 00:43:49 +00004895 db.make<SpecialName>("invocation function for block in ",
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004896 db.Names.back());
Howard Hinnant6c33e762013-06-17 18:10:34 +00004897 first = t;
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004898 }
4899 return first;
4900}
4901
Howard Hinnant6c33e762013-06-17 18:10:34 +00004902// extension
4903// <dot-suffix> := .<anything and everything>
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004904
4905const char*
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004906parse_dot_suffix(const char* first, const char* last, Db& db)
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004907{
Howard Hinnant6c33e762013-06-17 18:10:34 +00004908 if (first != last && *first == '.')
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004909 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004910 if (db.Names.empty())
Howard Hinnant753a30d2013-12-11 19:44:25 +00004911 return first;
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004912 db.Names.back() =
4913 db.make<DotSuffix>(db.Names.back(), StringView(first, last));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004914 first = last;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004915 }
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004916 return first;
4917}
4918
Erik Pilkington761e6b02018-01-31 20:17:06 +00004919enum {
4920 unknown_error = -4,
4921 invalid_args = -3,
4922 invalid_mangled_name,
4923 memory_alloc_failure,
4924 success
4925};
4926
Howard Hinnant5dd173b2013-04-10 19:44:03 +00004927// <block-involcaton-function> ___Z<encoding>_block_invoke
4928// <block-involcaton-function> ___Z<encoding>_block_invoke<decimal-digit>+
4929// <block-involcaton-function> ___Z<encoding>_block_invoke_<decimal-digit>+
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004930// <mangled-name> ::= _Z<encoding>
4931// ::= <type>
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004932void
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004933demangle(const char* first, const char* last, Db& db, int& status)
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004934{
Howard Hinnanteb8d46c2013-06-23 17:14:35 +00004935 if (first >= last)
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004936 {
Howard Hinnant6c33e762013-06-17 18:10:34 +00004937 status = invalid_mangled_name;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004938 return;
4939 }
Howard Hinnant6c33e762013-06-17 18:10:34 +00004940 if (*first == '_')
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004941 {
Howard Hinnant6c33e762013-06-17 18:10:34 +00004942 if (last - first >= 4)
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004943 {
Howard Hinnant6c33e762013-06-17 18:10:34 +00004944 if (first[1] == 'Z')
4945 {
4946 const char* t = parse_encoding(first+2, last, db);
4947 if (t != first+2 && t != last && *t == '.')
4948 t = parse_dot_suffix(t, last, db);
4949 if (t != last)
4950 status = invalid_mangled_name;
4951 }
4952 else if (first[1] == '_' && first[2] == '_' && first[3] == 'Z')
4953 {
4954 const char* t = parse_encoding(first+4, last, db);
4955 if (t != first+4 && t != last)
4956 {
4957 const char* t1 = parse_block_invoke(t, last, db);
4958 if (t1 != last)
4959 status = invalid_mangled_name;
4960 }
4961 else
4962 status = invalid_mangled_name;
4963 }
4964 else
4965 status = invalid_mangled_name;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004966 }
4967 else
Howard Hinnant6c33e762013-06-17 18:10:34 +00004968 status = invalid_mangled_name;
4969 }
4970 else
4971 {
4972 const char* t = parse_type(first, last, db);
4973 if (t != last)
4974 status = invalid_mangled_name;
4975 }
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00004976 if (status == success && db.Names.empty())
Howard Hinnanteb8d46c2013-06-23 17:14:35 +00004977 status = invalid_mangled_name;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004978}
4979
Howard Hinnant6c33e762013-06-17 18:10:34 +00004980} // unnamed namespace
4981
Erik Pilkington761e6b02018-01-31 20:17:06 +00004982
4983namespace __cxxabiv1 {
Saleem Abdulrasoolb4ec5792015-12-04 02:14:58 +00004984extern "C" _LIBCXXABI_FUNC_VIS char *
Saleem Abdulrasool77a304b2015-12-04 02:14:41 +00004985__cxa_demangle(const char *mangled_name, char *buf, size_t *n, int *status) {
Howard Hinnant6c33e762013-06-17 18:10:34 +00004986 if (mangled_name == nullptr || (buf != nullptr && n == nullptr))
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004987 {
4988 if (status)
Howard Hinnant6c33e762013-06-17 18:10:34 +00004989 *status = invalid_args;
4990 return nullptr;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004991 }
Saleem Abdulrasool8cfa5a32016-11-14 01:55:54 +00004992
Howard Hinnant8ad6a222013-07-26 22:14:53 +00004993 size_t internal_size = buf != nullptr ? *n : 0;
Erik Pilkingtonba34a242017-08-09 21:30:57 +00004994 Db db;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004995 int internal_status = success;
Jonathan Roelofs0cbb1da2017-01-18 18:12:39 +00004996 size_t len = std::strlen(mangled_name);
Howard Hinnantb2d1f942013-06-23 19:52:45 +00004997 demangle(mangled_name, mangled_name + len, db,
Howard Hinnant6c33e762013-06-17 18:10:34 +00004998 internal_status);
Erik Pilkington0024acd2017-07-28 00:43:49 +00004999
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00005000 if (internal_status == success && db.FixForwardReferences &&
Erik Pilkingtonba34a242017-08-09 21:30:57 +00005001 !db.TemplateParams.empty())
Howard Hinnantb2d1f942013-06-23 19:52:45 +00005002 {
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00005003 db.FixForwardReferences = false;
5004 db.TagTemplates = false;
5005 db.Names.clear();
5006 db.Subs.clear();
Howard Hinnantb2d1f942013-06-23 19:52:45 +00005007 demangle(mangled_name, mangled_name + len, db, internal_status);
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00005008 if (db.FixForwardReferences)
Howard Hinnantb2d1f942013-06-23 19:52:45 +00005009 internal_status = invalid_mangled_name;
5010 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00005011
Erik Pilkington761e6b02018-01-31 20:17:06 +00005012 if (internal_status == success &&
5013 db.Names.back()->containsUnexpandedParameterPack())
5014 internal_status = invalid_mangled_name;
5015
Howard Hinnant6c33e762013-06-17 18:10:34 +00005016 if (internal_status == success)
5017 {
Erik Pilkington0024acd2017-07-28 00:43:49 +00005018 if (!buf)
Howard Hinnant6c33e762013-06-17 18:10:34 +00005019 {
Erik Pilkington0024acd2017-07-28 00:43:49 +00005020 internal_size = 1024;
5021 buf = static_cast<char*>(std::malloc(internal_size));
Howard Hinnant6c33e762013-06-17 18:10:34 +00005022 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00005023
5024 if (buf)
Howard Hinnant6c33e762013-06-17 18:10:34 +00005025 {
Erik Pilkington0024acd2017-07-28 00:43:49 +00005026 OutputStream s(buf, internal_size);
Erik Pilkingtondc64cee2017-08-08 20:57:10 +00005027 db.Names.back()->print(s);
Erik Pilkington0024acd2017-07-28 00:43:49 +00005028 s += '\0';
5029 if (n) *n = s.getCurrentPosition();
5030 buf = s.getBuffer();
Howard Hinnant6c33e762013-06-17 18:10:34 +00005031 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00005032 else
5033 internal_status = memory_alloc_failure;
Howard Hinnant6c33e762013-06-17 18:10:34 +00005034 }
5035 else
5036 buf = nullptr;
5037 if (status)
5038 *status = internal_status;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00005039 return buf;
5040}
Howard Hinnant6c33e762013-06-17 18:10:34 +00005041} // __cxxabiv1