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"
30*263dcf45SHaojian Wu #include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
319b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tokens.h"
329b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tree.h"
339b3f38f9SIlya Biryukov #include "llvm/ADT/ArrayRef.h"
34a711a3a4SMarcel Hlopko #include "llvm/ADT/DenseMap.h"
35a711a3a4SMarcel Hlopko #include "llvm/ADT/PointerUnion.h"
369b3f38f9SIlya Biryukov #include "llvm/ADT/STLExtras.h"
377d382dcdSMarcel Hlopko #include "llvm/ADT/ScopeExit.h"
389b3f38f9SIlya Biryukov #include "llvm/ADT/SmallVector.h"
399b3f38f9SIlya Biryukov #include "llvm/Support/Allocator.h"
409b3f38f9SIlya Biryukov #include "llvm/Support/Casting.h"
4196065cf7SIlya Biryukov #include "llvm/Support/Compiler.h"
429b3f38f9SIlya Biryukov #include "llvm/Support/FormatVariadic.h"
431ad15046SIlya Biryukov #include "llvm/Support/MemoryBuffer.h"
449b3f38f9SIlya Biryukov #include "llvm/Support/raw_ostream.h"
45a711a3a4SMarcel Hlopko #include <cstddef>
469b3f38f9SIlya Biryukov #include <map>
479b3f38f9SIlya Biryukov 
489b3f38f9SIlya Biryukov using namespace clang;
499b3f38f9SIlya Biryukov 
502325d6b4SEduardo Caldas // Ignores the implicit `CXXConstructExpr` for copy/move constructor calls
512325d6b4SEduardo Caldas // generated by the compiler, as well as in implicit conversions like the one
522325d6b4SEduardo Caldas // wrapping `1` in `X x = 1;`.
IgnoreImplicitConstructorSingleStep(Expr * E)532325d6b4SEduardo Caldas static Expr *IgnoreImplicitConstructorSingleStep(Expr *E) {
542325d6b4SEduardo Caldas   if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
552325d6b4SEduardo Caldas     auto NumArgs = C->getNumArgs();
562325d6b4SEduardo Caldas     if (NumArgs == 1 || (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
572325d6b4SEduardo Caldas       Expr *A = C->getArg(0);
582325d6b4SEduardo Caldas       if (C->getParenOrBraceRange().isInvalid())
592325d6b4SEduardo Caldas         return A;
602325d6b4SEduardo Caldas     }
612325d6b4SEduardo Caldas   }
622325d6b4SEduardo Caldas   return E;
632325d6b4SEduardo Caldas }
642325d6b4SEduardo Caldas 
65134455a0SEduardo Caldas // In:
66134455a0SEduardo Caldas // struct X {
67134455a0SEduardo Caldas //   X(int)
68134455a0SEduardo Caldas // };
69134455a0SEduardo Caldas // X x = X(1);
70134455a0SEduardo Caldas // Ignores the implicit `CXXFunctionalCastExpr` that wraps
71134455a0SEduardo Caldas // `CXXConstructExpr X(1)`.
IgnoreCXXFunctionalCastExprWrappingConstructor(Expr * E)72134455a0SEduardo Caldas static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
73134455a0SEduardo Caldas   if (auto *F = dyn_cast<CXXFunctionalCastExpr>(E)) {
74134455a0SEduardo Caldas     if (F->getCastKind() == CK_ConstructorConversion)
75134455a0SEduardo Caldas       return F->getSubExpr();
76134455a0SEduardo Caldas   }
77134455a0SEduardo Caldas   return E;
78134455a0SEduardo Caldas }
79134455a0SEduardo Caldas 
IgnoreImplicit(Expr * E)802325d6b4SEduardo Caldas static Expr *IgnoreImplicit(Expr *E) {
812325d6b4SEduardo Caldas   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
82134455a0SEduardo Caldas                          IgnoreImplicitConstructorSingleStep,
83134455a0SEduardo Caldas                          IgnoreCXXFunctionalCastExprWrappingConstructor);
842325d6b4SEduardo Caldas }
852325d6b4SEduardo Caldas 
8696065cf7SIlya Biryukov LLVM_ATTRIBUTE_UNUSED
isImplicitExpr(Expr * E)872325d6b4SEduardo Caldas static bool isImplicitExpr(Expr *E) { return IgnoreImplicit(E) != E; }
8858fa50f4SIlya Biryukov 
897d382dcdSMarcel Hlopko namespace {
907d382dcdSMarcel Hlopko /// Get start location of the Declarator from the TypeLoc.
917d382dcdSMarcel Hlopko /// E.g.:
927d382dcdSMarcel Hlopko ///   loc of `(` in `int (a)`
937d382dcdSMarcel Hlopko ///   loc of `*` in `int *(a)`
947d382dcdSMarcel Hlopko ///   loc of the first `(` in `int (*a)(int)`
957d382dcdSMarcel Hlopko ///   loc of the `*` in `int *(a)(int)`
967d382dcdSMarcel Hlopko ///   loc of the first `*` in `const int *const *volatile a;`
977d382dcdSMarcel Hlopko ///
987d382dcdSMarcel Hlopko /// It is non-trivial to get the start location because TypeLocs are stored
997d382dcdSMarcel Hlopko /// inside out. In the example above `*volatile` is the TypeLoc returned
1007d382dcdSMarcel Hlopko /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()`
1017d382dcdSMarcel Hlopko /// returns.
1027d382dcdSMarcel Hlopko struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> {
VisitParenTypeLoc__anon43068c8b0111::GetStartLoc1037d382dcdSMarcel Hlopko   SourceLocation VisitParenTypeLoc(ParenTypeLoc T) {
1047d382dcdSMarcel Hlopko     auto L = Visit(T.getInnerLoc());
1057d382dcdSMarcel Hlopko     if (L.isValid())
1067d382dcdSMarcel Hlopko       return L;
1077d382dcdSMarcel Hlopko     return T.getLParenLoc();
1087d382dcdSMarcel Hlopko   }
1097d382dcdSMarcel Hlopko 
1107d382dcdSMarcel Hlopko   // Types spelled in the prefix part of the declarator.
VisitPointerTypeLoc__anon43068c8b0111::GetStartLoc1117d382dcdSMarcel Hlopko   SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) {
1127d382dcdSMarcel Hlopko     return HandlePointer(T);
1137d382dcdSMarcel Hlopko   }
1147d382dcdSMarcel Hlopko 
VisitMemberPointerTypeLoc__anon43068c8b0111::GetStartLoc1157d382dcdSMarcel Hlopko   SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
1167d382dcdSMarcel Hlopko     return HandlePointer(T);
1177d382dcdSMarcel Hlopko   }
1187d382dcdSMarcel Hlopko 
VisitBlockPointerTypeLoc__anon43068c8b0111::GetStartLoc1197d382dcdSMarcel Hlopko   SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
1207d382dcdSMarcel Hlopko     return HandlePointer(T);
1217d382dcdSMarcel Hlopko   }
1227d382dcdSMarcel Hlopko 
VisitReferenceTypeLoc__anon43068c8b0111::GetStartLoc1237d382dcdSMarcel Hlopko   SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) {
1247d382dcdSMarcel Hlopko     return HandlePointer(T);
1257d382dcdSMarcel Hlopko   }
1267d382dcdSMarcel Hlopko 
VisitObjCObjectPointerTypeLoc__anon43068c8b0111::GetStartLoc1277d382dcdSMarcel Hlopko   SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) {
1287d382dcdSMarcel Hlopko     return HandlePointer(T);
1297d382dcdSMarcel Hlopko   }
1307d382dcdSMarcel Hlopko 
1317d382dcdSMarcel Hlopko   // All other cases are not important, as they are either part of declaration
1327d382dcdSMarcel Hlopko   // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on
1337d382dcdSMarcel Hlopko   // existing declarators (e.g. QualifiedTypeLoc). They cannot start the
1347d382dcdSMarcel Hlopko   // declarator themselves, but their underlying type can.
VisitTypeLoc__anon43068c8b0111::GetStartLoc1357d382dcdSMarcel Hlopko   SourceLocation VisitTypeLoc(TypeLoc T) {
1367d382dcdSMarcel Hlopko     auto N = T.getNextTypeLoc();
1377d382dcdSMarcel Hlopko     if (!N)
1387d382dcdSMarcel Hlopko       return SourceLocation();
1397d382dcdSMarcel Hlopko     return Visit(N);
1407d382dcdSMarcel Hlopko   }
1417d382dcdSMarcel Hlopko 
VisitFunctionProtoTypeLoc__anon43068c8b0111::GetStartLoc1427d382dcdSMarcel Hlopko   SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) {
1437d382dcdSMarcel Hlopko     if (T.getTypePtr()->hasTrailingReturn())
1447d382dcdSMarcel Hlopko       return SourceLocation(); // avoid recursing into the suffix of declarator.
1457d382dcdSMarcel Hlopko     return VisitTypeLoc(T);
1467d382dcdSMarcel Hlopko   }
1477d382dcdSMarcel Hlopko 
1487d382dcdSMarcel Hlopko private:
HandlePointer__anon43068c8b0111::GetStartLoc1497d382dcdSMarcel Hlopko   template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) {
1507d382dcdSMarcel Hlopko     auto L = Visit(T.getPointeeLoc());
1517d382dcdSMarcel Hlopko     if (L.isValid())
1527d382dcdSMarcel Hlopko       return L;
1537d382dcdSMarcel Hlopko     return T.getLocalSourceRange().getBegin();
1547d382dcdSMarcel Hlopko   }
1557d382dcdSMarcel Hlopko };
1567d382dcdSMarcel Hlopko } // namespace
1577d382dcdSMarcel Hlopko 
dropDefaultArgs(CallExpr::arg_range Args)158f5087d5cSEduardo Caldas static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args) {
15916ceb44eSKazu Hirata   auto FirstDefaultArg =
16016ceb44eSKazu Hirata       llvm::find_if(Args, [](auto It) { return isa<CXXDefaultArgExpr>(It); });
16187f0b51dSEduardo Caldas   return llvm::make_range(Args.begin(), FirstDefaultArg);
162f5087d5cSEduardo Caldas }
163f5087d5cSEduardo Caldas 
getOperatorNodeKind(const CXXOperatorCallExpr & E)164ea8bba7eSEduardo Caldas static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
165ea8bba7eSEduardo Caldas   switch (E.getOperator()) {
166ea8bba7eSEduardo Caldas   // Comparison
167ea8bba7eSEduardo Caldas   case OO_EqualEqual:
168ea8bba7eSEduardo Caldas   case OO_ExclaimEqual:
169ea8bba7eSEduardo Caldas   case OO_Greater:
170ea8bba7eSEduardo Caldas   case OO_GreaterEqual:
171ea8bba7eSEduardo Caldas   case OO_Less:
172ea8bba7eSEduardo Caldas   case OO_LessEqual:
173ea8bba7eSEduardo Caldas   case OO_Spaceship:
174ea8bba7eSEduardo Caldas   // Assignment
175ea8bba7eSEduardo Caldas   case OO_Equal:
176ea8bba7eSEduardo Caldas   case OO_SlashEqual:
177ea8bba7eSEduardo Caldas   case OO_PercentEqual:
178ea8bba7eSEduardo Caldas   case OO_CaretEqual:
179ea8bba7eSEduardo Caldas   case OO_PipeEqual:
180ea8bba7eSEduardo Caldas   case OO_LessLessEqual:
181ea8bba7eSEduardo Caldas   case OO_GreaterGreaterEqual:
182ea8bba7eSEduardo Caldas   case OO_PlusEqual:
183ea8bba7eSEduardo Caldas   case OO_MinusEqual:
184ea8bba7eSEduardo Caldas   case OO_StarEqual:
185ea8bba7eSEduardo Caldas   case OO_AmpEqual:
186ea8bba7eSEduardo Caldas   // Binary computation
187ea8bba7eSEduardo Caldas   case OO_Slash:
188ea8bba7eSEduardo Caldas   case OO_Percent:
189ea8bba7eSEduardo Caldas   case OO_Caret:
190ea8bba7eSEduardo Caldas   case OO_Pipe:
191ea8bba7eSEduardo Caldas   case OO_LessLess:
192ea8bba7eSEduardo Caldas   case OO_GreaterGreater:
193ea8bba7eSEduardo Caldas   case OO_AmpAmp:
194ea8bba7eSEduardo Caldas   case OO_PipePipe:
195ea8bba7eSEduardo Caldas   case OO_ArrowStar:
196ea8bba7eSEduardo Caldas   case OO_Comma:
197ea8bba7eSEduardo Caldas     return syntax::NodeKind::BinaryOperatorExpression;
198ea8bba7eSEduardo Caldas   case OO_Tilde:
199ea8bba7eSEduardo Caldas   case OO_Exclaim:
200ea8bba7eSEduardo Caldas     return syntax::NodeKind::PrefixUnaryOperatorExpression;
201ea8bba7eSEduardo Caldas   // Prefix/Postfix increment/decrement
202ea8bba7eSEduardo Caldas   case OO_PlusPlus:
203ea8bba7eSEduardo Caldas   case OO_MinusMinus:
204ea8bba7eSEduardo Caldas     switch (E.getNumArgs()) {
205ea8bba7eSEduardo Caldas     case 1:
206ea8bba7eSEduardo Caldas       return syntax::NodeKind::PrefixUnaryOperatorExpression;
207ea8bba7eSEduardo Caldas     case 2:
208ea8bba7eSEduardo Caldas       return syntax::NodeKind::PostfixUnaryOperatorExpression;
209ea8bba7eSEduardo Caldas     default:
210ea8bba7eSEduardo Caldas       llvm_unreachable("Invalid number of arguments for operator");
211ea8bba7eSEduardo Caldas     }
212ea8bba7eSEduardo Caldas   // Operators that can be unary or binary
213ea8bba7eSEduardo Caldas   case OO_Plus:
214ea8bba7eSEduardo Caldas   case OO_Minus:
215ea8bba7eSEduardo Caldas   case OO_Star:
216ea8bba7eSEduardo Caldas   case OO_Amp:
217ea8bba7eSEduardo Caldas     switch (E.getNumArgs()) {
218ea8bba7eSEduardo Caldas     case 1:
219ea8bba7eSEduardo Caldas       return syntax::NodeKind::PrefixUnaryOperatorExpression;
220ea8bba7eSEduardo Caldas     case 2:
221ea8bba7eSEduardo Caldas       return syntax::NodeKind::BinaryOperatorExpression;
222ea8bba7eSEduardo Caldas     default:
223ea8bba7eSEduardo Caldas       llvm_unreachable("Invalid number of arguments for operator");
224ea8bba7eSEduardo Caldas     }
225ea8bba7eSEduardo Caldas     return syntax::NodeKind::BinaryOperatorExpression;
226ea8bba7eSEduardo Caldas   // Not yet supported by SyntaxTree
227ea8bba7eSEduardo Caldas   case OO_New:
228ea8bba7eSEduardo Caldas   case OO_Delete:
229ea8bba7eSEduardo Caldas   case OO_Array_New:
230ea8bba7eSEduardo Caldas   case OO_Array_Delete:
231ea8bba7eSEduardo Caldas   case OO_Coawait:
232ea8bba7eSEduardo Caldas   case OO_Subscript:
233ea8bba7eSEduardo Caldas   case OO_Arrow:
234ea8bba7eSEduardo Caldas     return syntax::NodeKind::UnknownExpression;
2352de2ca34SEduardo Caldas   case OO_Call:
2362de2ca34SEduardo Caldas     return syntax::NodeKind::CallExpression;
237ea8bba7eSEduardo Caldas   case OO_Conditional: // not overloadable
238ea8bba7eSEduardo Caldas   case NUM_OVERLOADED_OPERATORS:
239ea8bba7eSEduardo Caldas   case OO_None:
240ea8bba7eSEduardo Caldas     llvm_unreachable("Not an overloadable operator");
241ea8bba7eSEduardo Caldas   }
242397c6820SSimon Pilgrim   llvm_unreachable("Unknown OverloadedOperatorKind enum");
243ea8bba7eSEduardo Caldas }
244ea8bba7eSEduardo Caldas 
24538bc0060SEduardo Caldas /// Get the start of the qualified name. In the examples below it gives the
24638bc0060SEduardo Caldas /// location of the `^`:
24738bc0060SEduardo Caldas ///     `int ^a;`
248a1461953SEduardo Caldas ///     `int *^a;`
24938bc0060SEduardo Caldas ///     `int ^a::S::f(){}`
getQualifiedNameStart(NamedDecl * D)25038bc0060SEduardo Caldas static SourceLocation getQualifiedNameStart(NamedDecl *D) {
25138bc0060SEduardo Caldas   assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
25238bc0060SEduardo Caldas          "only DeclaratorDecl and TypedefNameDecl are supported.");
25338bc0060SEduardo Caldas 
25438bc0060SEduardo Caldas   auto DN = D->getDeclName();
25538bc0060SEduardo Caldas   bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
25638bc0060SEduardo Caldas   if (IsAnonymous)
25738bc0060SEduardo Caldas     return SourceLocation();
25838bc0060SEduardo Caldas 
25938bc0060SEduardo Caldas   if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
26038bc0060SEduardo Caldas     if (DD->getQualifierLoc()) {
26138bc0060SEduardo Caldas       return DD->getQualifierLoc().getBeginLoc();
26238bc0060SEduardo Caldas     }
26338bc0060SEduardo Caldas   }
26438bc0060SEduardo Caldas 
26538bc0060SEduardo Caldas   return D->getLocation();
26638bc0060SEduardo Caldas }
26738bc0060SEduardo Caldas 
26838bc0060SEduardo Caldas /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl].
26938bc0060SEduardo Caldas ///     `int a;` -> range of ``,
27038bc0060SEduardo Caldas ///     `int *a = nullptr` -> range of `= nullptr`.
27138bc0060SEduardo Caldas ///     `int a{}` -> range of `{}`.
27238bc0060SEduardo Caldas ///     `int a()` -> range of `()`.
getInitializerRange(Decl * D)27338bc0060SEduardo Caldas static SourceRange getInitializerRange(Decl *D) {
27438bc0060SEduardo Caldas   if (auto *V = dyn_cast<VarDecl>(D)) {
27538bc0060SEduardo Caldas     auto *I = V->getInit();
27638bc0060SEduardo Caldas     // Initializers in range-based-for are not part of the declarator
27738bc0060SEduardo Caldas     if (I && !V->isCXXForRangeDecl())
27838bc0060SEduardo Caldas       return I->getSourceRange();
27938bc0060SEduardo Caldas   }
28038bc0060SEduardo Caldas 
28138bc0060SEduardo Caldas   return SourceRange();
28238bc0060SEduardo Caldas }
28338bc0060SEduardo Caldas 
2847d382dcdSMarcel Hlopko /// Gets the range of declarator as defined by the C++ grammar. E.g.
2857d382dcdSMarcel Hlopko ///     `int a;` -> range of `a`,
2867d382dcdSMarcel Hlopko ///     `int *a;` -> range of `*a`,
2877d382dcdSMarcel Hlopko ///     `int a[10];` -> range of `a[10]`,
2887d382dcdSMarcel Hlopko ///     `int a[1][2][3];` -> range of `a[1][2][3]`,
2897d382dcdSMarcel Hlopko ///     `int *a = nullptr` -> range of `*a = nullptr`.
29038bc0060SEduardo Caldas ///     `int S::f(){}` -> range of `S::f()`.
291a1461953SEduardo Caldas /// FIXME: \p Name must be a source range.
getDeclaratorRange(const SourceManager & SM,TypeLoc T,SourceLocation Name,SourceRange Initializer)2927d382dcdSMarcel Hlopko static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
2937d382dcdSMarcel Hlopko                                       SourceLocation Name,
2947d382dcdSMarcel Hlopko                                       SourceRange Initializer) {
2957d382dcdSMarcel Hlopko   SourceLocation Start = GetStartLoc().Visit(T);
29638bc0060SEduardo Caldas   SourceLocation End = T.getEndLoc();
2977d382dcdSMarcel Hlopko   if (Name.isValid()) {
2987d382dcdSMarcel Hlopko     if (Start.isInvalid())
2997d382dcdSMarcel Hlopko       Start = Name;
300e159a3ceSHaojian Wu     // End of TypeLoc could be invalid if the type is invalid, fallback to the
301e159a3ceSHaojian Wu     // NameLoc.
302e159a3ceSHaojian Wu     if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name))
3037d382dcdSMarcel Hlopko       End = Name;
3047d382dcdSMarcel Hlopko   }
3057d382dcdSMarcel Hlopko   if (Initializer.isValid()) {
306cdce2fe5SMarcel Hlopko     auto InitializerEnd = Initializer.getEnd();
307f33c2c27SEduardo Caldas     assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
308f33c2c27SEduardo Caldas            End == InitializerEnd);
309cdce2fe5SMarcel Hlopko     End = InitializerEnd;
3107d382dcdSMarcel Hlopko   }
3117d382dcdSMarcel Hlopko   return SourceRange(Start, End);
3127d382dcdSMarcel Hlopko }
3137d382dcdSMarcel Hlopko 
314a711a3a4SMarcel Hlopko namespace {
315a711a3a4SMarcel Hlopko /// All AST hierarchy roots that can be represented as pointers.
316a711a3a4SMarcel Hlopko using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>;
317a711a3a4SMarcel Hlopko /// Maintains a mapping from AST to syntax tree nodes. This class will get more
318a711a3a4SMarcel Hlopko /// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
319a711a3a4SMarcel Hlopko /// FIXME: expose this as public API.
320a711a3a4SMarcel Hlopko class ASTToSyntaxMapping {
321a711a3a4SMarcel Hlopko public:
add(ASTPtr From,syntax::Tree * To)322a711a3a4SMarcel Hlopko   void add(ASTPtr From, syntax::Tree *To) {
323a711a3a4SMarcel Hlopko     assert(To != nullptr);
324a711a3a4SMarcel Hlopko     assert(!From.isNull());
325a711a3a4SMarcel Hlopko 
326a711a3a4SMarcel Hlopko     bool Added = Nodes.insert({From, To}).second;
327a711a3a4SMarcel Hlopko     (void)Added;
328a711a3a4SMarcel Hlopko     assert(Added && "mapping added twice");
329a711a3a4SMarcel Hlopko   }
330a711a3a4SMarcel Hlopko 
add(NestedNameSpecifierLoc From,syntax::Tree * To)331f9500cc4SEduardo Caldas   void add(NestedNameSpecifierLoc From, syntax::Tree *To) {
332f9500cc4SEduardo Caldas     assert(To != nullptr);
333f9500cc4SEduardo Caldas     assert(From.hasQualifier());
334f9500cc4SEduardo Caldas 
335f9500cc4SEduardo Caldas     bool Added = NNSNodes.insert({From, To}).second;
336f9500cc4SEduardo Caldas     (void)Added;
337f9500cc4SEduardo Caldas     assert(Added && "mapping added twice");
338f9500cc4SEduardo Caldas   }
339f9500cc4SEduardo Caldas 
find(ASTPtr P) const340a711a3a4SMarcel Hlopko   syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
341a711a3a4SMarcel Hlopko 
find(NestedNameSpecifierLoc P) const342f9500cc4SEduardo Caldas   syntax::Tree *find(NestedNameSpecifierLoc P) const {
343f9500cc4SEduardo Caldas     return NNSNodes.lookup(P);
344f9500cc4SEduardo Caldas   }
345f9500cc4SEduardo Caldas 
346a711a3a4SMarcel Hlopko private:
347a711a3a4SMarcel Hlopko   llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes;
348f9500cc4SEduardo Caldas   llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes;
349a711a3a4SMarcel Hlopko };
350a711a3a4SMarcel Hlopko } // namespace
351a711a3a4SMarcel Hlopko 
3529b3f38f9SIlya Biryukov /// A helper class for constructing the syntax tree while traversing a clang
3539b3f38f9SIlya Biryukov /// AST.
3549b3f38f9SIlya Biryukov ///
3559b3f38f9SIlya Biryukov /// At each point of the traversal we maintain a list of pending nodes.
3569b3f38f9SIlya Biryukov /// Initially all tokens are added as pending nodes. When processing a clang AST
3579b3f38f9SIlya Biryukov /// node, the clients need to:
3589b3f38f9SIlya Biryukov ///   - create a corresponding syntax node,
3599b3f38f9SIlya Biryukov ///   - assign roles to all pending child nodes with 'markChild' and
3609b3f38f9SIlya Biryukov ///     'markChildToken',
3619b3f38f9SIlya Biryukov ///   - replace the child nodes with the new syntax node in the pending list
3629b3f38f9SIlya Biryukov ///     with 'foldNode'.
3639b3f38f9SIlya Biryukov ///
3649b3f38f9SIlya Biryukov /// Note that all children are expected to be processed when building a node.
3659b3f38f9SIlya Biryukov ///
3669b3f38f9SIlya Biryukov /// Call finalize() to finish building the tree and consume the root node.
3679b3f38f9SIlya Biryukov class syntax::TreeBuilder {
3689b3f38f9SIlya Biryukov public:
TreeBuilder(syntax::Arena & Arena,TokenBufferTokenManager & TBTM)369*263dcf45SHaojian Wu   TreeBuilder(syntax::Arena &Arena, TokenBufferTokenManager& TBTM)
370*263dcf45SHaojian Wu       : Arena(Arena),
371*263dcf45SHaojian Wu         TBTM(TBTM),
372*263dcf45SHaojian Wu         Pending(Arena, TBTM.tokenBuffer()) {
373*263dcf45SHaojian Wu     for (const auto &T : TBTM.tokenBuffer().expandedTokens())
37478194118SMikhail Maltsev       LocationToToken.insert({T.location(), &T});
375c1bbefefSIlya Biryukov   }
3769b3f38f9SIlya Biryukov 
allocator()3774c14ee61SEduardo Caldas   llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); }
sourceManager() const3784c14ee61SEduardo Caldas   const SourceManager &sourceManager() const {
379*263dcf45SHaojian Wu     return TBTM.sourceManager();
3804c14ee61SEduardo Caldas   }
3819b3f38f9SIlya Biryukov 
3829b3f38f9SIlya Biryukov   /// Populate children for \p New node, assuming it covers tokens from \p
3839b3f38f9SIlya Biryukov   /// Range.
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,ASTPtr From)384ba41a0f7SEduardo Caldas   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) {
385a711a3a4SMarcel Hlopko     assert(New);
386*263dcf45SHaojian Wu     Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
387a711a3a4SMarcel Hlopko     if (From)
388a711a3a4SMarcel Hlopko       Mapping.add(From, New);
389a711a3a4SMarcel Hlopko   }
390f9500cc4SEduardo Caldas 
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,TypeLoc L)391ba41a0f7SEduardo Caldas   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) {
392a711a3a4SMarcel Hlopko     // FIXME: add mapping for TypeLocs
393a711a3a4SMarcel Hlopko     foldNode(Range, New, nullptr);
394a711a3a4SMarcel Hlopko   }
3959b3f38f9SIlya Biryukov 
foldNode(llvm::ArrayRef<syntax::Token> Range,syntax::Tree * New,NestedNameSpecifierLoc From)396f9500cc4SEduardo Caldas   void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
397f9500cc4SEduardo Caldas                 NestedNameSpecifierLoc From) {
398f9500cc4SEduardo Caldas     assert(New);
399*263dcf45SHaojian Wu     Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
400f9500cc4SEduardo Caldas     if (From)
401f9500cc4SEduardo Caldas       Mapping.add(From, New);
4028abb5fb6SEduardo Caldas   }
403f9500cc4SEduardo Caldas 
4045011d431SEduardo Caldas   /// Populate children for \p New list, assuming it covers tokens from a
4055011d431SEduardo Caldas   /// subrange of \p SuperRange.
foldList(ArrayRef<syntax::Token> SuperRange,syntax::List * New,ASTPtr From)4065011d431SEduardo Caldas   void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New,
4075011d431SEduardo Caldas                 ASTPtr From) {
4085011d431SEduardo Caldas     assert(New);
4095011d431SEduardo Caldas     auto ListRange = Pending.shrinkToFitList(SuperRange);
410*263dcf45SHaojian Wu     Pending.foldChildren(TBTM.tokenBuffer(), ListRange, New);
4115011d431SEduardo Caldas     if (From)
4125011d431SEduardo Caldas       Mapping.add(From, New);
4135011d431SEduardo Caldas   }
4145011d431SEduardo Caldas 
415e702bdb8SIlya Biryukov   /// Notifies that we should not consume trailing semicolon when computing
416e702bdb8SIlya Biryukov   /// token range of \p D.
4177d382dcdSMarcel Hlopko   void noticeDeclWithoutSemicolon(Decl *D);
418e702bdb8SIlya Biryukov 
41958fa50f4SIlya Biryukov   /// Mark the \p Child node with a corresponding \p Role. All marked children
42058fa50f4SIlya Biryukov   /// should be consumed by foldNode.
4217d382dcdSMarcel Hlopko   /// When called on expressions (clang::Expr is derived from clang::Stmt),
42258fa50f4SIlya Biryukov   /// wraps expressions into expression statement.
42358fa50f4SIlya Biryukov   void markStmtChild(Stmt *Child, NodeRole Role);
42458fa50f4SIlya Biryukov   /// Should be called for expressions in non-statement position to avoid
42558fa50f4SIlya Biryukov   /// wrapping into expression statement.
42658fa50f4SIlya Biryukov   void markExprChild(Expr *Child, NodeRole Role);
4279b3f38f9SIlya Biryukov   /// Set role for a token starting at \p Loc.
428def65bb4SIlya Biryukov   void markChildToken(SourceLocation Loc, NodeRole R);
4297d382dcdSMarcel Hlopko   /// Set role for \p T.
4307d382dcdSMarcel Hlopko   void markChildToken(const syntax::Token *T, NodeRole R);
4317d382dcdSMarcel Hlopko 
432a711a3a4SMarcel Hlopko   /// Set role for \p N.
433a711a3a4SMarcel Hlopko   void markChild(syntax::Node *N, NodeRole R);
434a711a3a4SMarcel Hlopko   /// Set role for the syntax node matching \p N.
435a711a3a4SMarcel Hlopko   void markChild(ASTPtr N, NodeRole R);
436f9500cc4SEduardo Caldas   /// Set role for the syntax node matching \p N.
437f9500cc4SEduardo Caldas   void markChild(NestedNameSpecifierLoc N, NodeRole R);
4389b3f38f9SIlya Biryukov 
4399b3f38f9SIlya Biryukov   /// Finish building the tree and consume the root node.
finalize()4409b3f38f9SIlya Biryukov   syntax::TranslationUnit *finalize() && {
441*263dcf45SHaojian Wu     auto Tokens = TBTM.tokenBuffer().expandedTokens();
442bfbf6b6cSIlya Biryukov     assert(!Tokens.empty());
443bfbf6b6cSIlya Biryukov     assert(Tokens.back().kind() == tok::eof);
444bfbf6b6cSIlya Biryukov 
4459b3f38f9SIlya Biryukov     // Build the root of the tree, consuming all the children.
446*263dcf45SHaojian Wu     Pending.foldChildren(TBTM.tokenBuffer(), Tokens.drop_back(),
4474c14ee61SEduardo Caldas                          new (Arena.getAllocator()) syntax::TranslationUnit);
4489b3f38f9SIlya Biryukov 
4493b929fe7SIlya Biryukov     auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize());
4503b929fe7SIlya Biryukov     TU->assertInvariantsRecursive();
4513b929fe7SIlya Biryukov     return TU;
4529b3f38f9SIlya Biryukov   }
4539b3f38f9SIlya Biryukov 
45488bf9b3dSMarcel Hlopko   /// Finds a token starting at \p L. The token must exist if \p L is valid.
45588bf9b3dSMarcel Hlopko   const syntax::Token *findToken(SourceLocation L) const;
45688bf9b3dSMarcel Hlopko 
457a711a3a4SMarcel Hlopko   /// Finds the syntax tokens corresponding to the \p SourceRange.
getRange(SourceRange Range) const458ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getRange(SourceRange Range) const {
459a711a3a4SMarcel Hlopko     assert(Range.isValid());
460a711a3a4SMarcel Hlopko     return getRange(Range.getBegin(), Range.getEnd());
461a711a3a4SMarcel Hlopko   }
462a711a3a4SMarcel Hlopko 
463a711a3a4SMarcel Hlopko   /// Finds the syntax tokens corresponding to the passed source locations.
4649b3f38f9SIlya Biryukov   /// \p First is the start position of the first token and \p Last is the start
4659b3f38f9SIlya Biryukov   /// position of the last token.
getRange(SourceLocation First,SourceLocation Last) const466ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getRange(SourceLocation First,
4679b3f38f9SIlya Biryukov                                    SourceLocation Last) const {
4689b3f38f9SIlya Biryukov     assert(First.isValid());
4699b3f38f9SIlya Biryukov     assert(Last.isValid());
4709b3f38f9SIlya Biryukov     assert(First == Last ||
471*263dcf45SHaojian Wu            TBTM.sourceManager().isBeforeInTranslationUnit(First, Last));
4729b3f38f9SIlya Biryukov     return llvm::makeArrayRef(findToken(First), std::next(findToken(Last)));
4739b3f38f9SIlya Biryukov   }
47488bf9b3dSMarcel Hlopko 
475ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token>
getTemplateRange(const ClassTemplateSpecializationDecl * D) const47688bf9b3dSMarcel Hlopko   getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
477a711a3a4SMarcel Hlopko     auto Tokens = getRange(D->getSourceRange());
47888bf9b3dSMarcel Hlopko     return maybeAppendSemicolon(Tokens, D);
47988bf9b3dSMarcel Hlopko   }
48088bf9b3dSMarcel Hlopko 
481cdce2fe5SMarcel Hlopko   /// Returns true if \p D is the last declarator in a chain and is thus
482cdce2fe5SMarcel Hlopko   /// reponsible for creating SimpleDeclaration for the whole chain.
isResponsibleForCreatingDeclaration(const Decl * D) const48338bc0060SEduardo Caldas   bool isResponsibleForCreatingDeclaration(const Decl *D) const {
48438bc0060SEduardo Caldas     assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
485cdce2fe5SMarcel Hlopko            "only DeclaratorDecl and TypedefNameDecl are supported.");
486cdce2fe5SMarcel Hlopko 
487cdce2fe5SMarcel Hlopko     const Decl *Next = D->getNextDeclInContext();
488cdce2fe5SMarcel Hlopko 
489cdce2fe5SMarcel Hlopko     // There's no next sibling, this one is responsible.
490cdce2fe5SMarcel Hlopko     if (Next == nullptr) {
491cdce2fe5SMarcel Hlopko       return true;
492cdce2fe5SMarcel Hlopko     }
493cdce2fe5SMarcel Hlopko 
494cdce2fe5SMarcel Hlopko     // Next sibling is not the same type, this one is responsible.
49538bc0060SEduardo Caldas     if (D->getKind() != Next->getKind()) {
496cdce2fe5SMarcel Hlopko       return true;
497cdce2fe5SMarcel Hlopko     }
498cdce2fe5SMarcel Hlopko     // Next sibling doesn't begin at the same loc, it must be a different
499cdce2fe5SMarcel Hlopko     // declaration, so this declarator is responsible.
50038bc0060SEduardo Caldas     if (Next->getBeginLoc() != D->getBeginLoc()) {
501cdce2fe5SMarcel Hlopko       return true;
502cdce2fe5SMarcel Hlopko     }
503cdce2fe5SMarcel Hlopko 
504cdce2fe5SMarcel Hlopko     // NextT is a member of the same declaration, and we need the last member to
505cdce2fe5SMarcel Hlopko     // create declaration. This one is not responsible.
506cdce2fe5SMarcel Hlopko     return false;
507cdce2fe5SMarcel Hlopko   }
508cdce2fe5SMarcel Hlopko 
getDeclarationRange(Decl * D)509ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
510ba41a0f7SEduardo Caldas     ArrayRef<syntax::Token> Tokens;
51188bf9b3dSMarcel Hlopko     // We want to drop the template parameters for specializations.
512ba41a0f7SEduardo Caldas     if (const auto *S = dyn_cast<TagDecl>(D))
51388bf9b3dSMarcel Hlopko       Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc());
51488bf9b3dSMarcel Hlopko     else
515a711a3a4SMarcel Hlopko       Tokens = getRange(D->getSourceRange());
51688bf9b3dSMarcel Hlopko     return maybeAppendSemicolon(Tokens, D);
5179b3f38f9SIlya Biryukov   }
518cdce2fe5SMarcel Hlopko 
getExprRange(const Expr * E) const519ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
520a711a3a4SMarcel Hlopko     return getRange(E->getSourceRange());
52158fa50f4SIlya Biryukov   }
522cdce2fe5SMarcel Hlopko 
52358fa50f4SIlya Biryukov   /// Find the adjusted range for the statement, consuming the trailing
52458fa50f4SIlya Biryukov   /// semicolon when needed.
getStmtRange(const Stmt * S) const525ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
526a711a3a4SMarcel Hlopko     auto Tokens = getRange(S->getSourceRange());
52758fa50f4SIlya Biryukov     if (isa<CompoundStmt>(S))
52858fa50f4SIlya Biryukov       return Tokens;
52958fa50f4SIlya Biryukov 
53058fa50f4SIlya Biryukov     // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and
53158fa50f4SIlya Biryukov     // all statements that end with those. Consume this semicolon here.
532e702bdb8SIlya Biryukov     if (Tokens.back().kind() == tok::semi)
533e702bdb8SIlya Biryukov       return Tokens;
534e702bdb8SIlya Biryukov     return withTrailingSemicolon(Tokens);
535e702bdb8SIlya Biryukov   }
536e702bdb8SIlya Biryukov 
537e702bdb8SIlya Biryukov private:
maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,const Decl * D) const538ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,
53988bf9b3dSMarcel Hlopko                                                const Decl *D) const {
540ba41a0f7SEduardo Caldas     if (isa<NamespaceDecl>(D))
54188bf9b3dSMarcel Hlopko       return Tokens;
54288bf9b3dSMarcel Hlopko     if (DeclsWithoutSemicolons.count(D))
54388bf9b3dSMarcel Hlopko       return Tokens;
54488bf9b3dSMarcel Hlopko     // FIXME: do not consume trailing semicolon on function definitions.
54588bf9b3dSMarcel Hlopko     // Most declarations own a semicolon in syntax trees, but not in clang AST.
54688bf9b3dSMarcel Hlopko     return withTrailingSemicolon(Tokens);
54788bf9b3dSMarcel Hlopko   }
54888bf9b3dSMarcel Hlopko 
549ba41a0f7SEduardo Caldas   ArrayRef<syntax::Token>
withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const550ba41a0f7SEduardo Caldas   withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const {
551e702bdb8SIlya Biryukov     assert(!Tokens.empty());
552e702bdb8SIlya Biryukov     assert(Tokens.back().kind() != tok::eof);
5537d382dcdSMarcel Hlopko     // We never consume 'eof', so looking at the next token is ok.
55458fa50f4SIlya Biryukov     if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi)
55558fa50f4SIlya Biryukov       return llvm::makeArrayRef(Tokens.begin(), Tokens.end() + 1);
55658fa50f4SIlya Biryukov     return Tokens;
5579b3f38f9SIlya Biryukov   }
5589b3f38f9SIlya Biryukov 
setRole(syntax::Node * N,NodeRole R)559a711a3a4SMarcel Hlopko   void setRole(syntax::Node *N, NodeRole R) {
5604c14ee61SEduardo Caldas     assert(N->getRole() == NodeRole::Detached);
561a711a3a4SMarcel Hlopko     N->setRole(R);
562a711a3a4SMarcel Hlopko   }
563a711a3a4SMarcel Hlopko 
5649b3f38f9SIlya Biryukov   /// A collection of trees covering the input tokens.
5659b3f38f9SIlya Biryukov   /// When created, each tree corresponds to a single token in the file.
5669b3f38f9SIlya Biryukov   /// Clients call 'foldChildren' to attach one or more subtrees to a parent
5679b3f38f9SIlya Biryukov   /// node and update the list of trees accordingly.
5689b3f38f9SIlya Biryukov   ///
5699b3f38f9SIlya Biryukov   /// Ensures that added nodes properly nest and cover the whole token stream.
5709b3f38f9SIlya Biryukov   struct Forest {
Forestsyntax::TreeBuilder::Forest571*263dcf45SHaojian Wu     Forest(syntax::Arena &A, const syntax::TokenBuffer &TB) {
572*263dcf45SHaojian Wu       assert(!TB.expandedTokens().empty());
573*263dcf45SHaojian Wu       assert(TB.expandedTokens().back().kind() == tok::eof);
5749b3f38f9SIlya Biryukov       // Create all leaf nodes.
575bfbf6b6cSIlya Biryukov       // Note that we do not have 'eof' in the tree.
576*263dcf45SHaojian Wu       for (const auto &T : TB.expandedTokens().drop_back()) {
577*263dcf45SHaojian Wu         auto *L = new (A.getAllocator())
578*263dcf45SHaojian Wu             syntax::Leaf(reinterpret_cast<TokenManager::Key>(&T));
5791ad15046SIlya Biryukov         L->Original = true;
580*263dcf45SHaojian Wu         L->CanModify = TB.spelledForExpanded(T).has_value();
581a711a3a4SMarcel Hlopko         Trees.insert(Trees.end(), {&T, L});
5821ad15046SIlya Biryukov       }
5839b3f38f9SIlya Biryukov     }
5849b3f38f9SIlya Biryukov 
assignRolesyntax::TreeBuilder::Forest585ba41a0f7SEduardo Caldas     void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) {
5869b3f38f9SIlya Biryukov       assert(!Range.empty());
5879b3f38f9SIlya Biryukov       auto It = Trees.lower_bound(Range.begin());
5889b3f38f9SIlya Biryukov       assert(It != Trees.end() && "no node found");
5899b3f38f9SIlya Biryukov       assert(It->first == Range.begin() && "no child with the specified range");
5909b3f38f9SIlya Biryukov       assert((std::next(It) == Trees.end() ||
5919b3f38f9SIlya Biryukov               std::next(It)->first == Range.end()) &&
5929b3f38f9SIlya Biryukov              "no child with the specified range");
5934c14ee61SEduardo Caldas       assert(It->second->getRole() == NodeRole::Detached &&
594a711a3a4SMarcel Hlopko              "re-assigning role for a child");
595a711a3a4SMarcel Hlopko       It->second->setRole(Role);
5969b3f38f9SIlya Biryukov     }
5979b3f38f9SIlya Biryukov 
5985011d431SEduardo Caldas     /// Shrink \p Range to a subrange that only contains tokens of a list.
5995011d431SEduardo Caldas     /// List elements and delimiters should already have correct roles.
shrinkToFitListsyntax::TreeBuilder::Forest6005011d431SEduardo Caldas     ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) {
6015011d431SEduardo Caldas       auto BeginChildren = Trees.lower_bound(Range.begin());
6025011d431SEduardo Caldas       assert((BeginChildren == Trees.end() ||
6035011d431SEduardo Caldas               BeginChildren->first == Range.begin()) &&
6045011d431SEduardo Caldas              "Range crosses boundaries of existing subtrees");
6055011d431SEduardo Caldas 
6065011d431SEduardo Caldas       auto EndChildren = Trees.lower_bound(Range.end());
6075011d431SEduardo Caldas       assert(
6085011d431SEduardo Caldas           (EndChildren == Trees.end() || EndChildren->first == Range.end()) &&
6095011d431SEduardo Caldas           "Range crosses boundaries of existing subtrees");
6105011d431SEduardo Caldas 
6115011d431SEduardo Caldas       auto BelongsToList = [](decltype(Trees)::value_type KV) {
6125011d431SEduardo Caldas         auto Role = KV.second->getRole();
6135011d431SEduardo Caldas         return Role == syntax::NodeRole::ListElement ||
6145011d431SEduardo Caldas                Role == syntax::NodeRole::ListDelimiter;
6155011d431SEduardo Caldas       };
6165011d431SEduardo Caldas 
6175011d431SEduardo Caldas       auto BeginListChildren =
6185011d431SEduardo Caldas           std::find_if(BeginChildren, EndChildren, BelongsToList);
6195011d431SEduardo Caldas 
6205011d431SEduardo Caldas       auto EndListChildren =
6215011d431SEduardo Caldas           std::find_if_not(BeginListChildren, EndChildren, BelongsToList);
6225011d431SEduardo Caldas 
6235011d431SEduardo Caldas       return ArrayRef<syntax::Token>(BeginListChildren->first,
6245011d431SEduardo Caldas                                      EndListChildren->first);
6255011d431SEduardo Caldas     }
6265011d431SEduardo Caldas 
627e702bdb8SIlya Biryukov     /// Add \p Node to the forest and attach child nodes based on \p Tokens.
foldChildrensyntax::TreeBuilder::Forest628*263dcf45SHaojian Wu     void foldChildren(const syntax::TokenBuffer &TB,
629*263dcf45SHaojian Wu                       ArrayRef<syntax::Token> Tokens, syntax::Tree *Node) {
630e702bdb8SIlya Biryukov       // Attach children to `Node`.
6314c14ee61SEduardo Caldas       assert(Node->getFirstChild() == nullptr && "node already has children");
632cdce2fe5SMarcel Hlopko 
633cdce2fe5SMarcel Hlopko       auto *FirstToken = Tokens.begin();
634cdce2fe5SMarcel Hlopko       auto BeginChildren = Trees.lower_bound(FirstToken);
635cdce2fe5SMarcel Hlopko 
636cdce2fe5SMarcel Hlopko       assert((BeginChildren == Trees.end() ||
637cdce2fe5SMarcel Hlopko               BeginChildren->first == FirstToken) &&
638cdce2fe5SMarcel Hlopko              "fold crosses boundaries of existing subtrees");
639cdce2fe5SMarcel Hlopko       auto EndChildren = Trees.lower_bound(Tokens.end());
640cdce2fe5SMarcel Hlopko       assert(
641cdce2fe5SMarcel Hlopko           (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) &&
642cdce2fe5SMarcel Hlopko           "fold crosses boundaries of existing subtrees");
643cdce2fe5SMarcel Hlopko 
64423657d9cSEduardo Caldas       for (auto It = BeginChildren; It != EndChildren; ++It) {
64523657d9cSEduardo Caldas         auto *C = It->second;
6464c14ee61SEduardo Caldas         if (C->getRole() == NodeRole::Detached)
647cdce2fe5SMarcel Hlopko           C->setRole(NodeRole::Unknown);
64823657d9cSEduardo Caldas         Node->appendChildLowLevel(C);
649e702bdb8SIlya Biryukov       }
6509b3f38f9SIlya Biryukov 
651cdce2fe5SMarcel Hlopko       // Mark that this node came from the AST and is backed by the source code.
652cdce2fe5SMarcel Hlopko       Node->Original = true;
6534c14ee61SEduardo Caldas       Node->CanModify =
654*263dcf45SHaojian Wu           TB.spelledForExpanded(Tokens).has_value();
6559b3f38f9SIlya Biryukov 
656cdce2fe5SMarcel Hlopko       Trees.erase(BeginChildren, EndChildren);
657cdce2fe5SMarcel Hlopko       Trees.insert({FirstToken, Node});
6589b3f38f9SIlya Biryukov     }
6599b3f38f9SIlya Biryukov 
6609b3f38f9SIlya Biryukov     // EXPECTS: all tokens were consumed and are owned by a single root node.
finalizesyntax::TreeBuilder::Forest6619b3f38f9SIlya Biryukov     syntax::Node *finalize() && {
6629b3f38f9SIlya Biryukov       assert(Trees.size() == 1);
663a711a3a4SMarcel Hlopko       auto *Root = Trees.begin()->second;
6649b3f38f9SIlya Biryukov       Trees = {};
6659b3f38f9SIlya Biryukov       return Root;
6669b3f38f9SIlya Biryukov     }
6679b3f38f9SIlya Biryukov 
strsyntax::TreeBuilder::Forest668*263dcf45SHaojian Wu     std::string str(const syntax::TokenBufferTokenManager &STM) const {
6699b3f38f9SIlya Biryukov       std::string R;
6709b3f38f9SIlya Biryukov       for (auto It = Trees.begin(); It != Trees.end(); ++It) {
6719b3f38f9SIlya Biryukov         unsigned CoveredTokens =
6729b3f38f9SIlya Biryukov             It != Trees.end()
6739b3f38f9SIlya Biryukov                 ? (std::next(It)->first - It->first)
674*263dcf45SHaojian Wu                 : STM.tokenBuffer().expandedTokens().end() - It->first;
6759b3f38f9SIlya Biryukov 
676ba41a0f7SEduardo Caldas         R += std::string(
6774c14ee61SEduardo Caldas             formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(),
678*263dcf45SHaojian Wu                     It->first->text(STM.sourceManager()), CoveredTokens));
679*263dcf45SHaojian Wu         R += It->second->dump(STM);
6809b3f38f9SIlya Biryukov       }
6819b3f38f9SIlya Biryukov       return R;
6829b3f38f9SIlya Biryukov     }
6839b3f38f9SIlya Biryukov 
6849b3f38f9SIlya Biryukov   private:
6859b3f38f9SIlya Biryukov     /// Maps from the start token to a subtree starting at that token.
686302cb3bcSIlya Biryukov     /// Keys in the map are pointers into the array of expanded tokens, so
687302cb3bcSIlya Biryukov     /// pointer order corresponds to the order of preprocessor tokens.
688a711a3a4SMarcel Hlopko     std::map<const syntax::Token *, syntax::Node *> Trees;
6899b3f38f9SIlya Biryukov   };
6909b3f38f9SIlya Biryukov 
6919b3f38f9SIlya Biryukov   /// For debugging purposes.
str()692*263dcf45SHaojian Wu   std::string str() { return Pending.str(TBTM); }
6939b3f38f9SIlya Biryukov 
6949b3f38f9SIlya Biryukov   syntax::Arena &Arena;
695*263dcf45SHaojian Wu   TokenBufferTokenManager& TBTM;
696c1bbefefSIlya Biryukov   /// To quickly find tokens by their start location.
69778194118SMikhail Maltsev   llvm::DenseMap<SourceLocation, const syntax::Token *> LocationToToken;
6989b3f38f9SIlya Biryukov   Forest Pending;
699e702bdb8SIlya Biryukov   llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
700a711a3a4SMarcel Hlopko   ASTToSyntaxMapping Mapping;
7019b3f38f9SIlya Biryukov };
7029b3f38f9SIlya Biryukov 
7039b3f38f9SIlya Biryukov namespace {
7049b3f38f9SIlya Biryukov class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
7059b3f38f9SIlya Biryukov public:
BuildTreeVisitor(ASTContext & Context,syntax::TreeBuilder & Builder)7061db5b348SEduardo Caldas   explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
7071db5b348SEduardo Caldas       : Builder(Builder), Context(Context) {}
7089b3f38f9SIlya Biryukov 
shouldTraversePostOrder() const7099b3f38f9SIlya Biryukov   bool shouldTraversePostOrder() const { return true; }
7109b3f38f9SIlya Biryukov 
WalkUpFromDeclaratorDecl(DeclaratorDecl * DD)7117d382dcdSMarcel Hlopko   bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
712cdce2fe5SMarcel Hlopko     return processDeclaratorAndDeclaration(DD);
7137d382dcdSMarcel Hlopko   }
7147d382dcdSMarcel Hlopko 
WalkUpFromTypedefNameDecl(TypedefNameDecl * TD)715cdce2fe5SMarcel Hlopko   bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
716cdce2fe5SMarcel Hlopko     return processDeclaratorAndDeclaration(TD);
7179b3f38f9SIlya Biryukov   }
7189b3f38f9SIlya Biryukov 
VisitDecl(Decl * D)7199b3f38f9SIlya Biryukov   bool VisitDecl(Decl *D) {
7209b3f38f9SIlya Biryukov     assert(!D->isImplicit());
721cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(D),
722a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownDeclaration(), D);
723e702bdb8SIlya Biryukov     return true;
724e702bdb8SIlya Biryukov   }
725e702bdb8SIlya Biryukov 
72688bf9b3dSMarcel Hlopko   // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
72788bf9b3dSMarcel Hlopko   // override Traverse.
72888bf9b3dSMarcel Hlopko   // FIXME: make RAV call WalkUpFrom* instead.
72988bf9b3dSMarcel Hlopko   bool
TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * C)73088bf9b3dSMarcel Hlopko   TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
73188bf9b3dSMarcel Hlopko     if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
73288bf9b3dSMarcel Hlopko       return false;
73388bf9b3dSMarcel Hlopko     if (C->isExplicitSpecialization())
73488bf9b3dSMarcel Hlopko       return true; // we are only interested in explicit instantiations.
735a711a3a4SMarcel Hlopko     auto *Declaration =
736a711a3a4SMarcel Hlopko         cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
73788bf9b3dSMarcel Hlopko     foldExplicitTemplateInstantiation(
73888bf9b3dSMarcel Hlopko         Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()),
739a711a3a4SMarcel Hlopko         Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
74088bf9b3dSMarcel Hlopko     return true;
74188bf9b3dSMarcel Hlopko   }
74288bf9b3dSMarcel Hlopko 
WalkUpFromTemplateDecl(TemplateDecl * S)74388bf9b3dSMarcel Hlopko   bool WalkUpFromTemplateDecl(TemplateDecl *S) {
74488bf9b3dSMarcel Hlopko     foldTemplateDeclaration(
745cdce2fe5SMarcel Hlopko         Builder.getDeclarationRange(S),
74688bf9b3dSMarcel Hlopko         Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
747cdce2fe5SMarcel Hlopko         Builder.getDeclarationRange(S->getTemplatedDecl()), S);
74888bf9b3dSMarcel Hlopko     return true;
74988bf9b3dSMarcel Hlopko   }
75088bf9b3dSMarcel Hlopko 
WalkUpFromTagDecl(TagDecl * C)751e702bdb8SIlya Biryukov   bool WalkUpFromTagDecl(TagDecl *C) {
75204f627f6SIlya Biryukov     // FIXME: build the ClassSpecifier node.
75388bf9b3dSMarcel Hlopko     if (!C->isFreeStanding()) {
75488bf9b3dSMarcel Hlopko       assert(C->getNumTemplateParameterLists() == 0);
75504f627f6SIlya Biryukov       return true;
75604f627f6SIlya Biryukov     }
757a711a3a4SMarcel Hlopko     handleFreeStandingTagDecl(C);
758a711a3a4SMarcel Hlopko     return true;
759a711a3a4SMarcel Hlopko   }
760a711a3a4SMarcel Hlopko 
handleFreeStandingTagDecl(TagDecl * C)761a711a3a4SMarcel Hlopko   syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
762a711a3a4SMarcel Hlopko     assert(C->isFreeStanding());
76388bf9b3dSMarcel Hlopko     // Class is a declaration specifier and needs a spanning declaration node.
764cdce2fe5SMarcel Hlopko     auto DeclarationRange = Builder.getDeclarationRange(C);
765a711a3a4SMarcel Hlopko     syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
766a711a3a4SMarcel Hlopko     Builder.foldNode(DeclarationRange, Result, nullptr);
76788bf9b3dSMarcel Hlopko 
76888bf9b3dSMarcel Hlopko     // Build TemplateDeclaration nodes if we had template parameters.
76988bf9b3dSMarcel Hlopko     auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
77088bf9b3dSMarcel Hlopko       const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
77188bf9b3dSMarcel Hlopko       auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end());
772a711a3a4SMarcel Hlopko       Result =
773a711a3a4SMarcel Hlopko           foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
77488bf9b3dSMarcel Hlopko       DeclarationRange = R;
77588bf9b3dSMarcel Hlopko     };
776ba41a0f7SEduardo Caldas     if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
77788bf9b3dSMarcel Hlopko       ConsumeTemplateParameters(*S->getTemplateParameters());
77888bf9b3dSMarcel Hlopko     for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
77988bf9b3dSMarcel Hlopko       ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
780a711a3a4SMarcel Hlopko     return Result;
7819b3f38f9SIlya Biryukov   }
7829b3f38f9SIlya Biryukov 
WalkUpFromTranslationUnitDecl(TranslationUnitDecl * TU)7839b3f38f9SIlya Biryukov   bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
7847d382dcdSMarcel Hlopko     // We do not want to call VisitDecl(), the declaration for translation
7859b3f38f9SIlya Biryukov     // unit is built by finalize().
7869b3f38f9SIlya Biryukov     return true;
7879b3f38f9SIlya Biryukov   }
7889b3f38f9SIlya Biryukov 
WalkUpFromCompoundStmt(CompoundStmt * S)7899b3f38f9SIlya Biryukov   bool WalkUpFromCompoundStmt(CompoundStmt *S) {
79051dad419SIlya Biryukov     using NodeRole = syntax::NodeRole;
7919b3f38f9SIlya Biryukov 
792def65bb4SIlya Biryukov     Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
79358fa50f4SIlya Biryukov     for (auto *Child : S->body())
794718e550cSEduardo Caldas       Builder.markStmtChild(Child, NodeRole::Statement);
795def65bb4SIlya Biryukov     Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
7969b3f38f9SIlya Biryukov 
79758fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
798a711a3a4SMarcel Hlopko                      new (allocator()) syntax::CompoundStatement, S);
7999b3f38f9SIlya Biryukov     return true;
8009b3f38f9SIlya Biryukov   }
8019b3f38f9SIlya Biryukov 
80258fa50f4SIlya Biryukov   // Some statements are not yet handled by syntax trees.
WalkUpFromStmt(Stmt * S)80358fa50f4SIlya Biryukov   bool WalkUpFromStmt(Stmt *S) {
80458fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
805a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownStatement, S);
80658fa50f4SIlya Biryukov     return true;
80758fa50f4SIlya Biryukov   }
80858fa50f4SIlya Biryukov 
TraverseIfStmt(IfStmt * S)8096c1a2330SHaojian Wu   bool TraverseIfStmt(IfStmt *S) {
8106c1a2330SHaojian Wu     bool Result = [&, this]() {
8116c1a2330SHaojian Wu       if (S->getInit() && !TraverseStmt(S->getInit())) {
8126c1a2330SHaojian Wu         return false;
8136c1a2330SHaojian Wu       }
8146c1a2330SHaojian Wu       // In cases where the condition is an initialized declaration in a
8156c1a2330SHaojian Wu       // statement, we want to preserve the declaration and ignore the
8166c1a2330SHaojian Wu       // implicit condition expression in the syntax tree.
8176c1a2330SHaojian Wu       if (S->hasVarStorage()) {
8186c1a2330SHaojian Wu         if (!TraverseStmt(S->getConditionVariableDeclStmt()))
8196c1a2330SHaojian Wu           return false;
8206c1a2330SHaojian Wu       } else if (S->getCond() && !TraverseStmt(S->getCond()))
8216c1a2330SHaojian Wu         return false;
8226c1a2330SHaojian Wu 
8236c1a2330SHaojian Wu       if (S->getThen() && !TraverseStmt(S->getThen()))
8246c1a2330SHaojian Wu         return false;
8256c1a2330SHaojian Wu       if (S->getElse() && !TraverseStmt(S->getElse()))
8266c1a2330SHaojian Wu         return false;
8276c1a2330SHaojian Wu       return true;
8286c1a2330SHaojian Wu     }();
8296c1a2330SHaojian Wu     WalkUpFromIfStmt(S);
8306c1a2330SHaojian Wu     return Result;
8316c1a2330SHaojian Wu   }
8326c1a2330SHaojian Wu 
TraverseCXXForRangeStmt(CXXForRangeStmt * S)83358fa50f4SIlya Biryukov   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
83458fa50f4SIlya Biryukov     // We override to traverse range initializer as VarDecl.
83558fa50f4SIlya Biryukov     // RAV traverses it as a statement, we produce invalid node kinds in that
83658fa50f4SIlya Biryukov     // case.
83758fa50f4SIlya Biryukov     // FIXME: should do this in RAV instead?
8387349479fSDmitri Gribenko     bool Result = [&, this]() {
83958fa50f4SIlya Biryukov       if (S->getInit() && !TraverseStmt(S->getInit()))
84058fa50f4SIlya Biryukov         return false;
84158fa50f4SIlya Biryukov       if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
84258fa50f4SIlya Biryukov         return false;
84358fa50f4SIlya Biryukov       if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
84458fa50f4SIlya Biryukov         return false;
84558fa50f4SIlya Biryukov       if (S->getBody() && !TraverseStmt(S->getBody()))
84658fa50f4SIlya Biryukov         return false;
84758fa50f4SIlya Biryukov       return true;
8487349479fSDmitri Gribenko     }();
8497349479fSDmitri Gribenko     WalkUpFromCXXForRangeStmt(S);
8507349479fSDmitri Gribenko     return Result;
85158fa50f4SIlya Biryukov   }
85258fa50f4SIlya Biryukov 
TraverseStmt(Stmt * S)85358fa50f4SIlya Biryukov   bool TraverseStmt(Stmt *S) {
854ba41a0f7SEduardo Caldas     if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) {
855e702bdb8SIlya Biryukov       // We want to consume the semicolon, make sure SimpleDeclaration does not.
856e702bdb8SIlya Biryukov       for (auto *D : DS->decls())
8577d382dcdSMarcel Hlopko         Builder.noticeDeclWithoutSemicolon(D);
858ba41a0f7SEduardo Caldas     } else if (auto *E = dyn_cast_or_null<Expr>(S)) {
8592325d6b4SEduardo Caldas       return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E));
86058fa50f4SIlya Biryukov     }
86158fa50f4SIlya Biryukov     return RecursiveASTVisitor::TraverseStmt(S);
86258fa50f4SIlya Biryukov   }
86358fa50f4SIlya Biryukov 
TraverseOpaqueValueExpr(OpaqueValueExpr * VE)864780ead41SHaojian Wu   bool TraverseOpaqueValueExpr(OpaqueValueExpr *VE) {
865780ead41SHaojian Wu     // OpaqueValue doesn't correspond to concrete syntax, ignore it.
866780ead41SHaojian Wu     return true;
867780ead41SHaojian Wu   }
868780ead41SHaojian Wu 
86958fa50f4SIlya Biryukov   // Some expressions are not yet handled by syntax trees.
WalkUpFromExpr(Expr * E)87058fa50f4SIlya Biryukov   bool WalkUpFromExpr(Expr *E) {
87158fa50f4SIlya Biryukov     assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
87258fa50f4SIlya Biryukov     Builder.foldNode(Builder.getExprRange(E),
873a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UnknownExpression, E);
87458fa50f4SIlya Biryukov     return true;
87558fa50f4SIlya Biryukov   }
87658fa50f4SIlya Biryukov 
TraverseUserDefinedLiteral(UserDefinedLiteral * S)877f33c2c27SEduardo Caldas   bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
878f33c2c27SEduardo Caldas     // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
879f33c2c27SEduardo Caldas     // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
880f33c2c27SEduardo Caldas     // UDL suffix location does not point to the beginning of a token, so we
881f33c2c27SEduardo Caldas     // can't represent the UDL suffix as a separate syntax tree node.
882f33c2c27SEduardo Caldas 
883f33c2c27SEduardo Caldas     return WalkUpFromUserDefinedLiteral(S);
884f33c2c27SEduardo Caldas   }
885f33c2c27SEduardo Caldas 
8861db5b348SEduardo Caldas   syntax::UserDefinedLiteralExpression *
buildUserDefinedLiteral(UserDefinedLiteral * S)8871db5b348SEduardo Caldas   buildUserDefinedLiteral(UserDefinedLiteral *S) {
888f33c2c27SEduardo Caldas     switch (S->getLiteralOperatorKind()) {
889ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Integer:
8901db5b348SEduardo Caldas       return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
891ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Floating:
8921db5b348SEduardo Caldas       return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
893ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Character:
8941db5b348SEduardo Caldas       return new (allocator()) syntax::CharUserDefinedLiteralExpression;
895ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_String:
8961db5b348SEduardo Caldas       return new (allocator()) syntax::StringUserDefinedLiteralExpression;
897ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Raw:
898ba41a0f7SEduardo Caldas     case UserDefinedLiteral::LOK_Template:
8991db5b348SEduardo Caldas       // For raw literal operator and numeric literal operator template we
9001db5b348SEduardo Caldas       // cannot get the type of the operand in the semantic AST. We get this
9011db5b348SEduardo Caldas       // information from the token. As integer and floating point have the same
9021db5b348SEduardo Caldas       // token kind, we run `NumericLiteralParser` again to distinguish them.
9031db5b348SEduardo Caldas       auto TokLoc = S->getBeginLoc();
9041db5b348SEduardo Caldas       auto TokSpelling =
905a474d5baSEduardo Caldas           Builder.findToken(TokLoc)->text(Context.getSourceManager());
9061db5b348SEduardo Caldas       auto Literal =
9071db5b348SEduardo Caldas           NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
9081db5b348SEduardo Caldas                                Context.getLangOpts(), Context.getTargetInfo(),
9091db5b348SEduardo Caldas                                Context.getDiagnostics());
9101db5b348SEduardo Caldas       if (Literal.isIntegerLiteral())
9111db5b348SEduardo Caldas         return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
912a474d5baSEduardo Caldas       else {
913a474d5baSEduardo Caldas         assert(Literal.isFloatingLiteral());
9141db5b348SEduardo Caldas         return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
915f33c2c27SEduardo Caldas       }
916f33c2c27SEduardo Caldas     }
917b8409c03SMichael Liao     llvm_unreachable("Unknown literal operator kind.");
918a474d5baSEduardo Caldas   }
919f33c2c27SEduardo Caldas 
WalkUpFromUserDefinedLiteral(UserDefinedLiteral * S)920f33c2c27SEduardo Caldas   bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
921f33c2c27SEduardo Caldas     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
9221db5b348SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
923f33c2c27SEduardo Caldas     return true;
924f33c2c27SEduardo Caldas   }
925f33c2c27SEduardo Caldas 
9268abb5fb6SEduardo Caldas   // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the
9278abb5fb6SEduardo Caldas   // `DependentTemplateSpecializationType` case.
928f9500cc4SEduardo Caldas   /// Given a nested-name-specifier return the range for the last name
929f9500cc4SEduardo Caldas   /// specifier.
9308abb5fb6SEduardo Caldas   ///
9318abb5fb6SEduardo Caldas   /// e.g. `std::T::template X<U>::` => `template X<U>::`
getLocalSourceRange(const NestedNameSpecifierLoc & NNSLoc)9328abb5fb6SEduardo Caldas   SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) {
9338abb5fb6SEduardo Caldas     auto SR = NNSLoc.getLocalSourceRange();
9348abb5fb6SEduardo Caldas 
935f9500cc4SEduardo Caldas     // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should*
936f9500cc4SEduardo Caldas     // return the desired `SourceRange`, but there is a corner case. For a
937f9500cc4SEduardo Caldas     // `DependentTemplateSpecializationType` this method returns its
9388abb5fb6SEduardo Caldas     // qualifiers as well, in other words in the example above this method
9398abb5fb6SEduardo Caldas     // returns `T::template X<U>::` instead of only `template X<U>::`
9408abb5fb6SEduardo Caldas     if (auto TL = NNSLoc.getTypeLoc()) {
9418abb5fb6SEduardo Caldas       if (auto DependentTL =
9428abb5fb6SEduardo Caldas               TL.getAs<DependentTemplateSpecializationTypeLoc>()) {
9438abb5fb6SEduardo Caldas         // The 'template' keyword is always present in dependent template
9448abb5fb6SEduardo Caldas         // specializations. Except in the case of incorrect code
9458abb5fb6SEduardo Caldas         // TODO: Treat the case of incorrect code.
9468abb5fb6SEduardo Caldas         SR.setBegin(DependentTL.getTemplateKeywordLoc());
9478abb5fb6SEduardo Caldas       }
9488abb5fb6SEduardo Caldas     }
9498abb5fb6SEduardo Caldas 
9508abb5fb6SEduardo Caldas     return SR;
9518abb5fb6SEduardo Caldas   }
9528abb5fb6SEduardo Caldas 
getNameSpecifierKind(const NestedNameSpecifier & NNS)953f9500cc4SEduardo Caldas   syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) {
954f9500cc4SEduardo Caldas     switch (NNS.getKind()) {
955f9500cc4SEduardo Caldas     case NestedNameSpecifier::Global:
956f9500cc4SEduardo Caldas       return syntax::NodeKind::GlobalNameSpecifier;
957f9500cc4SEduardo Caldas     case NestedNameSpecifier::Namespace:
958f9500cc4SEduardo Caldas     case NestedNameSpecifier::NamespaceAlias:
959f9500cc4SEduardo Caldas     case NestedNameSpecifier::Identifier:
960f9500cc4SEduardo Caldas       return syntax::NodeKind::IdentifierNameSpecifier;
961f9500cc4SEduardo Caldas     case NestedNameSpecifier::TypeSpecWithTemplate:
962f9500cc4SEduardo Caldas       return syntax::NodeKind::SimpleTemplateNameSpecifier;
963f9500cc4SEduardo Caldas     case NestedNameSpecifier::TypeSpec: {
964f9500cc4SEduardo Caldas       const auto *NNSType = NNS.getAsType();
965f9500cc4SEduardo Caldas       assert(NNSType);
966f9500cc4SEduardo Caldas       if (isa<DecltypeType>(NNSType))
967f9500cc4SEduardo Caldas         return syntax::NodeKind::DecltypeNameSpecifier;
968f9500cc4SEduardo Caldas       if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>(
969f9500cc4SEduardo Caldas               NNSType))
970f9500cc4SEduardo Caldas         return syntax::NodeKind::SimpleTemplateNameSpecifier;
971f9500cc4SEduardo Caldas       return syntax::NodeKind::IdentifierNameSpecifier;
972f9500cc4SEduardo Caldas     }
973f9500cc4SEduardo Caldas     default:
974f9500cc4SEduardo Caldas       // FIXME: Support Microsoft's __super
975f9500cc4SEduardo Caldas       llvm::report_fatal_error("We don't yet support the __super specifier",
976f9500cc4SEduardo Caldas                                true);
977f9500cc4SEduardo Caldas     }
978f9500cc4SEduardo Caldas   }
979f9500cc4SEduardo Caldas 
980f9500cc4SEduardo Caldas   syntax::NameSpecifier *
buildNameSpecifier(const NestedNameSpecifierLoc & NNSLoc)981ac87a0b5SEduardo Caldas   buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) {
982f9500cc4SEduardo Caldas     assert(NNSLoc.hasQualifier());
983f9500cc4SEduardo Caldas     auto NameSpecifierTokens =
984f9500cc4SEduardo Caldas         Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back();
985f9500cc4SEduardo Caldas     switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) {
986f9500cc4SEduardo Caldas     case syntax::NodeKind::GlobalNameSpecifier:
987f9500cc4SEduardo Caldas       return new (allocator()) syntax::GlobalNameSpecifier;
988f9500cc4SEduardo Caldas     case syntax::NodeKind::IdentifierNameSpecifier: {
989f9500cc4SEduardo Caldas       assert(NameSpecifierTokens.size() == 1);
990f9500cc4SEduardo Caldas       Builder.markChildToken(NameSpecifierTokens.begin(),
991f9500cc4SEduardo Caldas                              syntax::NodeRole::Unknown);
992f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::IdentifierNameSpecifier;
993f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
994f9500cc4SEduardo Caldas       return NS;
995f9500cc4SEduardo Caldas     }
996f9500cc4SEduardo Caldas     case syntax::NodeKind::SimpleTemplateNameSpecifier: {
997f9500cc4SEduardo Caldas       // TODO: Build `SimpleTemplateNameSpecifier` children and implement
998f9500cc4SEduardo Caldas       // accessors to them.
999f9500cc4SEduardo Caldas       // Be aware, we cannot do that simply by calling `TraverseTypeLoc`,
1000f9500cc4SEduardo Caldas       // some `TypeLoc`s have inside them the previous name specifier and
1001f9500cc4SEduardo Caldas       // we want to treat them independently.
1002f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier;
1003f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1004f9500cc4SEduardo Caldas       return NS;
1005f9500cc4SEduardo Caldas     }
1006f9500cc4SEduardo Caldas     case syntax::NodeKind::DecltypeNameSpecifier: {
1007f9500cc4SEduardo Caldas       const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>();
1008f9500cc4SEduardo Caldas       if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL))
10098abb5fb6SEduardo Caldas         return nullptr;
1010f9500cc4SEduardo Caldas       auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
1011f9500cc4SEduardo Caldas       // TODO: Implement accessor to `DecltypeNameSpecifier` inner
1012f9500cc4SEduardo Caldas       // `DecltypeTypeLoc`.
1013f9500cc4SEduardo Caldas       // For that add mapping from `TypeLoc` to `syntax::Node*` then:
1014f9500cc4SEduardo Caldas       // Builder.markChild(TypeLoc, syntax::NodeRole);
1015f9500cc4SEduardo Caldas       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1016f9500cc4SEduardo Caldas       return NS;
1017f9500cc4SEduardo Caldas     }
1018f9500cc4SEduardo Caldas     default:
1019f9500cc4SEduardo Caldas       llvm_unreachable("getChildKind() does not return this value");
1020f9500cc4SEduardo Caldas     }
1021f9500cc4SEduardo Caldas   }
1022f9500cc4SEduardo Caldas 
1023f9500cc4SEduardo Caldas   // To build syntax tree nodes for NestedNameSpecifierLoc we override
1024f9500cc4SEduardo Caldas   // Traverse instead of WalkUpFrom because we want to traverse the children
1025f9500cc4SEduardo Caldas   // ourselves and build a list instead of a nested tree of name specifier
1026f9500cc4SEduardo Caldas   // prefixes.
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc)1027f9500cc4SEduardo Caldas   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) {
1028f9500cc4SEduardo Caldas     if (!QualifierLoc)
1029f9500cc4SEduardo Caldas       return true;
103087f0b51dSEduardo Caldas     for (auto It = QualifierLoc; It; It = It.getPrefix()) {
103187f0b51dSEduardo Caldas       auto *NS = buildNameSpecifier(It);
1032f9500cc4SEduardo Caldas       if (!NS)
1033f9500cc4SEduardo Caldas         return false;
1034718e550cSEduardo Caldas       Builder.markChild(NS, syntax::NodeRole::ListElement);
103587f0b51dSEduardo Caldas       Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
10368abb5fb6SEduardo Caldas     }
1037f9500cc4SEduardo Caldas     Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1038f9500cc4SEduardo Caldas                      new (allocator()) syntax::NestedNameSpecifier,
10398abb5fb6SEduardo Caldas                      QualifierLoc);
1040f9500cc4SEduardo Caldas     return true;
10418abb5fb6SEduardo Caldas   }
10428abb5fb6SEduardo Caldas 
buildIdExpression(NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKeywordLoc,SourceRange UnqualifiedIdLoc,ASTPtr From)1043a4ef9e86SEduardo Caldas   syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1044a4ef9e86SEduardo Caldas                                           SourceLocation TemplateKeywordLoc,
1045a4ef9e86SEduardo Caldas                                           SourceRange UnqualifiedIdLoc,
1046a4ef9e86SEduardo Caldas                                           ASTPtr From) {
1047a4ef9e86SEduardo Caldas     if (QualifierLoc) {
1048718e550cSEduardo Caldas       Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1049ba32915dSEduardo Caldas       if (TemplateKeywordLoc.isValid())
1050ba32915dSEduardo Caldas         Builder.markChildToken(TemplateKeywordLoc,
1051ba32915dSEduardo Caldas                                syntax::NodeRole::TemplateKeyword);
1052a4ef9e86SEduardo Caldas     }
1053ba32915dSEduardo Caldas 
1054ba32915dSEduardo Caldas     auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1055a4ef9e86SEduardo Caldas     Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1056a4ef9e86SEduardo Caldas                      nullptr);
1057718e550cSEduardo Caldas     Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1058ba32915dSEduardo Caldas 
1059a4ef9e86SEduardo Caldas     auto IdExpressionBeginLoc =
1060a4ef9e86SEduardo Caldas         QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1061ba32915dSEduardo Caldas 
1062a4ef9e86SEduardo Caldas     auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1063a4ef9e86SEduardo Caldas     Builder.foldNode(
1064a4ef9e86SEduardo Caldas         Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1065a4ef9e86SEduardo Caldas         TheIdExpression, From);
1066a4ef9e86SEduardo Caldas 
1067a4ef9e86SEduardo Caldas     return TheIdExpression;
1068a4ef9e86SEduardo Caldas   }
1069a4ef9e86SEduardo Caldas 
WalkUpFromMemberExpr(MemberExpr * S)1070a4ef9e86SEduardo Caldas   bool WalkUpFromMemberExpr(MemberExpr *S) {
1071ba32915dSEduardo Caldas     // For `MemberExpr` with implicit `this->` we generate a simple
1072ba32915dSEduardo Caldas     // `id-expression` syntax node, beacuse an implicit `member-expression` is
1073ba32915dSEduardo Caldas     // syntactically undistinguishable from an `id-expression`
1074ba32915dSEduardo Caldas     if (S->isImplicitAccess()) {
1075a4ef9e86SEduardo Caldas       buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1076a4ef9e86SEduardo Caldas                         SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1077ba32915dSEduardo Caldas       return true;
1078ba32915dSEduardo Caldas     }
1079a4ef9e86SEduardo Caldas 
1080a4ef9e86SEduardo Caldas     auto *TheIdExpression = buildIdExpression(
1081a4ef9e86SEduardo Caldas         S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1082a4ef9e86SEduardo Caldas         SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1083ba32915dSEduardo Caldas 
1084718e550cSEduardo Caldas     Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1085ba32915dSEduardo Caldas 
1086718e550cSEduardo Caldas     Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1087718e550cSEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1088ba32915dSEduardo Caldas 
1089ba32915dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1090ba32915dSEduardo Caldas                      new (allocator()) syntax::MemberExpression, S);
1091ba32915dSEduardo Caldas     return true;
1092ba32915dSEduardo Caldas   }
1093ba32915dSEduardo Caldas 
WalkUpFromDeclRefExpr(DeclRefExpr * S)10941b2f6b4aSEduardo Caldas   bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
1095a4ef9e86SEduardo Caldas     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1096a4ef9e86SEduardo Caldas                       SourceRange(S->getLocation(), S->getEndLoc()), S);
10978abb5fb6SEduardo Caldas 
10988abb5fb6SEduardo Caldas     return true;
10991b2f6b4aSEduardo Caldas   }
11008abb5fb6SEduardo Caldas 
11018abb5fb6SEduardo Caldas   // Same logic as DeclRefExpr.
WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr * S)11028abb5fb6SEduardo Caldas   bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) {
1103a4ef9e86SEduardo Caldas     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1104a4ef9e86SEduardo Caldas                       SourceRange(S->getLocation(), S->getEndLoc()), S);
11058abb5fb6SEduardo Caldas 
11061b2f6b4aSEduardo Caldas     return true;
11071b2f6b4aSEduardo Caldas   }
11081b2f6b4aSEduardo Caldas 
WalkUpFromCXXThisExpr(CXXThisExpr * S)110985c15f17SEduardo Caldas   bool WalkUpFromCXXThisExpr(CXXThisExpr *S) {
111085c15f17SEduardo Caldas     if (!S->isImplicit()) {
111185c15f17SEduardo Caldas       Builder.markChildToken(S->getLocation(),
111285c15f17SEduardo Caldas                              syntax::NodeRole::IntroducerKeyword);
111385c15f17SEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
111485c15f17SEduardo Caldas                        new (allocator()) syntax::ThisExpression, S);
111585c15f17SEduardo Caldas     }
111685c15f17SEduardo Caldas     return true;
111785c15f17SEduardo Caldas   }
111885c15f17SEduardo Caldas 
WalkUpFromParenExpr(ParenExpr * S)1119fdbd7833SEduardo Caldas   bool WalkUpFromParenExpr(ParenExpr *S) {
1120fdbd7833SEduardo Caldas     Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1121718e550cSEduardo Caldas     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1122fdbd7833SEduardo Caldas     Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1123fdbd7833SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1124fdbd7833SEduardo Caldas                      new (allocator()) syntax::ParenExpression, S);
1125fdbd7833SEduardo Caldas     return true;
1126fdbd7833SEduardo Caldas   }
1127fdbd7833SEduardo Caldas 
WalkUpFromIntegerLiteral(IntegerLiteral * S)11283b739690SEduardo Caldas   bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
112942f6fec3SEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11303b739690SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11313b739690SEduardo Caldas                      new (allocator()) syntax::IntegerLiteralExpression, S);
11323b739690SEduardo Caldas     return true;
11333b739690SEduardo Caldas   }
11343b739690SEduardo Caldas 
WalkUpFromCharacterLiteral(CharacterLiteral * S)1135221d7bbeSEduardo Caldas   bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
1136221d7bbeSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1137221d7bbeSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1138221d7bbeSEduardo Caldas                      new (allocator()) syntax::CharacterLiteralExpression, S);
1139221d7bbeSEduardo Caldas     return true;
1140221d7bbeSEduardo Caldas   }
11417b404b6dSEduardo Caldas 
WalkUpFromFloatingLiteral(FloatingLiteral * S)11427b404b6dSEduardo Caldas   bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
11437b404b6dSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11447b404b6dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11457b404b6dSEduardo Caldas                      new (allocator()) syntax::FloatingLiteralExpression, S);
11467b404b6dSEduardo Caldas     return true;
11477b404b6dSEduardo Caldas   }
11487b404b6dSEduardo Caldas 
WalkUpFromStringLiteral(StringLiteral * S)1149466e8b7eSEduardo Caldas   bool WalkUpFromStringLiteral(StringLiteral *S) {
1150466e8b7eSEduardo Caldas     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1151466e8b7eSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1152466e8b7eSEduardo Caldas                      new (allocator()) syntax::StringLiteralExpression, S);
1153466e8b7eSEduardo Caldas     return true;
1154466e8b7eSEduardo Caldas   }
1155221d7bbeSEduardo Caldas 
WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr * S)11567b404b6dSEduardo Caldas   bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
11577b404b6dSEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11587b404b6dSEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11597b404b6dSEduardo Caldas                      new (allocator()) syntax::BoolLiteralExpression, S);
11607b404b6dSEduardo Caldas     return true;
11617b404b6dSEduardo Caldas   }
11627b404b6dSEduardo Caldas 
WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr * S)1163007098d7SEduardo Caldas   bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
116442f6fec3SEduardo Caldas     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1165007098d7SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
1166007098d7SEduardo Caldas                      new (allocator()) syntax::CxxNullPtrExpression, S);
1167007098d7SEduardo Caldas     return true;
1168007098d7SEduardo Caldas   }
1169007098d7SEduardo Caldas 
WalkUpFromUnaryOperator(UnaryOperator * S)1170461af57dSEduardo Caldas   bool WalkUpFromUnaryOperator(UnaryOperator *S) {
117142f6fec3SEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(),
1172718e550cSEduardo Caldas                            syntax::NodeRole::OperatorToken);
1173718e550cSEduardo Caldas     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1174461af57dSEduardo Caldas 
1175461af57dSEduardo Caldas     if (S->isPostfix())
1176461af57dSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1177461af57dSEduardo Caldas                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1178461af57dSEduardo Caldas                        S);
1179461af57dSEduardo Caldas     else
1180461af57dSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1181461af57dSEduardo Caldas                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1182461af57dSEduardo Caldas                        S);
1183461af57dSEduardo Caldas 
1184461af57dSEduardo Caldas     return true;
1185461af57dSEduardo Caldas   }
1186461af57dSEduardo Caldas 
WalkUpFromBinaryOperator(BinaryOperator * S)11873785eb83SEduardo Caldas   bool WalkUpFromBinaryOperator(BinaryOperator *S) {
1188718e550cSEduardo Caldas     Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
118942f6fec3SEduardo Caldas     Builder.markChildToken(S->getOperatorLoc(),
1190718e550cSEduardo Caldas                            syntax::NodeRole::OperatorToken);
1191718e550cSEduardo Caldas     Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
11923785eb83SEduardo Caldas     Builder.foldNode(Builder.getExprRange(S),
11933785eb83SEduardo Caldas                      new (allocator()) syntax::BinaryOperatorExpression, S);
11943785eb83SEduardo Caldas     return true;
11953785eb83SEduardo Caldas   }
11963785eb83SEduardo Caldas 
1197f5087d5cSEduardo Caldas   /// Builds `CallArguments` syntax node from arguments that appear in source
1198f5087d5cSEduardo Caldas   /// code, i.e. not default arguments.
1199f5087d5cSEduardo Caldas   syntax::CallArguments *
buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs)1200f5087d5cSEduardo Caldas   buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) {
1201f5087d5cSEduardo Caldas     auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1202e10df779SDmitri Gribenko     for (auto *Arg : Args) {
1203718e550cSEduardo Caldas       Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
12042de2ca34SEduardo Caldas       const auto *DelimiterToken =
12052de2ca34SEduardo Caldas           std::next(Builder.findToken(Arg->getEndLoc()));
12062de2ca34SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1207718e550cSEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
12082de2ca34SEduardo Caldas     }
12092de2ca34SEduardo Caldas 
12102de2ca34SEduardo Caldas     auto *Arguments = new (allocator()) syntax::CallArguments;
12112de2ca34SEduardo Caldas     if (!Args.empty())
12122de2ca34SEduardo Caldas       Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
12132de2ca34SEduardo Caldas                                         (*(Args.end() - 1))->getEndLoc()),
12142de2ca34SEduardo Caldas                        Arguments, nullptr);
12152de2ca34SEduardo Caldas 
12162de2ca34SEduardo Caldas     return Arguments;
12172de2ca34SEduardo Caldas   }
12182de2ca34SEduardo Caldas 
WalkUpFromCallExpr(CallExpr * S)12192de2ca34SEduardo Caldas   bool WalkUpFromCallExpr(CallExpr *S) {
1220718e550cSEduardo Caldas     Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
12212de2ca34SEduardo Caldas 
12222de2ca34SEduardo Caldas     const auto *LParenToken =
12232de2ca34SEduardo Caldas         std::next(Builder.findToken(S->getCallee()->getEndLoc()));
12242de2ca34SEduardo Caldas     // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
12252de2ca34SEduardo Caldas     // the test on decltype desctructors.
12262de2ca34SEduardo Caldas     if (LParenToken->kind() == clang::tok::l_paren)
12272de2ca34SEduardo Caldas       Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
12282de2ca34SEduardo Caldas 
12292de2ca34SEduardo Caldas     Builder.markChild(buildCallArguments(S->arguments()),
1230718e550cSEduardo Caldas                       syntax::NodeRole::Arguments);
12312de2ca34SEduardo Caldas 
12322de2ca34SEduardo Caldas     Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
12332de2ca34SEduardo Caldas 
12342de2ca34SEduardo Caldas     Builder.foldNode(Builder.getRange(S->getSourceRange()),
12352de2ca34SEduardo Caldas                      new (allocator()) syntax::CallExpression, S);
12362de2ca34SEduardo Caldas     return true;
12372de2ca34SEduardo Caldas   }
12382de2ca34SEduardo Caldas 
WalkUpFromCXXConstructExpr(CXXConstructExpr * S)123946f4439dSEduardo Caldas   bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
124046f4439dSEduardo Caldas     // Ignore the implicit calls to default constructors.
124146f4439dSEduardo Caldas     if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
124246f4439dSEduardo Caldas         S->getParenOrBraceRange().isInvalid())
124346f4439dSEduardo Caldas       return true;
124446f4439dSEduardo Caldas     return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
124546f4439dSEduardo Caldas   }
124646f4439dSEduardo Caldas 
TraverseCXXOperatorCallExpr(CXXOperatorCallExpr * S)1247ea8bba7eSEduardo Caldas   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1248ac37afa6SEduardo Caldas     // To construct a syntax tree of the same shape for calls to built-in and
1249ac37afa6SEduardo Caldas     // user-defined operators, ignore the `DeclRefExpr` that refers to the
1250ac37afa6SEduardo Caldas     // operator and treat it as a simple token. Do that by traversing
1251ac37afa6SEduardo Caldas     // arguments instead of children.
1252ac37afa6SEduardo Caldas     for (auto *child : S->arguments()) {
1253f33c2c27SEduardo Caldas       // A postfix unary operator is declared as taking two operands. The
1254f33c2c27SEduardo Caldas       // second operand is used to distinguish from its prefix counterpart. In
1255f33c2c27SEduardo Caldas       // the semantic AST this "phantom" operand is represented as a
1256ea8bba7eSEduardo Caldas       // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1257ea8bba7eSEduardo Caldas       // operand because it does not correspond to anything written in source
1258ac37afa6SEduardo Caldas       // code.
1259ac37afa6SEduardo Caldas       if (child->getSourceRange().isInvalid()) {
1260ac37afa6SEduardo Caldas         assert(getOperatorNodeKind(*S) ==
1261ac37afa6SEduardo Caldas                syntax::NodeKind::PostfixUnaryOperatorExpression);
1262ea8bba7eSEduardo Caldas         continue;
1263ac37afa6SEduardo Caldas       }
1264ea8bba7eSEduardo Caldas       if (!TraverseStmt(child))
1265ea8bba7eSEduardo Caldas         return false;
1266ea8bba7eSEduardo Caldas     }
1267ea8bba7eSEduardo Caldas     return WalkUpFromCXXOperatorCallExpr(S);
1268ea8bba7eSEduardo Caldas   }
1269ea8bba7eSEduardo Caldas 
WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr * S)12703a574a6cSEduardo Caldas   bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1271ea8bba7eSEduardo Caldas     switch (getOperatorNodeKind(*S)) {
1272ea8bba7eSEduardo Caldas     case syntax::NodeKind::BinaryOperatorExpression:
1273718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1274718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1275718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1276718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
12773a574a6cSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
12783a574a6cSEduardo Caldas                        new (allocator()) syntax::BinaryOperatorExpression, S);
12793a574a6cSEduardo Caldas       return true;
1280ea8bba7eSEduardo Caldas     case syntax::NodeKind::PrefixUnaryOperatorExpression:
1281718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1282718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1283718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1284ea8bba7eSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1285ea8bba7eSEduardo Caldas                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1286ea8bba7eSEduardo Caldas                        S);
1287ea8bba7eSEduardo Caldas       return true;
1288ea8bba7eSEduardo Caldas     case syntax::NodeKind::PostfixUnaryOperatorExpression:
1289718e550cSEduardo Caldas       Builder.markChildToken(S->getOperatorLoc(),
1290718e550cSEduardo Caldas                              syntax::NodeRole::OperatorToken);
1291718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1292ea8bba7eSEduardo Caldas       Builder.foldNode(Builder.getExprRange(S),
1293ea8bba7eSEduardo Caldas                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1294ea8bba7eSEduardo Caldas                        S);
1295ea8bba7eSEduardo Caldas       return true;
12962de2ca34SEduardo Caldas     case syntax::NodeKind::CallExpression: {
1297718e550cSEduardo Caldas       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
12982de2ca34SEduardo Caldas 
12992de2ca34SEduardo Caldas       const auto *LParenToken =
13002de2ca34SEduardo Caldas           std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
13012de2ca34SEduardo Caldas       // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
13022de2ca34SEduardo Caldas       // fixed the test on decltype desctructors.
13032de2ca34SEduardo Caldas       if (LParenToken->kind() == clang::tok::l_paren)
13042de2ca34SEduardo Caldas         Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
13052de2ca34SEduardo Caldas 
13062de2ca34SEduardo Caldas       Builder.markChild(buildCallArguments(CallExpr::arg_range(
13072de2ca34SEduardo Caldas                             S->arg_begin() + 1, S->arg_end())),
1308718e550cSEduardo Caldas                         syntax::NodeRole::Arguments);
13092de2ca34SEduardo Caldas 
13102de2ca34SEduardo Caldas       Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
13112de2ca34SEduardo Caldas 
13122de2ca34SEduardo Caldas       Builder.foldNode(Builder.getRange(S->getSourceRange()),
13132de2ca34SEduardo Caldas                        new (allocator()) syntax::CallExpression, S);
13142de2ca34SEduardo Caldas       return true;
13152de2ca34SEduardo Caldas     }
1316ea8bba7eSEduardo Caldas     case syntax::NodeKind::UnknownExpression:
13172de2ca34SEduardo Caldas       return WalkUpFromExpr(S);
1318ea8bba7eSEduardo Caldas     default:
1319ea8bba7eSEduardo Caldas       llvm_unreachable("getOperatorNodeKind() does not return this value");
1320ea8bba7eSEduardo Caldas     }
13213a574a6cSEduardo Caldas   }
13223a574a6cSEduardo Caldas 
WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr * S)1323f5087d5cSEduardo Caldas   bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; }
1324f5087d5cSEduardo Caldas 
WalkUpFromNamespaceDecl(NamespaceDecl * S)1325be14a22bSIlya Biryukov   bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
1326cdce2fe5SMarcel Hlopko     auto Tokens = Builder.getDeclarationRange(S);
1327be14a22bSIlya Biryukov     if (Tokens.front().kind() == tok::coloncolon) {
1328be14a22bSIlya Biryukov       // Handle nested namespace definitions. Those start at '::' token, e.g.
1329be14a22bSIlya Biryukov       // namespace a^::b {}
1330be14a22bSIlya Biryukov       // FIXME: build corresponding nodes for the name of this namespace.
1331be14a22bSIlya Biryukov       return true;
1332be14a22bSIlya Biryukov     }
1333a711a3a4SMarcel Hlopko     Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1334be14a22bSIlya Biryukov     return true;
1335be14a22bSIlya Biryukov   }
1336be14a22bSIlya Biryukov 
13378ce15f7eSEduardo Caldas   // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
13388ce15f7eSEduardo Caldas   // results. Find test coverage or remove it.
TraverseParenTypeLoc(ParenTypeLoc L)13397d382dcdSMarcel Hlopko   bool TraverseParenTypeLoc(ParenTypeLoc L) {
13407d382dcdSMarcel Hlopko     // We reverse order of traversal to get the proper syntax structure.
13417d382dcdSMarcel Hlopko     if (!WalkUpFromParenTypeLoc(L))
13427d382dcdSMarcel Hlopko       return false;
13437d382dcdSMarcel Hlopko     return TraverseTypeLoc(L.getInnerLoc());
13447d382dcdSMarcel Hlopko   }
13457d382dcdSMarcel Hlopko 
WalkUpFromParenTypeLoc(ParenTypeLoc L)13467d382dcdSMarcel Hlopko   bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
13477d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
13487d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13497d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1350a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ParenDeclarator, L);
13517d382dcdSMarcel Hlopko     return true;
13527d382dcdSMarcel Hlopko   }
13537d382dcdSMarcel Hlopko 
13547d382dcdSMarcel Hlopko   // Declarator chunks, they are produced by type locs and some clang::Decls.
WalkUpFromArrayTypeLoc(ArrayTypeLoc L)13557d382dcdSMarcel Hlopko   bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
13567d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1357718e550cSEduardo Caldas     Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
13587d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
13597d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1360a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ArraySubscript, L);
13617d382dcdSMarcel Hlopko     return true;
13627d382dcdSMarcel Hlopko   }
13637d382dcdSMarcel Hlopko 
1364dc3d4743SEduardo Caldas   syntax::ParameterDeclarationList *
buildParameterDeclarationList(ArrayRef<ParmVarDecl * > Params)1365dc3d4743SEduardo Caldas   buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) {
1366dc3d4743SEduardo Caldas     for (auto *P : Params) {
1367718e550cSEduardo Caldas       Builder.markChild(P, syntax::NodeRole::ListElement);
1368dc3d4743SEduardo Caldas       const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1369dc3d4743SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1370718e550cSEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1371dc3d4743SEduardo Caldas     }
1372dc3d4743SEduardo Caldas     auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1373dc3d4743SEduardo Caldas     if (!Params.empty())
1374dc3d4743SEduardo Caldas       Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1375dc3d4743SEduardo Caldas                                         Params.back()->getEndLoc()),
1376dc3d4743SEduardo Caldas                        Parameters, nullptr);
1377dc3d4743SEduardo Caldas     return Parameters;
1378dc3d4743SEduardo Caldas   }
1379dc3d4743SEduardo Caldas 
WalkUpFromFunctionTypeLoc(FunctionTypeLoc L)13807d382dcdSMarcel Hlopko   bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
13817d382dcdSMarcel Hlopko     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1382dc3d4743SEduardo Caldas 
1383dc3d4743SEduardo Caldas     Builder.markChild(buildParameterDeclarationList(L.getParams()),
1384718e550cSEduardo Caldas                       syntax::NodeRole::Parameters);
1385dc3d4743SEduardo Caldas 
13867d382dcdSMarcel Hlopko     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13877d382dcdSMarcel Hlopko     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1388a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ParametersAndQualifiers, L);
13897d382dcdSMarcel Hlopko     return true;
13907d382dcdSMarcel Hlopko   }
13917d382dcdSMarcel Hlopko 
WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L)13927d382dcdSMarcel Hlopko   bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
13937d382dcdSMarcel Hlopko     if (!L.getTypePtr()->hasTrailingReturn())
13947d382dcdSMarcel Hlopko       return WalkUpFromFunctionTypeLoc(L);
13957d382dcdSMarcel Hlopko 
1396ac87a0b5SEduardo Caldas     auto *TrailingReturnTokens = buildTrailingReturn(L);
13977d382dcdSMarcel Hlopko     // Finish building the node for parameters.
1398718e550cSEduardo Caldas     Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
13997d382dcdSMarcel Hlopko     return WalkUpFromFunctionTypeLoc(L);
14007d382dcdSMarcel Hlopko   }
14017d382dcdSMarcel Hlopko 
TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L)14028ce15f7eSEduardo Caldas   bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) {
14038ce15f7eSEduardo Caldas     // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
14048ce15f7eSEduardo Caldas     // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
14058ce15f7eSEduardo Caldas     // "(Y::*mp)" We thus reverse the order of traversal to get the proper
14068ce15f7eSEduardo Caldas     // syntax structure.
14078ce15f7eSEduardo Caldas     if (!WalkUpFromMemberPointerTypeLoc(L))
14088ce15f7eSEduardo Caldas       return false;
14098ce15f7eSEduardo Caldas     return TraverseTypeLoc(L.getPointeeLoc());
14108ce15f7eSEduardo Caldas   }
14118ce15f7eSEduardo Caldas 
WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L)14127d382dcdSMarcel Hlopko   bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
14137d382dcdSMarcel Hlopko     auto SR = L.getLocalSourceRange();
1414a711a3a4SMarcel Hlopko     Builder.foldNode(Builder.getRange(SR),
1415a711a3a4SMarcel Hlopko                      new (allocator()) syntax::MemberPointer, L);
14167d382dcdSMarcel Hlopko     return true;
14177d382dcdSMarcel Hlopko   }
14187d382dcdSMarcel Hlopko 
141958fa50f4SIlya Biryukov   // The code below is very regular, it could even be generated with some
142058fa50f4SIlya Biryukov   // preprocessor magic. We merely assign roles to the corresponding children
142158fa50f4SIlya Biryukov   // and fold resulting nodes.
WalkUpFromDeclStmt(DeclStmt * S)142258fa50f4SIlya Biryukov   bool WalkUpFromDeclStmt(DeclStmt *S) {
142358fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1424a711a3a4SMarcel Hlopko                      new (allocator()) syntax::DeclarationStatement, S);
142558fa50f4SIlya Biryukov     return true;
142658fa50f4SIlya Biryukov   }
142758fa50f4SIlya Biryukov 
WalkUpFromNullStmt(NullStmt * S)142858fa50f4SIlya Biryukov   bool WalkUpFromNullStmt(NullStmt *S) {
142958fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1430a711a3a4SMarcel Hlopko                      new (allocator()) syntax::EmptyStatement, S);
143158fa50f4SIlya Biryukov     return true;
143258fa50f4SIlya Biryukov   }
143358fa50f4SIlya Biryukov 
WalkUpFromSwitchStmt(SwitchStmt * S)143458fa50f4SIlya Biryukov   bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1435def65bb4SIlya Biryukov     Builder.markChildToken(S->getSwitchLoc(),
143658fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
143758fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
143858fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1439a711a3a4SMarcel Hlopko                      new (allocator()) syntax::SwitchStatement, S);
144058fa50f4SIlya Biryukov     return true;
144158fa50f4SIlya Biryukov   }
144258fa50f4SIlya Biryukov 
WalkUpFromCaseStmt(CaseStmt * S)144358fa50f4SIlya Biryukov   bool WalkUpFromCaseStmt(CaseStmt *S) {
1444def65bb4SIlya Biryukov     Builder.markChildToken(S->getKeywordLoc(),
144558fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
1446718e550cSEduardo Caldas     Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
144758fa50f4SIlya Biryukov     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
144858fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1449a711a3a4SMarcel Hlopko                      new (allocator()) syntax::CaseStatement, S);
145058fa50f4SIlya Biryukov     return true;
145158fa50f4SIlya Biryukov   }
145258fa50f4SIlya Biryukov 
WalkUpFromDefaultStmt(DefaultStmt * S)145358fa50f4SIlya Biryukov   bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1454def65bb4SIlya Biryukov     Builder.markChildToken(S->getKeywordLoc(),
145558fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
145658fa50f4SIlya Biryukov     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
145758fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1458a711a3a4SMarcel Hlopko                      new (allocator()) syntax::DefaultStatement, S);
145958fa50f4SIlya Biryukov     return true;
146058fa50f4SIlya Biryukov   }
146158fa50f4SIlya Biryukov 
WalkUpFromIfStmt(IfStmt * S)146258fa50f4SIlya Biryukov   bool WalkUpFromIfStmt(IfStmt *S) {
1463def65bb4SIlya Biryukov     Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
14646c1a2330SHaojian Wu     Stmt *ConditionStatement = S->getCond();
14656c1a2330SHaojian Wu     if (S->hasVarStorage())
14666c1a2330SHaojian Wu       ConditionStatement = S->getConditionVariableDeclStmt();
14676c1a2330SHaojian Wu     Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
1468718e550cSEduardo Caldas     Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1469718e550cSEduardo Caldas     Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1470718e550cSEduardo Caldas     Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
147158fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1472a711a3a4SMarcel Hlopko                      new (allocator()) syntax::IfStatement, S);
147358fa50f4SIlya Biryukov     return true;
147458fa50f4SIlya Biryukov   }
147558fa50f4SIlya Biryukov 
WalkUpFromForStmt(ForStmt * S)147658fa50f4SIlya Biryukov   bool WalkUpFromForStmt(ForStmt *S) {
1477def65bb4SIlya Biryukov     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
147858fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
147958fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1480a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ForStatement, S);
148158fa50f4SIlya Biryukov     return true;
148258fa50f4SIlya Biryukov   }
148358fa50f4SIlya Biryukov 
WalkUpFromWhileStmt(WhileStmt * S)148458fa50f4SIlya Biryukov   bool WalkUpFromWhileStmt(WhileStmt *S) {
1485def65bb4SIlya Biryukov     Builder.markChildToken(S->getWhileLoc(),
148658fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
148758fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
148858fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1489a711a3a4SMarcel Hlopko                      new (allocator()) syntax::WhileStatement, S);
149058fa50f4SIlya Biryukov     return true;
149158fa50f4SIlya Biryukov   }
149258fa50f4SIlya Biryukov 
WalkUpFromContinueStmt(ContinueStmt * S)149358fa50f4SIlya Biryukov   bool WalkUpFromContinueStmt(ContinueStmt *S) {
1494def65bb4SIlya Biryukov     Builder.markChildToken(S->getContinueLoc(),
149558fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
149658fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1497a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ContinueStatement, S);
149858fa50f4SIlya Biryukov     return true;
149958fa50f4SIlya Biryukov   }
150058fa50f4SIlya Biryukov 
WalkUpFromBreakStmt(BreakStmt * S)150158fa50f4SIlya Biryukov   bool WalkUpFromBreakStmt(BreakStmt *S) {
1502def65bb4SIlya Biryukov     Builder.markChildToken(S->getBreakLoc(),
150358fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
150458fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1505a711a3a4SMarcel Hlopko                      new (allocator()) syntax::BreakStatement, S);
150658fa50f4SIlya Biryukov     return true;
150758fa50f4SIlya Biryukov   }
150858fa50f4SIlya Biryukov 
WalkUpFromReturnStmt(ReturnStmt * S)150958fa50f4SIlya Biryukov   bool WalkUpFromReturnStmt(ReturnStmt *S) {
1510def65bb4SIlya Biryukov     Builder.markChildToken(S->getReturnLoc(),
151158fa50f4SIlya Biryukov                            syntax::NodeRole::IntroducerKeyword);
1512718e550cSEduardo Caldas     Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
151358fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1514a711a3a4SMarcel Hlopko                      new (allocator()) syntax::ReturnStatement, S);
151558fa50f4SIlya Biryukov     return true;
151658fa50f4SIlya Biryukov   }
151758fa50f4SIlya Biryukov 
WalkUpFromCXXForRangeStmt(CXXForRangeStmt * S)151858fa50f4SIlya Biryukov   bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1519def65bb4SIlya Biryukov     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
152058fa50f4SIlya Biryukov     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
152158fa50f4SIlya Biryukov     Builder.foldNode(Builder.getStmtRange(S),
1522a711a3a4SMarcel Hlopko                      new (allocator()) syntax::RangeBasedForStatement, S);
152358fa50f4SIlya Biryukov     return true;
152458fa50f4SIlya Biryukov   }
152558fa50f4SIlya Biryukov 
WalkUpFromEmptyDecl(EmptyDecl * S)1526be14a22bSIlya Biryukov   bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1527cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1528a711a3a4SMarcel Hlopko                      new (allocator()) syntax::EmptyDeclaration, S);
1529be14a22bSIlya Biryukov     return true;
1530be14a22bSIlya Biryukov   }
1531be14a22bSIlya Biryukov 
WalkUpFromStaticAssertDecl(StaticAssertDecl * S)1532be14a22bSIlya Biryukov   bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1533718e550cSEduardo Caldas     Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1534718e550cSEduardo Caldas     Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1535cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1536a711a3a4SMarcel Hlopko                      new (allocator()) syntax::StaticAssertDeclaration, S);
1537be14a22bSIlya Biryukov     return true;
1538be14a22bSIlya Biryukov   }
1539be14a22bSIlya Biryukov 
WalkUpFromLinkageSpecDecl(LinkageSpecDecl * S)1540be14a22bSIlya Biryukov   bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1541cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1542a711a3a4SMarcel Hlopko                      new (allocator()) syntax::LinkageSpecificationDeclaration,
1543a711a3a4SMarcel Hlopko                      S);
1544be14a22bSIlya Biryukov     return true;
1545be14a22bSIlya Biryukov   }
1546be14a22bSIlya Biryukov 
WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl * S)1547be14a22bSIlya Biryukov   bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1548cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1549a711a3a4SMarcel Hlopko                      new (allocator()) syntax::NamespaceAliasDefinition, S);
1550be14a22bSIlya Biryukov     return true;
1551be14a22bSIlya Biryukov   }
1552be14a22bSIlya Biryukov 
WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl * S)1553be14a22bSIlya Biryukov   bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1554cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1555a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingNamespaceDirective, S);
1556be14a22bSIlya Biryukov     return true;
1557be14a22bSIlya Biryukov   }
1558be14a22bSIlya Biryukov 
WalkUpFromUsingDecl(UsingDecl * S)1559be14a22bSIlya Biryukov   bool WalkUpFromUsingDecl(UsingDecl *S) {
1560cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1561a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1562be14a22bSIlya Biryukov     return true;
1563be14a22bSIlya Biryukov   }
1564be14a22bSIlya Biryukov 
WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * S)1565be14a22bSIlya Biryukov   bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1566cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1567a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1568be14a22bSIlya Biryukov     return true;
1569be14a22bSIlya Biryukov   }
1570be14a22bSIlya Biryukov 
WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * S)1571be14a22bSIlya Biryukov   bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1572cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1573a711a3a4SMarcel Hlopko                      new (allocator()) syntax::UsingDeclaration, S);
1574be14a22bSIlya Biryukov     return true;
1575be14a22bSIlya Biryukov   }
1576be14a22bSIlya Biryukov 
WalkUpFromTypeAliasDecl(TypeAliasDecl * S)1577be14a22bSIlya Biryukov   bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1578cdce2fe5SMarcel Hlopko     Builder.foldNode(Builder.getDeclarationRange(S),
1579a711a3a4SMarcel Hlopko                      new (allocator()) syntax::TypeAliasDeclaration, S);
1580be14a22bSIlya Biryukov     return true;
1581be14a22bSIlya Biryukov   }
1582be14a22bSIlya Biryukov 
15839b3f38f9SIlya Biryukov private:
1584cdce2fe5SMarcel Hlopko   /// Folds SimpleDeclarator node (if present) and in case this is the last
1585cdce2fe5SMarcel Hlopko   /// declarator in the chain it also folds SimpleDeclaration node.
processDeclaratorAndDeclaration(T * D)1586cdce2fe5SMarcel Hlopko   template <class T> bool processDeclaratorAndDeclaration(T *D) {
158738bc0060SEduardo Caldas     auto Range = getDeclaratorRange(
158838bc0060SEduardo Caldas         Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
158938bc0060SEduardo Caldas         getQualifiedNameStart(D), getInitializerRange(D));
1590cdce2fe5SMarcel Hlopko 
1591cdce2fe5SMarcel Hlopko     // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1592cdce2fe5SMarcel Hlopko     // declaration, but no declarator).
15935011d431SEduardo Caldas     if (!Range.getBegin().isValid()) {
15945011d431SEduardo Caldas       Builder.markChild(new (allocator()) syntax::DeclaratorList,
15955011d431SEduardo Caldas                         syntax::NodeRole::Declarators);
15965011d431SEduardo Caldas       Builder.foldNode(Builder.getDeclarationRange(D),
15975011d431SEduardo Caldas                        new (allocator()) syntax::SimpleDeclaration, D);
15985011d431SEduardo Caldas       return true;
1599cdce2fe5SMarcel Hlopko     }
1600cdce2fe5SMarcel Hlopko 
16015011d431SEduardo Caldas     auto *N = new (allocator()) syntax::SimpleDeclarator;
16025011d431SEduardo Caldas     Builder.foldNode(Builder.getRange(Range), N, nullptr);
16035011d431SEduardo Caldas     Builder.markChild(N, syntax::NodeRole::ListElement);
16045011d431SEduardo Caldas 
16055011d431SEduardo Caldas     if (!Builder.isResponsibleForCreatingDeclaration(D)) {
16065011d431SEduardo Caldas       // If this is not the last declarator in the declaration we expect a
16075011d431SEduardo Caldas       // delimiter after it.
16085011d431SEduardo Caldas       const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
16095011d431SEduardo Caldas       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
16105011d431SEduardo Caldas         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
16115011d431SEduardo Caldas     } else {
16125011d431SEduardo Caldas       auto *DL = new (allocator()) syntax::DeclaratorList;
16135011d431SEduardo Caldas       auto DeclarationRange = Builder.getDeclarationRange(D);
16145011d431SEduardo Caldas       Builder.foldList(DeclarationRange, DL, nullptr);
16155011d431SEduardo Caldas 
16165011d431SEduardo Caldas       Builder.markChild(DL, syntax::NodeRole::Declarators);
16175011d431SEduardo Caldas       Builder.foldNode(DeclarationRange,
1618cdce2fe5SMarcel Hlopko                        new (allocator()) syntax::SimpleDeclaration, D);
1619cdce2fe5SMarcel Hlopko     }
1620cdce2fe5SMarcel Hlopko     return true;
1621cdce2fe5SMarcel Hlopko   }
1622cdce2fe5SMarcel Hlopko 
16237d382dcdSMarcel Hlopko   /// Returns the range of the built node.
buildTrailingReturn(FunctionProtoTypeLoc L)1624ac87a0b5SEduardo Caldas   syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
16257d382dcdSMarcel Hlopko     assert(L.getTypePtr()->hasTrailingReturn());
16267d382dcdSMarcel Hlopko 
16277d382dcdSMarcel Hlopko     auto ReturnedType = L.getReturnLoc();
16287d382dcdSMarcel Hlopko     // Build node for the declarator, if any.
162938bc0060SEduardo Caldas     auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
163038bc0060SEduardo Caldas                                              ReturnedType.getEndLoc());
1631a711a3a4SMarcel Hlopko     syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
16327d382dcdSMarcel Hlopko     if (ReturnDeclaratorRange.isValid()) {
1633a711a3a4SMarcel Hlopko       ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1634a711a3a4SMarcel Hlopko       Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1635a711a3a4SMarcel Hlopko                        ReturnDeclarator, nullptr);
16367d382dcdSMarcel Hlopko     }
16377d382dcdSMarcel Hlopko 
16387d382dcdSMarcel Hlopko     // Build node for trailing return type.
1639a711a3a4SMarcel Hlopko     auto Return = Builder.getRange(ReturnedType.getSourceRange());
16407d382dcdSMarcel Hlopko     const auto *Arrow = Return.begin() - 1;
16417d382dcdSMarcel Hlopko     assert(Arrow->kind() == tok::arrow);
16427d382dcdSMarcel Hlopko     auto Tokens = llvm::makeArrayRef(Arrow, Return.end());
164342f6fec3SEduardo Caldas     Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1644a711a3a4SMarcel Hlopko     if (ReturnDeclarator)
1645718e550cSEduardo Caldas       Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1646a711a3a4SMarcel Hlopko     auto *R = new (allocator()) syntax::TrailingReturnType;
1647cdce2fe5SMarcel Hlopko     Builder.foldNode(Tokens, R, L);
1648a711a3a4SMarcel Hlopko     return R;
16497d382dcdSMarcel Hlopko   }
165088bf9b3dSMarcel Hlopko 
foldExplicitTemplateInstantiation(ArrayRef<syntax::Token> Range,const syntax::Token * ExternKW,const syntax::Token * TemplateKW,syntax::SimpleDeclaration * InnerDeclaration,Decl * From)1651a711a3a4SMarcel Hlopko   void foldExplicitTemplateInstantiation(
1652a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
165388bf9b3dSMarcel Hlopko       const syntax::Token *TemplateKW,
1654a711a3a4SMarcel Hlopko       syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
165588bf9b3dSMarcel Hlopko     assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
165688bf9b3dSMarcel Hlopko     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
165742f6fec3SEduardo Caldas     Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
165888bf9b3dSMarcel Hlopko     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1659718e550cSEduardo Caldas     Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1660a711a3a4SMarcel Hlopko     Builder.foldNode(
1661a711a3a4SMarcel Hlopko         Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
166288bf9b3dSMarcel Hlopko   }
166388bf9b3dSMarcel Hlopko 
foldTemplateDeclaration(ArrayRef<syntax::Token> Range,const syntax::Token * TemplateKW,ArrayRef<syntax::Token> TemplatedDeclaration,Decl * From)1664a711a3a4SMarcel Hlopko   syntax::TemplateDeclaration *foldTemplateDeclaration(
1665a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1666a711a3a4SMarcel Hlopko       ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
166788bf9b3dSMarcel Hlopko     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
166888bf9b3dSMarcel Hlopko     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1669a711a3a4SMarcel Hlopko 
1670a711a3a4SMarcel Hlopko     auto *N = new (allocator()) syntax::TemplateDeclaration;
1671a711a3a4SMarcel Hlopko     Builder.foldNode(Range, N, From);
1672718e550cSEduardo Caldas     Builder.markChild(N, syntax::NodeRole::Declaration);
1673a711a3a4SMarcel Hlopko     return N;
167488bf9b3dSMarcel Hlopko   }
167588bf9b3dSMarcel Hlopko 
16769b3f38f9SIlya Biryukov   /// A small helper to save some typing.
allocator()16779b3f38f9SIlya Biryukov   llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
16789b3f38f9SIlya Biryukov 
16799b3f38f9SIlya Biryukov   syntax::TreeBuilder &Builder;
16801db5b348SEduardo Caldas   const ASTContext &Context;
16819b3f38f9SIlya Biryukov };
16829b3f38f9SIlya Biryukov } // namespace
16839b3f38f9SIlya Biryukov 
noticeDeclWithoutSemicolon(Decl * D)16847d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1685e702bdb8SIlya Biryukov   DeclsWithoutSemicolons.insert(D);
1686e702bdb8SIlya Biryukov }
1687e702bdb8SIlya Biryukov 
markChildToken(SourceLocation Loc,NodeRole Role)1688def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
16899b3f38f9SIlya Biryukov   if (Loc.isInvalid())
16909b3f38f9SIlya Biryukov     return;
16919b3f38f9SIlya Biryukov   Pending.assignRole(*findToken(Loc), Role);
16929b3f38f9SIlya Biryukov }
16939b3f38f9SIlya Biryukov 
markChildToken(const syntax::Token * T,NodeRole R)16947d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
16957d382dcdSMarcel Hlopko   if (!T)
16967d382dcdSMarcel Hlopko     return;
16977d382dcdSMarcel Hlopko   Pending.assignRole(*T, R);
16987d382dcdSMarcel Hlopko }
16997d382dcdSMarcel Hlopko 
markChild(syntax::Node * N,NodeRole R)1700a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1701a711a3a4SMarcel Hlopko   assert(N);
1702a711a3a4SMarcel Hlopko   setRole(N, R);
1703a711a3a4SMarcel Hlopko }
1704a711a3a4SMarcel Hlopko 
markChild(ASTPtr N,NodeRole R)1705a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1706a711a3a4SMarcel Hlopko   auto *SN = Mapping.find(N);
1707a711a3a4SMarcel Hlopko   assert(SN != nullptr);
1708a711a3a4SMarcel Hlopko   setRole(SN, R);
17097d382dcdSMarcel Hlopko }
markChild(NestedNameSpecifierLoc NNSLoc,NodeRole R)1710f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1711f9500cc4SEduardo Caldas   auto *SN = Mapping.find(NNSLoc);
1712f9500cc4SEduardo Caldas   assert(SN != nullptr);
1713f9500cc4SEduardo Caldas   setRole(SN, R);
1714f9500cc4SEduardo Caldas }
17157d382dcdSMarcel Hlopko 
markStmtChild(Stmt * Child,NodeRole Role)171658fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
171758fa50f4SIlya Biryukov   if (!Child)
171858fa50f4SIlya Biryukov     return;
171958fa50f4SIlya Biryukov 
1720b34b7691SDmitri Gribenko   syntax::Tree *ChildNode;
1721b34b7691SDmitri Gribenko   if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
172258fa50f4SIlya Biryukov     // This is an expression in a statement position, consume the trailing
172358fa50f4SIlya Biryukov     // semicolon and form an 'ExpressionStatement' node.
1724718e550cSEduardo Caldas     markExprChild(ChildExpr, NodeRole::Expression);
1725a711a3a4SMarcel Hlopko     ChildNode = new (allocator()) syntax::ExpressionStatement;
1726a711a3a4SMarcel Hlopko     // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1727*263dcf45SHaojian Wu     Pending.foldChildren(TBTM.tokenBuffer(), getStmtRange(Child), ChildNode);
1728b34b7691SDmitri Gribenko   } else {
1729b34b7691SDmitri Gribenko     ChildNode = Mapping.find(Child);
173058fa50f4SIlya Biryukov   }
1731b34b7691SDmitri Gribenko   assert(ChildNode != nullptr);
1732a711a3a4SMarcel Hlopko   setRole(ChildNode, Role);
173358fa50f4SIlya Biryukov }
173458fa50f4SIlya Biryukov 
markExprChild(Expr * Child,NodeRole Role)173558fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1736be14a22bSIlya Biryukov   if (!Child)
1737be14a22bSIlya Biryukov     return;
17382325d6b4SEduardo Caldas   Child = IgnoreImplicit(Child);
1739be14a22bSIlya Biryukov 
1740a711a3a4SMarcel Hlopko   syntax::Tree *ChildNode = Mapping.find(Child);
1741a711a3a4SMarcel Hlopko   assert(ChildNode != nullptr);
1742a711a3a4SMarcel Hlopko   setRole(ChildNode, Role);
174358fa50f4SIlya Biryukov }
174458fa50f4SIlya Biryukov 
findToken(SourceLocation L) const17459b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
174688bf9b3dSMarcel Hlopko   if (L.isInvalid())
174788bf9b3dSMarcel Hlopko     return nullptr;
174878194118SMikhail Maltsev   auto It = LocationToToken.find(L);
1749c1bbefefSIlya Biryukov   assert(It != LocationToToken.end());
1750c1bbefefSIlya Biryukov   return It->second;
17519b3f38f9SIlya Biryukov }
17529b3f38f9SIlya Biryukov 
buildSyntaxTree(Arena & A,TokenBufferTokenManager & TBTM,ASTContext & Context)1753142c6f82SKirill Bobyrev syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A,
1754*263dcf45SHaojian Wu                                                  TokenBufferTokenManager& TBTM,
1755142c6f82SKirill Bobyrev                                                  ASTContext &Context) {
1756*263dcf45SHaojian Wu   TreeBuilder Builder(A, TBTM);
1757142c6f82SKirill Bobyrev   BuildTreeVisitor(Context, Builder).TraverseAST(Context);
17589b3f38f9SIlya Biryukov   return std::move(Builder).finalize();
17599b3f38f9SIlya Biryukov }
1760