19b3f38f9SIlya Biryukov //===- BuildTree.cpp ------------------------------------------*- C++ -*-=====//
29b3f38f9SIlya Biryukov //
39b3f38f9SIlya Biryukov // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
49b3f38f9SIlya Biryukov // See https://llvm.org/LICENSE.txt for license information.
59b3f38f9SIlya Biryukov // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69b3f38f9SIlya Biryukov //
79b3f38f9SIlya Biryukov //===----------------------------------------------------------------------===//
89b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/BuildTree.h"
97d382dcdSMarcel Hlopko #include "clang/AST/ASTFwd.h"
10e702bdb8SIlya Biryukov #include "clang/AST/Decl.h"
11e702bdb8SIlya Biryukov #include "clang/AST/DeclBase.h"
127d382dcdSMarcel Hlopko #include "clang/AST/DeclCXX.h"
137d382dcdSMarcel Hlopko #include "clang/AST/DeclarationName.h"
143785eb83SEduardo Caldas #include "clang/AST/Expr.h"
15ea8bba7eSEduardo Caldas #include "clang/AST/ExprCXX.h"
162325d6b4SEduardo Caldas #include "clang/AST/IgnoreExpr.h"
17134455a0SEduardo Caldas #include "clang/AST/OperationKinds.h"
189b3f38f9SIlya Biryukov #include "clang/AST/RecursiveASTVisitor.h"
199b3f38f9SIlya Biryukov #include "clang/AST/Stmt.h"
207d382dcdSMarcel Hlopko #include "clang/AST/TypeLoc.h"
217d382dcdSMarcel Hlopko #include "clang/AST/TypeLocVisitor.h"
229b3f38f9SIlya Biryukov #include "clang/Basic/LLVM.h"
239b3f38f9SIlya Biryukov #include "clang/Basic/SourceLocation.h"
249b3f38f9SIlya Biryukov #include "clang/Basic/SourceManager.h"
2588bf9b3dSMarcel Hlopko #include "clang/Basic/Specifiers.h"
269b3f38f9SIlya Biryukov #include "clang/Basic/TokenKinds.h"
279b3f38f9SIlya Biryukov #include "clang/Lex/Lexer.h"
281db5b348SEduardo Caldas #include "clang/Lex/LiteralSupport.h"
299b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Nodes.h"
309b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tokens.h"
319b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tree.h"
329b3f38f9SIlya Biryukov #include "llvm/ADT/ArrayRef.h"
33a711a3a4SMarcel Hlopko #include "llvm/ADT/DenseMap.h"
34a711a3a4SMarcel Hlopko #include "llvm/ADT/PointerUnion.h"
359b3f38f9SIlya Biryukov #include "llvm/ADT/STLExtras.h"
367d382dcdSMarcel Hlopko #include "llvm/ADT/ScopeExit.h"
379b3f38f9SIlya Biryukov #include "llvm/ADT/SmallVector.h"
389b3f38f9SIlya Biryukov #include "llvm/Support/Allocator.h"
399b3f38f9SIlya Biryukov #include "llvm/Support/Casting.h"
4096065cf7SIlya Biryukov #include "llvm/Support/Compiler.h"
419b3f38f9SIlya Biryukov #include "llvm/Support/FormatVariadic.h"
421ad15046SIlya Biryukov #include "llvm/Support/MemoryBuffer.h"
439b3f38f9SIlya Biryukov #include "llvm/Support/raw_ostream.h"
44a711a3a4SMarcel Hlopko #include <cstddef>
459b3f38f9SIlya Biryukov #include <map>
469b3f38f9SIlya Biryukov 
479b3f38f9SIlya Biryukov using namespace clang;
489b3f38f9SIlya Biryukov 
492325d6b4SEduardo Caldas // Ignores the implicit `CXXConstructExpr` for copy/move constructor calls
502325d6b4SEduardo Caldas // generated by the compiler, as well as in implicit conversions like the one
512325d6b4SEduardo Caldas // wrapping `1` in `X x = 1;`.
522325d6b4SEduardo Caldas static Expr *IgnoreImplicitConstructorSingleStep(Expr *E) {
532325d6b4SEduardo Caldas   if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
542325d6b4SEduardo Caldas     auto NumArgs = C->getNumArgs();
552325d6b4SEduardo Caldas     if (NumArgs == 1 || (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
562325d6b4SEduardo Caldas       Expr *A = C->getArg(0);
572325d6b4SEduardo Caldas       if (C->getParenOrBraceRange().isInvalid())
582325d6b4SEduardo Caldas         return A;
592325d6b4SEduardo Caldas     }
602325d6b4SEduardo Caldas   }
612325d6b4SEduardo Caldas   return E;
622325d6b4SEduardo Caldas }
632325d6b4SEduardo Caldas 
64134455a0SEduardo Caldas // In:
65134455a0SEduardo Caldas // struct X {
66134455a0SEduardo Caldas //   X(int)
67134455a0SEduardo Caldas // };
68134455a0SEduardo Caldas // X x = X(1);
69134455a0SEduardo Caldas // Ignores the implicit `CXXFunctionalCastExpr` that wraps
70134455a0SEduardo Caldas // `CXXConstructExpr X(1)`.
71134455a0SEduardo Caldas static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
72134455a0SEduardo Caldas   if (auto *F = dyn_cast<CXXFunctionalCastExpr>(E)) {
73134455a0SEduardo Caldas     if (F->getCastKind() == CK_ConstructorConversion)
74134455a0SEduardo Caldas       return F->getSubExpr();
75134455a0SEduardo Caldas   }
76134455a0SEduardo Caldas   return E;
77134455a0SEduardo Caldas }
78134455a0SEduardo Caldas 
792325d6b4SEduardo Caldas static Expr *IgnoreImplicit(Expr *E) {
802325d6b4SEduardo Caldas   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
81134455a0SEduardo Caldas                          IgnoreImplicitConstructorSingleStep,
82134455a0SEduardo Caldas                          IgnoreCXXFunctionalCastExprWrappingConstructor);
832325d6b4SEduardo Caldas }
842325d6b4SEduardo Caldas 
8596065cf7SIlya Biryukov LLVM_ATTRIBUTE_UNUSED
862325d6b4SEduardo Caldas static bool isImplicitExpr(Expr *E) { return IgnoreImplicit(E) != E; }
8758fa50f4SIlya Biryukov 
887d382dcdSMarcel Hlopko namespace {
897d382dcdSMarcel Hlopko /// Get start location of the Declarator from the TypeLoc.
907d382dcdSMarcel Hlopko /// E.g.:
917d382dcdSMarcel Hlopko ///   loc of `(` in `int (a)`
927d382dcdSMarcel Hlopko ///   loc of `*` in `int *(a)`
937d382dcdSMarcel Hlopko ///   loc of the first `(` in `int (*a)(int)`
947d382dcdSMarcel Hlopko ///   loc of the `*` in `int *(a)(int)`
957d382dcdSMarcel Hlopko ///   loc of the first `*` in `const int *const *volatile a;`
967d382dcdSMarcel Hlopko ///
977d382dcdSMarcel Hlopko /// It is non-trivial to get the start location because TypeLocs are stored
987d382dcdSMarcel Hlopko /// inside out. In the example above `*volatile` is the TypeLoc returned
997d382dcdSMarcel Hlopko /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()`
1007d382dcdSMarcel Hlopko /// returns.
1017d382dcdSMarcel Hlopko struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> {
1027d382dcdSMarcel Hlopko   SourceLocation VisitParenTypeLoc(ParenTypeLoc T) {
1037d382dcdSMarcel Hlopko     auto L = Visit(T.getInnerLoc());
1047d382dcdSMarcel Hlopko     if (L.isValid())
1057d382dcdSMarcel Hlopko       return L;
1067d382dcdSMarcel Hlopko     return T.getLParenLoc();
1077d382dcdSMarcel Hlopko   }
1087d382dcdSMarcel Hlopko 
1097d382dcdSMarcel Hlopko   // Types spelled in the prefix part of the declarator.
1107d382dcdSMarcel Hlopko   SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) {
1117d382dcdSMarcel Hlopko     return HandlePointer(T);
1127d382dcdSMarcel Hlopko   }
1137d382dcdSMarcel Hlopko 
1147d382dcdSMarcel Hlopko   SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
1157d382dcdSMarcel Hlopko     return HandlePointer(T);
1167d382dcdSMarcel Hlopko   }
1177d382dcdSMarcel Hlopko 
1187d382dcdSMarcel Hlopko   SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
1197d382dcdSMarcel Hlopko     return HandlePointer(T);
1207d382dcdSMarcel Hlopko   }
1217d382dcdSMarcel Hlopko 
1227d382dcdSMarcel Hlopko   SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) {
1237d382dcdSMarcel Hlopko     return HandlePointer(T);
1247d382dcdSMarcel Hlopko   }
1257d382dcdSMarcel Hlopko 
1267d382dcdSMarcel Hlopko   SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) {
1277d382dcdSMarcel Hlopko     return HandlePointer(T);
1287d382dcdSMarcel Hlopko   }
1297d382dcdSMarcel Hlopko 
1307d382dcdSMarcel Hlopko   // All other cases are not important, as they are either part of declaration
1317d382dcdSMarcel Hlopko   // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on
1327d382dcdSMarcel Hlopko   // existing declarators (e.g. QualifiedTypeLoc). They cannot start the
1337d382dcdSMarcel Hlopko   // declarator themselves, but their underlying type can.
1347d382dcdSMarcel Hlopko   SourceLocation VisitTypeLoc(TypeLoc T) {
1357d382dcdSMarcel Hlopko     auto N = T.getNextTypeLoc();
1367d382dcdSMarcel Hlopko     if (!N)
1377d382dcdSMarcel Hlopko       return SourceLocation();
1387d382dcdSMarcel Hlopko     return Visit(N);
1397d382dcdSMarcel Hlopko   }
1407d382dcdSMarcel Hlopko 
1417d382dcdSMarcel Hlopko   SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) {
1427d382dcdSMarcel Hlopko     if (T.getTypePtr()->hasTrailingReturn())
1437d382dcdSMarcel Hlopko       return SourceLocation(); // avoid recursing into the suffix of declarator.
1447d382dcdSMarcel Hlopko     return VisitTypeLoc(T);
1457d382dcdSMarcel Hlopko   }
1467d382dcdSMarcel Hlopko 
1477d382dcdSMarcel Hlopko private:
1487d382dcdSMarcel Hlopko   template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) {
1497d382dcdSMarcel Hlopko     auto L = Visit(T.getPointeeLoc());
1507d382dcdSMarcel Hlopko     if (L.isValid())
1517d382dcdSMarcel Hlopko       return L;
1527d382dcdSMarcel Hlopko     return T.getLocalSourceRange().getBegin();
1537d382dcdSMarcel Hlopko   }
1547d382dcdSMarcel Hlopko };
1557d382dcdSMarcel Hlopko } // namespace
1567d382dcdSMarcel Hlopko 
157f5087d5cSEduardo Caldas static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args) {
158*16ceb44eSKazu Hirata   auto FirstDefaultArg =
159*16ceb44eSKazu Hirata       llvm::find_if(Args, [](auto It) { return isa<CXXDefaultArgExpr>(It); });
16087f0b51dSEduardo Caldas   return llvm::make_range(Args.begin(), FirstDefaultArg);
161f5087d5cSEduardo Caldas }
162f5087d5cSEduardo Caldas 
163ea8bba7eSEduardo Caldas static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
164ea8bba7eSEduardo Caldas   switch (E.getOperator()) {
165ea8bba7eSEduardo Caldas   // Comparison
166ea8bba7eSEduardo Caldas   case OO_EqualEqual:
167ea8bba7eSEduardo Caldas   case OO_ExclaimEqual:
168ea8bba7eSEduardo Caldas   case OO_Greater:
169ea8bba7eSEduardo Caldas   case OO_GreaterEqual:
170ea8bba7eSEduardo Caldas   case OO_Less:
171ea8bba7eSEduardo Caldas   case OO_LessEqual:
172ea8bba7eSEduardo Caldas   case OO_Spaceship:
173ea8bba7eSEduardo Caldas   // Assignment
174ea8bba7eSEduardo Caldas   case OO_Equal:
175ea8bba7eSEduardo Caldas   case OO_SlashEqual:
176ea8bba7eSEduardo Caldas   case OO_PercentEqual:
177ea8bba7eSEduardo Caldas   case OO_CaretEqual:
178ea8bba7eSEduardo Caldas   case OO_PipeEqual:
179ea8bba7eSEduardo Caldas   case OO_LessLessEqual:
180ea8bba7eSEduardo Caldas   case OO_GreaterGreaterEqual:
181ea8bba7eSEduardo Caldas   case OO_PlusEqual:
182ea8bba7eSEduardo Caldas   case OO_MinusEqual:
183ea8bba7eSEduardo Caldas   case OO_StarEqual:
184ea8bba7eSEduardo Caldas   case OO_AmpEqual:
185ea8bba7eSEduardo Caldas   // Binary computation
186ea8bba7eSEduardo Caldas   case OO_Slash:
187ea8bba7eSEduardo Caldas   case OO_Percent:
188ea8bba7eSEduardo Caldas   case OO_Caret:
189ea8bba7eSEduardo Caldas   case OO_Pipe:
190ea8bba7eSEduardo Caldas   case OO_LessLess:
191ea8bba7eSEduardo Caldas   case OO_GreaterGreater:
192ea8bba7eSEduardo Caldas   case OO_AmpAmp:
193ea8bba7eSEduardo Caldas   case OO_PipePipe:
194ea8bba7eSEduardo Caldas   case OO_ArrowStar:
195ea8bba7eSEduardo Caldas   case OO_Comma:
196ea8bba7eSEduardo Caldas     return syntax::NodeKind::BinaryOperatorExpression;
197ea8bba7eSEduardo Caldas   case OO_Tilde:
198ea8bba7eSEduardo Caldas   case OO_Exclaim:
199ea8bba7eSEduardo Caldas     return syntax::NodeKind::PrefixUnaryOperatorExpression;
200ea8bba7eSEduardo Caldas   // Prefix/Postfix increment/decrement
201ea8bba7eSEduardo Caldas   case OO_PlusPlus:
202ea8bba7eSEduardo Caldas   case OO_MinusMinus:
203ea8bba7eSEduardo Caldas     switch (E.getNumArgs()) {
204ea8bba7eSEduardo Caldas     case 1:
205ea8bba7eSEduardo Caldas       return syntax::NodeKind::PrefixUnaryOperatorExpression;
206ea8bba7eSEduardo Caldas     case 2:
207ea8bba7eSEduardo Caldas       return syntax::NodeKind::PostfixUnaryOperatorExpression;
208ea8bba7eSEduardo Caldas     default:
209ea8bba7eSEduardo Caldas       llvm_unreachable("Invalid number of arguments for operator");
210ea8bba7eSEduardo Caldas     }
211ea8bba7eSEduardo Caldas   // Operators that can be unary or binary
212ea8bba7eSEduardo Caldas   case OO_Plus:
213ea8bba7eSEduardo Caldas   case OO_Minus:
214ea8bba7eSEduardo Caldas   case OO_Star:
215ea8bba7eSEduardo Caldas   case OO_Amp:
216ea8bba7eSEduardo Caldas     switch (E.getNumArgs()) {
217ea8bba7eSEduardo Caldas     case 1:
218ea8bba7eSEduardo Caldas       return syntax::NodeKind::PrefixUnaryOperatorExpression;
219ea8bba7eSEduardo Caldas     case 2:
220ea8bba7eSEduardo Caldas       return syntax::NodeKind::BinaryOperatorExpression;
221ea8bba7eSEduardo Caldas     default:
222ea8bba7eSEduardo Caldas       llvm_unreachable("Invalid number of arguments for operator");
223ea8bba7eSEduardo Caldas     }
224ea8bba7eSEduardo Caldas     return syntax::NodeKind::BinaryOperatorExpression;
225ea8bba7eSEduardo Caldas   // Not yet supported by SyntaxTree
226ea8bba7eSEduardo Caldas   case OO_New:
227ea8bba7eSEduardo Caldas   case OO_Delete:
228ea8bba7eSEduardo Caldas   case OO_Array_New:
229ea8bba7eSEduardo Caldas   case OO_Array_Delete:
230ea8bba7eSEduardo Caldas   case OO_Coawait:
231ea8bba7eSEduardo Caldas   case OO_Subscript:
232ea8bba7eSEduardo Caldas   case OO_Arrow:
233ea8bba7eSEduardo Caldas     return syntax::NodeKind::UnknownExpression;
2342de2ca34SEduardo Caldas   case OO_Call:
2352de2ca34SEduardo Caldas     return syntax::NodeKind::CallExpression;
236ea8bba7eSEduardo Caldas   case OO_Conditional: // not overloadable
237ea8bba7eSEduardo Caldas   case NUM_OVERLOADED_OPERATORS:
238ea8bba7eSEduardo Caldas   case OO_None:
239ea8bba7eSEduardo Caldas     llvm_unreachable("Not an overloadable operator");
240ea8bba7eSEduardo Caldas   }
241397c6820SSimon Pilgrim   llvm_unreachable("Unknown OverloadedOperatorKind enum");
242ea8bba7eSEduardo Caldas }
243ea8bba7eSEduardo Caldas 
24438bc0060SEduardo Caldas /// Get the start of the qualified name. In the examples below it gives the
24538bc0060SEduardo Caldas /// location of the `^`:
24638bc0060SEduardo Caldas ///     `int ^a;`
247a1461953SEduardo Caldas ///     `int *^a;`
24838bc0060SEduardo Caldas ///     `int ^a::S::f(){}`
24938bc0060SEduardo Caldas static SourceLocation getQualifiedNameStart(NamedDecl *D) {
25038bc0060SEduardo Caldas   assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
25138bc0060SEduardo Caldas          "only DeclaratorDecl and TypedefNameDecl are supported.");
25238bc0060SEduardo Caldas 
25338bc0060SEduardo Caldas   auto DN = D->getDeclName();
25438bc0060SEduardo Caldas   bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
25538bc0060SEduardo Caldas   if (IsAnonymous)
25638bc0060SEduardo Caldas     return SourceLocation();
25738bc0060SEduardo Caldas 
25838bc0060SEduardo Caldas   if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
25938bc0060SEduardo Caldas     if (DD->getQualifierLoc()) {
26038bc0060SEduardo Caldas       return DD->getQualifierLoc().getBeginLoc();
26138bc0060SEduardo Caldas     }
26238bc0060SEduardo Caldas   }
26338bc0060SEduardo Caldas 
26438bc0060SEduardo Caldas   return D->getLocation();
26538bc0060SEduardo Caldas }
26638bc0060SEduardo Caldas 
26738bc0060SEduardo Caldas /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl].
26838bc0060SEduardo Caldas ///     `int a;` -> range of ``,
26938bc0060SEduardo Caldas ///     `int *a = nullptr` -> range of `= nullptr`.
27038bc0060SEduardo Caldas ///     `int a{}` -> range of `{}`.
27138bc0060SEduardo Caldas ///     `int a()` -> range of `()`.
27238bc0060SEduardo Caldas static SourceRange getInitializerRange(Decl *D) {
27338bc0060SEduardo Caldas   if (auto *V = dyn_cast<VarDecl>(D)) {
27438bc0060SEduardo Caldas     auto *I = V->getInit();
27538bc0060SEduardo Caldas     // Initializers in range-based-for are not part of the declarator
27638bc0060SEduardo Caldas     if (I && !V->isCXXForRangeDecl())
27738bc0060SEduardo Caldas       return I->getSourceRange();
27838bc0060SEduardo Caldas   }
27938bc0060SEduardo Caldas 
28038bc0060SEduardo Caldas   return SourceRange();
28138bc0060SEduardo Caldas }
28238bc0060SEduardo Caldas 
2837d382dcdSMarcel Hlopko /// Gets the range of declarator as defined by the C++ grammar. E.g.
2847d382dcdSMarcel Hlopko ///     `int a;` -> range of `a`,
2857d382dcdSMarcel Hlopko ///     `int *a;` -> range of `*a`,
2867d382dcdSMarcel Hlopko ///     `int a[10];` -> range of `a[10]`,
2877d382dcdSMarcel Hlopko ///     `int a[1][2][3];` -> range of `a[1][2][3]`,
2887d382dcdSMarcel Hlopko ///     `int *a = nullptr` -> range of `*a = nullptr`.
28938bc0060SEduardo Caldas ///     `int S::f(){}` -> range of `S::f()`.
290a1461953SEduardo Caldas /// FIXME: \p Name must be a source range.
2917d382dcdSMarcel Hlopko static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
2927d382dcdSMarcel Hlopko                                       SourceLocation Name,
2937d382dcdSMarcel Hlopko                                       SourceRange Initializer) {
2947d382dcdSMarcel Hlopko   SourceLocation Start = GetStartLoc().Visit(T);
29538bc0060SEduardo Caldas   SourceLocation End = T.getEndLoc();
2967d382dcdSMarcel Hlopko   if (Name.isValid()) {
2977d382dcdSMarcel Hlopko     if (Start.isInvalid())
2987d382dcdSMarcel Hlopko       Start = Name;
299e159a3ceSHaojian Wu     // End of TypeLoc could be invalid if the type is invalid, fallback to the
300e159a3ceSHaojian Wu     // NameLoc.
301e159a3ceSHaojian Wu     if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name))
3027d382dcdSMarcel Hlopko       End = Name;
3037d382dcdSMarcel Hlopko   }
3047d382dcdSMarcel Hlopko   if (Initializer.isValid()) {
305cdce2fe5SMarcel Hlopko     auto InitializerEnd = Initializer.getEnd();
306f33c2c27SEduardo Caldas     assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
307f33c2c27SEduardo Caldas            End == InitializerEnd);
308cdce2fe5SMarcel Hlopko     End = InitializerEnd;
3097d382dcdSMarcel Hlopko   }
3107d382dcdSMarcel Hlopko   return SourceRange(Start, End);
3117d382dcdSMarcel Hlopko }
3127d382dcdSMarcel Hlopko 
313a711a3a4SMarcel Hlopko namespace {
314a711a3a4SMarcel Hlopko /// All AST hierarchy roots that can be represented as pointers.
315a711a3a4SMarcel Hlopko using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>;
316a711a3a4SMarcel Hlopko /// Maintains a mapping from AST to syntax tree nodes. This class will get more
317a711a3a4SMarcel Hlopko /// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
318a711a3a4SMarcel Hlopko /// FIXME: expose this as public API.
319a711a3a4SMarcel Hlopko class ASTToSyntaxMapping {
320a711a3a4SMarcel Hlopko public:
321a711a3a4SMarcel Hlopko   void add(ASTPtr From, syntax::Tree *To) {
322a711a3a4SMarcel Hlopko     assert(To != nullptr);
323a711a3a4SMarcel Hlopko     assert(!From.isNull());
324a711a3a4SMarcel Hlopko 
325a711a3a4SMarcel Hlopko     bool Added = Nodes.insert({From, To}).second;
326a711a3a4SMarcel Hlopko     (void)Added;
327a711a3a4SMarcel Hlopko     assert(Added && "mapping added twice");
328a711a3a4SMarcel Hlopko   }
329a711a3a4SMarcel Hlopko 
330f9500cc4SEduardo Caldas   void add(NestedNameSpecifierLoc From, syntax::Tree *To) {
331f9500cc4SEduardo Caldas     assert(To != nullptr);
332f9500cc4SEduardo Caldas     assert(From.hasQualifier());
333f9500cc4SEduardo Caldas 
334f9500cc4SEduardo Caldas     bool Added = NNSNodes.insert({From, To}).second;
335f9500cc4SEduardo Caldas     (void)Added;
336f9500cc4SEduardo Caldas     assert(Added && "mapping added twice");
337f9500cc4SEduardo Caldas   }
338f9500cc4SEduardo Caldas 
339a711a3a4SMarcel Hlopko   syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
340a711a3a4SMarcel Hlopko 
341f9500cc4SEduardo Caldas   syntax::Tree *find(NestedNameSpecifierLoc P) const {
342f9500cc4SEduardo Caldas     return NNSNodes.lookup(P);
343f9500cc4SEduardo Caldas   }
344f9500cc4SEduardo Caldas 
345a711a3a4SMarcel Hlopko private:
346a711a3a4SMarcel Hlopko   llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes;
347f9500cc4SEduardo Caldas   llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes;
348a711a3a4SMarcel Hlopko };
349a711a3a4SMarcel Hlopko } // namespace
350a711a3a4SMarcel Hlopko 
3519b3f38f9SIlya Biryukov /// A helper class for constructing the syntax tree while traversing a clang
3529b3f38f9SIlya Biryukov /// AST.
3539b3f38f9SIlya Biryukov ///
3549b3f38f9SIlya Biryukov /// At each point of the traversal we maintain a list of pending nodes.
3559b3f38f9SIlya Biryukov /// Initially all tokens are added as pending nodes. When processing a clang AST
3569b3f38f9SIlya Biryukov /// node, the clients need to:
3579b3f38f9SIlya Biryukov ///   - create a corresponding syntax node,
3589b3f38f9SIlya Biryukov ///   - assign roles to all pending child nodes with 'markChild' and
3599b3f38f9SIlya Biryukov ///     'markChildToken',
3609b3f38f9SIlya Biryukov ///   - replace the child nodes with the new syntax node in the pending list
3619b3f38f9SIlya Biryukov ///     with 'foldNode'.
3629b3f38f9SIlya Biryukov ///
3639b3f38f9SIlya Biryukov /// Note that all children are expected to be processed when building a node.
3649b3f38f9SIlya Biryukov ///
3659b3f38f9SIlya Biryukov /// Call finalize() to finish building the tree and consume the root node.
3669b3f38f9SIlya Biryukov class syntax::TreeBuilder {
3679b3f38f9SIlya Biryukov public:
368c1bbefefSIlya Biryukov   TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) {
3694c14ee61SEduardo Caldas     for (const auto &T : Arena.getTokenBuffer().expandedTokens())
37078194118SMikhail Maltsev       LocationToToken.insert({T.location(), &T});
371c1bbefefSIlya Biryukov   }
3729b3f38f9SIlya Biryukov 
3734c14ee61SEduardo Caldas   llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); }
3744c14ee61SEduardo Caldas   const SourceManager &sourceManager() const {
3754c14ee61SEduardo Caldas     return Arena.getSourceManager();
3764c14ee61SEduardo Caldas   }
3779b3f38f9SIlya Biryukov 
3789b3f38f9SIlya Biryukov   /// Populate children for \p New node, assuming it covers tokens from \p
3799b3f38f9SIlya Biryukov   /// Range.
380ba41a0f7SEduardo Caldas   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) {
381a711a3a4SMarcel Hlopko     assert(New);
382a711a3a4SMarcel Hlopko     Pending.foldChildren(Arena, Range, New);
383a711a3a4SMarcel Hlopko     if (From)
384a711a3a4SMarcel Hlopko       Mapping.add(From, New);
385a711a3a4SMarcel Hlopko   }
386f9500cc4SEduardo Caldas 
387ba41a0f7SEduardo Caldas   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) {
388a711a3a4SMarcel Hlopko     // FIXME: add mapping for TypeLocs
389a711a3a4SMarcel Hlopko     foldNode(Range, New, nullptr);
390a711a3a4SMarcel Hlopko   }
3919b3f38f9SIlya Biryukov 
392f9500cc4SEduardo Caldas   void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
393f9500cc4SEduardo Caldas                 NestedNameSpecifierLoc From) {
394f9500cc4SEduardo Caldas     assert(New);
395f9500cc4SEduardo Caldas     Pending.foldChildren(Arena, Range, New);
396f9500cc4SEduardo Caldas     if (From)
397f9500cc4SEduardo Caldas       Mapping.add(From, New);
3988abb5fb6SEduardo Caldas   }
399f9500cc4SEduardo Caldas 
4005011d431SEduardo Caldas   /// Populate children for \p New list, assuming it covers tokens from a
4015011d431SEduardo Caldas   /// subrange of \p SuperRange.
4025011d431SEduardo Caldas   void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New,
4035011d431SEduardo Caldas                 ASTPtr From) {
4045011d431SEduardo Caldas     assert(New);
4055011d431SEduardo Caldas     auto ListRange = Pending.shrinkToFitList(SuperRange);
4065011d431SEduardo Caldas     Pending.foldChildren(Arena, ListRange, New);
4075011d431SEduardo Caldas     if (From)
4085011d431SEduardo Caldas       Mapping.add(From, New);
4095011d431SEduardo Caldas   }
4105011d431SEduardo Caldas 
411e702bdb8SIlya Biryukov   /// Notifies that we should not consume trailing semicolon when computing
412e702bdb8SIlya Biryukov   /// token range of \p D.
4137d382dcdSMarcel Hlopko   void noticeDeclWithoutSemicolon(Decl *D);
414e702bdb8SIlya Biryukov 
41558fa50f4SIlya Biryukov   /// Mark the \p Child node with a corresponding \p Role. All marked children
41658fa50f4SIlya Biryukov   /// should be consumed by foldNode.
4177d382dcdSMarcel Hlopko   /// When called on expressions (clang::Expr is derived from clang::Stmt),
41858fa50f4SIlya Biryukov   /// wraps expressions into expression statement.
41958fa50f4SIlya Biryukov   void markStmtChild(Stmt *Child, NodeRole Role);
42058fa50f4SIlya Biryukov   /// Should be called for expressions in non-statement position to avoid
42158fa50f4SIlya Biryukov   /// wrapping into expression statement.
42258fa50f4SIlya Biryukov   void markExprChild(Expr *Child, NodeRole Role);
4239b3f38f9SIlya Biryukov   /// Set role for a token starting at \p Loc.
424def65bb4SIlya Biryukov   void markChildToken(SourceLocation Loc, NodeRole R);
4257d382dcdSMarcel Hlopko   /// Set role for \p T.
4267d382dcdSMarcel Hlopko   void markChildToken(const syntax::Token *T, NodeRole R);
4277d382dcdSMarcel Hlopko 
428a711a3a4SMarcel Hlopko   /// Set role for \p N.
429a711a3a4SMarcel Hlopko   void markChild(syntax::Node *N, NodeRole R);
430a711a3a4SMarcel Hlopko   /// Set role for the syntax node matching \p N.
431a711a3a4SMarcel Hlopko   void markChild(ASTPtr N, NodeRole R);
432f9500cc4SEduardo Caldas   /// Set role for the syntax node matching \p N.
433f9500cc4SEduardo Caldas   void markChild(NestedNameSpecifierLoc N, NodeRole R);
4349b3f38f9SIlya Biryukov 
4359b3f38f9SIlya Biryukov   /// Finish building the tree and consume the root node.
4369b3f38f9SIlya Biryukov   syntax::TranslationUnit *finalize() && {
4374c14ee61SEduardo Caldas     auto Tokens = Arena.getTokenBuffer().expandedTokens();
438bfbf6b6cSIlya Biryukov     assert(!Tokens.empty());
439bfbf6b6cSIlya Biryukov     assert(Tokens.back().kind() == tok::eof);
440bfbf6b6cSIlya Biryukov 
4419b3f38f9SIlya Biryukov     // Build the root of the tree, consuming all the children.
4421ad15046SIlya Biryukov     Pending.foldChildren(Arena, Tokens.drop_back(),
4434c14ee61SEduardo Caldas                          new (Arena.getAllocator()) syntax::TranslationUnit);
4449b3f38f9SIlya Biryukov 
4453b929fe7SIlya Biryukov     auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize());
4463b929fe7SIlya Biryukov     TU->assertInvariantsRecursive();
4473b929fe7SIlya Biryukov     return TU;
4489b3f38f9SIlya Biryukov   }
4499b3f38f9SIlya Biryukov 
45088bf9b3dSMarcel Hlopko   /// Finds a token starting at \p L. The token must exist if \p L is valid.
45188bf9b3dSMarcel Hlopko   const syntax::Token *findToken(SourceLocation L) const;
45288bf9b3dSMarcel Hlopko 
453a711a3a4SMarcel Hlopko   /// Finds the syntax tokens corresponding to the \p SourceRange.
454ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getRange(SourceRange Range) const {
455a711a3a4SMarcel Hlopko     assert(Range.isValid());
456a711a3a4SMarcel Hlopko     return getRange(Range.getBegin(), Range.getEnd());
457a711a3a4SMarcel Hlopko   }
458a711a3a4SMarcel Hlopko 
459a711a3a4SMarcel Hlopko   /// Finds the syntax tokens corresponding to the passed source locations.
4609b3f38f9SIlya Biryukov   /// \p First is the start position of the first token and \p Last is the start
4619b3f38f9SIlya Biryukov   /// position of the last token.
462ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getRange(SourceLocation First,
4639b3f38f9SIlya Biryukov                                    SourceLocation Last) const {
4649b3f38f9SIlya Biryukov     assert(First.isValid());
4659b3f38f9SIlya Biryukov     assert(Last.isValid());
4669b3f38f9SIlya Biryukov     assert(First == Last ||
4674c14ee61SEduardo Caldas            Arena.getSourceManager().isBeforeInTranslationUnit(First, Last));
4689b3f38f9SIlya Biryukov     return llvm::makeArrayRef(findToken(First), std::next(findToken(Last)));
4699b3f38f9SIlya Biryukov   }
47088bf9b3dSMarcel Hlopko 
471ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token>
47288bf9b3dSMarcel Hlopko   getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
473a711a3a4SMarcel Hlopko     auto Tokens = getRange(D->getSourceRange());
47488bf9b3dSMarcel Hlopko     return maybeAppendSemicolon(Tokens, D);
47588bf9b3dSMarcel Hlopko   }
47688bf9b3dSMarcel Hlopko 
477cdce2fe5SMarcel Hlopko   /// Returns true if \p D is the last declarator in a chain and is thus
478cdce2fe5SMarcel Hlopko   /// reponsible for creating SimpleDeclaration for the whole chain.
47938bc0060SEduardo Caldas   bool isResponsibleForCreatingDeclaration(const Decl *D) const {
48038bc0060SEduardo Caldas     assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
481cdce2fe5SMarcel Hlopko            "only DeclaratorDecl and TypedefNameDecl are supported.");
482cdce2fe5SMarcel Hlopko 
483cdce2fe5SMarcel Hlopko     const Decl *Next = D->getNextDeclInContext();
484cdce2fe5SMarcel Hlopko 
485cdce2fe5SMarcel Hlopko     // There's no next sibling, this one is responsible.
486cdce2fe5SMarcel Hlopko     if (Next == nullptr) {
487cdce2fe5SMarcel Hlopko       return true;
488cdce2fe5SMarcel Hlopko     }
489cdce2fe5SMarcel Hlopko 
490cdce2fe5SMarcel Hlopko     // Next sibling is not the same type, this one is responsible.
49138bc0060SEduardo Caldas     if (D->getKind() != Next->getKind()) {
492cdce2fe5SMarcel Hlopko       return true;
493cdce2fe5SMarcel Hlopko     }
494cdce2fe5SMarcel Hlopko     // Next sibling doesn't begin at the same loc, it must be a different
495cdce2fe5SMarcel Hlopko     // declaration, so this declarator is responsible.
49638bc0060SEduardo Caldas     if (Next->getBeginLoc() != D->getBeginLoc()) {
497cdce2fe5SMarcel Hlopko       return true;
498cdce2fe5SMarcel Hlopko     }
499cdce2fe5SMarcel Hlopko 
500cdce2fe5SMarcel Hlopko     // NextT is a member of the same declaration, and we need the last member to
501cdce2fe5SMarcel Hlopko     // create declaration. This one is not responsible.
502cdce2fe5SMarcel Hlopko     return false;
503cdce2fe5SMarcel Hlopko   }
504cdce2fe5SMarcel Hlopko 
505ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
506ba41a0f7SEduardo Caldas     ArrayRef<syntax::Token> Tokens;
50788bf9b3dSMarcel Hlopko     // We want to drop the template parameters for specializations.
508ba41a0f7SEduardo Caldas     if (const auto *S = dyn_cast<TagDecl>(D))
50988bf9b3dSMarcel Hlopko       Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc());
51088bf9b3dSMarcel Hlopko     else
511a711a3a4SMarcel Hlopko       Tokens = getRange(D->getSourceRange());
51288bf9b3dSMarcel Hlopko     return maybeAppendSemicolon(Tokens, D);
5139b3f38f9SIlya Biryukov   }
514cdce2fe5SMarcel Hlopko 
515ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
516a711a3a4SMarcel Hlopko     return getRange(E->getSourceRange());
51758fa50f4SIlya Biryukov   }
518cdce2fe5SMarcel Hlopko 
51958fa50f4SIlya Biryukov   /// Find the adjusted range for the statement, consuming the trailing
52058fa50f4SIlya Biryukov   /// semicolon when needed.
521ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
522a711a3a4SMarcel Hlopko     auto Tokens = getRange(S->getSourceRange());
52358fa50f4SIlya Biryukov     if (isa<CompoundStmt>(S))
52458fa50f4SIlya Biryukov       return Tokens;
52558fa50f4SIlya Biryukov 
52658fa50f4SIlya Biryukov     // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and
52758fa50f4SIlya Biryukov     // all statements that end with those. Consume this semicolon here.
528e702bdb8SIlya Biryukov     if (Tokens.back().kind() == tok::semi)
529e702bdb8SIlya Biryukov       return Tokens;
530e702bdb8SIlya Biryukov     return withTrailingSemicolon(Tokens);
531e702bdb8SIlya Biryukov   }
532e702bdb8SIlya Biryukov 
533e702bdb8SIlya Biryukov private:
534ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,
53588bf9b3dSMarcel Hlopko                                                const Decl *D) const {
536ba41a0f7SEduardo Caldas     if (isa<NamespaceDecl>(D))
53788bf9b3dSMarcel Hlopko       return Tokens;
53888bf9b3dSMarcel Hlopko     if (DeclsWithoutSemicolons.count(D))
53988bf9b3dSMarcel Hlopko       return Tokens;
54088bf9b3dSMarcel Hlopko     // FIXME: do not consume trailing semicolon on function definitions.
54188bf9b3dSMarcel Hlopko     // Most declarations own a semicolon in syntax trees, but not in clang AST.
54288bf9b3dSMarcel Hlopko     return withTrailingSemicolon(Tokens);
54388bf9b3dSMarcel Hlopko   }
54488bf9b3dSMarcel Hlopko 
545ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token>
546ba41a0f7SEduardo Caldas   withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const {
547e702bdb8SIlya Biryukov     assert(!Tokens.empty());
548e702bdb8SIlya Biryukov     assert(Tokens.back().kind() != tok::eof);
5497d382dcdSMarcel Hlopko     // We never consume 'eof', so looking at the next token is ok.
55058fa50f4SIlya Biryukov     if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi)
55158fa50f4SIlya Biryukov       return llvm::makeArrayRef(Tokens.begin(), Tokens.end() + 1);
55258fa50f4SIlya Biryukov     return Tokens;
5539b3f38f9SIlya Biryukov   }
5549b3f38f9SIlya Biryukov 
555a711a3a4SMarcel Hlopko   void setRole(syntax::Node *N, NodeRole R) {
5564c14ee61SEduardo Caldas     assert(N->getRole() == NodeRole::Detached);
557a711a3a4SMarcel Hlopko     N->setRole(R);
558a711a3a4SMarcel Hlopko   }
559a711a3a4SMarcel Hlopko 
5609b3f38f9SIlya Biryukov   /// A collection of trees covering the input tokens.
5619b3f38f9SIlya Biryukov   /// When created, each tree corresponds to a single token in the file.
5629b3f38f9SIlya Biryukov   /// Clients call 'foldChildren' to attach one or more subtrees to a parent
5639b3f38f9SIlya Biryukov   /// node and update the list of trees accordingly.
5649b3f38f9SIlya Biryukov   ///
5659b3f38f9SIlya Biryukov   /// Ensures that added nodes properly nest and cover the whole token stream.
5669b3f38f9SIlya Biryukov   struct Forest {
5679b3f38f9SIlya Biryukov     Forest(syntax::Arena &A) {
5684c14ee61SEduardo Caldas       assert(!A.getTokenBuffer().expandedTokens().empty());
5694c14ee61SEduardo Caldas       assert(A.getTokenBuffer().expandedTokens().back().kind() == tok::eof);
5709b3f38f9SIlya Biryukov       // Create all leaf nodes.
571bfbf6b6cSIlya Biryukov       // Note that we do not have 'eof' in the tree.
572238ae4eeSEduardo Caldas       for (const auto &T : A.getTokenBuffer().expandedTokens().drop_back()) {
5734c14ee61SEduardo Caldas         auto *L = new (A.getAllocator()) syntax::Leaf(&T);
5741ad15046SIlya Biryukov         L->Original = true;
5754c14ee61SEduardo Caldas         L->CanModify = A.getTokenBuffer().spelledForExpanded(T).hasValue();
576a711a3a4SMarcel Hlopko         Trees.insert(Trees.end(), {&T, L});
5771ad15046SIlya Biryukov       }
5789b3f38f9SIlya Biryukov     }
5799b3f38f9SIlya Biryukov 
580ba41a0f7SEduardo Caldas     void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) {
5819b3f38f9SIlya Biryukov       assert(!Range.empty());
5829b3f38f9SIlya Biryukov       auto It = Trees.lower_bound(Range.begin());
5839b3f38f9SIlya Biryukov       assert(It != Trees.end() && "no node found");
5849b3f38f9SIlya Biryukov       assert(It->first == Range.begin() && "no child with the specified range");
5859b3f38f9SIlya Biryukov       assert((std::next(It) == Trees.end() ||
5869b3f38f9SIlya Biryukov               std::next(It)->first == Range.end()) &&
5879b3f38f9SIlya Biryukov              "no child with the specified range");
5884c14ee61SEduardo Caldas       assert(It->second->getRole() == NodeRole::Detached &&
589a711a3a4SMarcel Hlopko              "re-assigning role for a child");
590a711a3a4SMarcel Hlopko       It->second->setRole(Role);
5919b3f38f9SIlya Biryukov     }
5929b3f38f9SIlya Biryukov 
5935011d431SEduardo Caldas     /// Shrink \p Range to a subrange that only contains tokens of a list.
5945011d431SEduardo Caldas     /// List elements and delimiters should already have correct roles.
5955011d431SEduardo Caldas     ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) {
5965011d431SEduardo Caldas       auto BeginChildren = Trees.lower_bound(Range.begin());
5975011d431SEduardo Caldas       assert((BeginChildren == Trees.end() ||
5985011d431SEduardo Caldas               BeginChildren->first == Range.begin()) &&
5995011d431SEduardo Caldas              "Range crosses boundaries of existing subtrees");
6005011d431SEduardo Caldas 
6015011d431SEduardo Caldas       auto EndChildren = Trees.lower_bound(Range.end());
6025011d431SEduardo Caldas       assert(
6035011d431SEduardo Caldas           (EndChildren == Trees.end() || EndChildren->first == Range.end()) &&
6045011d431SEduardo Caldas           "Range crosses boundaries of existing subtrees");
6055011d431SEduardo Caldas 
6065011d431SEduardo Caldas       auto BelongsToList = [](decltype(Trees)::value_type KV) {
6075011d431SEduardo Caldas         auto Role = KV.second->getRole();
6085011d431SEduardo Caldas         return Role == syntax::NodeRole::ListElement ||
6095011d431SEduardo Caldas                Role == syntax::NodeRole::ListDelimiter;
6105011d431SEduardo Caldas       };
6115011d431SEduardo Caldas 
6125011d431SEduardo Caldas       auto BeginListChildren =
6135011d431SEduardo Caldas           std::find_if(BeginChildren, EndChildren, BelongsToList);
6145011d431SEduardo Caldas 
6155011d431SEduardo Caldas       auto EndListChildren =
6165011d431SEduardo Caldas           std::find_if_not(BeginListChildren, EndChildren, BelongsToList);
6175011d431SEduardo Caldas 
6185011d431SEduardo Caldas       return ArrayRef<syntax::Token>(BeginListChildren->first,
6195011d431SEduardo Caldas                                      EndListChildren->first);
6205011d431SEduardo Caldas     }
6215011d431SEduardo Caldas 
622e702bdb8SIlya Biryukov     /// Add \p Node to the forest and attach child nodes based on \p Tokens.
623ba41a0f7SEduardo Caldas     void foldChildren(const syntax::Arena &A, ArrayRef<syntax::Token> Tokens,
6249b3f38f9SIlya Biryukov                       syntax::Tree *Node) {
625e702bdb8SIlya Biryukov       // Attach children to `Node`.
6264c14ee61SEduardo Caldas       assert(Node->getFirstChild() == nullptr && "node already has children");
627cdce2fe5SMarcel Hlopko 
628cdce2fe5SMarcel Hlopko       auto *FirstToken = Tokens.begin();
629cdce2fe5SMarcel Hlopko       auto BeginChildren = Trees.lower_bound(FirstToken);
630cdce2fe5SMarcel Hlopko 
631cdce2fe5SMarcel Hlopko       assert((BeginChildren == Trees.end() ||
632cdce2fe5SMarcel Hlopko               BeginChildren->first == FirstToken) &&
633cdce2fe5SMarcel Hlopko              "fold crosses boundaries of existing subtrees");
634cdce2fe5SMarcel Hlopko       auto EndChildren = Trees.lower_bound(Tokens.end());
635cdce2fe5SMarcel Hlopko       assert(
636cdce2fe5SMarcel Hlopko           (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) &&
637cdce2fe5SMarcel Hlopko           "fold crosses boundaries of existing subtrees");
638cdce2fe5SMarcel Hlopko 
63923657d9cSEduardo Caldas       for (auto It = BeginChildren; It != EndChildren; ++It) {
64023657d9cSEduardo Caldas         auto *C = It->second;
6414c14ee61SEduardo Caldas         if (C->getRole() == NodeRole::Detached)
642cdce2fe5SMarcel Hlopko           C->setRole(NodeRole::Unknown);
64323657d9cSEduardo Caldas         Node->appendChildLowLevel(C);
644e702bdb8SIlya Biryukov       }
6459b3f38f9SIlya Biryukov 
646cdce2fe5SMarcel Hlopko       // Mark that this node came from the AST and is backed by the source code.
647cdce2fe5SMarcel Hlopko       Node->Original = true;
6484c14ee61SEduardo Caldas       Node->CanModify =
6494c14ee61SEduardo Caldas           A.getTokenBuffer().spelledForExpanded(Tokens).hasValue();
6509b3f38f9SIlya Biryukov 
651cdce2fe5SMarcel Hlopko       Trees.erase(BeginChildren, EndChildren);
652cdce2fe5SMarcel Hlopko       Trees.insert({FirstToken, Node});
6539b3f38f9SIlya Biryukov     }
6549b3f38f9SIlya Biryukov 
6559b3f38f9SIlya Biryukov     // EXPECTS: all tokens were consumed and are owned by a single root node.
6569b3f38f9SIlya Biryukov     syntax::Node *finalize() && {
6579b3f38f9SIlya Biryukov       assert(Trees.size() == 1);
658a711a3a4SMarcel Hlopko       auto *Root = Trees.begin()->second;
6599b3f38f9SIlya Biryukov       Trees = {};
6609b3f38f9SIlya Biryukov       return Root;
6619b3f38f9SIlya Biryukov     }
6629b3f38f9SIlya Biryukov 
6639b3f38f9SIlya Biryukov     std::string str(const syntax::Arena &A) const {
6649b3f38f9SIlya Biryukov       std::string R;
6659b3f38f9SIlya Biryukov       for (auto It = Trees.begin(); It != Trees.end(); ++It) {
6669b3f38f9SIlya Biryukov         unsigned CoveredTokens =
6679b3f38f9SIlya Biryukov             It != Trees.end()
6689b3f38f9SIlya Biryukov                 ? (std::next(It)->first - It->first)
6694c14ee61SEduardo Caldas                 : A.getTokenBuffer().expandedTokens().end() - It->first;
6709b3f38f9SIlya Biryukov 
671ba41a0f7SEduardo Caldas         R += std::string(
6724c14ee61SEduardo Caldas             formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(),
6734c14ee61SEduardo Caldas                     It->first->text(A.getSourceManager()), CoveredTokens));
6744c14ee61SEduardo Caldas         R += It->second->dump(A.getSourceManager());
6759b3f38f9SIlya Biryukov       }
6769b3f38f9SIlya Biryukov       return R;
6779b3f38f9SIlya Biryukov     }
6789b3f38f9SIlya Biryukov 
6799b3f38f9SIlya Biryukov   private:
6809b3f38f9SIlya Biryukov     /// Maps from the start token to a subtree starting at that token.
681302cb3bcSIlya Biryukov     /// Keys in the map are pointers into the array of expanded tokens, so
682302cb3bcSIlya Biryukov     /// pointer order corresponds to the order of preprocessor tokens.
683a711a3a4SMarcel Hlopko     std::map<const syntax::Token *, syntax::Node *> Trees;
6849b3f38f9SIlya Biryukov   };
6859b3f38f9SIlya Biryukov 
6869b3f38f9SIlya Biryukov   /// For debugging purposes.
6879b3f38f9SIlya Biryukov   std::string str() { return Pending.str(Arena); }
6889b3f38f9SIlya Biryukov 
6899b3f38f9SIlya Biryukov   syntax::Arena &Arena;
690c1bbefefSIlya Biryukov   /// To quickly find tokens by their start location.
69178194118SMikhail Maltsev   llvm::DenseMap<SourceLocation, const syntax::Token *> LocationToToken;
6929b3f38f9SIlya Biryukov   Forest Pending;
693e702bdb8SIlya Biryukov   llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
694a711a3a4SMarcel Hlopko   ASTToSyntaxMapping Mapping;
6959b3f38f9SIlya Biryukov };
6969b3f38f9SIlya Biryukov 
6979b3f38f9SIlya Biryukov namespace {
6989b3f38f9SIlya Biryukov class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
6999b3f38f9SIlya Biryukov public:
7001db5b348SEduardo Caldas   explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
7011db5b348SEduardo Caldas       : Builder(Builder), Context(Context) {}
7029b3f38f9SIlya Biryukov 
7039b3f38f9SIlya Biryukov   bool shouldTraversePostOrder() const { return true; }
7049b3f38f9SIlya Biryukov 
7057d382dcdSMarcel Hlopko   bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
706cdce2fe5SMarcel Hlopko     return processDeclaratorAndDeclaration(DD);
7077d382dcdSMarcel Hlopko   }
7087d382dcdSMarcel Hlopko 
709cdce2fe5SMarcel Hlopko   bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
710cdce2fe5SMarcel Hlopko     return processDeclaratorAndDeclaration(TD);
7119b3f38f9SIlya Biryukov   }
7129b3f38f9SIlya Biryukov 
7139b3f38f9SIlya Biryukov   bool VisitDecl(Decl *D) {
7149b3f38f9SIlya Biryukov     assert(!D->isImplicit());
715cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(D),
716a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownDeclaration(), D);
717e702bdb8SIlya Biryukov     return true;
718e702bdb8SIlya Biryukov   }
719e702bdb8SIlya Biryukov 
72088bf9b3dSMarcel Hlopko   // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
72188bf9b3dSMarcel Hlopko   // override Traverse.
72288bf9b3dSMarcel Hlopko   // FIXME: make RAV call WalkUpFrom* instead.
72388bf9b3dSMarcel Hlopko   bool
72488bf9b3dSMarcel Hlopko   TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
72588bf9b3dSMarcel Hlopko     if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
72688bf9b3dSMarcel Hlopko       return false;
72788bf9b3dSMarcel Hlopko     if (C->isExplicitSpecialization())
72888bf9b3dSMarcel Hlopko       return true; // we are only interested in explicit instantiations.
729a711a3a4SMarcel Hlopko     auto *Declaration =
730a711a3a4SMarcel Hlopko         cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
73188bf9b3dSMarcel Hlopko     foldExplicitTemplateInstantiation(
73288bf9b3dSMarcel Hlopko         Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()),
733a711a3a4SMarcel Hlopko         Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
73488bf9b3dSMarcel Hlopko     return true;
73588bf9b3dSMarcel Hlopko   }
73688bf9b3dSMarcel Hlopko 
73788bf9b3dSMarcel Hlopko   bool WalkUpFromTemplateDecl(TemplateDecl *S) {
73888bf9b3dSMarcel Hlopko     foldTemplateDeclaration(
739cdce2fe5SMarcel Hlopko         Builder.getDeclarationRange(S),
74088bf9b3dSMarcel Hlopko         Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
741cdce2fe5SMarcel Hlopko         Builder.getDeclarationRange(S->getTemplatedDecl()), S);
74288bf9b3dSMarcel Hlopko     return true;
74388bf9b3dSMarcel Hlopko   }
74488bf9b3dSMarcel Hlopko 
745e702bdb8SIlya Biryukov   bool WalkUpFromTagDecl(TagDecl *C) {
74604f627f6SIlya Biryukov     // FIXME: build the ClassSpecifier node.
74788bf9b3dSMarcel Hlopko     if (!C->isFreeStanding()) {
74888bf9b3dSMarcel Hlopko       assert(C->getNumTemplateParameterLists() == 0);
74904f627f6SIlya Biryukov       return true;
75004f627f6SIlya Biryukov     }
751a711a3a4SMarcel Hlopko     handleFreeStandingTagDecl(C);
752a711a3a4SMarcel Hlopko     return true;
753a711a3a4SMarcel Hlopko   }
754a711a3a4SMarcel Hlopko 
755a711a3a4SMarcel Hlopko   syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
756a711a3a4SMarcel Hlopko     assert(C->isFreeStanding());
75788bf9b3dSMarcel Hlopko     // Class is a declaration specifier and needs a spanning declaration node.
758cdce2fe5SMarcel Hlopko     auto DeclarationRange = Builder.getDeclarationRange(C);
759a711a3a4SMarcel Hlopko     syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
760a711a3a4SMarcel Hlopko     Builder.foldNode(DeclarationRange, Result, nullptr);
76188bf9b3dSMarcel Hlopko 
76288bf9b3dSMarcel Hlopko     // Build TemplateDeclaration nodes if we had template parameters.
76388bf9b3dSMarcel Hlopko     auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
76488bf9b3dSMarcel Hlopko       const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
76588bf9b3dSMarcel Hlopko       auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end());
766a711a3a4SMarcel Hlopko       Result =
767a711a3a4SMarcel Hlopko           foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
76888bf9b3dSMarcel Hlopko       DeclarationRange = R;
76988bf9b3dSMarcel Hlopko     };
770ba41a0f7SEduardo Caldas     if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
77188bf9b3dSMarcel Hlopko       ConsumeTemplateParameters(*S->getTemplateParameters());
77288bf9b3dSMarcel Hlopko     for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
77388bf9b3dSMarcel Hlopko       ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
774a711a3a4SMarcel Hlopko     return Result;
7759b3f38f9SIlya Biryukov   }
7769b3f38f9SIlya Biryukov 
7779b3f38f9SIlya Biryukov   bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
7787d382dcdSMarcel Hlopko     // We do not want to call VisitDecl(), the declaration for translation
7799b3f38f9SIlya Biryukov     // unit is built by finalize().
7809b3f38f9SIlya Biryukov     return true;
7819b3f38f9SIlya Biryukov   }
7829b3f38f9SIlya Biryukov 
7839b3f38f9SIlya Biryukov   bool WalkUpFromCompoundStmt(CompoundStmt *S) {
78451dad419SIlya Biryukov     using NodeRole = syntax::NodeRole;
7859b3f38f9SIlya Biryukov 
786def65bb4SIlya Biryukov     Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
78758fa50f4SIlya Biryukov     for (auto *Child : S->body())
788718e550cSEduardo Caldas       Builder.markStmtChild(Child, NodeRole::Statement);
789def65bb4SIlya Biryukov     Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
7909b3f38f9SIlya Biryukov 
79158fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
792a711a3a4SMarcel Hlopko                      new (allocator()) syntax::CompoundStatement, S);
7939b3f38f9SIlya Biryukov     return true;
7949b3f38f9SIlya Biryukov   }
7959b3f38f9SIlya Biryukov 
79658fa50f4SIlya Biryukov   // Some statements are not yet handled by syntax trees.
79758fa50f4SIlya Biryukov   bool WalkUpFromStmt(Stmt *S) {
79858fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
799a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownStatement, S);
80058fa50f4SIlya Biryukov     return true;
80158fa50f4SIlya Biryukov   }
80258fa50f4SIlya Biryukov 
8036c1a2330SHaojian Wu   bool TraverseIfStmt(IfStmt *S) {
8046c1a2330SHaojian Wu     bool Result = [&, this]() {
8056c1a2330SHaojian Wu       if (S->getInit() && !TraverseStmt(S->getInit())) {
8066c1a2330SHaojian Wu         return false;
8076c1a2330SHaojian Wu       }
8086c1a2330SHaojian Wu       // In cases where the condition is an initialized declaration in a
8096c1a2330SHaojian Wu       // statement, we want to preserve the declaration and ignore the
8106c1a2330SHaojian Wu       // implicit condition expression in the syntax tree.
8116c1a2330SHaojian Wu       if (S->hasVarStorage()) {
8126c1a2330SHaojian Wu         if (!TraverseStmt(S->getConditionVariableDeclStmt()))
8136c1a2330SHaojian Wu           return false;
8146c1a2330SHaojian Wu       } else if (S->getCond() && !TraverseStmt(S->getCond()))
8156c1a2330SHaojian Wu         return false;
8166c1a2330SHaojian Wu 
8176c1a2330SHaojian Wu       if (S->getThen() && !TraverseStmt(S->getThen()))
8186c1a2330SHaojian Wu         return false;
8196c1a2330SHaojian Wu       if (S->getElse() && !TraverseStmt(S->getElse()))
8206c1a2330SHaojian Wu         return false;
8216c1a2330SHaojian Wu       return true;
8226c1a2330SHaojian Wu     }();
8236c1a2330SHaojian Wu     WalkUpFromIfStmt(S);
8246c1a2330SHaojian Wu     return Result;
8256c1a2330SHaojian Wu   }
8266c1a2330SHaojian Wu 
82758fa50f4SIlya Biryukov   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
82858fa50f4SIlya Biryukov     // We override to traverse range initializer as VarDecl.
82958fa50f4SIlya Biryukov     // RAV traverses it as a statement, we produce invalid node kinds in that
83058fa50f4SIlya Biryukov     // case.
83158fa50f4SIlya Biryukov     // FIXME: should do this in RAV instead?
8327349479fSDmitri Gribenko     bool Result = [&, this]() {
83358fa50f4SIlya Biryukov       if (S->getInit() && !TraverseStmt(S->getInit()))
83458fa50f4SIlya Biryukov         return false;
83558fa50f4SIlya Biryukov       if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
83658fa50f4SIlya Biryukov         return false;
83758fa50f4SIlya Biryukov       if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
83858fa50f4SIlya Biryukov         return false;
83958fa50f4SIlya Biryukov       if (S->getBody() && !TraverseStmt(S->getBody()))
84058fa50f4SIlya Biryukov         return false;
84158fa50f4SIlya Biryukov       return true;
8427349479fSDmitri Gribenko     }();
8437349479fSDmitri Gribenko     WalkUpFromCXXForRangeStmt(S);
8447349479fSDmitri Gribenko     return Result;
84558fa50f4SIlya Biryukov   }
84658fa50f4SIlya Biryukov 
84758fa50f4SIlya Biryukov   bool TraverseStmt(Stmt *S) {
848ba41a0f7SEduardo Caldas     if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) {
849e702bdb8SIlya Biryukov       // We want to consume the semicolon, make sure SimpleDeclaration does not.
850e702bdb8SIlya Biryukov       for (auto *D : DS->decls())
8517d382dcdSMarcel Hlopko         Builder.noticeDeclWithoutSemicolon(D);
852ba41a0f7SEduardo Caldas     } else if (auto *E = dyn_cast_or_null<Expr>(S)) {
8532325d6b4SEduardo Caldas       return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E));
85458fa50f4SIlya Biryukov     }
85558fa50f4SIlya Biryukov     return RecursiveASTVisitor::TraverseStmt(S);
85658fa50f4SIlya Biryukov   }
85758fa50f4SIlya Biryukov 
858780ead41SHaojian Wu   bool TraverseOpaqueValueExpr(OpaqueValueExpr *VE) {
859780ead41SHaojian Wu     // OpaqueValue doesn't correspond to concrete syntax, ignore it.
860780ead41SHaojian Wu     return true;
861780ead41SHaojian Wu   }
862780ead41SHaojian Wu 
86358fa50f4SIlya Biryukov   // Some expressions are not yet handled by syntax trees.
86458fa50f4SIlya Biryukov   bool WalkUpFromExpr(Expr *E) {
86558fa50f4SIlya Biryukov     assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
86658fa50f4SIlya Biryukov     Builder.foldNode(Builder.getExprRange(E),
867a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownExpression, E);
86858fa50f4SIlya Biryukov     return true;
86958fa50f4SIlya Biryukov   }
87058fa50f4SIlya Biryukov 
871f33c2c27SEduardo Caldas   bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
872f33c2c27SEduardo Caldas     // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
873f33c2c27SEduardo Caldas     // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
874f33c2c27SEduardo Caldas     // UDL suffix location does not point to the beginning of a token, so we
875f33c2c27SEduardo Caldas     // can't represent the UDL suffix as a separate syntax tree node.
876f33c2c27SEduardo Caldas 
877f33c2c27SEduardo Caldas     return WalkUpFromUserDefinedLiteral(S);
878f33c2c27SEduardo Caldas   }
879f33c2c27SEduardo Caldas 
8801db5b348SEduardo Caldas   syntax::UserDefinedLiteralExpression *
8811db5b348SEduardo Caldas   buildUserDefinedLiteral(UserDefinedLiteral *S) {
882f33c2c27SEduardo Caldas     switch (S->getLiteralOperatorKind()) {
883ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Integer:
8841db5b348SEduardo Caldas       return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
885ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Floating:
8861db5b348SEduardo Caldas       return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
887ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Character:
8881db5b348SEduardo Caldas       return new (allocator()) syntax::CharUserDefinedLiteralExpression;
889ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_String:
8901db5b348SEduardo Caldas       return new (allocator()) syntax::StringUserDefinedLiteralExpression;
891ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Raw:
892ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Template:
8931db5b348SEduardo Caldas       // For raw literal operator and numeric literal operator template we
8941db5b348SEduardo Caldas       // cannot get the type of the operand in the semantic AST. We get this
8951db5b348SEduardo Caldas       // information from the token. As integer and floating point have the same
8961db5b348SEduardo Caldas       // token kind, we run `NumericLiteralParser` again to distinguish them.
8971db5b348SEduardo Caldas       auto TokLoc = S->getBeginLoc();
8981db5b348SEduardo Caldas       auto TokSpelling =
899a474d5baSEduardo Caldas           Builder.findToken(TokLoc)->text(Context.getSourceManager());
9001db5b348SEduardo Caldas       auto Literal =
9011db5b348SEduardo Caldas           NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
9021db5b348SEduardo Caldas                                Context.getLangOpts(), Context.getTargetInfo(),
9031db5b348SEduardo Caldas                                Context.getDiagnostics());
9041db5b348SEduardo Caldas       if (Literal.isIntegerLiteral())
9051db5b348SEduardo Caldas         return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
906a474d5baSEduardo Caldas       else {
907a474d5baSEduardo Caldas         assert(Literal.isFloatingLiteral());
9081db5b348SEduardo Caldas         return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
909f33c2c27SEduardo Caldas       }
910f33c2c27SEduardo Caldas     }
911b8409c03SMichael Liao     llvm_unreachable("Unknown literal operator kind.");
912a474d5baSEduardo Caldas   }
913f33c2c27SEduardo Caldas 
914f33c2c27SEduardo Caldas   bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
915f33c2c27SEduardo Caldas     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
9161db5b348SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
917f33c2c27SEduardo Caldas     return true;
918f33c2c27SEduardo Caldas   }
919f33c2c27SEduardo Caldas 
9208abb5fb6SEduardo Caldas   // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the
9218abb5fb6SEduardo Caldas   // `DependentTemplateSpecializationType` case.
922f9500cc4SEduardo Caldas   /// Given a nested-name-specifier return the range for the last name
923f9500cc4SEduardo Caldas   /// specifier.
9248abb5fb6SEduardo Caldas   ///
9258abb5fb6SEduardo Caldas   /// e.g. `std::T::template X<U>::` => `template X<U>::`
9268abb5fb6SEduardo Caldas   SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) {
9278abb5fb6SEduardo Caldas     auto SR = NNSLoc.getLocalSourceRange();
9288abb5fb6SEduardo Caldas 
929f9500cc4SEduardo Caldas     // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should*
930f9500cc4SEduardo Caldas     // return the desired `SourceRange`, but there is a corner case. For a
931f9500cc4SEduardo Caldas     // `DependentTemplateSpecializationType` this method returns its
9328abb5fb6SEduardo Caldas     // qualifiers as well, in other words in the example above this method
9338abb5fb6SEduardo Caldas     // returns `T::template X<U>::` instead of only `template X<U>::`
9348abb5fb6SEduardo Caldas     if (auto TL = NNSLoc.getTypeLoc()) {
9358abb5fb6SEduardo Caldas       if (auto DependentTL =
9368abb5fb6SEduardo Caldas               TL.getAs<DependentTemplateSpecializationTypeLoc>()) {
9378abb5fb6SEduardo Caldas         // The 'template' keyword is always present in dependent template
9388abb5fb6SEduardo Caldas         // specializations. Except in the case of incorrect code
9398abb5fb6SEduardo Caldas         // TODO: Treat the case of incorrect code.
9408abb5fb6SEduardo Caldas         SR.setBegin(DependentTL.getTemplateKeywordLoc());
9418abb5fb6SEduardo Caldas       }
9428abb5fb6SEduardo Caldas     }
9438abb5fb6SEduardo Caldas 
9448abb5fb6SEduardo Caldas     return SR;
9458abb5fb6SEduardo Caldas   }
9468abb5fb6SEduardo Caldas 
947f9500cc4SEduardo Caldas   syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) {
948f9500cc4SEduardo Caldas     switch (NNS.getKind()) {
949f9500cc4SEduardo Caldas     case NestedNameSpecifier::Global:
950f9500cc4SEduardo Caldas       return syntax::NodeKind::GlobalNameSpecifier;
951f9500cc4SEduardo Caldas     case NestedNameSpecifier::Namespace:
952f9500cc4SEduardo Caldas     case NestedNameSpecifier::NamespaceAlias:
953f9500cc4SEduardo Caldas     case NestedNameSpecifier::Identifier:
954f9500cc4SEduardo Caldas       return syntax::NodeKind::IdentifierNameSpecifier;
955f9500cc4SEduardo Caldas     case NestedNameSpecifier::TypeSpecWithTemplate:
956f9500cc4SEduardo Caldas       return syntax::NodeKind::SimpleTemplateNameSpecifier;
957f9500cc4SEduardo Caldas     case NestedNameSpecifier::TypeSpec: {
958f9500cc4SEduardo Caldas       const auto *NNSType = NNS.getAsType();
959f9500cc4SEduardo Caldas       assert(NNSType);
960f9500cc4SEduardo Caldas       if (isa<DecltypeType>(NNSType))
961f9500cc4SEduardo Caldas         return syntax::NodeKind::DecltypeNameSpecifier;
962f9500cc4SEduardo Caldas       if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>(
963f9500cc4SEduardo Caldas               NNSType))
964f9500cc4SEduardo Caldas         return syntax::NodeKind::SimpleTemplateNameSpecifier;
965f9500cc4SEduardo Caldas       return syntax::NodeKind::IdentifierNameSpecifier;
966f9500cc4SEduardo Caldas     }
967f9500cc4SEduardo Caldas     default:
968f9500cc4SEduardo Caldas       // FIXME: Support Microsoft's __super
969f9500cc4SEduardo Caldas       llvm::report_fatal_error("We don't yet support the __super specifier",
970f9500cc4SEduardo Caldas                                true);
971f9500cc4SEduardo Caldas     }
972f9500cc4SEduardo Caldas   }
973f9500cc4SEduardo Caldas 
974f9500cc4SEduardo Caldas   syntax::NameSpecifier *
975ac87a0b5SEduardo Caldas   buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) {
976f9500cc4SEduardo Caldas     assert(NNSLoc.hasQualifier());
977f9500cc4SEduardo Caldas     auto NameSpecifierTokens =
978f9500cc4SEduardo Caldas         Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back();
979f9500cc4SEduardo Caldas     switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) {
980f9500cc4SEduardo Caldas     case syntax::NodeKind::GlobalNameSpecifier:
981f9500cc4SEduardo Caldas       return new (allocator()) syntax::GlobalNameSpecifier;
982f9500cc4SEduardo Caldas     case syntax::NodeKind::IdentifierNameSpecifier: {
983f9500cc4SEduardo Caldas       assert(NameSpecifierTokens.size() == 1);
984f9500cc4SEduardo Caldas       Builder.markChildToken(NameSpecifierTokens.begin(),
985f9500cc4SEduardo Caldas                              syntax::NodeRole::Unknown);
986f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::IdentifierNameSpecifier;
987f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
988f9500cc4SEduardo Caldas       return NS;
989f9500cc4SEduardo Caldas     }
990f9500cc4SEduardo Caldas     case syntax::NodeKind::SimpleTemplateNameSpecifier: {
991f9500cc4SEduardo Caldas       // TODO: Build `SimpleTemplateNameSpecifier` children and implement
992f9500cc4SEduardo Caldas       // accessors to them.
993f9500cc4SEduardo Caldas       // Be aware, we cannot do that simply by calling `TraverseTypeLoc`,
994f9500cc4SEduardo Caldas       // some `TypeLoc`s have inside them the previous name specifier and
995f9500cc4SEduardo Caldas       // we want to treat them independently.
996f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier;
997f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
998f9500cc4SEduardo Caldas       return NS;
999f9500cc4SEduardo Caldas     }
1000f9500cc4SEduardo Caldas     case syntax::NodeKind::DecltypeNameSpecifier: {
1001f9500cc4SEduardo Caldas       const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>();
1002f9500cc4SEduardo Caldas       if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL))
10038abb5fb6SEduardo Caldas         return nullptr;
1004f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
1005f9500cc4SEduardo Caldas       // TODO: Implement accessor to `DecltypeNameSpecifier` inner
1006f9500cc4SEduardo Caldas       // `DecltypeTypeLoc`.
1007f9500cc4SEduardo Caldas       // For that add mapping from `TypeLoc` to `syntax::Node*` then:
1008f9500cc4SEduardo Caldas       // Builder.markChild(TypeLoc, syntax::NodeRole);
1009f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1010f9500cc4SEduardo Caldas       return NS;
1011f9500cc4SEduardo Caldas     }
1012f9500cc4SEduardo Caldas     default:
1013f9500cc4SEduardo Caldas       llvm_unreachable("getChildKind() does not return this value");
1014f9500cc4SEduardo Caldas     }
1015f9500cc4SEduardo Caldas   }
1016f9500cc4SEduardo Caldas 
1017f9500cc4SEduardo Caldas   // To build syntax tree nodes for NestedNameSpecifierLoc we override
1018f9500cc4SEduardo Caldas   // Traverse instead of WalkUpFrom because we want to traverse the children
1019f9500cc4SEduardo Caldas   // ourselves and build a list instead of a nested tree of name specifier
1020f9500cc4SEduardo Caldas   // prefixes.
1021f9500cc4SEduardo Caldas   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) {
1022f9500cc4SEduardo Caldas     if (!QualifierLoc)
1023f9500cc4SEduardo Caldas       return true;
102487f0b51dSEduardo Caldas     for (auto It = QualifierLoc; It; It = It.getPrefix()) {
102587f0b51dSEduardo Caldas       auto *NS = buildNameSpecifier(It);
1026f9500cc4SEduardo Caldas       if (!NS)
1027f9500cc4SEduardo Caldas         return false;
1028718e550cSEduardo Caldas       Builder.markChild(NS, syntax::NodeRole::ListElement);
102987f0b51dSEduardo Caldas       Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
10308abb5fb6SEduardo Caldas     }
1031f9500cc4SEduardo Caldas     Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1032f9500cc4SEduardo Caldas                      new (allocator()) syntax::NestedNameSpecifier,
10338abb5fb6SEduardo Caldas                      QualifierLoc);
1034f9500cc4SEduardo Caldas     return true;
10358abb5fb6SEduardo Caldas   }
10368abb5fb6SEduardo Caldas 
1037a4ef9e86SEduardo Caldas   syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1038a4ef9e86SEduardo Caldas                                           SourceLocation TemplateKeywordLoc,
1039a4ef9e86SEduardo Caldas                                           SourceRange UnqualifiedIdLoc,
1040a4ef9e86SEduardo Caldas                                           ASTPtr From) {
1041a4ef9e86SEduardo Caldas     if (QualifierLoc) {
1042718e550cSEduardo Caldas       Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1043ba32915dSEduardo Caldas       if (TemplateKeywordLoc.isValid())
1044ba32915dSEduardo Caldas         Builder.markChildToken(TemplateKeywordLoc,
1045ba32915dSEduardo Caldas                                syntax::NodeRole::TemplateKeyword);
1046a4ef9e86SEduardo Caldas     }
1047ba32915dSEduardo Caldas 
1048ba32915dSEduardo Caldas     auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1049a4ef9e86SEduardo Caldas     Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1050a4ef9e86SEduardo Caldas                      nullptr);
1051718e550cSEduardo Caldas     Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1052ba32915dSEduardo Caldas 
1053a4ef9e86SEduardo Caldas     auto IdExpressionBeginLoc =
1054a4ef9e86SEduardo Caldas         QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1055ba32915dSEduardo Caldas 
1056a4ef9e86SEduardo Caldas     auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1057a4ef9e86SEduardo Caldas     Builder.foldNode(
1058a4ef9e86SEduardo Caldas         Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1059a4ef9e86SEduardo Caldas         TheIdExpression, From);
1060a4ef9e86SEduardo Caldas 
1061a4ef9e86SEduardo Caldas     return TheIdExpression;
1062a4ef9e86SEduardo Caldas   }
1063a4ef9e86SEduardo Caldas 
1064a4ef9e86SEduardo Caldas   bool WalkUpFromMemberExpr(MemberExpr *S) {
1065ba32915dSEduardo Caldas     // For `MemberExpr` with implicit `this->` we generate a simple
1066ba32915dSEduardo Caldas     // `id-expression` syntax node, beacuse an implicit `member-expression` is
1067ba32915dSEduardo Caldas     // syntactically undistinguishable from an `id-expression`
1068ba32915dSEduardo Caldas     if (S->isImplicitAccess()) {
1069a4ef9e86SEduardo Caldas       buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1070a4ef9e86SEduardo Caldas                         SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1071ba32915dSEduardo Caldas       return true;
1072ba32915dSEduardo Caldas     }
1073a4ef9e86SEduardo Caldas 
1074a4ef9e86SEduardo Caldas     auto *TheIdExpression = buildIdExpression(
1075a4ef9e86SEduardo Caldas         S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1076a4ef9e86SEduardo Caldas         SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1077ba32915dSEduardo Caldas 
1078718e550cSEduardo Caldas     Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1079ba32915dSEduardo Caldas 
1080718e550cSEduardo Caldas     Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1081718e550cSEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1082ba32915dSEduardo Caldas 
1083ba32915dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1084ba32915dSEduardo Caldas                      new (allocator()) syntax::MemberExpression, S);
1085ba32915dSEduardo Caldas     return true;
1086ba32915dSEduardo Caldas   }
1087ba32915dSEduardo Caldas 
10881b2f6b4aSEduardo Caldas   bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
1089a4ef9e86SEduardo Caldas     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1090a4ef9e86SEduardo Caldas                       SourceRange(S->getLocation(), S->getEndLoc()), S);
10918abb5fb6SEduardo Caldas 
10928abb5fb6SEduardo Caldas     return true;
10931b2f6b4aSEduardo Caldas   }
10948abb5fb6SEduardo Caldas 
10958abb5fb6SEduardo Caldas   // Same logic as DeclRefExpr.
10968abb5fb6SEduardo Caldas   bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) {
1097a4ef9e86SEduardo Caldas     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1098a4ef9e86SEduardo Caldas                       SourceRange(S->getLocation(), S->getEndLoc()), S);
10998abb5fb6SEduardo Caldas 
11001b2f6b4aSEduardo Caldas     return true;
11011b2f6b4aSEduardo Caldas   }
11021b2f6b4aSEduardo Caldas 
110385c15f17SEduardo Caldas   bool WalkUpFromCXXThisExpr(CXXThisExpr *S) {
110485c15f17SEduardo Caldas     if (!S->isImplicit()) {
110585c15f17SEduardo Caldas       Builder.markChildToken(S->getLocation(),
110685c15f17SEduardo Caldas                              syntax::NodeRole::IntroducerKeyword);
110785c15f17SEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
110885c15f17SEduardo Caldas                        new (allocator()) syntax::ThisExpression, S);
110985c15f17SEduardo Caldas     }
111085c15f17SEduardo Caldas     return true;
111185c15f17SEduardo Caldas   }
111285c15f17SEduardo Caldas 
1113fdbd7833SEduardo Caldas   bool WalkUpFromParenExpr(ParenExpr *S) {
1114fdbd7833SEduardo Caldas     Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1115718e550cSEduardo Caldas     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1116fdbd7833SEduardo Caldas     Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1117fdbd7833SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1118fdbd7833SEduardo Caldas                      new (allocator()) syntax::ParenExpression, S);
1119fdbd7833SEduardo Caldas     return true;
1120fdbd7833SEduardo Caldas   }
1121fdbd7833SEduardo Caldas 
11223b739690SEduardo Caldas   bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
112342f6fec3SEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11243b739690SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11253b739690SEduardo Caldas                      new (allocator()) syntax::IntegerLiteralExpression, S);
11263b739690SEduardo Caldas     return true;
11273b739690SEduardo Caldas   }
11283b739690SEduardo Caldas 
1129221d7bbeSEduardo Caldas   bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
1130221d7bbeSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1131221d7bbeSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1132221d7bbeSEduardo Caldas                      new (allocator()) syntax::CharacterLiteralExpression, S);
1133221d7bbeSEduardo Caldas     return true;
1134221d7bbeSEduardo Caldas   }
11357b404b6dSEduardo Caldas 
11367b404b6dSEduardo Caldas   bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
11377b404b6dSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11387b404b6dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11397b404b6dSEduardo Caldas                      new (allocator()) syntax::FloatingLiteralExpression, S);
11407b404b6dSEduardo Caldas     return true;
11417b404b6dSEduardo Caldas   }
11427b404b6dSEduardo Caldas 
1143466e8b7eSEduardo Caldas   bool WalkUpFromStringLiteral(StringLiteral *S) {
1144466e8b7eSEduardo Caldas     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1145466e8b7eSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1146466e8b7eSEduardo Caldas                      new (allocator()) syntax::StringLiteralExpression, S);
1147466e8b7eSEduardo Caldas     return true;
1148466e8b7eSEduardo Caldas   }
1149221d7bbeSEduardo Caldas 
11507b404b6dSEduardo Caldas   bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
11517b404b6dSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11527b404b6dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11537b404b6dSEduardo Caldas                      new (allocator()) syntax::BoolLiteralExpression, S);
11547b404b6dSEduardo Caldas     return true;
11557b404b6dSEduardo Caldas   }
11567b404b6dSEduardo Caldas 
1157007098d7SEduardo Caldas   bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
115842f6fec3SEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1159007098d7SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1160007098d7SEduardo Caldas                      new (allocator()) syntax::CxxNullPtrExpression, S);
1161007098d7SEduardo Caldas     return true;
1162007098d7SEduardo Caldas   }
1163007098d7SEduardo Caldas 
1164461af57dSEduardo Caldas   bool WalkUpFromUnaryOperator(UnaryOperator *S) {
116542f6fec3SEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(),
1166718e550cSEduardo Caldas                            syntax::NodeRole::OperatorToken);
1167718e550cSEduardo Caldas     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1168461af57dSEduardo Caldas 
1169461af57dSEduardo Caldas     if (S->isPostfix())
1170461af57dSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1171461af57dSEduardo Caldas                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1172461af57dSEduardo Caldas                        S);
1173461af57dSEduardo Caldas     else
1174461af57dSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1175461af57dSEduardo Caldas                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1176461af57dSEduardo Caldas                        S);
1177461af57dSEduardo Caldas 
1178461af57dSEduardo Caldas     return true;
1179461af57dSEduardo Caldas   }
1180461af57dSEduardo Caldas 
11813785eb83SEduardo Caldas   bool WalkUpFromBinaryOperator(BinaryOperator *S) {
1182718e550cSEduardo Caldas     Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
118342f6fec3SEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(),
1184718e550cSEduardo Caldas                            syntax::NodeRole::OperatorToken);
1185718e550cSEduardo Caldas     Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
11863785eb83SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11873785eb83SEduardo Caldas                      new (allocator()) syntax::BinaryOperatorExpression, S);
11883785eb83SEduardo Caldas     return true;
11893785eb83SEduardo Caldas   }
11903785eb83SEduardo Caldas 
1191f5087d5cSEduardo Caldas   /// Builds `CallArguments` syntax node from arguments that appear in source
1192f5087d5cSEduardo Caldas   /// code, i.e. not default arguments.
1193f5087d5cSEduardo Caldas   syntax::CallArguments *
1194f5087d5cSEduardo Caldas   buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) {
1195f5087d5cSEduardo Caldas     auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1196e10df779SDmitri Gribenko     for (auto *Arg : Args) {
1197718e550cSEduardo Caldas       Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
11982de2ca34SEduardo Caldas       const auto *DelimiterToken =
11992de2ca34SEduardo Caldas           std::next(Builder.findToken(Arg->getEndLoc()));
12002de2ca34SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1201718e550cSEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
12022de2ca34SEduardo Caldas     }
12032de2ca34SEduardo Caldas 
12042de2ca34SEduardo Caldas     auto *Arguments = new (allocator()) syntax::CallArguments;
12052de2ca34SEduardo Caldas     if (!Args.empty())
12062de2ca34SEduardo Caldas       Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
12072de2ca34SEduardo Caldas                                         (*(Args.end() - 1))->getEndLoc()),
12082de2ca34SEduardo Caldas                        Arguments, nullptr);
12092de2ca34SEduardo Caldas 
12102de2ca34SEduardo Caldas     return Arguments;
12112de2ca34SEduardo Caldas   }
12122de2ca34SEduardo Caldas 
12132de2ca34SEduardo Caldas   bool WalkUpFromCallExpr(CallExpr *S) {
1214718e550cSEduardo Caldas     Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
12152de2ca34SEduardo Caldas 
12162de2ca34SEduardo Caldas     const auto *LParenToken =
12172de2ca34SEduardo Caldas         std::next(Builder.findToken(S->getCallee()->getEndLoc()));
12182de2ca34SEduardo Caldas     // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
12192de2ca34SEduardo Caldas     // the test on decltype desctructors.
12202de2ca34SEduardo Caldas     if (LParenToken->kind() == clang::tok::l_paren)
12212de2ca34SEduardo Caldas       Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
12222de2ca34SEduardo Caldas 
12232de2ca34SEduardo Caldas     Builder.markChild(buildCallArguments(S->arguments()),
1224718e550cSEduardo Caldas                       syntax::NodeRole::Arguments);
12252de2ca34SEduardo Caldas 
12262de2ca34SEduardo Caldas     Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
12272de2ca34SEduardo Caldas 
12282de2ca34SEduardo Caldas     Builder.foldNode(Builder.getRange(S->getSourceRange()),
12292de2ca34SEduardo Caldas                      new (allocator()) syntax::CallExpression, S);
12302de2ca34SEduardo Caldas     return true;
12312de2ca34SEduardo Caldas   }
12322de2ca34SEduardo Caldas 
123346f4439dSEduardo Caldas   bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
123446f4439dSEduardo Caldas     // Ignore the implicit calls to default constructors.
123546f4439dSEduardo Caldas     if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
123646f4439dSEduardo Caldas         S->getParenOrBraceRange().isInvalid())
123746f4439dSEduardo Caldas       return true;
123846f4439dSEduardo Caldas     return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
123946f4439dSEduardo Caldas   }
124046f4439dSEduardo Caldas 
1241ea8bba7eSEduardo Caldas   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1242ac37afa6SEduardo Caldas     // To construct a syntax tree of the same shape for calls to built-in and
1243ac37afa6SEduardo Caldas     // user-defined operators, ignore the `DeclRefExpr` that refers to the
1244ac37afa6SEduardo Caldas     // operator and treat it as a simple token. Do that by traversing
1245ac37afa6SEduardo Caldas     // arguments instead of children.
1246ac37afa6SEduardo Caldas     for (auto *child : S->arguments()) {
1247f33c2c27SEduardo Caldas       // A postfix unary operator is declared as taking two operands. The
1248f33c2c27SEduardo Caldas       // second operand is used to distinguish from its prefix counterpart. In
1249f33c2c27SEduardo Caldas       // the semantic AST this "phantom" operand is represented as a
1250ea8bba7eSEduardo Caldas       // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1251ea8bba7eSEduardo Caldas       // operand because it does not correspond to anything written in source
1252ac37afa6SEduardo Caldas       // code.
1253ac37afa6SEduardo Caldas       if (child->getSourceRange().isInvalid()) {
1254ac37afa6SEduardo Caldas         assert(getOperatorNodeKind(*S) ==
1255ac37afa6SEduardo Caldas                syntax::NodeKind::PostfixUnaryOperatorExpression);
1256ea8bba7eSEduardo Caldas         continue;
1257ac37afa6SEduardo Caldas       }
1258ea8bba7eSEduardo Caldas       if (!TraverseStmt(child))
1259ea8bba7eSEduardo Caldas         return false;
1260ea8bba7eSEduardo Caldas     }
1261ea8bba7eSEduardo Caldas     return WalkUpFromCXXOperatorCallExpr(S);
1262ea8bba7eSEduardo Caldas   }
1263ea8bba7eSEduardo Caldas 
12643a574a6cSEduardo Caldas   bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1265ea8bba7eSEduardo Caldas     switch (getOperatorNodeKind(*S)) {
1266ea8bba7eSEduardo Caldas     case syntax::NodeKind::BinaryOperatorExpression:
1267718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1268718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1269718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1270718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
12713a574a6cSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
12723a574a6cSEduardo Caldas                        new (allocator()) syntax::BinaryOperatorExpression, S);
12733a574a6cSEduardo Caldas       return true;
1274ea8bba7eSEduardo Caldas     case syntax::NodeKind::PrefixUnaryOperatorExpression:
1275718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1276718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1277718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1278ea8bba7eSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1279ea8bba7eSEduardo Caldas                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1280ea8bba7eSEduardo Caldas                        S);
1281ea8bba7eSEduardo Caldas       return true;
1282ea8bba7eSEduardo Caldas     case syntax::NodeKind::PostfixUnaryOperatorExpression:
1283718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1284718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1285718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1286ea8bba7eSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1287ea8bba7eSEduardo Caldas                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1288ea8bba7eSEduardo Caldas                        S);
1289ea8bba7eSEduardo Caldas       return true;
12902de2ca34SEduardo Caldas     case syntax::NodeKind::CallExpression: {
1291718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
12922de2ca34SEduardo Caldas 
12932de2ca34SEduardo Caldas       const auto *LParenToken =
12942de2ca34SEduardo Caldas           std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
12952de2ca34SEduardo Caldas       // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
12962de2ca34SEduardo Caldas       // fixed the test on decltype desctructors.
12972de2ca34SEduardo Caldas       if (LParenToken->kind() == clang::tok::l_paren)
12982de2ca34SEduardo Caldas         Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
12992de2ca34SEduardo Caldas 
13002de2ca34SEduardo Caldas       Builder.markChild(buildCallArguments(CallExpr::arg_range(
13012de2ca34SEduardo Caldas                             S->arg_begin() + 1, S->arg_end())),
1302718e550cSEduardo Caldas                         syntax::NodeRole::Arguments);
13032de2ca34SEduardo Caldas 
13042de2ca34SEduardo Caldas       Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
13052de2ca34SEduardo Caldas 
13062de2ca34SEduardo Caldas       Builder.foldNode(Builder.getRange(S->getSourceRange()),
13072de2ca34SEduardo Caldas                        new (allocator()) syntax::CallExpression, S);
13082de2ca34SEduardo Caldas       return true;
13092de2ca34SEduardo Caldas     }
1310ea8bba7eSEduardo Caldas     case syntax::NodeKind::UnknownExpression:
13112de2ca34SEduardo Caldas       return WalkUpFromExpr(S);
1312ea8bba7eSEduardo Caldas     default:
1313ea8bba7eSEduardo Caldas       llvm_unreachable("getOperatorNodeKind() does not return this value");
1314ea8bba7eSEduardo Caldas     }
13153a574a6cSEduardo Caldas   }
13163a574a6cSEduardo Caldas 
1317f5087d5cSEduardo Caldas   bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; }
1318f5087d5cSEduardo Caldas 
1319be14a22bSIlya Biryukov   bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
1320cdce2fe5SMarcel Hlopko     auto Tokens = Builder.getDeclarationRange(S);
1321be14a22bSIlya Biryukov     if (Tokens.front().kind() == tok::coloncolon) {
1322be14a22bSIlya Biryukov       // Handle nested namespace definitions. Those start at '::' token, e.g.
1323be14a22bSIlya Biryukov       // namespace a^::b {}
1324be14a22bSIlya Biryukov       // FIXME: build corresponding nodes for the name of this namespace.
1325be14a22bSIlya Biryukov       return true;
1326be14a22bSIlya Biryukov     }
1327a711a3a4SMarcel Hlopko     Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1328be14a22bSIlya Biryukov     return true;
1329be14a22bSIlya Biryukov   }
1330be14a22bSIlya Biryukov 
13318ce15f7eSEduardo Caldas   // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
13328ce15f7eSEduardo Caldas   // results. Find test coverage or remove it.
13337d382dcdSMarcel Hlopko   bool TraverseParenTypeLoc(ParenTypeLoc L) {
13347d382dcdSMarcel Hlopko     // We reverse order of traversal to get the proper syntax structure.
13357d382dcdSMarcel Hlopko     if (!WalkUpFromParenTypeLoc(L))
13367d382dcdSMarcel Hlopko       return false;
13377d382dcdSMarcel Hlopko     return TraverseTypeLoc(L.getInnerLoc());
13387d382dcdSMarcel Hlopko   }
13397d382dcdSMarcel Hlopko 
13407d382dcdSMarcel Hlopko   bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
13417d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
13427d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13437d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1344a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ParenDeclarator, L);
13457d382dcdSMarcel Hlopko     return true;
13467d382dcdSMarcel Hlopko   }
13477d382dcdSMarcel Hlopko 
13487d382dcdSMarcel Hlopko   // Declarator chunks, they are produced by type locs and some clang::Decls.
13497d382dcdSMarcel Hlopko   bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
13507d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1351718e550cSEduardo Caldas     Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
13527d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
13537d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1354a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ArraySubscript, L);
13557d382dcdSMarcel Hlopko     return true;
13567d382dcdSMarcel Hlopko   }
13577d382dcdSMarcel Hlopko 
1358dc3d4743SEduardo Caldas   syntax::ParameterDeclarationList *
1359dc3d4743SEduardo Caldas   buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) {
1360dc3d4743SEduardo Caldas     for (auto *P : Params) {
1361718e550cSEduardo Caldas       Builder.markChild(P, syntax::NodeRole::ListElement);
1362dc3d4743SEduardo Caldas       const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1363dc3d4743SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1364718e550cSEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1365dc3d4743SEduardo Caldas     }
1366dc3d4743SEduardo Caldas     auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1367dc3d4743SEduardo Caldas     if (!Params.empty())
1368dc3d4743SEduardo Caldas       Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1369dc3d4743SEduardo Caldas                                         Params.back()->getEndLoc()),
1370dc3d4743SEduardo Caldas                        Parameters, nullptr);
1371dc3d4743SEduardo Caldas     return Parameters;
1372dc3d4743SEduardo Caldas   }
1373dc3d4743SEduardo Caldas 
13747d382dcdSMarcel Hlopko   bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
13757d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1376dc3d4743SEduardo Caldas 
1377dc3d4743SEduardo Caldas     Builder.markChild(buildParameterDeclarationList(L.getParams()),
1378718e550cSEduardo Caldas                       syntax::NodeRole::Parameters);
1379dc3d4743SEduardo Caldas 
13807d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13817d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1382a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ParametersAndQualifiers, L);
13837d382dcdSMarcel Hlopko     return true;
13847d382dcdSMarcel Hlopko   }
13857d382dcdSMarcel Hlopko 
13867d382dcdSMarcel Hlopko   bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
13877d382dcdSMarcel Hlopko     if (!L.getTypePtr()->hasTrailingReturn())
13887d382dcdSMarcel Hlopko       return WalkUpFromFunctionTypeLoc(L);
13897d382dcdSMarcel Hlopko 
1390ac87a0b5SEduardo Caldas     auto *TrailingReturnTokens = buildTrailingReturn(L);
13917d382dcdSMarcel Hlopko     // Finish building the node for parameters.
1392718e550cSEduardo Caldas     Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
13937d382dcdSMarcel Hlopko     return WalkUpFromFunctionTypeLoc(L);
13947d382dcdSMarcel Hlopko   }
13957d382dcdSMarcel Hlopko 
13968ce15f7eSEduardo Caldas   bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) {
13978ce15f7eSEduardo Caldas     // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
13988ce15f7eSEduardo Caldas     // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
13998ce15f7eSEduardo Caldas     // "(Y::*mp)" We thus reverse the order of traversal to get the proper
14008ce15f7eSEduardo Caldas     // syntax structure.
14018ce15f7eSEduardo Caldas     if (!WalkUpFromMemberPointerTypeLoc(L))
14028ce15f7eSEduardo Caldas       return false;
14038ce15f7eSEduardo Caldas     return TraverseTypeLoc(L.getPointeeLoc());
14048ce15f7eSEduardo Caldas   }
14058ce15f7eSEduardo Caldas 
14067d382dcdSMarcel Hlopko   bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
14077d382dcdSMarcel Hlopko     auto SR = L.getLocalSourceRange();
1408a711a3a4SMarcel Hlopko     Builder.foldNode(Builder.getRange(SR),
1409a711a3a4SMarcel Hlopko                      new (allocator()) syntax::MemberPointer, L);
14107d382dcdSMarcel Hlopko     return true;
14117d382dcdSMarcel Hlopko   }
14127d382dcdSMarcel Hlopko 
141358fa50f4SIlya Biryukov   // The code below is very regular, it could even be generated with some
141458fa50f4SIlya Biryukov   // preprocessor magic. We merely assign roles to the corresponding children
141558fa50f4SIlya Biryukov   // and fold resulting nodes.
141658fa50f4SIlya Biryukov   bool WalkUpFromDeclStmt(DeclStmt *S) {
141758fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1418a711a3a4SMarcel Hlopko                      new (allocator()) syntax::DeclarationStatement, S);
141958fa50f4SIlya Biryukov     return true;
142058fa50f4SIlya Biryukov   }
142158fa50f4SIlya Biryukov 
142258fa50f4SIlya Biryukov   bool WalkUpFromNullStmt(NullStmt *S) {
142358fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1424a711a3a4SMarcel Hlopko                      new (allocator()) syntax::EmptyStatement, S);
142558fa50f4SIlya Biryukov     return true;
142658fa50f4SIlya Biryukov   }
142758fa50f4SIlya Biryukov 
142858fa50f4SIlya Biryukov   bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1429def65bb4SIlya Biryukov     Builder.markChildToken(S->getSwitchLoc(),
143058fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
143158fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
143258fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1433a711a3a4SMarcel Hlopko                      new (allocator()) syntax::SwitchStatement, S);
143458fa50f4SIlya Biryukov     return true;
143558fa50f4SIlya Biryukov   }
143658fa50f4SIlya Biryukov 
143758fa50f4SIlya Biryukov   bool WalkUpFromCaseStmt(CaseStmt *S) {
1438def65bb4SIlya Biryukov     Builder.markChildToken(S->getKeywordLoc(),
143958fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
1440718e550cSEduardo Caldas     Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
144158fa50f4SIlya Biryukov     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
144258fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1443a711a3a4SMarcel Hlopko                      new (allocator()) syntax::CaseStatement, S);
144458fa50f4SIlya Biryukov     return true;
144558fa50f4SIlya Biryukov   }
144658fa50f4SIlya Biryukov 
144758fa50f4SIlya Biryukov   bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1448def65bb4SIlya Biryukov     Builder.markChildToken(S->getKeywordLoc(),
144958fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
145058fa50f4SIlya Biryukov     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
145158fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1452a711a3a4SMarcel Hlopko                      new (allocator()) syntax::DefaultStatement, S);
145358fa50f4SIlya Biryukov     return true;
145458fa50f4SIlya Biryukov   }
145558fa50f4SIlya Biryukov 
145658fa50f4SIlya Biryukov   bool WalkUpFromIfStmt(IfStmt *S) {
1457def65bb4SIlya Biryukov     Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
14586c1a2330SHaojian Wu     Stmt *ConditionStatement = S->getCond();
14596c1a2330SHaojian Wu     if (S->hasVarStorage())
14606c1a2330SHaojian Wu       ConditionStatement = S->getConditionVariableDeclStmt();
14616c1a2330SHaojian Wu     Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
1462718e550cSEduardo Caldas     Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1463718e550cSEduardo Caldas     Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1464718e550cSEduardo Caldas     Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
146558fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1466a711a3a4SMarcel Hlopko                      new (allocator()) syntax::IfStatement, S);
146758fa50f4SIlya Biryukov     return true;
146858fa50f4SIlya Biryukov   }
146958fa50f4SIlya Biryukov 
147058fa50f4SIlya Biryukov   bool WalkUpFromForStmt(ForStmt *S) {
1471def65bb4SIlya Biryukov     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
147258fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
147358fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1474a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ForStatement, S);
147558fa50f4SIlya Biryukov     return true;
147658fa50f4SIlya Biryukov   }
147758fa50f4SIlya Biryukov 
147858fa50f4SIlya Biryukov   bool WalkUpFromWhileStmt(WhileStmt *S) {
1479def65bb4SIlya Biryukov     Builder.markChildToken(S->getWhileLoc(),
148058fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
148158fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
148258fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1483a711a3a4SMarcel Hlopko                      new (allocator()) syntax::WhileStatement, S);
148458fa50f4SIlya Biryukov     return true;
148558fa50f4SIlya Biryukov   }
148658fa50f4SIlya Biryukov 
148758fa50f4SIlya Biryukov   bool WalkUpFromContinueStmt(ContinueStmt *S) {
1488def65bb4SIlya Biryukov     Builder.markChildToken(S->getContinueLoc(),
148958fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
149058fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1491a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ContinueStatement, S);
149258fa50f4SIlya Biryukov     return true;
149358fa50f4SIlya Biryukov   }
149458fa50f4SIlya Biryukov 
149558fa50f4SIlya Biryukov   bool WalkUpFromBreakStmt(BreakStmt *S) {
1496def65bb4SIlya Biryukov     Builder.markChildToken(S->getBreakLoc(),
149758fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
149858fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1499a711a3a4SMarcel Hlopko                      new (allocator()) syntax::BreakStatement, S);
150058fa50f4SIlya Biryukov     return true;
150158fa50f4SIlya Biryukov   }
150258fa50f4SIlya Biryukov 
150358fa50f4SIlya Biryukov   bool WalkUpFromReturnStmt(ReturnStmt *S) {
1504def65bb4SIlya Biryukov     Builder.markChildToken(S->getReturnLoc(),
150558fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
1506718e550cSEduardo Caldas     Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
150758fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1508a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ReturnStatement, S);
150958fa50f4SIlya Biryukov     return true;
151058fa50f4SIlya Biryukov   }
151158fa50f4SIlya Biryukov 
151258fa50f4SIlya Biryukov   bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1513def65bb4SIlya Biryukov     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
151458fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
151558fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1516a711a3a4SMarcel Hlopko                      new (allocator()) syntax::RangeBasedForStatement, S);
151758fa50f4SIlya Biryukov     return true;
151858fa50f4SIlya Biryukov   }
151958fa50f4SIlya Biryukov 
1520be14a22bSIlya Biryukov   bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1521cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1522a711a3a4SMarcel Hlopko                      new (allocator()) syntax::EmptyDeclaration, S);
1523be14a22bSIlya Biryukov     return true;
1524be14a22bSIlya Biryukov   }
1525be14a22bSIlya Biryukov 
1526be14a22bSIlya Biryukov   bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1527718e550cSEduardo Caldas     Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1528718e550cSEduardo Caldas     Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1529cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1530a711a3a4SMarcel Hlopko                      new (allocator()) syntax::StaticAssertDeclaration, S);
1531be14a22bSIlya Biryukov     return true;
1532be14a22bSIlya Biryukov   }
1533be14a22bSIlya Biryukov 
1534be14a22bSIlya Biryukov   bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1535cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1536a711a3a4SMarcel Hlopko                      new (allocator()) syntax::LinkageSpecificationDeclaration,
1537a711a3a4SMarcel Hlopko                      S);
1538be14a22bSIlya Biryukov     return true;
1539be14a22bSIlya Biryukov   }
1540be14a22bSIlya Biryukov 
1541be14a22bSIlya Biryukov   bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1542cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1543a711a3a4SMarcel Hlopko                      new (allocator()) syntax::NamespaceAliasDefinition, S);
1544be14a22bSIlya Biryukov     return true;
1545be14a22bSIlya Biryukov   }
1546be14a22bSIlya Biryukov 
1547be14a22bSIlya Biryukov   bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1548cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1549a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingNamespaceDirective, S);
1550be14a22bSIlya Biryukov     return true;
1551be14a22bSIlya Biryukov   }
1552be14a22bSIlya Biryukov 
1553be14a22bSIlya Biryukov   bool WalkUpFromUsingDecl(UsingDecl *S) {
1554cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1555a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1556be14a22bSIlya Biryukov     return true;
1557be14a22bSIlya Biryukov   }
1558be14a22bSIlya Biryukov 
1559be14a22bSIlya Biryukov   bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1560cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1561a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1562be14a22bSIlya Biryukov     return true;
1563be14a22bSIlya Biryukov   }
1564be14a22bSIlya Biryukov 
1565be14a22bSIlya Biryukov   bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1566cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1567a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1568be14a22bSIlya Biryukov     return true;
1569be14a22bSIlya Biryukov   }
1570be14a22bSIlya Biryukov 
1571be14a22bSIlya Biryukov   bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1572cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1573a711a3a4SMarcel Hlopko                      new (allocator()) syntax::TypeAliasDeclaration, S);
1574be14a22bSIlya Biryukov     return true;
1575be14a22bSIlya Biryukov   }
1576be14a22bSIlya Biryukov 
15779b3f38f9SIlya Biryukov private:
1578cdce2fe5SMarcel Hlopko   /// Folds SimpleDeclarator node (if present) and in case this is the last
1579cdce2fe5SMarcel Hlopko   /// declarator in the chain it also folds SimpleDeclaration node.
1580cdce2fe5SMarcel Hlopko   template <class T> bool processDeclaratorAndDeclaration(T *D) {
158138bc0060SEduardo Caldas     auto Range = getDeclaratorRange(
158238bc0060SEduardo Caldas         Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
158338bc0060SEduardo Caldas         getQualifiedNameStart(D), getInitializerRange(D));
1584cdce2fe5SMarcel Hlopko 
1585cdce2fe5SMarcel Hlopko     // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1586cdce2fe5SMarcel Hlopko     // declaration, but no declarator).
15875011d431SEduardo Caldas     if (!Range.getBegin().isValid()) {
15885011d431SEduardo Caldas       Builder.markChild(new (allocator()) syntax::DeclaratorList,
15895011d431SEduardo Caldas                         syntax::NodeRole::Declarators);
15905011d431SEduardo Caldas       Builder.foldNode(Builder.getDeclarationRange(D),
15915011d431SEduardo Caldas                        new (allocator()) syntax::SimpleDeclaration, D);
15925011d431SEduardo Caldas       return true;
1593cdce2fe5SMarcel Hlopko     }
1594cdce2fe5SMarcel Hlopko 
15955011d431SEduardo Caldas     auto *N = new (allocator()) syntax::SimpleDeclarator;
15965011d431SEduardo Caldas     Builder.foldNode(Builder.getRange(Range), N, nullptr);
15975011d431SEduardo Caldas     Builder.markChild(N, syntax::NodeRole::ListElement);
15985011d431SEduardo Caldas 
15995011d431SEduardo Caldas     if (!Builder.isResponsibleForCreatingDeclaration(D)) {
16005011d431SEduardo Caldas       // If this is not the last declarator in the declaration we expect a
16015011d431SEduardo Caldas       // delimiter after it.
16025011d431SEduardo Caldas       const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
16035011d431SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
16045011d431SEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
16055011d431SEduardo Caldas     } else {
16065011d431SEduardo Caldas       auto *DL = new (allocator()) syntax::DeclaratorList;
16075011d431SEduardo Caldas       auto DeclarationRange = Builder.getDeclarationRange(D);
16085011d431SEduardo Caldas       Builder.foldList(DeclarationRange, DL, nullptr);
16095011d431SEduardo Caldas 
16105011d431SEduardo Caldas       Builder.markChild(DL, syntax::NodeRole::Declarators);
16115011d431SEduardo Caldas       Builder.foldNode(DeclarationRange,
1612cdce2fe5SMarcel Hlopko                        new (allocator()) syntax::SimpleDeclaration, D);
1613cdce2fe5SMarcel Hlopko     }
1614cdce2fe5SMarcel Hlopko     return true;
1615cdce2fe5SMarcel Hlopko   }
1616cdce2fe5SMarcel Hlopko 
16177d382dcdSMarcel Hlopko   /// Returns the range of the built node.
1618ac87a0b5SEduardo Caldas   syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
16197d382dcdSMarcel Hlopko     assert(L.getTypePtr()->hasTrailingReturn());
16207d382dcdSMarcel Hlopko 
16217d382dcdSMarcel Hlopko     auto ReturnedType = L.getReturnLoc();
16227d382dcdSMarcel Hlopko     // Build node for the declarator, if any.
162338bc0060SEduardo Caldas     auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
162438bc0060SEduardo Caldas                                              ReturnedType.getEndLoc());
1625a711a3a4SMarcel Hlopko     syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
16267d382dcdSMarcel Hlopko     if (ReturnDeclaratorRange.isValid()) {
1627a711a3a4SMarcel Hlopko       ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1628a711a3a4SMarcel Hlopko       Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1629a711a3a4SMarcel Hlopko                        ReturnDeclarator, nullptr);
16307d382dcdSMarcel Hlopko     }
16317d382dcdSMarcel Hlopko 
16327d382dcdSMarcel Hlopko     // Build node for trailing return type.
1633a711a3a4SMarcel Hlopko     auto Return = Builder.getRange(ReturnedType.getSourceRange());
16347d382dcdSMarcel Hlopko     const auto *Arrow = Return.begin() - 1;
16357d382dcdSMarcel Hlopko     assert(Arrow->kind() == tok::arrow);
16367d382dcdSMarcel Hlopko     auto Tokens = llvm::makeArrayRef(Arrow, Return.end());
163742f6fec3SEduardo Caldas     Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1638a711a3a4SMarcel Hlopko     if (ReturnDeclarator)
1639718e550cSEduardo Caldas       Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1640a711a3a4SMarcel Hlopko     auto *R = new (allocator()) syntax::TrailingReturnType;
1641cdce2fe5SMarcel Hlopko     Builder.foldNode(Tokens, R, L);
1642a711a3a4SMarcel Hlopko     return R;
16437d382dcdSMarcel Hlopko   }
164488bf9b3dSMarcel Hlopko 
1645a711a3a4SMarcel Hlopko   void foldExplicitTemplateInstantiation(
1646a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
164788bf9b3dSMarcel Hlopko       const syntax::Token *TemplateKW,
1648a711a3a4SMarcel Hlopko       syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
164988bf9b3dSMarcel Hlopko     assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
165088bf9b3dSMarcel Hlopko     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
165142f6fec3SEduardo Caldas     Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
165288bf9b3dSMarcel Hlopko     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1653718e550cSEduardo Caldas     Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1654a711a3a4SMarcel Hlopko     Builder.foldNode(
1655a711a3a4SMarcel Hlopko         Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
165688bf9b3dSMarcel Hlopko   }
165788bf9b3dSMarcel Hlopko 
1658a711a3a4SMarcel Hlopko   syntax::TemplateDeclaration *foldTemplateDeclaration(
1659a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1660a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
166188bf9b3dSMarcel Hlopko     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
166288bf9b3dSMarcel Hlopko     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1663a711a3a4SMarcel Hlopko 
1664a711a3a4SMarcel Hlopko     auto *N = new (allocator()) syntax::TemplateDeclaration;
1665a711a3a4SMarcel Hlopko     Builder.foldNode(Range, N, From);
1666718e550cSEduardo Caldas     Builder.markChild(N, syntax::NodeRole::Declaration);
1667a711a3a4SMarcel Hlopko     return N;
166888bf9b3dSMarcel Hlopko   }
166988bf9b3dSMarcel Hlopko 
16709b3f38f9SIlya Biryukov   /// A small helper to save some typing.
16719b3f38f9SIlya Biryukov   llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
16729b3f38f9SIlya Biryukov 
16739b3f38f9SIlya Biryukov   syntax::TreeBuilder &Builder;
16741db5b348SEduardo Caldas   const ASTContext &Context;
16759b3f38f9SIlya Biryukov };
16769b3f38f9SIlya Biryukov } // namespace
16779b3f38f9SIlya Biryukov 
16787d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1679e702bdb8SIlya Biryukov   DeclsWithoutSemicolons.insert(D);
1680e702bdb8SIlya Biryukov }
1681e702bdb8SIlya Biryukov 
1682def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
16839b3f38f9SIlya Biryukov   if (Loc.isInvalid())
16849b3f38f9SIlya Biryukov     return;
16859b3f38f9SIlya Biryukov   Pending.assignRole(*findToken(Loc), Role);
16869b3f38f9SIlya Biryukov }
16879b3f38f9SIlya Biryukov 
16887d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
16897d382dcdSMarcel Hlopko   if (!T)
16907d382dcdSMarcel Hlopko     return;
16917d382dcdSMarcel Hlopko   Pending.assignRole(*T, R);
16927d382dcdSMarcel Hlopko }
16937d382dcdSMarcel Hlopko 
1694a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1695a711a3a4SMarcel Hlopko   assert(N);
1696a711a3a4SMarcel Hlopko   setRole(N, R);
1697a711a3a4SMarcel Hlopko }
1698a711a3a4SMarcel Hlopko 
1699a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1700a711a3a4SMarcel Hlopko   auto *SN = Mapping.find(N);
1701a711a3a4SMarcel Hlopko   assert(SN != nullptr);
1702a711a3a4SMarcel Hlopko   setRole(SN, R);
17037d382dcdSMarcel Hlopko }
1704f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1705f9500cc4SEduardo Caldas   auto *SN = Mapping.find(NNSLoc);
1706f9500cc4SEduardo Caldas   assert(SN != nullptr);
1707f9500cc4SEduardo Caldas   setRole(SN, R);
1708f9500cc4SEduardo Caldas }
17097d382dcdSMarcel Hlopko 
171058fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
171158fa50f4SIlya Biryukov   if (!Child)
171258fa50f4SIlya Biryukov     return;
171358fa50f4SIlya Biryukov 
1714b34b7691SDmitri Gribenko   syntax::Tree *ChildNode;
1715b34b7691SDmitri Gribenko   if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
171658fa50f4SIlya Biryukov     // This is an expression in a statement position, consume the trailing
171758fa50f4SIlya Biryukov     // semicolon and form an 'ExpressionStatement' node.
1718718e550cSEduardo Caldas     markExprChild(ChildExpr, NodeRole::Expression);
1719a711a3a4SMarcel Hlopko     ChildNode = new (allocator()) syntax::ExpressionStatement;
1720a711a3a4SMarcel Hlopko     // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1721a711a3a4SMarcel Hlopko     Pending.foldChildren(Arena, getStmtRange(Child), ChildNode);
1722b34b7691SDmitri Gribenko   } else {
1723b34b7691SDmitri Gribenko     ChildNode = Mapping.find(Child);
172458fa50f4SIlya Biryukov   }
1725b34b7691SDmitri Gribenko   assert(ChildNode != nullptr);
1726a711a3a4SMarcel Hlopko   setRole(ChildNode, Role);
172758fa50f4SIlya Biryukov }
172858fa50f4SIlya Biryukov 
172958fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1730be14a22bSIlya Biryukov   if (!Child)
1731be14a22bSIlya Biryukov     return;
17322325d6b4SEduardo Caldas   Child = IgnoreImplicit(Child);
1733be14a22bSIlya Biryukov 
1734a711a3a4SMarcel Hlopko   syntax::Tree *ChildNode = Mapping.find(Child);
1735a711a3a4SMarcel Hlopko   assert(ChildNode != nullptr);
1736a711a3a4SMarcel Hlopko   setRole(ChildNode, Role);
173758fa50f4SIlya Biryukov }
173858fa50f4SIlya Biryukov 
17399b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
174088bf9b3dSMarcel Hlopko   if (L.isInvalid())
174188bf9b3dSMarcel Hlopko     return nullptr;
174278194118SMikhail Maltsev   auto It = LocationToToken.find(L);
1743c1bbefefSIlya Biryukov   assert(It != LocationToToken.end());
1744c1bbefefSIlya Biryukov   return It->second;
17459b3f38f9SIlya Biryukov }
17469b3f38f9SIlya Biryukov 
1747142c6f82SKirill Bobyrev syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A,
1748142c6f82SKirill Bobyrev                                                  ASTContext &Context) {
17499b3f38f9SIlya Biryukov   TreeBuilder Builder(A);
1750142c6f82SKirill Bobyrev   BuildTreeVisitor(Context, Builder).TraverseAST(Context);
17519b3f38f9SIlya Biryukov   return std::move(Builder).finalize();
17529b3f38f9SIlya Biryukov }
1753