blob: d0362dcfc1e64ba1d68227c064445db9ec886dee [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
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002005 Db(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
2006
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002007 template <class T, class... Args> T *make(Args &&... args) {
2008 return new (ASTAllocator.allocate(sizeof(T)))
2009 T(std::forward<Args>(args)...);
2010 }
2011
2012 template <class It> NodeArray makeNodeArray(It begin, It end) {
2013 size_t sz = static_cast<size_t>(end - begin);
2014 void *mem = ASTAllocator.allocate(sizeof(Node *) * sz);
2015 Node **data = new (mem) Node *[sz];
2016 std::copy(begin, end, data);
2017 return NodeArray(data, sz);
2018 }
2019
2020 NodeArray popTrailingNodeArray(size_t FromPosition) {
2021 assert(FromPosition <= Names.size());
2022 NodeArray res =
2023 makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
2024 Names.dropBack(FromPosition);
2025 return res;
2026 }
2027
2028 bool consumeIf(StringView S) {
2029 if (StringView(First, Last).startsWith(S)) {
2030 First += S.size();
2031 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002032 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002033 return false;
2034 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002035
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002036 bool consumeIf(char C) {
2037 if (First != Last && *First == C) {
2038 ++First;
2039 return true;
Erik Pilkington0024acd2017-07-28 00:43:49 +00002040 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002041 return false;
2042 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00002043
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002044 char consume() { return First != Last ? *First++ : '\0'; }
2045
2046 char look(unsigned Lookahead = 0) {
2047 if (static_cast<size_t>(Last - First) <= Lookahead)
2048 return '\0';
2049 return First[Lookahead];
2050 }
2051
2052 size_t numLeft() const { return static_cast<size_t>(Last - First); }
2053
2054 StringView parseNumber(bool AllowNegative = false);
2055 Qualifiers parseCVQualifiers();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002056 bool parsePositiveInteger(size_t *Out);
2057 StringView parseBareSourceName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002058
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002059 bool parseSeqId(size_t *Out);
2060 Node *parseSubstitution();
2061 Node *parseTemplateParam();
2062 Node *parseTemplateArgs();
2063 Node *parseTemplateArg();
2064
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002065 /// Parse the <expr> production.
2066 Node *parseExpr();
2067 Node *parsePrefixExpr(StringView Kind);
2068 Node *parseBinaryExpr(StringView Kind);
2069 Node *parseIntegerLiteral(StringView Lit);
2070 Node *parseExprPrimary();
2071 template <class Float> Node *parseFloatingLiteral();
2072 Node *parseFunctionParam();
2073 Node *parseNewExpr();
2074 Node *parseConversionExpr();
Erik Pilkington88a1cf62018-02-13 00:15:56 +00002075 Node *parseBracedExpr();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002076
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002077 /// Parse the <type> production.
2078 Node *parseType();
2079 Node *parseFunctionType();
2080 Node *parseVectorType();
2081 Node *parseDecltype();
2082 Node *parseArrayType();
2083 Node *parsePointerToMemberType();
2084 Node *parseClassEnumType();
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002085 Node *parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002086
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002087 Node *parseEncoding();
2088 bool parseCallOffset();
2089 Node *parseSpecialName();
2090
2091 /// Holds some extra information about a <name> that is being parsed. This
2092 /// information is only pertinent if the <name> refers to an <encoding>.
2093 struct NameState {
2094 bool CtorDtorConversion = false;
2095 bool EndsWithTemplateArgs = false;
2096 Qualifiers CVQualifiers = QualNone;
2097 FunctionRefQual ReferenceQualifier = FrefQualNone;
2098 };
2099
2100 /// Parse the <name> production>
2101 Node *parseName(NameState *State = nullptr);
2102 Node *parseLocalName(NameState *State);
2103 Node *parseOperatorName(NameState *State);
2104 Node *parseUnqualifiedName(NameState *State);
2105 Node *parseUnnamedTypeName(NameState *State);
2106 Node *parseSourceName(NameState *State);
2107 Node *parseUnscopedName(NameState *State);
2108 Node *parseNestedName(NameState *State);
2109 Node *parseCtorDtorName(Node *&SoFar, NameState *State);
2110
Erik Pilkington2808f772018-02-13 17:09:03 +00002111 Node *parseAbiTags(Node *N);
2112
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002113 /// Parse the <unresolved-name> production.
2114 Node *parseUnresolvedName();
2115 Node *parseSimpleId();
2116 Node *parseBaseUnresolvedName();
2117 Node *parseUnresolvedType();
2118 Node *parseDestructorName();
2119
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002120 /// Top-level entry point into the parser.
2121 Node *parse();
Erik Pilkington0024acd2017-07-28 00:43:49 +00002122};
Erik Pilkingtonc3926622017-07-08 18:54:08 +00002123
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002124const char* parse_discriminator(const char* first, const char* last);
Erik Pilkington2808f772018-02-13 17:09:03 +00002125
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002126// <name> ::= <nested-name> // N
2127// ::= <local-name> # See Scope Encoding below // Z
2128// ::= <unscoped-template-name> <template-args>
2129// ::= <unscoped-name>
2130//
2131// <unscoped-template-name> ::= <unscoped-name>
2132// ::= <substitution>
2133Node *Db::parseName(NameState *State) {
2134 consumeIf('L'); // extension
2135
2136 if (look() == 'N')
2137 return parseNestedName(State);
2138 if (look() == 'Z')
2139 return parseLocalName(State);
2140
2141 // ::= <unscoped-template-name> <template-args>
2142 if (look() == 'S' && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002143 Node *S = parseSubstitution();
2144 if (S == nullptr)
2145 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002146 if (look() != 'I')
2147 return nullptr;
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002148 Node *TA = parseTemplateArgs();
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002149 if (TA == nullptr)
2150 return nullptr;
2151 if (State) State->EndsWithTemplateArgs = true;
2152 return make<NameWithTemplateArgs>(S, TA);
2153 }
2154
2155 Node *N = parseUnscopedName(State);
2156 if (N == nullptr)
2157 return nullptr;
2158 // ::= <unscoped-template-name> <template-args>
2159 if (look() == 'I') {
2160 Subs.push_back(N);
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002161 Node *TA = parseTemplateArgs();
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002162 if (TA == nullptr)
2163 return nullptr;
2164 if (State) State->EndsWithTemplateArgs = true;
2165 return make<NameWithTemplateArgs>(N, TA);
2166 }
2167 // ::= <unscoped-name>
2168 return N;
2169}
2170
2171// <local-name> := Z <function encoding> E <entity name> [<discriminator>]
2172// := Z <function encoding> E s [<discriminator>]
2173// := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
2174Node *Db::parseLocalName(NameState *State) {
2175 if (!consumeIf('Z'))
2176 return nullptr;
2177 Node *Encoding = parseEncoding();
2178 if (Encoding == nullptr || !consumeIf('E'))
2179 return nullptr;
2180
2181 if (consumeIf('s')) {
2182 First = parse_discriminator(First, Last);
2183 return make<QualifiedName>(Encoding, make<NameType>("string literal"));
2184 }
2185
2186 if (consumeIf('d')) {
2187 parseNumber(true);
2188 if (!consumeIf('_'))
2189 return nullptr;
2190 Node *N = parseName(State);
2191 if (N == nullptr)
2192 return nullptr;
2193 return make<QualifiedName>(Encoding, N);
2194 }
2195
2196 Node *Entity = parseName(State);
2197 if (Entity == nullptr)
2198 return nullptr;
2199 First = parse_discriminator(First, Last);
2200 return make<QualifiedName>(Encoding, Entity);
2201}
2202
2203// <unscoped-name> ::= <unqualified-name>
2204// ::= St <unqualified-name> # ::std::
2205// extension ::= StL<unqualified-name>
2206Node *Db::parseUnscopedName(NameState *State) {
2207 if (consumeIf("StL") || consumeIf("St")) {
2208 Node *R = parseUnqualifiedName(State);
2209 if (R == nullptr)
2210 return nullptr;
2211 return make<StdQualifiedName>(R);
2212 }
2213 return parseUnqualifiedName(State);
2214}
2215
2216// <unqualified-name> ::= <operator-name> [abi-tags]
2217// ::= <ctor-dtor-name>
2218// ::= <source-name>
2219// ::= <unnamed-type-name>
2220// FIXME: ::= DC <source-name>+ E # structured binding declaration
2221Node *Db::parseUnqualifiedName(NameState *State) {
2222 // <ctor-dtor-name>s are special-cased in parseNestedName().
2223 Node *Result;
2224 if (look() == 'U')
2225 Result = parseUnnamedTypeName(State);
2226 else if (look() >= '1' && look() <= '9')
2227 Result = parseSourceName(State);
2228 else
2229 Result = parseOperatorName(State);
2230 if (Result != nullptr)
2231 Result = parseAbiTags(Result);
2232 return Result;
2233}
2234
2235// <unnamed-type-name> ::= Ut [<nonnegative number>] _
2236// ::= <closure-type-name>
2237//
2238// <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
2239//
2240// <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
2241Node *Db::parseUnnamedTypeName(NameState *) {
2242 if (consumeIf("Ut")) {
2243 StringView Count = parseNumber();
2244 if (!consumeIf('_'))
2245 return nullptr;
2246 return make<UnnamedTypeName>(Count);
2247 }
2248 if (consumeIf("Ul")) {
2249 NodeArray Params;
2250 if (!consumeIf("vE")) {
2251 size_t ParamsBegin = Names.size();
2252 do {
2253 Node *P = parseType();
2254 if (P == nullptr)
2255 return nullptr;
2256 Names.push_back(P);
2257 } while (!consumeIf('E'));
2258 Params = popTrailingNodeArray(ParamsBegin);
2259 }
2260 StringView Count = parseNumber();
2261 if (!consumeIf('_'))
2262 return nullptr;
2263 return make<ClosureTypeName>(Params, Count);
2264 }
2265 return nullptr;
2266}
2267
2268// <source-name> ::= <positive length number> <identifier>
2269Node *Db::parseSourceName(NameState *) {
2270 size_t Length = 0;
2271 if (parsePositiveInteger(&Length))
2272 return nullptr;
2273 if (numLeft() < Length || Length == 0)
2274 return nullptr;
2275 StringView Name(First, First + Length);
2276 First += Length;
2277 if (Name.startsWith("_GLOBAL__N"))
2278 return make<NameType>("(anonymous namespace)");
2279 return make<NameType>(Name);
2280}
2281
2282// <operator-name> ::= aa # &&
2283// ::= ad # & (unary)
2284// ::= an # &
2285// ::= aN # &=
2286// ::= aS # =
2287// ::= cl # ()
2288// ::= cm # ,
2289// ::= co # ~
2290// ::= cv <type> # (cast)
2291// ::= da # delete[]
2292// ::= de # * (unary)
2293// ::= dl # delete
2294// ::= dv # /
2295// ::= dV # /=
2296// ::= eo # ^
2297// ::= eO # ^=
2298// ::= eq # ==
2299// ::= ge # >=
2300// ::= gt # >
2301// ::= ix # []
2302// ::= le # <=
2303// ::= li <source-name> # operator ""
2304// ::= ls # <<
2305// ::= lS # <<=
2306// ::= lt # <
2307// ::= mi # -
2308// ::= mI # -=
2309// ::= ml # *
2310// ::= mL # *=
2311// ::= mm # -- (postfix in <expression> context)
2312// ::= na # new[]
2313// ::= ne # !=
2314// ::= ng # - (unary)
2315// ::= nt # !
2316// ::= nw # new
2317// ::= oo # ||
2318// ::= or # |
2319// ::= oR # |=
2320// ::= pm # ->*
2321// ::= pl # +
2322// ::= pL # +=
2323// ::= pp # ++ (postfix in <expression> context)
2324// ::= ps # + (unary)
2325// ::= pt # ->
2326// ::= qu # ?
2327// ::= rm # %
2328// ::= rM # %=
2329// ::= rs # >>
2330// ::= rS # >>=
2331// ::= ss # <=> C++2a
2332// ::= v <digit> <source-name> # vendor extended operator
2333Node *Db::parseOperatorName(NameState *State) {
2334 switch (look()) {
2335 case 'a':
2336 switch (look(1)) {
2337 case 'a':
2338 First += 2;
2339 return make<NameType>("operator&&");
2340 case 'd':
2341 case 'n':
2342 First += 2;
2343 return make<NameType>("operator&");
2344 case 'N':
2345 First += 2;
2346 return make<NameType>("operator&=");
2347 case 'S':
2348 First += 2;
2349 return make<NameType>("operator=");
2350 }
2351 return nullptr;
2352 case 'c':
2353 switch (look(1)) {
2354 case 'l':
2355 First += 2;
2356 return make<NameType>("operator()");
2357 case 'm':
2358 First += 2;
2359 return make<NameType>("operator,");
2360 case 'o':
2361 First += 2;
2362 return make<NameType>("operator~");
2363 // ::= cv <type> # (cast)
2364 case 'v': {
2365 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false);
2366 First += 2;
2367 Node *Ty = parseType();
2368 if (Ty == nullptr)
2369 return nullptr;
2370 if (State) State->CtorDtorConversion = true;
2371 return make<ConversionOperatorType>(Ty);
2372 }
2373 }
2374 return nullptr;
2375 case 'd':
2376 switch (look(1)) {
2377 case 'a':
2378 First += 2;
2379 return make<NameType>("operator delete[]");
2380 case 'e':
2381 First += 2;
2382 return make<NameType>("operator*");
2383 case 'l':
2384 First += 2;
2385 return make<NameType>("operator delete");
2386 case 'v':
2387 First += 2;
2388 return make<NameType>("operator/");
2389 case 'V':
2390 First += 2;
2391 return make<NameType>("operator/=");
2392 }
2393 return nullptr;
2394 case 'e':
2395 switch (look(1)) {
2396 case 'o':
2397 First += 2;
2398 return make<NameType>("operator^");
2399 case 'O':
2400 First += 2;
2401 return make<NameType>("operator^=");
2402 case 'q':
2403 First += 2;
2404 return make<NameType>("operator==");
2405 }
2406 return nullptr;
2407 case 'g':
2408 switch (look(1)) {
2409 case 'e':
2410 First += 2;
2411 return make<NameType>("operator>=");
2412 case 't':
2413 First += 2;
2414 return make<NameType>("operator>");
2415 }
2416 return nullptr;
2417 case 'i':
2418 if (look(1) == 'x') {
2419 First += 2;
2420 return make<NameType>("operator[]");
2421 }
2422 return nullptr;
2423 case 'l':
2424 switch (look(1)) {
2425 case 'e':
2426 First += 2;
2427 return make<NameType>("operator<=");
2428 // ::= li <source-name> # operator ""
2429 case 'i': {
2430 First += 2;
2431 Node *SN = parseSourceName(State);
2432 if (SN == nullptr)
2433 return nullptr;
2434 return make<LiteralOperator>(SN);
2435 }
2436 case 's':
2437 First += 2;
2438 return make<NameType>("operator<<");
2439 case 'S':
2440 First += 2;
2441 return make<NameType>("operator<<=");
2442 case 't':
2443 First += 2;
2444 return make<NameType>("operator<");
2445 }
2446 return nullptr;
2447 case 'm':
2448 switch (look(1)) {
2449 case 'i':
2450 First += 2;
2451 return make<NameType>("operator-");
2452 case 'I':
2453 First += 2;
2454 return make<NameType>("operator-=");
2455 case 'l':
2456 First += 2;
2457 return make<NameType>("operator*");
2458 case 'L':
2459 First += 2;
2460 return make<NameType>("operator*=");
2461 case 'm':
2462 First += 2;
2463 return make<NameType>("operator--");
2464 }
2465 return nullptr;
2466 case 'n':
2467 switch (look(1)) {
2468 case 'a':
2469 First += 2;
2470 return make<NameType>("operator new[]");
2471 case 'e':
2472 First += 2;
2473 return make<NameType>("operator!=");
2474 case 'g':
2475 First += 2;
2476 return make<NameType>("operator-");
2477 case 't':
2478 First += 2;
2479 return make<NameType>("operator!");
2480 case 'w':
2481 First += 2;
2482 return make<NameType>("operator new");
2483 }
2484 return nullptr;
2485 case 'o':
2486 switch (look(1)) {
2487 case 'o':
2488 First += 2;
2489 return make<NameType>("operator||");
2490 case 'r':
2491 First += 2;
2492 return make<NameType>("operator|");
2493 case 'R':
2494 First += 2;
2495 return make<NameType>("operator|=");
2496 }
2497 return nullptr;
2498 case 'p':
2499 switch (look(1)) {
2500 case 'm':
2501 First += 2;
2502 return make<NameType>("operator->*");
2503 case 'l':
2504 First += 2;
2505 return make<NameType>("operator+");
2506 case 'L':
2507 First += 2;
2508 return make<NameType>("operator+=");
2509 case 'p':
2510 First += 2;
2511 return make<NameType>("operator++");
2512 case 's':
2513 First += 2;
2514 return make<NameType>("operator+");
2515 case 't':
2516 First += 2;
2517 return make<NameType>("operator->");
2518 }
2519 return nullptr;
2520 case 'q':
2521 if (look(1) == 'u') {
2522 First += 2;
2523 return make<NameType>("operator?");
2524 }
2525 return nullptr;
2526 case 'r':
2527 switch (look(1)) {
2528 case 'm':
2529 First += 2;
2530 return make<NameType>("operator%");
2531 case 'M':
2532 First += 2;
2533 return make<NameType>("operator%=");
2534 case 's':
2535 First += 2;
2536 return make<NameType>("operator>>");
2537 case 'S':
2538 First += 2;
2539 return make<NameType>("operator>>=");
2540 }
2541 return nullptr;
2542 case 's':
2543 if (look(1) == 's') {
2544 First += 2;
2545 return make<NameType>("operator<=>");
2546 }
2547 return nullptr;
2548 // ::= v <digit> <source-name> # vendor extended operator
2549 case 'v':
2550 if (std::isdigit(look(1))) {
2551 First += 2;
2552 Node *SN = parseSourceName(State);
2553 if (SN == nullptr)
2554 return nullptr;
2555 return make<ConversionOperatorType>(SN);
2556 }
2557 return nullptr;
2558 }
2559 return nullptr;
2560}
2561
Erik Pilkington2808f772018-02-13 17:09:03 +00002562// <ctor-dtor-name> ::= C1 # complete object constructor
2563// ::= C2 # base object constructor
2564// ::= C3 # complete object allocating constructor
2565// extension ::= C5 # ?
2566// ::= D0 # deleting destructor
2567// ::= D1 # complete object destructor
2568// ::= D2 # base object destructor
2569// extension ::= D5 # ?
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002570Node *Db::parseCtorDtorName(Node *&SoFar, NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002571 if (SoFar->K == Node::KSpecialSubstitution) {
2572 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK;
2573 switch (SSK) {
2574 case SpecialSubKind::string:
2575 case SpecialSubKind::istream:
2576 case SpecialSubKind::ostream:
2577 case SpecialSubKind::iostream:
2578 SoFar = make<ExpandedSpecialSubstitution>(SSK);
2579 default:
2580 break;
2581 }
2582 }
2583
2584 if (consumeIf('C')) {
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002585 bool IsInherited = consumeIf('I');
Erik Pilkington2808f772018-02-13 17:09:03 +00002586 if (look() != '1' && look() != '2' && look() != '3' && look() != '5')
2587 return nullptr;
2588 ++First;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002589 if (State) State->CtorDtorConversion = true;
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002590 if (IsInherited) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002591 if (parseName() == nullptr)
Erik Pilkington5f0867c2018-02-13 17:09:07 +00002592 return nullptr;
2593 }
Erik Pilkington2808f772018-02-13 17:09:03 +00002594 return make<CtorDtorName>(SoFar, false);
2595 }
2596
2597 if (look() == 'D' &&
2598 (look(1) == '0' || look(1) == '1' || look(1) == '2' || look(1) == '5')) {
2599 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002600 if (State) State->CtorDtorConversion = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002601 return make<CtorDtorName>(SoFar, true);
2602 }
2603
2604 return nullptr;
2605}
2606
2607// <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
2608// ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
2609//
2610// <prefix> ::= <prefix> <unqualified-name>
2611// ::= <template-prefix> <template-args>
2612// ::= <template-param>
2613// ::= <decltype>
2614// ::= # empty
2615// ::= <substitution>
2616// ::= <prefix> <data-member-prefix>
2617// extension ::= L
2618//
2619// <template-prefix> ::= <prefix> <template unqualified-name>
2620// ::= <template-param>
2621// ::= <substitution>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002622Node *Db::parseNestedName(NameState *State) {
Erik Pilkington2808f772018-02-13 17:09:03 +00002623 if (!consumeIf('N'))
2624 return nullptr;
2625
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002626 Qualifiers CVTmp = parseCVQualifiers();
2627 if (State) State->CVQualifiers = CVTmp;
2628
2629 if (consumeIf('O')) {
2630 if (State) State->ReferenceQualifier = FrefQualRValue;
2631 } else if (consumeIf('R')) {
2632 if (State) State->ReferenceQualifier = FrefQualLValue;
2633 } else
2634 if (State) State->ReferenceQualifier = FrefQualNone;
Erik Pilkington2808f772018-02-13 17:09:03 +00002635
2636 Node *SoFar = nullptr;
2637 auto PushComponent = [&](Node *Comp) {
2638 if (SoFar) SoFar = make<QualifiedName>(SoFar, Comp);
2639 else SoFar = Comp;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002640 if (State) State->EndsWithTemplateArgs = false;
Erik Pilkington2808f772018-02-13 17:09:03 +00002641 };
2642
2643 if (consumeIf("St"))
2644 SoFar = make<NameType>("std");
2645
2646 while (!consumeIf('E')) {
2647 consumeIf('L'); // extension
2648
2649 // ::= <template-param>
2650 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002651 Node *TP = parseTemplateParam();
Erik Pilkington2808f772018-02-13 17:09:03 +00002652 if (TP == nullptr)
2653 return nullptr;
2654 PushComponent(TP);
2655 Subs.push_back(SoFar);
2656 continue;
2657 }
2658
2659 // ::= <template-prefix> <template-args>
2660 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002661 Node *TA = parseTemplateArgs();
Erik Pilkington2808f772018-02-13 17:09:03 +00002662 if (TA == nullptr || SoFar == nullptr)
2663 return nullptr;
2664 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002665 if (State) State->EndsWithTemplateArgs = true;
Erik Pilkington2808f772018-02-13 17:09:03 +00002666 Subs.push_back(SoFar);
2667 continue;
2668 }
2669
2670 // ::= <decltype>
2671 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002672 Node *DT = parseDecltype();
Erik Pilkington2808f772018-02-13 17:09:03 +00002673 if (DT == nullptr)
2674 return nullptr;
2675 PushComponent(DT);
2676 Subs.push_back(SoFar);
2677 continue;
2678 }
2679
2680 // ::= <substitution>
2681 if (look() == 'S' && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002682 Node *S = parseSubstitution();
Erik Pilkington2808f772018-02-13 17:09:03 +00002683 if (S == nullptr)
2684 return nullptr;
2685 PushComponent(S);
2686 if (SoFar != S)
2687 Subs.push_back(S);
2688 continue;
2689 }
2690
2691 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>.
2692 if (look() == 'C' || look() == 'D') {
2693 if (SoFar == nullptr)
2694 return nullptr;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002695 Node *CtorDtor = parseCtorDtorName(SoFar, State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002696 if (CtorDtor == nullptr)
2697 return nullptr;
2698 PushComponent(CtorDtor);
2699 SoFar = parseAbiTags(SoFar);
2700 if (SoFar == nullptr)
2701 return nullptr;
2702 Subs.push_back(SoFar);
2703 continue;
2704 }
2705
2706 // ::= <prefix> <unqualified-name>
Erik Pilkingtone1d61622018-03-05 16:35:06 +00002707 Node *N = parseUnqualifiedName(State);
Erik Pilkington2808f772018-02-13 17:09:03 +00002708 if (N == nullptr)
2709 return nullptr;
2710 PushComponent(N);
2711 Subs.push_back(SoFar);
2712 }
2713
2714 if (SoFar == nullptr || Subs.empty())
2715 return nullptr;
2716
2717 Subs.pop_back();
2718 return SoFar;
2719}
2720
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002721// <simple-id> ::= <source-name> [ <template-args> ]
2722Node *Db::parseSimpleId() {
2723 Node *SN = parseSourceName(/*NameState=*/nullptr);
2724 if (SN == nullptr)
2725 return nullptr;
2726 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002727 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002728 if (TA == nullptr)
2729 return nullptr;
2730 return make<NameWithTemplateArgs>(SN, TA);
2731 }
2732 return SN;
2733}
2734
2735// <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
2736// ::= <simple-id> # e.g., ~A<2*N>
2737Node *Db::parseDestructorName() {
2738 Node *Result;
2739 if (std::isdigit(look()))
2740 Result = parseSimpleId();
2741 else
2742 Result = parseUnresolvedType();
2743 if (Result == nullptr)
2744 return nullptr;
2745 return make<DtorName>(Result);
2746}
2747
2748// <unresolved-type> ::= <template-param>
2749// ::= <decltype>
2750// ::= <substitution>
2751Node *Db::parseUnresolvedType() {
2752 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002753 Node *TP = parseTemplateParam();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002754 if (TP == nullptr)
2755 return nullptr;
2756 Subs.push_back(TP);
2757 return TP;
2758 }
2759 if (look() == 'D') {
2760 Node *DT = parseDecltype();
2761 if (DT == nullptr)
2762 return nullptr;
2763 Subs.push_back(DT);
2764 return DT;
2765 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002766 return parseSubstitution();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002767}
2768
2769// <base-unresolved-name> ::= <simple-id> # unresolved name
2770// extension ::= <operator-name> # unresolved operator-function-id
2771// extension ::= <operator-name> <template-args> # unresolved operator template-id
2772// ::= on <operator-name> # unresolved operator-function-id
2773// ::= on <operator-name> <template-args> # unresolved operator template-id
2774// ::= dn <destructor-name> # destructor or pseudo-destructor;
2775// # e.g. ~X or ~X<N-1>
2776Node *Db::parseBaseUnresolvedName() {
2777 if (std::isdigit(look()))
2778 return parseSimpleId();
2779
2780 if (consumeIf("dn"))
2781 return parseDestructorName();
2782
2783 consumeIf("on");
2784
2785 Node *Oper = parseOperatorName(/*NameState=*/nullptr);
2786 if (Oper == nullptr)
2787 return nullptr;
2788 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002789 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002790 if (TA == nullptr)
2791 return nullptr;
2792 return make<NameWithTemplateArgs>(Oper, TA);
2793 }
2794 return Oper;
2795}
2796
2797// <unresolved-name>
2798// extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2799// ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
2800// ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2801// # A::x, N::y, A<T>::z; "gs" means leading "::"
2802// ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
2803// extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
2804// # T::N::x /decltype(p)::N::x
2805// (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2806//
2807// <unresolved-qualifier-level> ::= <simple-id>
2808Node *Db::parseUnresolvedName() {
2809 Node *SoFar = nullptr;
2810
2811 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
2812 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
2813 if (consumeIf("srN")) {
2814 SoFar = parseUnresolvedType();
2815 if (SoFar == nullptr)
2816 return nullptr;
2817
2818 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002819 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002820 if (TA == nullptr)
2821 return nullptr;
2822 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2823 }
2824
2825 while (!consumeIf('E')) {
2826 Node *Qual = parseSimpleId();
2827 if (Qual == nullptr)
2828 return nullptr;
2829 SoFar = make<QualifiedName>(SoFar, Qual);
2830 }
2831
2832 Node *Base = parseBaseUnresolvedName();
2833 if (Base == nullptr)
2834 return nullptr;
2835 return make<QualifiedName>(SoFar, Base);
2836 }
2837
2838 bool Global = consumeIf("gs");
2839
2840 // [gs] <base-unresolved-name> # x or (with "gs") ::x
2841 if (!consumeIf("sr")) {
2842 SoFar = parseBaseUnresolvedName();
2843 if (SoFar == nullptr)
2844 return nullptr;
2845 if (Global)
2846 SoFar = make<GlobalQualifiedName>(SoFar);
2847 return SoFar;
2848 }
2849
2850 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
2851 if (std::isdigit(look())) {
2852 do {
2853 Node *Qual = parseSimpleId();
2854 if (Qual == nullptr)
2855 return nullptr;
2856 if (SoFar)
2857 SoFar = make<QualifiedName>(SoFar, Qual);
2858 else if (Global)
2859 SoFar = make<GlobalQualifiedName>(Qual);
2860 else
2861 SoFar = Qual;
2862 } while (!consumeIf('E'));
2863 }
2864 // sr <unresolved-type> <base-unresolved-name>
2865 // sr <unresolved-type> <template-args> <base-unresolved-name>
2866 else {
2867 SoFar = parseUnresolvedType();
2868 if (SoFar == nullptr)
2869 return nullptr;
2870
2871 if (look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00002872 Node *TA = parseTemplateArgs();
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00002873 if (TA == nullptr)
2874 return nullptr;
2875 SoFar = make<NameWithTemplateArgs>(SoFar, TA);
2876 }
2877 }
2878
2879 assert(SoFar != nullptr);
2880
2881 Node *Base = parseBaseUnresolvedName();
2882 if (Base == nullptr)
2883 return nullptr;
2884 return make<QualifiedName>(SoFar, Base);
2885}
2886
Erik Pilkington2808f772018-02-13 17:09:03 +00002887// <abi-tags> ::= <abi-tag> [<abi-tags>]
2888// <abi-tag> ::= B <source-name>
2889Node *Db::parseAbiTags(Node *N) {
2890 while (consumeIf('B')) {
2891 StringView SN = parseBareSourceName();
2892 if (SN.empty())
2893 return nullptr;
2894 N = make<AbiTagAttr>(N, SN);
2895 }
2896 return N;
2897}
2898
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00002899// <number> ::= [n] <non-negative decimal integer>
2900StringView Db::parseNumber(bool AllowNegative) {
2901 const char *Tmp = First;
2902 if (AllowNegative)
2903 consumeIf('n');
2904 if (numLeft() == 0 || !std::isdigit(*First))
2905 return StringView();
2906 while (numLeft() != 0 && std::isdigit(*First))
2907 ++First;
2908 return StringView(Tmp, First);
2909}
2910
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002911// <positive length number> ::= [0-9]*
2912bool Db::parsePositiveInteger(size_t *Out) {
2913 *Out = 0;
2914 if (look() < '0' || look() > '9')
2915 return true;
2916 while (look() >= '0' && look() <= '9') {
2917 *Out *= 10;
2918 *Out += static_cast<size_t>(consume() - '0');
2919 }
2920 return false;
2921}
2922
2923StringView Db::parseBareSourceName() {
2924 size_t Int = 0;
2925 if (parsePositiveInteger(&Int) || numLeft() < Int)
2926 return StringView();
2927 StringView R(First, First + Int);
2928 First += Int;
2929 return R;
2930}
2931
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002932// <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002933//
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002934// <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
2935// ::= DO <expression> E # computed (instantiation-dependent) noexcept
2936// ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
2937//
2938// <ref-qualifier> ::= R # & ref-qualifier
2939// <ref-qualifier> ::= O # && ref-qualifier
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002940Node *Db::parseFunctionType() {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00002941 Qualifiers CVQuals = parseCVQualifiers();
Erik Pilkington7e027ac2018-02-14 01:08:20 +00002942
2943 Node *ExceptionSpec = nullptr;
2944 if (consumeIf("Do")) {
2945 ExceptionSpec = make<NameType>("noexcept");
2946 } else if (consumeIf("DO")) {
2947 Node *E = parseExpr();
2948 if (E == nullptr || !consumeIf('E'))
2949 return nullptr;
2950 ExceptionSpec = make<NoexceptSpec>(E);
2951 } else if (consumeIf("Dw")) {
2952 size_t SpecsBegin = Names.size();
2953 while (!consumeIf('E')) {
2954 Node *T = parseType();
2955 if (T == nullptr)
2956 return nullptr;
2957 Names.push_back(T);
2958 }
2959 ExceptionSpec =
2960 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
2961 }
2962
2963 consumeIf("Dx"); // transaction safe
2964
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002965 if (!consumeIf('F'))
2966 return nullptr;
2967 consumeIf('Y'); // extern "C"
2968 Node *ReturnType = parseType();
2969 if (ReturnType == nullptr)
2970 return nullptr;
2971
2972 FunctionRefQual ReferenceQualifier = FrefQualNone;
2973 size_t ParamsBegin = Names.size();
2974 while (true) {
2975 if (consumeIf('E'))
2976 break;
2977 if (consumeIf('v'))
2978 continue;
2979 if (consumeIf("RE")) {
2980 ReferenceQualifier = FrefQualLValue;
2981 break;
2982 }
2983 if (consumeIf("OE")) {
2984 ReferenceQualifier = FrefQualRValue;
2985 break;
2986 }
2987 Node *T = parseType();
2988 if (T == nullptr)
2989 return nullptr;
2990 Names.push_back(T);
2991 }
2992
2993 NodeArray Params = popTrailingNodeArray(ParamsBegin);
Erik Pilkington7e027ac2018-02-14 01:08:20 +00002994 return make<FunctionType>(ReturnType, Params, CVQuals,
2995 ReferenceQualifier, ExceptionSpec);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00002996}
2997
2998// extension:
2999// <vector-type> ::= Dv <positive dimension number> _ <extended element type>
3000// ::= Dv [<dimension expression>] _ <element type>
3001// <extended element type> ::= <element type>
3002// ::= p # AltiVec vector pixel
3003Node *Db::parseVectorType() {
3004 if (!consumeIf("Dv"))
3005 return nullptr;
3006 if (look() >= '1' && look() <= '9') {
3007 StringView DimensionNumber = parseNumber();
3008 if (!consumeIf('_'))
3009 return nullptr;
3010 if (consumeIf('p'))
3011 return make<VectorType>(DimensionNumber);
3012 Node *ElemType = parseType();
3013 if (ElemType == nullptr)
3014 return nullptr;
3015 return make<VectorType>(ElemType, DimensionNumber);
3016 }
3017
3018 if (!consumeIf('_')) {
3019 Node *DimExpr = parseExpr();
3020 if (!DimExpr)
3021 return nullptr;
3022 if (!consumeIf('_'))
3023 return nullptr;
3024 Node *ElemType = parseType();
3025 if (!ElemType)
3026 return nullptr;
3027 return make<VectorType>(ElemType, DimExpr);
3028 }
3029 Node *ElemType = parseType();
3030 if (!ElemType)
3031 return nullptr;
3032 return make<VectorType>(ElemType, StringView());
3033}
3034
3035// <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
3036// ::= DT <expression> E # decltype of an expression (C++0x)
3037Node *Db::parseDecltype() {
3038 if (!consumeIf('D'))
3039 return nullptr;
3040 if (!consumeIf('t') && !consumeIf('T'))
3041 return nullptr;
3042 Node *E = parseExpr();
3043 if (E == nullptr)
3044 return nullptr;
3045 if (!consumeIf('E'))
3046 return nullptr;
3047 return make<EnclosingExpr>("decltype(", E, ")");
3048}
3049
3050// <array-type> ::= A <positive dimension number> _ <element type>
3051// ::= A [<dimension expression>] _ <element type>
3052Node *Db::parseArrayType() {
3053 if (!consumeIf('A'))
3054 return nullptr;
3055
3056 if (std::isdigit(look())) {
3057 StringView Dimension = parseNumber();
3058 if (!consumeIf('_'))
3059 return nullptr;
3060 Node *Ty = parseType();
3061 if (Ty == nullptr)
3062 return nullptr;
3063 return make<ArrayType>(Ty, Dimension);
3064 }
3065
3066 if (!consumeIf('_')) {
3067 Node *DimExpr = parseExpr();
3068 if (DimExpr == nullptr)
3069 return nullptr;
3070 if (!consumeIf('_'))
3071 return nullptr;
3072 Node *ElementType = parseType();
3073 if (ElementType == nullptr)
3074 return nullptr;
3075 return make<ArrayType>(ElementType, DimExpr);
3076 }
3077
3078 Node *Ty = parseType();
3079 if (Ty == nullptr)
3080 return nullptr;
3081 return make<ArrayType>(Ty);
3082}
3083
3084// <pointer-to-member-type> ::= M <class type> <member type>
3085Node *Db::parsePointerToMemberType() {
3086 if (!consumeIf('M'))
3087 return nullptr;
3088 Node *ClassType = parseType();
3089 if (ClassType == nullptr)
3090 return nullptr;
3091 Node *MemberType = parseType();
3092 if (MemberType == nullptr)
3093 return nullptr;
3094 return make<PointerToMemberType>(ClassType, MemberType);
3095}
3096
3097// <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
3098// ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
3099// ::= Tu <name> # dependent elaborated type specifier using 'union'
3100// ::= Te <name> # dependent elaborated type specifier using 'enum'
3101Node *Db::parseClassEnumType() {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003102 StringView ElabSpef;
3103 if (consumeIf("Ts"))
3104 ElabSpef = "struct";
3105 else if (consumeIf("Tu"))
3106 ElabSpef = "union";
3107 else if (consumeIf("Te"))
3108 ElabSpef = "enum";
3109
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003110 Node *Name = parseName();
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003111 if (Name == nullptr)
3112 return nullptr;
3113
3114 if (!ElabSpef.empty())
3115 return make<ElaboratedTypeSpefType>(ElabSpef, Name);
3116
3117 return Name;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003118}
3119
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003120// <qualified-type> ::= <qualifiers> <type>
3121// <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
3122// <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003123Node *Db::parseQualifiedType() {
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003124 if (consumeIf('U')) {
3125 StringView Qual = parseBareSourceName();
3126 if (Qual.empty())
3127 return nullptr;
3128
3129 // FIXME parse the optional <template-args> here!
3130
3131 // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3132 if (Qual.startsWith("objcproto")) {
3133 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
3134 StringView Proto;
3135 {
3136 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()),
3137 SaveLast(Last, ProtoSourceName.end());
3138 Proto = parseBareSourceName();
3139 }
3140 if (Proto.empty())
3141 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003142 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003143 if (Child == nullptr)
3144 return nullptr;
3145 return make<ObjCProtoName>(Child, Proto);
3146 }
3147
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003148 Node *Child = parseQualifiedType();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003149 if (Child == nullptr)
3150 return nullptr;
3151 return make<VendorExtQualType>(Child, Qual);
3152 }
3153
3154 Qualifiers Quals = parseCVQualifiers();
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003155 Node *Ty = parseType();
3156 if (Ty == nullptr)
3157 return nullptr;
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003158 if (Quals != QualNone)
3159 Ty = make<QualType>(Ty, Quals);
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003160 return Ty;
3161}
3162
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003163// <type> ::= <builtin-type>
3164// ::= <qualified-type>
3165// ::= <function-type>
3166// ::= <class-enum-type>
3167// ::= <array-type>
3168// ::= <pointer-to-member-type>
3169// ::= <template-param>
3170// ::= <template-template-param> <template-args>
3171// ::= <decltype>
3172// ::= P <type> # pointer
3173// ::= R <type> # l-value reference
3174// ::= O <type> # r-value reference (C++11)
3175// ::= C <type> # complex pair (C99)
3176// ::= G <type> # imaginary (C99)
3177// ::= <substitution> # See Compression below
3178// extension ::= U <objc-name> <objc-type> # objc-type<identifier>
3179// extension ::= <vector-type> # <vector-type> starts with Dv
3180//
3181// <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
3182// <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
3183Node *Db::parseType() {
3184 Node *Result = nullptr;
3185
3186 switch (look()) {
3187 // ::= <qualified-type>
3188 case 'r':
3189 case 'V':
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003190 case 'K': {
3191 unsigned AfterQuals = 0;
3192 if (look(AfterQuals) == 'r') ++AfterQuals;
3193 if (look(AfterQuals) == 'V') ++AfterQuals;
3194 if (look(AfterQuals) == 'K') ++AfterQuals;
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003195
3196 if (look(AfterQuals) == 'F' ||
3197 (look(AfterQuals) == 'D' &&
3198 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
3199 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003200 Result = parseFunctionType();
3201 break;
3202 }
3203 _LIBCPP_FALLTHROUGH();
3204 }
Erik Pilkingtoncf29d3b2018-02-13 00:15:46 +00003205 case 'U': {
Erik Pilkingtonbdaf8822018-02-14 01:08:17 +00003206 Result = parseQualifiedType();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003207 break;
3208 }
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003209 // <builtin-type> ::= v # void
3210 case 'v':
3211 ++First;
3212 return make<NameType>("void");
3213 // ::= w # wchar_t
3214 case 'w':
3215 ++First;
3216 return make<NameType>("wchar_t");
3217 // ::= b # bool
3218 case 'b':
3219 ++First;
3220 return make<NameType>("bool");
3221 // ::= c # char
3222 case 'c':
3223 ++First;
3224 return make<NameType>("char");
3225 // ::= a # signed char
3226 case 'a':
3227 ++First;
3228 return make<NameType>("signed char");
3229 // ::= h # unsigned char
3230 case 'h':
3231 ++First;
3232 return make<NameType>("unsigned char");
3233 // ::= s # short
3234 case 's':
3235 ++First;
3236 return make<NameType>("short");
3237 // ::= t # unsigned short
3238 case 't':
3239 ++First;
3240 return make<NameType>("unsigned short");
3241 // ::= i # int
3242 case 'i':
3243 ++First;
3244 return make<NameType>("int");
3245 // ::= j # unsigned int
3246 case 'j':
3247 ++First;
3248 return make<NameType>("unsigned int");
3249 // ::= l # long
3250 case 'l':
3251 ++First;
3252 return make<NameType>("long");
3253 // ::= m # unsigned long
3254 case 'm':
3255 ++First;
3256 return make<NameType>("unsigned long");
3257 // ::= x # long long, __int64
3258 case 'x':
3259 ++First;
3260 return make<NameType>("long long");
3261 // ::= y # unsigned long long, __int64
3262 case 'y':
3263 ++First;
3264 return make<NameType>("unsigned long long");
3265 // ::= n # __int128
3266 case 'n':
3267 ++First;
3268 return make<NameType>("__int128");
3269 // ::= o # unsigned __int128
3270 case 'o':
3271 ++First;
3272 return make<NameType>("unsigned __int128");
3273 // ::= f # float
3274 case 'f':
3275 ++First;
3276 return make<NameType>("float");
3277 // ::= d # double
3278 case 'd':
3279 ++First;
3280 return make<NameType>("double");
3281 // ::= e # long double, __float80
3282 case 'e':
3283 ++First;
3284 return make<NameType>("long double");
3285 // ::= g # __float128
3286 case 'g':
3287 ++First;
3288 return make<NameType>("__float128");
3289 // ::= z # ellipsis
3290 case 'z':
3291 ++First;
3292 return make<NameType>("...");
3293
3294 // <builtin-type> ::= u <source-name> # vendor extended type
3295 case 'u': {
3296 ++First;
3297 StringView Res = parseBareSourceName();
3298 if (Res.empty())
3299 return nullptr;
3300 return make<NameType>(Res);
3301 }
3302 case 'D':
3303 switch (look(1)) {
3304 // ::= Dd # IEEE 754r decimal floating point (64 bits)
3305 case 'd':
3306 First += 2;
3307 return make<NameType>("decimal64");
3308 // ::= De # IEEE 754r decimal floating point (128 bits)
3309 case 'e':
3310 First += 2;
3311 return make<NameType>("decimal128");
3312 // ::= Df # IEEE 754r decimal floating point (32 bits)
3313 case 'f':
3314 First += 2;
3315 return make<NameType>("decimal32");
3316 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3317 case 'h':
3318 First += 2;
3319 return make<NameType>("decimal16");
3320 // ::= Di # char32_t
3321 case 'i':
3322 First += 2;
3323 return make<NameType>("char32_t");
3324 // ::= Ds # char16_t
3325 case 's':
3326 First += 2;
3327 return make<NameType>("char16_t");
3328 // ::= Da # auto (in dependent new-expressions)
3329 case 'a':
3330 First += 2;
3331 return make<NameType>("auto");
3332 // ::= Dc # decltype(auto)
3333 case 'c':
3334 First += 2;
3335 return make<NameType>("decltype(auto)");
3336 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3337 case 'n':
3338 First += 2;
3339 return make<NameType>("std::nullptr_t");
3340
3341 // ::= <decltype>
3342 case 't':
3343 case 'T': {
3344 Result = parseDecltype();
3345 break;
3346 }
3347 // extension ::= <vector-type> # <vector-type> starts with Dv
3348 case 'v': {
3349 Result = parseVectorType();
3350 break;
3351 }
3352 // ::= Dp <type> # pack expansion (C++0x)
3353 case 'p': {
3354 First += 2;
3355 Node *Child = parseType();
3356 if (!Child)
3357 return nullptr;
3358 Result = make<ParameterPackExpansion>(Child);
3359 break;
3360 }
Erik Pilkington7e027ac2018-02-14 01:08:20 +00003361 // Exception specifier on a function type.
3362 case 'o':
3363 case 'O':
3364 case 'w':
3365 // Transaction safe function type.
3366 case 'x':
3367 Result = parseFunctionType();
3368 break;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003369 }
3370 break;
3371 // ::= <function-type>
3372 case 'F': {
3373 Result = parseFunctionType();
3374 break;
3375 }
3376 // ::= <array-type>
3377 case 'A': {
3378 Result = parseArrayType();
3379 break;
3380 }
3381 // ::= <pointer-to-member-type>
3382 case 'M': {
3383 Result = parsePointerToMemberType();
3384 break;
3385 }
3386 // ::= <template-param>
3387 case 'T': {
Erik Pilkington13fb7dc2018-02-13 00:15:53 +00003388 // This could be an elaborate type specifier on a <class-enum-type>.
3389 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
3390 Result = parseClassEnumType();
3391 break;
3392 }
3393
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003394 Result = parseTemplateParam();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003395 if (Result == nullptr)
3396 return nullptr;
3397
3398 // Result could be either of:
3399 // <type> ::= <template-param>
3400 // <type> ::= <template-template-param> <template-args>
3401 //
3402 // <template-template-param> ::= <template-param>
3403 // ::= <substitution>
3404 //
3405 // If this is followed by some <template-args>, and we're permitted to
3406 // parse them, take the second production.
3407
3408 if (TryToParseTemplateArgs && look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003409 Node *TA = parseTemplateArgs();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003410 if (TA == nullptr)
3411 return nullptr;
3412 Result = make<NameWithTemplateArgs>(Result, TA);
3413 }
3414 break;
3415 }
3416 // ::= P <type> # pointer
3417 case 'P': {
3418 ++First;
3419 Node *Ptr = parseType();
3420 if (Ptr == nullptr)
3421 return nullptr;
3422 Result = make<PointerType>(Ptr);
3423 break;
3424 }
3425 // ::= R <type> # l-value reference
3426 case 'R': {
3427 ++First;
3428 Node *Ref = parseType();
3429 if (Ref == nullptr)
3430 return nullptr;
3431 Result = make<LValueReferenceType>(Ref);
3432 break;
3433 }
3434 // ::= O <type> # r-value reference (C++11)
3435 case 'O': {
3436 ++First;
3437 Node *Ref = parseType();
3438 if (Ref == nullptr)
3439 return nullptr;
3440 Result = make<RValueReferenceType>(Ref);
3441 break;
3442 }
3443 // ::= C <type> # complex pair (C99)
3444 case 'C': {
3445 ++First;
3446 Node *P = parseType();
3447 if (P == nullptr)
3448 return nullptr;
3449 Result = make<PostfixQualifiedType>(P, " complex");
3450 break;
3451 }
3452 // ::= G <type> # imaginary (C99)
3453 case 'G': {
3454 ++First;
3455 Node *P = parseType();
3456 if (P == nullptr)
3457 return P;
3458 Result = make<PostfixQualifiedType>(P, " imaginary");
3459 break;
3460 }
3461 // ::= <substitution> # See Compression below
3462 case 'S': {
3463 if (look(1) && look(1) != 't') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003464 Node *Sub = parseSubstitution();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003465 if (Sub == nullptr)
3466 return nullptr;
3467
3468 // Sub could be either of:
3469 // <type> ::= <substitution>
3470 // <type> ::= <template-template-param> <template-args>
3471 //
3472 // <template-template-param> ::= <template-param>
3473 // ::= <substitution>
3474 //
3475 // If this is followed by some <template-args>, and we're permitted to
3476 // parse them, take the second production.
3477
3478 if (TryToParseTemplateArgs && look() == 'I') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003479 Node *TA = parseTemplateArgs();
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003480 if (TA == nullptr)
3481 return nullptr;
3482 Result = make<NameWithTemplateArgs>(Sub, TA);
3483 break;
3484 }
3485
3486 // If all we parsed was a substitution, don't re-insert into the
3487 // substitution table.
3488 return Sub;
3489 }
3490 _LIBCPP_FALLTHROUGH();
3491 }
3492 // ::= <class-enum-type>
3493 default: {
3494 Result = parseClassEnumType();
3495 break;
3496 }
3497 }
3498
3499 // If we parsed a type, insert it into the substitution table. Note that all
3500 // <builtin-type>s and <substitution>s have already bailed out, because they
3501 // don't get substitutions.
3502 if (Result != nullptr)
3503 Subs.push_back(Result);
3504 return Result;
3505}
3506
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003507Node *Db::parsePrefixExpr(StringView Kind) {
3508 Node *E = parseExpr();
3509 if (E == nullptr)
3510 return nullptr;
3511 return make<PrefixExpr>(Kind, E);
3512}
3513
3514Node *Db::parseBinaryExpr(StringView Kind) {
3515 Node *LHS = parseExpr();
3516 if (LHS == nullptr)
3517 return nullptr;
3518 Node *RHS = parseExpr();
3519 if (RHS == nullptr)
3520 return nullptr;
3521 return make<BinaryExpr>(LHS, Kind, RHS);
3522}
3523
3524Node *Db::parseIntegerLiteral(StringView Lit) {
3525 StringView Tmp = parseNumber(true);
3526 if (!Tmp.empty() && consumeIf('E'))
3527 return make<IntegerExpr>(Lit, Tmp);
3528 return nullptr;
3529}
3530
Erik Pilkington2808f772018-02-13 17:09:03 +00003531// <CV-Qualifiers> ::= [r] [V] [K]
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003532Qualifiers Db::parseCVQualifiers() {
3533 Qualifiers CVR = QualNone;
3534 if (consumeIf('r'))
3535 addQualifiers(CVR, QualRestrict);
3536 if (consumeIf('V'))
3537 addQualifiers(CVR, QualVolatile);
3538 if (consumeIf('K'))
3539 addQualifiers(CVR, QualConst);
3540 return CVR;
3541}
3542
3543// <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
3544// ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
3545// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
3546// ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
3547Node *Db::parseFunctionParam() {
3548 if (consumeIf("fp")) {
3549 parseCVQualifiers();
3550 StringView Num = parseNumber();
3551 if (!consumeIf('_'))
3552 return nullptr;
3553 return make<FunctionParam>(Num);
3554 }
3555 if (consumeIf("fL")) {
3556 if (parseNumber().empty())
3557 return nullptr;
3558 if (!consumeIf('p'))
3559 return nullptr;
3560 parseCVQualifiers();
3561 StringView Num = parseNumber();
3562 if (!consumeIf('_'))
3563 return nullptr;
3564 return make<FunctionParam>(Num);
3565 }
3566 return nullptr;
3567}
3568
3569// [gs] nw <expression>* _ <type> E # new (expr-list) type
3570// [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3571// [gs] na <expression>* _ <type> E # new[] (expr-list) type
3572// [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3573// <initializer> ::= pi <expression>* E # parenthesized initialization
3574Node *Db::parseNewExpr() {
3575 bool Global = consumeIf("gs");
3576 bool IsArray = look(1) == 'a';
3577 if (!consumeIf("nw") && !consumeIf("na"))
3578 return nullptr;
3579 size_t Exprs = Names.size();
3580 while (!consumeIf('_')) {
3581 Node *Ex = parseExpr();
3582 if (Ex == nullptr)
3583 return nullptr;
3584 Names.push_back(Ex);
3585 }
3586 NodeArray ExprList = popTrailingNodeArray(Exprs);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003587 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003588 if (Ty == nullptr)
3589 return Ty;
3590 if (consumeIf("pi")) {
3591 size_t InitsBegin = Names.size();
3592 while (!consumeIf('E')) {
3593 Node *Init = parseExpr();
3594 if (Init == nullptr)
3595 return Init;
3596 Names.push_back(Init);
3597 }
3598 NodeArray Inits = popTrailingNodeArray(InitsBegin);
3599 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray);
3600 } else if (!consumeIf('E'))
3601 return nullptr;
3602 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray);
3603}
3604
3605// cv <type> <expression> # conversion with one argument
3606// cv <type> _ <expression>* E # conversion with a different number of arguments
3607Node *Db::parseConversionExpr() {
3608 if (!consumeIf("cv"))
3609 return nullptr;
3610 Node *Ty;
3611 {
3612 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false);
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003613 Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003614 }
3615
3616 if (Ty == nullptr)
3617 return nullptr;
3618
3619 if (consumeIf('_')) {
3620 size_t ExprsBegin = Names.size();
3621 while (!consumeIf('E')) {
3622 Node *E = parseExpr();
3623 if (E == nullptr)
3624 return E;
3625 Names.push_back(E);
3626 }
3627 NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
3628 return make<ConversionExpr>(Ty, Exprs);
3629 }
3630
3631 Node *E[1] = {parseExpr()};
3632 if (E[0] == nullptr)
3633 return nullptr;
3634 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
3635}
3636
3637// <expr-primary> ::= L <type> <value number> E # integer literal
3638// ::= L <type> <value float> E # floating literal
3639// ::= L <string type> E # string literal
3640// ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
3641// FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
3642// ::= L <mangled-name> E # external name
3643Node *Db::parseExprPrimary() {
3644 if (!consumeIf('L'))
3645 return nullptr;
3646 switch (look()) {
3647 case 'w':
3648 ++First;
3649 return parseIntegerLiteral("wchar_t");
3650 case 'b':
3651 if (consumeIf("b0E"))
3652 return make<BoolExpr>(0);
3653 if (consumeIf("b1E"))
3654 return make<BoolExpr>(1);
3655 return nullptr;
3656 case 'c':
3657 ++First;
3658 return parseIntegerLiteral("char");
3659 case 'a':
3660 ++First;
3661 return parseIntegerLiteral("signed char");
3662 case 'h':
3663 ++First;
3664 return parseIntegerLiteral("unsigned char");
3665 case 's':
3666 ++First;
3667 return parseIntegerLiteral("short");
3668 case 't':
3669 ++First;
3670 return parseIntegerLiteral("unsigned short");
3671 case 'i':
3672 ++First;
3673 return parseIntegerLiteral("");
3674 case 'j':
3675 ++First;
3676 return parseIntegerLiteral("u");
3677 case 'l':
3678 ++First;
3679 return parseIntegerLiteral("l");
3680 case 'm':
3681 ++First;
3682 return parseIntegerLiteral("ul");
3683 case 'x':
3684 ++First;
3685 return parseIntegerLiteral("ll");
3686 case 'y':
3687 ++First;
3688 return parseIntegerLiteral("ull");
3689 case 'n':
3690 ++First;
3691 return parseIntegerLiteral("__int128");
3692 case 'o':
3693 ++First;
3694 return parseIntegerLiteral("unsigned __int128");
3695 case 'f':
3696 ++First;
3697 return parseFloatingLiteral<float>();
3698 case 'd':
3699 ++First;
3700 return parseFloatingLiteral<double>();
3701 case 'e':
3702 ++First;
3703 return parseFloatingLiteral<long double>();
3704 case '_':
3705 if (consumeIf("_Z")) {
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003706 Node *R = parseEncoding();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003707 if (R != nullptr && consumeIf('E'))
3708 return R;
3709 }
3710 return nullptr;
3711 case 'T':
3712 // Invalid mangled name per
3713 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
3714 return nullptr;
3715 default: {
3716 // might be named type
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003717 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003718 if (T == nullptr)
3719 return nullptr;
3720 StringView N = parseNumber();
3721 if (!N.empty()) {
3722 if (!consumeIf('E'))
3723 return nullptr;
3724 return make<IntegerCastExpr>(T, N);
3725 }
3726 if (consumeIf('E'))
3727 return T;
3728 return nullptr;
3729 }
3730 }
3731}
3732
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003733// <braced-expression> ::= <expression>
3734// ::= di <field source-name> <braced-expression> # .name = expr
3735// ::= dx <index expression> <braced-expression> # [expr] = expr
3736// ::= dX <range begin expression> <range end expression> <braced-expression>
3737Node *Db::parseBracedExpr() {
3738 if (look() == 'd') {
3739 switch (look(1)) {
3740 case 'i': {
3741 First += 2;
Erik Pilkingtone1d61622018-03-05 16:35:06 +00003742 Node *Field = parseSourceName(/*NameState=*/nullptr);
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003743 if (Field == nullptr)
3744 return nullptr;
3745 Node *Init = parseBracedExpr();
3746 if (Init == nullptr)
3747 return nullptr;
3748 return make<BracedExpr>(Field, Init, /*isArray=*/false);
3749 }
3750 case 'x': {
3751 First += 2;
3752 Node *Index = parseExpr();
3753 if (Index == nullptr)
3754 return nullptr;
3755 Node *Init = parseBracedExpr();
3756 if (Init == nullptr)
3757 return nullptr;
3758 return make<BracedExpr>(Index, Init, /*isArray=*/true);
3759 }
3760 case 'X': {
3761 First += 2;
3762 Node *RangeBegin = parseExpr();
3763 if (RangeBegin == nullptr)
3764 return nullptr;
3765 Node *RangeEnd = parseExpr();
3766 if (RangeEnd == nullptr)
3767 return nullptr;
3768 Node *Init = parseBracedExpr();
3769 if (Init == nullptr)
3770 return nullptr;
3771 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
3772 }
3773 }
3774 }
3775 return parseExpr();
3776}
3777
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003778// <expression> ::= <unary operator-name> <expression>
3779// ::= <binary operator-name> <expression> <expression>
3780// ::= <ternary operator-name> <expression> <expression> <expression>
3781// ::= cl <expression>+ E # call
3782// ::= cv <type> <expression> # conversion with one argument
3783// ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3784// ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
3785// ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
3786// ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
3787// ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
3788// ::= [gs] dl <expression> # delete expression
3789// ::= [gs] da <expression> # delete[] expression
3790// ::= pp_ <expression> # prefix ++
3791// ::= mm_ <expression> # prefix --
3792// ::= ti <type> # typeid (type)
3793// ::= te <expression> # typeid (expression)
3794// ::= dc <type> <expression> # dynamic_cast<type> (expression)
3795// ::= sc <type> <expression> # static_cast<type> (expression)
3796// ::= cc <type> <expression> # const_cast<type> (expression)
3797// ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3798// ::= st <type> # sizeof (a type)
3799// ::= sz <expression> # sizeof (an expression)
3800// ::= at <type> # alignof (a type)
3801// ::= az <expression> # alignof (an expression)
3802// ::= nx <expression> # noexcept (expression)
3803// ::= <template-param>
3804// ::= <function-param>
3805// ::= dt <expression> <unresolved-name> # expr.name
3806// ::= pt <expression> <unresolved-name> # expr->name
3807// ::= ds <expression> <expression> # expr.*expr
3808// ::= sZ <template-param> # size of a parameter pack
3809// ::= sZ <function-param> # size of a function parameter pack
3810// ::= sp <expression> # pack expansion
3811// ::= tw <expression> # throw expression
3812// ::= tr # throw with no operand (rethrow)
3813// ::= <unresolved-name> # f(p), N::f(p), ::f(p),
3814// # freestanding dependent name (e.g., T::x),
3815// # objectless nonstatic member reference
3816// ::= fL <binary-operator-name> <expression> <expression>
3817// ::= fR <binary-operator-name> <expression> <expression>
3818// ::= fl <binary-operator-name> <expression>
3819// ::= fr <binary-operator-name> <expression>
3820// ::= <expr-primary>
3821Node *Db::parseExpr() {
3822 bool Global = consumeIf("gs");
3823 if (numLeft() < 2)
3824 return nullptr;
3825
3826 switch (*First) {
3827 case 'L':
3828 return parseExprPrimary();
3829 case 'T':
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00003830 return parseTemplateParam();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003831 case 'f':
3832 return parseFunctionParam();
3833 case 'a':
3834 switch (First[1]) {
3835 case 'a':
3836 First += 2;
3837 return parseBinaryExpr("&&");
3838 case 'd':
3839 First += 2;
3840 return parsePrefixExpr("&");
3841 case 'n':
3842 First += 2;
3843 return parseBinaryExpr("&");
3844 case 'N':
3845 First += 2;
3846 return parseBinaryExpr("&=");
3847 case 'S':
3848 First += 2;
3849 return parseBinaryExpr("=");
3850 case 't': {
3851 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003852 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003853 if (Ty == nullptr)
3854 return nullptr;
3855 return make<EnclosingExpr>("alignof (", Ty, ")");
3856 }
3857 case 'z': {
3858 First += 2;
3859 Node *Ty = parseExpr();
3860 if (Ty == nullptr)
3861 return nullptr;
3862 return make<EnclosingExpr>("alignof (", Ty, ")");
3863 }
3864 }
3865 return nullptr;
3866 case 'c':
3867 switch (First[1]) {
3868 // cc <type> <expression> # const_cast<type>(expression)
3869 case 'c': {
3870 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003871 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003872 if (Ty == nullptr)
3873 return Ty;
3874 Node *Ex = parseExpr();
3875 if (Ex == nullptr)
3876 return Ex;
3877 return make<CastExpr>("const_cast", Ty, Ex);
3878 }
3879 // cl <expression>+ E # call
3880 case 'l': {
3881 First += 2;
3882 Node *Callee = parseExpr();
3883 if (Callee == nullptr)
3884 return Callee;
3885 size_t ExprsBegin = Names.size();
3886 while (!consumeIf('E')) {
3887 Node *E = parseExpr();
3888 if (E == nullptr)
3889 return E;
3890 Names.push_back(E);
3891 }
3892 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin));
3893 }
3894 case 'm':
3895 First += 2;
3896 return parseBinaryExpr(",");
3897 case 'o':
3898 First += 2;
3899 return parsePrefixExpr("~");
3900 case 'v':
3901 return parseConversionExpr();
3902 }
3903 return nullptr;
3904 case 'd':
3905 switch (First[1]) {
3906 case 'a': {
3907 First += 2;
3908 Node *Ex = parseExpr();
3909 if (Ex == nullptr)
3910 return Ex;
3911 return make<DeleteExpr>(Ex, Global, /*is_array=*/true);
3912 }
3913 case 'c': {
3914 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00003915 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003916 if (T == nullptr)
3917 return T;
3918 Node *Ex = parseExpr();
3919 if (Ex == nullptr)
3920 return Ex;
3921 return make<CastExpr>("dynamic_cast", T, Ex);
3922 }
3923 case 'e':
3924 First += 2;
3925 return parsePrefixExpr("*");
3926 case 'l': {
3927 First += 2;
3928 Node *E = parseExpr();
3929 if (E == nullptr)
3930 return E;
3931 return make<DeleteExpr>(E, Global, /*is_array=*/false);
3932 }
3933 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00003934 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003935 case 's': {
3936 First += 2;
3937 Node *LHS = parseExpr();
3938 if (LHS == nullptr)
3939 return nullptr;
3940 Node *RHS = parseExpr();
3941 if (RHS == nullptr)
3942 return nullptr;
3943 return make<MemberExpr>(LHS, ".*", RHS);
3944 }
3945 case 't': {
3946 First += 2;
3947 Node *LHS = parseExpr();
3948 if (LHS == nullptr)
3949 return LHS;
3950 Node *RHS = parseExpr();
3951 if (RHS == nullptr)
3952 return nullptr;
3953 return make<MemberExpr>(LHS, ".", RHS);
3954 }
3955 case 'v':
3956 First += 2;
3957 return parseBinaryExpr("/");
3958 case 'V':
3959 First += 2;
3960 return parseBinaryExpr("/=");
3961 }
3962 return nullptr;
3963 case 'e':
3964 switch (First[1]) {
3965 case 'o':
3966 First += 2;
3967 return parseBinaryExpr("^");
3968 case 'O':
3969 First += 2;
3970 return parseBinaryExpr("^=");
3971 case 'q':
3972 First += 2;
3973 return parseBinaryExpr("==");
3974 }
3975 return nullptr;
3976 case 'g':
3977 switch (First[1]) {
3978 case 'e':
3979 First += 2;
3980 return parseBinaryExpr(">=");
3981 case 't':
3982 First += 2;
3983 return parseBinaryExpr(">");
3984 }
3985 return nullptr;
3986 case 'i':
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003987 switch (First[1]) {
3988 case 'x': {
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00003989 First += 2;
3990 Node *Base = parseExpr();
3991 if (Base == nullptr)
3992 return nullptr;
3993 Node *Index = parseExpr();
3994 if (Index == nullptr)
3995 return Index;
3996 return make<ArraySubscriptExpr>(Base, Index);
3997 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00003998 case 'l': {
3999 First += 2;
4000 size_t InitsBegin = Names.size();
4001 while (!consumeIf('E')) {
4002 Node *E = parseBracedExpr();
4003 if (E == nullptr)
4004 return nullptr;
4005 Names.push_back(E);
4006 }
4007 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
4008 }
4009 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004010 return nullptr;
4011 case 'l':
4012 switch (First[1]) {
4013 case 'e':
4014 First += 2;
4015 return parseBinaryExpr("<=");
4016 case 's':
4017 First += 2;
4018 return parseBinaryExpr("<<");
4019 case 'S':
4020 First += 2;
4021 return parseBinaryExpr("<<=");
4022 case 't':
4023 First += 2;
4024 return parseBinaryExpr("<");
4025 }
4026 return nullptr;
4027 case 'm':
4028 switch (First[1]) {
4029 case 'i':
4030 First += 2;
4031 return parseBinaryExpr("-");
4032 case 'I':
4033 First += 2;
4034 return parseBinaryExpr("-=");
4035 case 'l':
4036 First += 2;
4037 return parseBinaryExpr("*");
4038 case 'L':
4039 First += 2;
4040 return parseBinaryExpr("*=");
4041 case 'm':
4042 First += 2;
4043 if (consumeIf('_'))
4044 return parsePrefixExpr("--");
4045 Node *Ex = parseExpr();
4046 if (Ex == nullptr)
4047 return nullptr;
4048 return make<PostfixExpr>(Ex, "--");
4049 }
4050 return nullptr;
4051 case 'n':
4052 switch (First[1]) {
4053 case 'a':
4054 case 'w':
4055 return parseNewExpr();
4056 case 'e':
4057 First += 2;
4058 return parseBinaryExpr("!=");
4059 case 'g':
4060 First += 2;
4061 return parsePrefixExpr("-");
4062 case 't':
4063 First += 2;
4064 return parsePrefixExpr("!");
4065 case 'x':
4066 First += 2;
4067 Node *Ex = parseExpr();
4068 if (Ex == nullptr)
4069 return Ex;
4070 return make<EnclosingExpr>("noexcept (", Ex, ")");
4071 }
4072 return nullptr;
4073 case 'o':
4074 switch (First[1]) {
4075 case 'n':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004076 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004077 case 'o':
4078 First += 2;
4079 return parseBinaryExpr("||");
4080 case 'r':
4081 First += 2;
4082 return parseBinaryExpr("|");
4083 case 'R':
4084 First += 2;
4085 return parseBinaryExpr("|=");
4086 }
4087 return nullptr;
4088 case 'p':
4089 switch (First[1]) {
4090 case 'm':
4091 First += 2;
4092 return parseBinaryExpr("->*");
4093 case 'l':
4094 First += 2;
4095 return parseBinaryExpr("+");
4096 case 'L':
4097 First += 2;
4098 return parseBinaryExpr("+=");
4099 case 'p': {
4100 First += 2;
4101 if (consumeIf('_'))
4102 return parsePrefixExpr("++");
4103 Node *Ex = parseExpr();
4104 if (Ex == nullptr)
4105 return Ex;
4106 return make<PostfixExpr>(Ex, "++");
4107 }
4108 case 's':
4109 First += 2;
4110 return parsePrefixExpr("+");
4111 case 't': {
4112 First += 2;
4113 Node *L = parseExpr();
4114 if (L == nullptr)
4115 return nullptr;
4116 Node *R = parseExpr();
4117 if (R == nullptr)
4118 return nullptr;
4119 return make<MemberExpr>(L, "->", R);
4120 }
4121 }
4122 return nullptr;
4123 case 'q':
4124 if (First[1] == 'u') {
4125 First += 2;
4126 Node *Cond = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004127 if (Cond == nullptr)
4128 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004129 Node *LHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004130 if (LHS == nullptr)
4131 return nullptr;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004132 Node *RHS = parseExpr();
Erik Pilkington24e8b732018-02-05 02:34:41 +00004133 if (RHS == nullptr)
4134 return nullptr;
4135 return make<ConditionalExpr>(Cond, LHS, RHS);
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004136 }
4137 return nullptr;
4138 case 'r':
4139 switch (First[1]) {
4140 case 'c': {
4141 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004142 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004143 if (T == nullptr)
4144 return T;
4145 Node *Ex = parseExpr();
4146 if (Ex == nullptr)
4147 return Ex;
4148 return make<CastExpr>("reinterpret_cast", T, Ex);
4149 }
4150 case 'm':
4151 First += 2;
4152 return parseBinaryExpr("%");
4153 case 'M':
4154 First += 2;
4155 return parseBinaryExpr("%=");
4156 case 's':
4157 First += 2;
4158 return parseBinaryExpr(">>");
4159 case 'S':
4160 First += 2;
4161 return parseBinaryExpr(">>=");
4162 }
4163 return nullptr;
4164 case 's':
4165 switch (First[1]) {
4166 case 'c': {
4167 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004168 Node *T = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004169 if (T == nullptr)
4170 return T;
4171 Node *Ex = parseExpr();
4172 if (Ex == nullptr)
4173 return Ex;
4174 return make<CastExpr>("static_cast", T, Ex);
4175 }
4176 case 'p': {
4177 First += 2;
4178 Node *Child = parseExpr();
4179 if (Child == nullptr)
4180 return nullptr;
4181 return make<ParameterPackExpansion>(Child);
4182 }
4183 case 'r':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004184 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004185 case 't': {
4186 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004187 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004188 if (Ty == nullptr)
4189 return Ty;
4190 return make<EnclosingExpr>("sizeof (", Ty, ")");
4191 }
4192 case 'z': {
4193 First += 2;
4194 Node *Ex = parseExpr();
4195 if (Ex == nullptr)
4196 return Ex;
4197 return make<EnclosingExpr>("sizeof (", Ex, ")");
4198 }
4199 case 'Z':
4200 First += 2;
4201 if (look() == 'T') {
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004202 Node *R = parseTemplateParam();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004203 if (R == nullptr)
4204 return nullptr;
4205 return make<SizeofParamPackExpr>(R);
4206 } else if (look() == 'f') {
4207 Node *FP = parseFunctionParam();
4208 if (FP == nullptr)
4209 return nullptr;
4210 return make<EnclosingExpr>("sizeof...", FP, ")");
4211 }
4212 return nullptr;
4213 }
4214 return nullptr;
4215 case 't':
4216 switch (First[1]) {
4217 case 'e': {
4218 First += 2;
4219 Node *Ex = parseExpr();
4220 if (Ex == nullptr)
4221 return Ex;
4222 return make<EnclosingExpr>("typeid (", Ex, ")");
4223 }
4224 case 'i': {
4225 First += 2;
Erik Pilkingtonf23deca2018-02-05 22:41:20 +00004226 Node *Ty = parseType();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004227 if (Ty == nullptr)
4228 return Ty;
4229 return make<EnclosingExpr>("typeid (", Ty, ")");
4230 }
Erik Pilkington88a1cf62018-02-13 00:15:56 +00004231 case 'l': {
4232 First += 2;
4233 Node *Ty = parseType();
4234 if (Ty == nullptr)
4235 return nullptr;
4236 size_t InitsBegin = Names.size();
4237 while (!consumeIf('E')) {
4238 Node *E = parseBracedExpr();
4239 if (E == nullptr)
4240 return nullptr;
4241 Names.push_back(E);
4242 }
4243 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
4244 }
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004245 case 'r':
4246 First += 2;
4247 return make<NameType>("throw");
4248 case 'w': {
4249 First += 2;
4250 Node *Ex = parseExpr();
4251 if (Ex == nullptr)
4252 return nullptr;
4253 return make<ThrowExpr>(Ex);
4254 }
4255 }
4256 return nullptr;
4257 case '1':
4258 case '2':
4259 case '3':
4260 case '4':
4261 case '5':
4262 case '6':
4263 case '7':
4264 case '8':
4265 case '9':
Erik Pilkingtond0dd97d2018-03-06 14:21:08 +00004266 return parseUnresolvedName();
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004267 }
4268 return nullptr;
4269}
Erik Pilkingtonc3926622017-07-08 18:54:08 +00004270
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004271// <call-offset> ::= h <nv-offset> _
4272// ::= v <v-offset> _
4273//
4274// <nv-offset> ::= <offset number>
4275// # non-virtual base override
4276//
4277// <v-offset> ::= <offset number> _ <virtual offset number>
4278// # virtual base override, with vcall offset
4279bool Db::parseCallOffset() {
4280 // Just scan through the call offset, we never add this information into the
4281 // output.
4282 if (consumeIf('h'))
4283 return parseNumber(true).empty() || !consumeIf('_');
4284 if (consumeIf('v'))
4285 return parseNumber(true).empty() || !consumeIf('_') ||
4286 parseNumber(true).empty() || !consumeIf('_');
4287 return true;
4288}
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004289
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004290// <special-name> ::= TV <type> # virtual table
4291// ::= TT <type> # VTT structure (construction vtable index)
4292// ::= TI <type> # typeinfo structure
4293// ::= TS <type> # typeinfo name (null-terminated byte string)
4294// ::= Tc <call-offset> <call-offset> <base encoding>
4295// # base is the nominal target function of thunk
4296// # first call-offset is 'this' adjustment
4297// # second call-offset is result adjustment
4298// ::= T <call-offset> <base encoding>
4299// # base is the nominal target function of thunk
4300// ::= GV <object name> # Guard variable for one-time initialization
4301// # No <type>
4302// ::= TW <object name> # Thread-local wrapper
4303// ::= TH <object name> # Thread-local initialization
4304// extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first
4305// extension ::= GR <object name> # reference temporary for object
4306Node *Db::parseSpecialName() {
4307 switch (look()) {
4308 case 'T':
4309 switch (look(1)) {
4310 // TV <type> # virtual table
4311 case 'V': {
4312 First += 2;
4313 Node *Ty = parseType();
4314 if (Ty == nullptr)
4315 return nullptr;
4316 return make<SpecialName>("vtable for ", Ty);
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004317 }
Erik Pilkingtone1d61622018-03-05 16:35:06 +00004318 // TT <type> # VTT structure (construction vtable index)
4319 case 'T': {
4320 First += 2;
4321 Node *Ty = parseType();
4322 if (Ty == nullptr)
4323 return nullptr;
4324 return make<SpecialName>("VTT for ", Ty);
4325 }
4326 // TI <type> # typeinfo structure
4327 case 'I': {
4328 First += 2;
4329 Node *Ty = parseType();
4330 if (Ty == nullptr)
4331 return nullptr;
4332 return make<SpecialName>("typeinfo for ", Ty);
4333 }
4334 // TS <type> # typeinfo name (null-terminated byte string)
4335 case 'S': {
4336 First += 2;
4337 Node *Ty = parseType();
4338 if (Ty == nullptr)
4339 return nullptr;
4340 return make<SpecialName>("typeinfo name for ", Ty);
4341 }
4342 // Tc <call-offset> <call-offset> <base encoding>
4343 case 'c': {
4344 First += 2;
4345 if (parseCallOffset() || parseCallOffset())
4346 return nullptr;
4347 Node *Encoding = parseEncoding();
4348 if (Encoding == nullptr)
4349 return nullptr;
4350 return make<SpecialName>("covariant return thunk to ", Encoding);
4351 }
4352 // extension ::= TC <first type> <number> _ <second type>
4353 // # construction vtable for second-in-first
4354 case 'C': {
4355 First += 2;
4356 Node *FirstType = parseType();
4357 if (FirstType == nullptr)
4358 return nullptr;
4359 if (parseNumber(true).empty() || !consumeIf('_'))
4360 return nullptr;
4361 Node *SecondType = parseType();
4362 if (SecondType == nullptr)
4363 return nullptr;
4364 return make<CtorVtableSpecialName>(SecondType, FirstType);
4365 }
4366 // TW <object name> # Thread-local wrapper
4367 case 'W': {
4368 First += 2;
4369 Node *Name = parseName();
4370 if (Name == nullptr)
4371 return nullptr;
4372 return make<SpecialName>("thread-local wrapper routine for ", Name);
4373 }
4374 // TH <object name> # Thread-local initialization
4375 case 'H': {
4376 First += 2;
4377 Node *Name = parseName();
4378 if (Name == nullptr)
4379 return nullptr;
4380 return make<SpecialName>("thread-local initialization routine for ", Name);
4381 }
4382 // T <call-offset> <base encoding>
4383 default: {
4384 ++First;
4385 bool IsVirt = look() == 'v';
4386 if (parseCallOffset())
4387 return nullptr;
4388 Node *BaseEncoding = parseEncoding();
4389 if (BaseEncoding == nullptr)
4390 return nullptr;
4391 if (IsVirt)
4392 return make<SpecialName>("virtual thunk to ", BaseEncoding);
4393 else
4394 return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
4395 }
4396 }
4397 case 'G':
4398 switch (look(1)) {
4399 // GV <object name> # Guard variable for one-time initialization
4400 case 'V': {
4401 First += 2;
4402 Node *Name = parseName();
4403 if (Name == nullptr)
4404 return nullptr;
4405 return make<SpecialName>("guard variable for ", Name);
4406 }
4407 // GR <object name> # reference temporary for object
4408 case 'R': {
4409 First += 2;
4410 Node *Name = parseName();
4411 if (Name == nullptr)
4412 return nullptr;
4413 return make<SpecialName>("reference temporary for ", Name);
4414 }
4415 }
4416 }
4417 return nullptr;
4418}
4419
4420// <encoding> ::= <function name> <bare-function-type>
4421// ::= <data name>
4422// ::= <special-name>
4423Node *Db::parseEncoding() {
4424 // Always "tag" templates (insert them into Db::TemplateParams) unless we're
4425 // doing a second parse to resolve a forward template reference, in which case
4426 // we only tag templates if EncodingDepth > 1.
4427 // FIXME: This is kinda broken; it would be better to make a forward reference
4428 // and patch it all in one pass.
4429 SwapAndRestore<bool> SaveTagTemplates(TagTemplates,
4430 TagTemplates || EncodingDepth);
4431 SwapAndRestore<unsigned> SaveEncodingDepth(EncodingDepth, EncodingDepth + 1);
4432
4433 if (look() == 'G' || look() == 'T')
4434 return parseSpecialName();
4435
4436 auto IsEndOfEncoding = [&] {
4437 // The set of chars that can potentially follow an <encoding> (none of which
4438 // can start a <type>). Enumerating these allows us to avoid speculative
4439 // parsing.
4440 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
4441 };
4442
4443 NameState NameInfo;
4444 Node *Name = parseName(&NameInfo);
4445 if (Name == nullptr || IsEndOfEncoding())
4446 return Name;
4447
4448 TagTemplates = false;
4449
4450 Node *ReturnType = nullptr;
4451 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
4452 ReturnType = parseType();
4453 if (ReturnType == nullptr)
4454 return nullptr;
4455 }
4456
4457 if (consumeIf('v'))
4458 return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
4459 NameInfo.CVQualifiers,
4460 NameInfo.ReferenceQualifier);
4461
4462 size_t ParamsBegin = Names.size();
4463 do {
4464 Node *Ty = parseType();
4465 if (Ty == nullptr)
4466 return nullptr;
4467 Names.push_back(Ty);
4468 } while (!IsEndOfEncoding());
4469
4470 return make<FunctionEncoding>(ReturnType, Name,
4471 popTrailingNodeArray(ParamsBegin),
4472 NameInfo.CVQualifiers,
4473 NameInfo.ReferenceQualifier);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004474}
4475
4476template <class Float>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004477struct FloatData;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004478
4479template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004480struct FloatData<float>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004481{
4482 static const size_t mangled_size = 8;
4483 static const size_t max_demangled_size = 24;
Howard Hinnantc62cbea2013-06-17 20:25:21 +00004484 static constexpr const char* spec = "%af";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004485};
4486
Erik Pilkington0024acd2017-07-28 00:43:49 +00004487constexpr const char* FloatData<float>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004488
4489template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004490struct FloatData<double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004491{
4492 static const size_t mangled_size = 16;
4493 static const size_t max_demangled_size = 32;
4494 static constexpr const char* spec = "%a";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004495};
4496
Erik Pilkington0024acd2017-07-28 00:43:49 +00004497constexpr const char* FloatData<double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004498
4499template <>
Erik Pilkington0024acd2017-07-28 00:43:49 +00004500struct FloatData<long double>
Howard Hinnant6c33e762013-06-17 18:10:34 +00004501{
Dan Gohmand04ecd02016-01-13 16:39:30 +00004502#if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
4503 defined(__wasm__)
Daniel Sanders52cf98b2015-07-30 16:11:04 +00004504 static const size_t mangled_size = 32;
Ben Craig9ef2c6e2016-01-20 14:10:23 +00004505#elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
Logan Chien05d51bc2014-05-10 00:42:10 +00004506 static const size_t mangled_size = 16;
4507#else
Howard Hinnant6c33e762013-06-17 18:10:34 +00004508 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 +00004509#endif
Howard Hinnant6c33e762013-06-17 18:10:34 +00004510 static const size_t max_demangled_size = 40;
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004511 static constexpr const char *spec = "%LaL";
Howard Hinnant6c33e762013-06-17 18:10:34 +00004512};
4513
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004514constexpr const char *FloatData<long double>::spec;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004515
Erik Pilkingtonb679cfd2018-02-02 18:04:32 +00004516template <class Float> Node *Db::parseFloatingLiteral() {
4517 const size_t N = FloatData<Float>::mangled_size;
4518 if (numLeft() <= N)
4519 return nullptr;
4520 StringView Data(First, First + N);
4521 for (char C : Data)
4522 if (!std::isxdigit(C))
4523 return nullptr;
4524 First += N;
4525 if (!consumeIf('E'))
4526 return nullptr;
4527 return make<FloatExpr<Float>>(Data);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004528}
4529
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004530// <seq-id> ::= <0-9A-Z>+
4531bool Db::parseSeqId(size_t *Out) {
4532 if (!(look() >= '0' && look() <= '9') &&
4533 !(look() >= 'A' && look() <= 'Z'))
4534 return true;
4535
4536 size_t Id = 0;
4537 while (true) {
4538 if (look() >= '0' && look() <= '9') {
4539 Id *= 36;
4540 Id += static_cast<size_t>(look() - '0');
4541 } else if (look() >= 'A' && look() <= 'Z') {
4542 Id *= 36;
4543 Id += static_cast<size_t>(look() - 'A') + 10;
4544 } else {
4545 *Out = Id;
4546 return false;
4547 }
4548 ++First;
4549 }
4550}
4551
Howard Hinnant6c33e762013-06-17 18:10:34 +00004552// <substitution> ::= S <seq-id> _
4553// ::= S_
4554// <substitution> ::= Sa # ::std::allocator
4555// <substitution> ::= Sb # ::std::basic_string
4556// <substitution> ::= Ss # ::std::basic_string < char,
4557// ::std::char_traits<char>,
4558// ::std::allocator<char> >
4559// <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
4560// <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
4561// <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004562Node *Db::parseSubstitution() {
4563 if (!consumeIf('S'))
4564 return nullptr;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004565
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004566 if (std::islower(look())) {
4567 Node *SpecialSub;
4568 switch (look()) {
4569 case 'a':
4570 ++First;
4571 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator);
4572 break;
4573 case 'b':
4574 ++First;
4575 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string);
4576 break;
4577 case 's':
4578 ++First;
4579 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string);
4580 break;
4581 case 'i':
4582 ++First;
4583 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream);
4584 break;
4585 case 'o':
4586 ++First;
4587 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream);
4588 break;
4589 case 'd':
4590 ++First;
4591 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream);
4592 break;
4593 default:
4594 return nullptr;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004595 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004596 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
4597 // has ABI tags, the tags are appended to the substitution; the result is a
4598 // substitutable component.
4599 Node *WithTags = parseAbiTags(SpecialSub);
4600 if (WithTags != SpecialSub) {
4601 Subs.push_back(WithTags);
4602 SpecialSub = WithTags;
4603 }
4604 return SpecialSub;
4605 }
4606
4607 // ::= S_
4608 if (consumeIf('_')) {
4609 if (Subs.empty())
4610 return nullptr;
4611 return Subs[0];
4612 }
4613
4614 // ::= S <seq-id> _
4615 size_t Index = 0;
4616 if (parseSeqId(&Index))
4617 return nullptr;
4618 ++Index;
4619 if (!consumeIf('_') || Index >= Subs.size())
4620 return nullptr;
4621 return Subs[Index];
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004622}
4623
Howard Hinnant6c33e762013-06-17 18:10:34 +00004624// <template-param> ::= T_ # first template parameter
4625// ::= T <parameter-2 non-negative number> _
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004626Node *Db::parseTemplateParam() {
4627 if (!consumeIf('T'))
4628 return nullptr;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004629
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004630 if (consumeIf('_')) {
4631 if (TemplateParams.empty()) {
4632 FixForwardReferences = true;
4633 return make<NameType>("FORWARD_REFERENCE");
Howard Hinnant6c33e762013-06-17 18:10:34 +00004634 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004635 return TemplateParams[0];
4636 }
4637
4638 size_t Index;
4639 if (parsePositiveInteger(&Index))
4640 return nullptr;
4641 ++Index;
4642 if (!consumeIf('_'))
4643 return nullptr;
4644 if (Index >= TemplateParams.size()) {
4645 FixForwardReferences = true;
4646 return make<NameType>("FORWARD_REFERENCE");
4647 }
4648 return TemplateParams[Index];
Howard Hinnant6c33e762013-06-17 18:10:34 +00004649}
4650
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004651// <template-arg> ::= <type> # type or template
4652// ::= X <expression> E # expression
4653// ::= <expr-primary> # simple expressions
4654// ::= J <template-arg>* E # argument pack
4655// ::= LZ <encoding> E # extension
4656Node *Db::parseTemplateArg() {
4657 switch (look()) {
4658 case 'X': {
4659 ++First;
4660 Node *Arg = parseExpr();
4661 if (Arg == nullptr || !consumeIf('E'))
4662 return nullptr;
4663 return Arg;
4664 }
4665 case 'J': {
4666 ++First;
4667 size_t ArgsBegin = Names.size();
4668 while (!consumeIf('E')) {
4669 Node *Arg = parseTemplateArg();
4670 if (Arg == nullptr)
4671 return nullptr;
4672 Names.push_back(Arg);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004673 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004674 NodeArray Args = popTrailingNodeArray(ArgsBegin);
4675 return make<TemplateArgumentPack>(Args);
4676 }
4677 case 'L': {
4678 // ::= LZ <encoding> E # extension
4679 if (look(1) == 'Z') {
4680 First += 2;
4681 Node *Arg = parseEncoding();
4682 if (Arg == nullptr || !consumeIf('E'))
4683 return nullptr;
4684 return Arg;
4685 }
4686 // ::= <expr-primary> # simple expressions
4687 return parseExprPrimary();
4688 }
4689 default:
4690 return parseType();
4691 }
Howard Hinnant6c33e762013-06-17 18:10:34 +00004692}
4693
4694// <template-args> ::= I <template-arg>* E
4695// extension, the abi says <template-arg>+
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004696Node *Db::parseTemplateArgs() {
4697 if (!consumeIf('I'))
4698 return nullptr;
4699
4700 // <template-params> refer to the innermost <template-args>. Clear out any
4701 // outer args that we may have inserted into TemplateParams.
4702 if (TagTemplates)
4703 TemplateParams.clear();
4704
4705 size_t ArgsBegin = Names.size();
4706 while (!consumeIf('E')) {
4707 if (TagTemplates) {
4708 auto OldParams = std::move(TemplateParams);
4709 Node *Arg = parseTemplateArg();
4710 TemplateParams = std::move(OldParams);
4711 if (Arg == nullptr)
4712 return nullptr;
4713 Names.push_back(Arg);
4714 Node *TableEntry = Arg;
4715 if (Arg->getKind() == Node::KTemplateArgumentPack) {
4716 TableEntry = make<ParameterPack>(
4717 static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
4718 }
4719 TemplateParams.push_back(TableEntry);
4720 } else {
4721 Node *Arg = parseTemplateArg();
4722 if (Arg == nullptr)
4723 return nullptr;
4724 Names.push_back(Arg);
Howard Hinnant6c33e762013-06-17 18:10:34 +00004725 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004726 }
4727 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
Howard Hinnant6c33e762013-06-17 18:10:34 +00004728}
4729
Howard Hinnant6c33e762013-06-17 18:10:34 +00004730// <discriminator> := _ <non-negative number> # when number < 10
4731// := __ <non-negative number> _ # when number >= 10
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004732// extension := decimal-digit+ # at the end of string
Howard Hinnant6c33e762013-06-17 18:10:34 +00004733
4734const char*
4735parse_discriminator(const char* first, const char* last)
4736{
4737 // parse but ignore discriminator
4738 if (first != last)
4739 {
4740 if (*first == '_')
4741 {
4742 const char* t1 = first+1;
4743 if (t1 != last)
4744 {
4745 if (std::isdigit(*t1))
4746 first = t1+1;
4747 else if (*t1 == '_')
4748 {
4749 for (++t1; t1 != last && std::isdigit(*t1); ++t1)
4750 ;
4751 if (t1 != last && *t1 == '_')
4752 first = t1 + 1;
4753 }
4754 }
4755 }
4756 else if (std::isdigit(*first))
4757 {
4758 const char* t1 = first+1;
4759 for (; t1 != last && std::isdigit(*t1); ++t1)
4760 ;
Marshall Clow6c6d9cb2015-10-08 03:02:09 +00004761 if (t1 == last)
4762 first = last;
Howard Hinnant6c33e762013-06-17 18:10:34 +00004763 }
4764 }
4765 return first;
4766}
4767
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004768// <mangled-name> ::= _Z <encoding>
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004769// ::= <type>
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004770// extension ::= ___Z <encoding> _block_invoke
4771// extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
4772// extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
4773Node *Db::parse() {
4774 if (consumeIf("_Z")) {
4775 Node *Encoding = parseEncoding();
4776 if (Encoding == nullptr)
4777 return nullptr;
4778 if (look() == '.') {
4779 Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
4780 First = Last;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004781 }
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004782 if (numLeft() != 0)
4783 return nullptr;
4784 return Encoding;
4785 }
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004786
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004787 if (consumeIf("___Z")) {
4788 Node *Encoding = parseEncoding();
4789 if (Encoding == nullptr || !consumeIf("_block_invoke"))
4790 return nullptr;
4791 consumeIf('_');
4792 if (parseNumber().empty())
4793 return nullptr;
4794 if (numLeft() != 0)
4795 return nullptr;
4796 return make<SpecialName>("invocation function for block in ", Encoding);
4797 }
4798
4799 Node *Ty = parseType();
4800 if (numLeft() != 0)
4801 return nullptr;
4802 return Ty;
4803}
Howard Hinnant6c33e762013-06-17 18:10:34 +00004804} // unnamed namespace
4805
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004806enum {
4807 unknown_error = -4,
4808 invalid_args = -3,
4809 invalid_mangled_name = -2,
4810 memory_alloc_failure = -1,
4811 success = 0,
4812};
Erik Pilkington761e6b02018-01-31 20:17:06 +00004813
4814namespace __cxxabiv1 {
Saleem Abdulrasoolb4ec5792015-12-04 02:14:58 +00004815extern "C" _LIBCXXABI_FUNC_VIS char *
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004816__cxa_demangle(const char *MangledName, char *Buf, size_t *N, int *Status) {
4817 if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
4818 if (Status)
4819 *Status = invalid_args;
4820 return nullptr;
4821 }
4822
4823 size_t BufSize = Buf != nullptr ? *N : 0;
4824 int InternalStatus = success;
4825 size_t MangledNameLength = std::strlen(MangledName);
4826
4827 Db Parser(MangledName, MangledName + MangledNameLength);
4828 Node *AST = Parser.parse();
4829
4830 if (AST == nullptr)
4831 InternalStatus = invalid_mangled_name;
4832
4833 if (InternalStatus == success && Parser.FixForwardReferences &&
4834 !Parser.TemplateParams.empty()) {
4835 Parser.FixForwardReferences = false;
4836 Parser.TagTemplates = false;
4837 Parser.Names.clear();
4838 Parser.Subs.clear();
4839 Parser.First = MangledName;
4840 Parser.Last = MangledName + MangledNameLength;
4841 AST = Parser.parse();
4842 if (AST == nullptr || Parser.FixForwardReferences)
4843 InternalStatus = invalid_mangled_name;
4844 }
4845
4846 if (InternalStatus == success && AST->containsUnexpandedParameterPack())
4847 InternalStatus = invalid_mangled_name;
4848
4849 if (InternalStatus == success) {
4850 if (Buf == nullptr) {
4851 BufSize = 1024;
4852 Buf = static_cast<char*>(std::malloc(BufSize));
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004853 }
Saleem Abdulrasool8cfa5a32016-11-14 01:55:54 +00004854
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004855 if (Buf) {
4856 OutputStream Stream(Buf, BufSize);
4857 AST->print(Stream);
4858 Stream += '\0';
4859 if (N != nullptr)
4860 *N = Stream.getCurrentPosition();
4861 Buf = Stream.getBuffer();
4862 } else
4863 InternalStatus = memory_alloc_failure;
4864 }
Erik Pilkington0024acd2017-07-28 00:43:49 +00004865
Erik Pilkingtonf26c8d12018-03-06 14:21:10 +00004866 if (Status)
4867 *Status = InternalStatus;
4868 return InternalStatus == success ? Buf : nullptr;
Howard Hinnantd213ffd2011-05-05 15:27:28 +00004869}
Howard Hinnant6c33e762013-06-17 18:10:34 +00004870} // __cxxabiv1