xref: /openbsd-src/gnu/llvm/clang/lib/Tooling/Syntax/BuildTree.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- BuildTree.cpp ------------------------------------------*- C++ -*-=====//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick #include "clang/Tooling/Syntax/BuildTree.h"
9ec727ea7Spatrick #include "clang/AST/ASTFwd.h"
10e5dd7070Spatrick #include "clang/AST/Decl.h"
11e5dd7070Spatrick #include "clang/AST/DeclBase.h"
12ec727ea7Spatrick #include "clang/AST/DeclCXX.h"
13ec727ea7Spatrick #include "clang/AST/DeclarationName.h"
14ec727ea7Spatrick #include "clang/AST/Expr.h"
15ec727ea7Spatrick #include "clang/AST/ExprCXX.h"
16a9ac8606Spatrick #include "clang/AST/IgnoreExpr.h"
17a9ac8606Spatrick #include "clang/AST/OperationKinds.h"
18e5dd7070Spatrick #include "clang/AST/RecursiveASTVisitor.h"
19e5dd7070Spatrick #include "clang/AST/Stmt.h"
20ec727ea7Spatrick #include "clang/AST/TypeLoc.h"
21ec727ea7Spatrick #include "clang/AST/TypeLocVisitor.h"
22e5dd7070Spatrick #include "clang/Basic/LLVM.h"
23e5dd7070Spatrick #include "clang/Basic/SourceLocation.h"
24e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
25ec727ea7Spatrick #include "clang/Basic/Specifiers.h"
26e5dd7070Spatrick #include "clang/Basic/TokenKinds.h"
27e5dd7070Spatrick #include "clang/Lex/Lexer.h"
28ec727ea7Spatrick #include "clang/Lex/LiteralSupport.h"
29e5dd7070Spatrick #include "clang/Tooling/Syntax/Nodes.h"
30*12c85518Srobert #include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
31e5dd7070Spatrick #include "clang/Tooling/Syntax/Tokens.h"
32e5dd7070Spatrick #include "clang/Tooling/Syntax/Tree.h"
33e5dd7070Spatrick #include "llvm/ADT/ArrayRef.h"
34ec727ea7Spatrick #include "llvm/ADT/DenseMap.h"
35ec727ea7Spatrick #include "llvm/ADT/PointerUnion.h"
36e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
37ec727ea7Spatrick #include "llvm/ADT/ScopeExit.h"
38e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
39e5dd7070Spatrick #include "llvm/Support/Allocator.h"
40e5dd7070Spatrick #include "llvm/Support/Casting.h"
41e5dd7070Spatrick #include "llvm/Support/Compiler.h"
42e5dd7070Spatrick #include "llvm/Support/FormatVariadic.h"
43e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
44e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
45ec727ea7Spatrick #include <cstddef>
46e5dd7070Spatrick #include <map>
47e5dd7070Spatrick 
48e5dd7070Spatrick using namespace clang;
49e5dd7070Spatrick 
50a9ac8606Spatrick // Ignores the implicit `CXXConstructExpr` for copy/move constructor calls
51a9ac8606Spatrick // generated by the compiler, as well as in implicit conversions like the one
52a9ac8606Spatrick // wrapping `1` in `X x = 1;`.
IgnoreImplicitConstructorSingleStep(Expr * E)53a9ac8606Spatrick static Expr *IgnoreImplicitConstructorSingleStep(Expr *E) {
54a9ac8606Spatrick   if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
55a9ac8606Spatrick     auto NumArgs = C->getNumArgs();
56a9ac8606Spatrick     if (NumArgs == 1 || (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
57a9ac8606Spatrick       Expr *A = C->getArg(0);
58a9ac8606Spatrick       if (C->getParenOrBraceRange().isInvalid())
59a9ac8606Spatrick         return A;
60a9ac8606Spatrick     }
61a9ac8606Spatrick   }
62a9ac8606Spatrick   return E;
63a9ac8606Spatrick }
64a9ac8606Spatrick 
65a9ac8606Spatrick // In:
66a9ac8606Spatrick // struct X {
67a9ac8606Spatrick //   X(int)
68a9ac8606Spatrick // };
69a9ac8606Spatrick // X x = X(1);
70a9ac8606Spatrick // Ignores the implicit `CXXFunctionalCastExpr` that wraps
71a9ac8606Spatrick // `CXXConstructExpr X(1)`.
IgnoreCXXFunctionalCastExprWrappingConstructor(Expr * E)72a9ac8606Spatrick static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
73a9ac8606Spatrick   if (auto *F = dyn_cast<CXXFunctionalCastExpr>(E)) {
74a9ac8606Spatrick     if (F->getCastKind() == CK_ConstructorConversion)
75a9ac8606Spatrick       return F->getSubExpr();
76a9ac8606Spatrick   }
77a9ac8606Spatrick   return E;
78a9ac8606Spatrick }
79a9ac8606Spatrick 
IgnoreImplicit(Expr * E)80a9ac8606Spatrick static Expr *IgnoreImplicit(Expr *E) {
81a9ac8606Spatrick   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
82a9ac8606Spatrick                          IgnoreImplicitConstructorSingleStep,
83a9ac8606Spatrick                          IgnoreCXXFunctionalCastExprWrappingConstructor);
84a9ac8606Spatrick }
85a9ac8606Spatrick 
86e5dd7070Spatrick LLVM_ATTRIBUTE_UNUSED
isImplicitExpr(Expr * E)87a9ac8606Spatrick static bool isImplicitExpr(Expr *E) { return IgnoreImplicit(E) != E; }
88e5dd7070Spatrick 
89ec727ea7Spatrick namespace {
90ec727ea7Spatrick /// Get start location of the Declarator from the TypeLoc.
91ec727ea7Spatrick /// E.g.:
92ec727ea7Spatrick ///   loc of `(` in `int (a)`
93ec727ea7Spatrick ///   loc of `*` in `int *(a)`
94ec727ea7Spatrick ///   loc of the first `(` in `int (*a)(int)`
95ec727ea7Spatrick ///   loc of the `*` in `int *(a)(int)`
96ec727ea7Spatrick ///   loc of the first `*` in `const int *const *volatile a;`
97ec727ea7Spatrick ///
98ec727ea7Spatrick /// It is non-trivial to get the start location because TypeLocs are stored
99ec727ea7Spatrick /// inside out. In the example above `*volatile` is the TypeLoc returned
100ec727ea7Spatrick /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()`
101ec727ea7Spatrick /// returns.
102ec727ea7Spatrick struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> {
VisitParenTypeLoc__anon5b12a8520111::GetStartLoc103ec727ea7Spatrick   SourceLocation VisitParenTypeLoc(ParenTypeLoc T) {
104ec727ea7Spatrick     auto L = Visit(T.getInnerLoc());
105ec727ea7Spatrick     if (L.isValid())
106ec727ea7Spatrick       return L;
107ec727ea7Spatrick     return T.getLParenLoc();
108ec727ea7Spatrick   }
109ec727ea7Spatrick 
110ec727ea7Spatrick   // Types spelled in the prefix part of the declarator.
VisitPointerTypeLoc__anon5b12a8520111::GetStartLoc111ec727ea7Spatrick   SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) {
112ec727ea7Spatrick     return HandlePointer(T);
113ec727ea7Spatrick   }
114ec727ea7Spatrick 
VisitMemberPointerTypeLoc__anon5b12a8520111::GetStartLoc115ec727ea7Spatrick   SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
116ec727ea7Spatrick     return HandlePointer(T);
117ec727ea7Spatrick   }
118ec727ea7Spatrick 
VisitBlockPointerTypeLoc__anon5b12a8520111::GetStartLoc119ec727ea7Spatrick   SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
120ec727ea7Spatrick     return HandlePointer(T);
121ec727ea7Spatrick   }
122ec727ea7Spatrick 
VisitReferenceTypeLoc__anon5b12a8520111::GetStartLoc123ec727ea7Spatrick   SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) {
124ec727ea7Spatrick     return HandlePointer(T);
125ec727ea7Spatrick   }
126ec727ea7Spatrick 
VisitObjCObjectPointerTypeLoc__anon5b12a8520111::GetStartLoc127ec727ea7Spatrick   SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) {
128ec727ea7Spatrick     return HandlePointer(T);
129ec727ea7Spatrick   }
130ec727ea7Spatrick 
131ec727ea7Spatrick   // All other cases are not important, as they are either part of declaration
132ec727ea7Spatrick   // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on
133ec727ea7Spatrick   // existing declarators (e.g. QualifiedTypeLoc). They cannot start the
134ec727ea7Spatrick   // declarator themselves, but their underlying type can.
VisitTypeLoc__anon5b12a8520111::GetStartLoc135ec727ea7Spatrick   SourceLocation VisitTypeLoc(TypeLoc T) {
136ec727ea7Spatrick     auto N = T.getNextTypeLoc();
137ec727ea7Spatrick     if (!N)
138ec727ea7Spatrick       return SourceLocation();
139ec727ea7Spatrick     return Visit(N);
140ec727ea7Spatrick   }
141ec727ea7Spatrick 
VisitFunctionProtoTypeLoc__anon5b12a8520111::GetStartLoc142ec727ea7Spatrick   SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) {
143ec727ea7Spatrick     if (T.getTypePtr()->hasTrailingReturn())
144ec727ea7Spatrick       return SourceLocation(); // avoid recursing into the suffix of declarator.
145ec727ea7Spatrick     return VisitTypeLoc(T);
146ec727ea7Spatrick   }
147ec727ea7Spatrick 
148ec727ea7Spatrick private:
HandlePointer__anon5b12a8520111::GetStartLoc149ec727ea7Spatrick   template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) {
150ec727ea7Spatrick     auto L = Visit(T.getPointeeLoc());
151ec727ea7Spatrick     if (L.isValid())
152ec727ea7Spatrick       return L;
153ec727ea7Spatrick     return T.getLocalSourceRange().getBegin();
154ec727ea7Spatrick   }
155ec727ea7Spatrick };
156ec727ea7Spatrick } // namespace
157ec727ea7Spatrick 
dropDefaultArgs(CallExpr::arg_range Args)158a9ac8606Spatrick static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args) {
159*12c85518Srobert   auto FirstDefaultArg =
160*12c85518Srobert       llvm::find_if(Args, [](auto It) { return isa<CXXDefaultArgExpr>(It); });
161a9ac8606Spatrick   return llvm::make_range(Args.begin(), FirstDefaultArg);
162a9ac8606Spatrick }
163a9ac8606Spatrick 
getOperatorNodeKind(const CXXOperatorCallExpr & E)164ec727ea7Spatrick static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
165ec727ea7Spatrick   switch (E.getOperator()) {
166ec727ea7Spatrick   // Comparison
167ec727ea7Spatrick   case OO_EqualEqual:
168ec727ea7Spatrick   case OO_ExclaimEqual:
169ec727ea7Spatrick   case OO_Greater:
170ec727ea7Spatrick   case OO_GreaterEqual:
171ec727ea7Spatrick   case OO_Less:
172ec727ea7Spatrick   case OO_LessEqual:
173ec727ea7Spatrick   case OO_Spaceship:
174ec727ea7Spatrick   // Assignment
175ec727ea7Spatrick   case OO_Equal:
176ec727ea7Spatrick   case OO_SlashEqual:
177ec727ea7Spatrick   case OO_PercentEqual:
178ec727ea7Spatrick   case OO_CaretEqual:
179ec727ea7Spatrick   case OO_PipeEqual:
180ec727ea7Spatrick   case OO_LessLessEqual:
181ec727ea7Spatrick   case OO_GreaterGreaterEqual:
182ec727ea7Spatrick   case OO_PlusEqual:
183ec727ea7Spatrick   case OO_MinusEqual:
184ec727ea7Spatrick   case OO_StarEqual:
185ec727ea7Spatrick   case OO_AmpEqual:
186ec727ea7Spatrick   // Binary computation
187ec727ea7Spatrick   case OO_Slash:
188ec727ea7Spatrick   case OO_Percent:
189ec727ea7Spatrick   case OO_Caret:
190ec727ea7Spatrick   case OO_Pipe:
191ec727ea7Spatrick   case OO_LessLess:
192ec727ea7Spatrick   case OO_GreaterGreater:
193ec727ea7Spatrick   case OO_AmpAmp:
194ec727ea7Spatrick   case OO_PipePipe:
195ec727ea7Spatrick   case OO_ArrowStar:
196ec727ea7Spatrick   case OO_Comma:
197ec727ea7Spatrick     return syntax::NodeKind::BinaryOperatorExpression;
198ec727ea7Spatrick   case OO_Tilde:
199ec727ea7Spatrick   case OO_Exclaim:
200ec727ea7Spatrick     return syntax::NodeKind::PrefixUnaryOperatorExpression;
201ec727ea7Spatrick   // Prefix/Postfix increment/decrement
202ec727ea7Spatrick   case OO_PlusPlus:
203ec727ea7Spatrick   case OO_MinusMinus:
204ec727ea7Spatrick     switch (E.getNumArgs()) {
205ec727ea7Spatrick     case 1:
206ec727ea7Spatrick       return syntax::NodeKind::PrefixUnaryOperatorExpression;
207ec727ea7Spatrick     case 2:
208ec727ea7Spatrick       return syntax::NodeKind::PostfixUnaryOperatorExpression;
209ec727ea7Spatrick     default:
210ec727ea7Spatrick       llvm_unreachable("Invalid number of arguments for operator");
211ec727ea7Spatrick     }
212ec727ea7Spatrick   // Operators that can be unary or binary
213ec727ea7Spatrick   case OO_Plus:
214ec727ea7Spatrick   case OO_Minus:
215ec727ea7Spatrick   case OO_Star:
216ec727ea7Spatrick   case OO_Amp:
217ec727ea7Spatrick     switch (E.getNumArgs()) {
218ec727ea7Spatrick     case 1:
219ec727ea7Spatrick       return syntax::NodeKind::PrefixUnaryOperatorExpression;
220ec727ea7Spatrick     case 2:
221ec727ea7Spatrick       return syntax::NodeKind::BinaryOperatorExpression;
222ec727ea7Spatrick     default:
223ec727ea7Spatrick       llvm_unreachable("Invalid number of arguments for operator");
224ec727ea7Spatrick     }
225ec727ea7Spatrick     return syntax::NodeKind::BinaryOperatorExpression;
226ec727ea7Spatrick   // Not yet supported by SyntaxTree
227ec727ea7Spatrick   case OO_New:
228ec727ea7Spatrick   case OO_Delete:
229ec727ea7Spatrick   case OO_Array_New:
230ec727ea7Spatrick   case OO_Array_Delete:
231ec727ea7Spatrick   case OO_Coawait:
232ec727ea7Spatrick   case OO_Subscript:
233ec727ea7Spatrick   case OO_Arrow:
234ec727ea7Spatrick     return syntax::NodeKind::UnknownExpression;
235a9ac8606Spatrick   case OO_Call:
236a9ac8606Spatrick     return syntax::NodeKind::CallExpression;
237ec727ea7Spatrick   case OO_Conditional: // not overloadable
238ec727ea7Spatrick   case NUM_OVERLOADED_OPERATORS:
239ec727ea7Spatrick   case OO_None:
240ec727ea7Spatrick     llvm_unreachable("Not an overloadable operator");
241ec727ea7Spatrick   }
242ec727ea7Spatrick   llvm_unreachable("Unknown OverloadedOperatorKind enum");
243ec727ea7Spatrick }
244ec727ea7Spatrick 
245a9ac8606Spatrick /// Get the start of the qualified name. In the examples below it gives the
246a9ac8606Spatrick /// location of the `^`:
247a9ac8606Spatrick ///     `int ^a;`
248a9ac8606Spatrick ///     `int *^a;`
249a9ac8606Spatrick ///     `int ^a::S::f(){}`
getQualifiedNameStart(NamedDecl * D)250a9ac8606Spatrick static SourceLocation getQualifiedNameStart(NamedDecl *D) {
251a9ac8606Spatrick   assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
252a9ac8606Spatrick          "only DeclaratorDecl and TypedefNameDecl are supported.");
253a9ac8606Spatrick 
254a9ac8606Spatrick   auto DN = D->getDeclName();
255a9ac8606Spatrick   bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
256a9ac8606Spatrick   if (IsAnonymous)
257a9ac8606Spatrick     return SourceLocation();
258a9ac8606Spatrick 
259a9ac8606Spatrick   if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
260a9ac8606Spatrick     if (DD->getQualifierLoc()) {
261a9ac8606Spatrick       return DD->getQualifierLoc().getBeginLoc();
262a9ac8606Spatrick     }
263a9ac8606Spatrick   }
264a9ac8606Spatrick 
265a9ac8606Spatrick   return D->getLocation();
266a9ac8606Spatrick }
267a9ac8606Spatrick 
268a9ac8606Spatrick /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl].
269a9ac8606Spatrick ///     `int a;` -> range of ``,
270a9ac8606Spatrick ///     `int *a = nullptr` -> range of `= nullptr`.
271a9ac8606Spatrick ///     `int a{}` -> range of `{}`.
272a9ac8606Spatrick ///     `int a()` -> range of `()`.
getInitializerRange(Decl * D)273a9ac8606Spatrick static SourceRange getInitializerRange(Decl *D) {
274a9ac8606Spatrick   if (auto *V = dyn_cast<VarDecl>(D)) {
275a9ac8606Spatrick     auto *I = V->getInit();
276a9ac8606Spatrick     // Initializers in range-based-for are not part of the declarator
277a9ac8606Spatrick     if (I && !V->isCXXForRangeDecl())
278a9ac8606Spatrick       return I->getSourceRange();
279a9ac8606Spatrick   }
280a9ac8606Spatrick 
281a9ac8606Spatrick   return SourceRange();
282a9ac8606Spatrick }
283a9ac8606Spatrick 
284ec727ea7Spatrick /// Gets the range of declarator as defined by the C++ grammar. E.g.
285ec727ea7Spatrick ///     `int a;` -> range of `a`,
286ec727ea7Spatrick ///     `int *a;` -> range of `*a`,
287ec727ea7Spatrick ///     `int a[10];` -> range of `a[10]`,
288ec727ea7Spatrick ///     `int a[1][2][3];` -> range of `a[1][2][3]`,
289ec727ea7Spatrick ///     `int *a = nullptr` -> range of `*a = nullptr`.
290a9ac8606Spatrick ///     `int S::f(){}` -> range of `S::f()`.
291a9ac8606Spatrick /// FIXME: \p Name must be a source range.
getDeclaratorRange(const SourceManager & SM,TypeLoc T,SourceLocation Name,SourceRange Initializer)292ec727ea7Spatrick static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
293ec727ea7Spatrick                                       SourceLocation Name,
294ec727ea7Spatrick                                       SourceRange Initializer) {
295ec727ea7Spatrick   SourceLocation Start = GetStartLoc().Visit(T);
296a9ac8606Spatrick   SourceLocation End = T.getEndLoc();
297ec727ea7Spatrick   if (Name.isValid()) {
298ec727ea7Spatrick     if (Start.isInvalid())
299ec727ea7Spatrick       Start = Name;
300a9ac8606Spatrick     // End of TypeLoc could be invalid if the type is invalid, fallback to the
301a9ac8606Spatrick     // NameLoc.
302a9ac8606Spatrick     if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name))
303ec727ea7Spatrick       End = Name;
304ec727ea7Spatrick   }
305ec727ea7Spatrick   if (Initializer.isValid()) {
306ec727ea7Spatrick     auto InitializerEnd = Initializer.getEnd();
307ec727ea7Spatrick     assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
308ec727ea7Spatrick            End == InitializerEnd);
309ec727ea7Spatrick     End = InitializerEnd;
310ec727ea7Spatrick   }
311ec727ea7Spatrick   return SourceRange(Start, End);
312ec727ea7Spatrick }
313ec727ea7Spatrick 
314ec727ea7Spatrick namespace {
315ec727ea7Spatrick /// All AST hierarchy roots that can be represented as pointers.
316ec727ea7Spatrick using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>;
317ec727ea7Spatrick /// Maintains a mapping from AST to syntax tree nodes. This class will get more
318ec727ea7Spatrick /// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
319ec727ea7Spatrick /// FIXME: expose this as public API.
320ec727ea7Spatrick class ASTToSyntaxMapping {
321ec727ea7Spatrick public:
add(ASTPtr From,syntax::Tree * To)322ec727ea7Spatrick   void add(ASTPtr From, syntax::Tree *To) {
323ec727ea7Spatrick     assert(To != nullptr);
324ec727ea7Spatrick     assert(!From.isNull());
325ec727ea7Spatrick 
326ec727ea7Spatrick     bool Added = Nodes.insert({From, To}).second;
327ec727ea7Spatrick     (void)Added;
328ec727ea7Spatrick     assert(Added && "mapping added twice");
329ec727ea7Spatrick   }
330ec727ea7Spatrick 
add(NestedNameSpecifierLoc From,syntax::Tree * To)331a9ac8606Spatrick   void add(NestedNameSpecifierLoc From, syntax::Tree *To) {
332a9ac8606Spatrick     assert(To != nullptr);
333a9ac8606Spatrick     assert(From.hasQualifier());
334a9ac8606Spatrick 
335a9ac8606Spatrick     bool Added = NNSNodes.insert({From, To}).second;
336a9ac8606Spatrick     (void)Added;
337a9ac8606Spatrick     assert(Added && "mapping added twice");
338a9ac8606Spatrick   }
339a9ac8606Spatrick 
find(ASTPtr P) const340ec727ea7Spatrick   syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
341ec727ea7Spatrick 
find(NestedNameSpecifierLoc P) const342a9ac8606Spatrick   syntax::Tree *find(NestedNameSpecifierLoc P) const {
343a9ac8606Spatrick     return NNSNodes.lookup(P);
344a9ac8606Spatrick   }
345a9ac8606Spatrick 
346ec727ea7Spatrick private:
347ec727ea7Spatrick   llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes;
348a9ac8606Spatrick   llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes;
349ec727ea7Spatrick };
350ec727ea7Spatrick } // namespace
351ec727ea7Spatrick 
352e5dd7070Spatrick /// A helper class for constructing the syntax tree while traversing a clang
353e5dd7070Spatrick /// AST.
354e5dd7070Spatrick ///
355e5dd7070Spatrick /// At each point of the traversal we maintain a list of pending nodes.
356e5dd7070Spatrick /// Initially all tokens are added as pending nodes. When processing a clang AST
357e5dd7070Spatrick /// node, the clients need to:
358e5dd7070Spatrick ///   - create a corresponding syntax node,
359e5dd7070Spatrick ///   - assign roles to all pending child nodes with 'markChild' and
360e5dd7070Spatrick ///     'markChildToken',
361e5dd7070Spatrick ///   - replace the child nodes with the new syntax node in the pending list
362e5dd7070Spatrick ///     with 'foldNode'.
363e5dd7070Spatrick ///
364e5dd7070Spatrick /// Note that all children are expected to be processed when building a node.
365e5dd7070Spatrick ///
366e5dd7070Spatrick /// Call finalize() to finish building the tree and consume the root node.
367e5dd7070Spatrick class syntax::TreeBuilder {
368e5dd7070Spatrick public:
TreeBuilder(syntax::Arena & Arena,TokenBufferTokenManager & TBTM)369*12c85518Srobert   TreeBuilder(syntax::Arena &Arena, TokenBufferTokenManager& TBTM)
370*12c85518Srobert       : Arena(Arena),
371*12c85518Srobert         TBTM(TBTM),
372*12c85518Srobert         Pending(Arena, TBTM.tokenBuffer()) {
373*12c85518Srobert     for (const auto &T : TBTM.tokenBuffer().expandedTokens())
374a9ac8606Spatrick       LocationToToken.insert({T.location(), &T});
375e5dd7070Spatrick   }
376e5dd7070Spatrick 
allocator()377a9ac8606Spatrick   llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); }
sourceManager() const378a9ac8606Spatrick   const SourceManager &sourceManager() const {
379*12c85518Srobert     return TBTM.sourceManager();
380a9ac8606Spatrick   }
381e5dd7070Spatrick 
382e5dd7070Spatrick   /// Populate children for \p New node, assuming it covers tokens from \p
383e5dd7070Spatrick   /// Range.
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,ASTPtr From)384a9ac8606Spatrick   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) {
385ec727ea7Spatrick     assert(New);
386*12c85518Srobert     Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
387ec727ea7Spatrick     if (From)
388ec727ea7Spatrick       Mapping.add(From, New);
389ec727ea7Spatrick   }
390a9ac8606Spatrick 
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,TypeLoc L)391a9ac8606Spatrick   void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) {
392ec727ea7Spatrick     // FIXME: add mapping for TypeLocs
393ec727ea7Spatrick     foldNode(Range, New, nullptr);
394ec727ea7Spatrick   }
395e5dd7070Spatrick 
foldNode(llvm::ArrayRef<syntax::Token> Range,syntax::Tree * New,NestedNameSpecifierLoc From)396a9ac8606Spatrick   void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
397a9ac8606Spatrick                 NestedNameSpecifierLoc From) {
398a9ac8606Spatrick     assert(New);
399*12c85518Srobert     Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
400a9ac8606Spatrick     if (From)
401a9ac8606Spatrick       Mapping.add(From, New);
402a9ac8606Spatrick   }
403a9ac8606Spatrick 
404a9ac8606Spatrick   /// Populate children for \p New list, assuming it covers tokens from a
405a9ac8606Spatrick   /// subrange of \p SuperRange.
foldList(ArrayRef<syntax::Token> SuperRange,syntax::List * New,ASTPtr From)406a9ac8606Spatrick   void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New,
407a9ac8606Spatrick                 ASTPtr From) {
408a9ac8606Spatrick     assert(New);
409a9ac8606Spatrick     auto ListRange = Pending.shrinkToFitList(SuperRange);
410*12c85518Srobert     Pending.foldChildren(TBTM.tokenBuffer(), ListRange, New);
411a9ac8606Spatrick     if (From)
412a9ac8606Spatrick       Mapping.add(From, New);
413a9ac8606Spatrick   }
414a9ac8606Spatrick 
415e5dd7070Spatrick   /// Notifies that we should not consume trailing semicolon when computing
416e5dd7070Spatrick   /// token range of \p D.
417ec727ea7Spatrick   void noticeDeclWithoutSemicolon(Decl *D);
418e5dd7070Spatrick 
419e5dd7070Spatrick   /// Mark the \p Child node with a corresponding \p Role. All marked children
420e5dd7070Spatrick   /// should be consumed by foldNode.
421ec727ea7Spatrick   /// When called on expressions (clang::Expr is derived from clang::Stmt),
422e5dd7070Spatrick   /// wraps expressions into expression statement.
423e5dd7070Spatrick   void markStmtChild(Stmt *Child, NodeRole Role);
424e5dd7070Spatrick   /// Should be called for expressions in non-statement position to avoid
425e5dd7070Spatrick   /// wrapping into expression statement.
426e5dd7070Spatrick   void markExprChild(Expr *Child, NodeRole Role);
427e5dd7070Spatrick   /// Set role for a token starting at \p Loc.
428e5dd7070Spatrick   void markChildToken(SourceLocation Loc, NodeRole R);
429ec727ea7Spatrick   /// Set role for \p T.
430ec727ea7Spatrick   void markChildToken(const syntax::Token *T, NodeRole R);
431ec727ea7Spatrick 
432ec727ea7Spatrick   /// Set role for \p N.
433ec727ea7Spatrick   void markChild(syntax::Node *N, NodeRole R);
434ec727ea7Spatrick   /// Set role for the syntax node matching \p N.
435ec727ea7Spatrick   void markChild(ASTPtr N, NodeRole R);
436a9ac8606Spatrick   /// Set role for the syntax node matching \p N.
437a9ac8606Spatrick   void markChild(NestedNameSpecifierLoc N, NodeRole R);
438e5dd7070Spatrick 
439e5dd7070Spatrick   /// Finish building the tree and consume the root node.
finalize()440e5dd7070Spatrick   syntax::TranslationUnit *finalize() && {
441*12c85518Srobert     auto Tokens = TBTM.tokenBuffer().expandedTokens();
442e5dd7070Spatrick     assert(!Tokens.empty());
443e5dd7070Spatrick     assert(Tokens.back().kind() == tok::eof);
444e5dd7070Spatrick 
445e5dd7070Spatrick     // Build the root of the tree, consuming all the children.
446*12c85518Srobert     Pending.foldChildren(TBTM.tokenBuffer(), Tokens.drop_back(),
447a9ac8606Spatrick                          new (Arena.getAllocator()) syntax::TranslationUnit);
448e5dd7070Spatrick 
449e5dd7070Spatrick     auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize());
450e5dd7070Spatrick     TU->assertInvariantsRecursive();
451e5dd7070Spatrick     return TU;
452e5dd7070Spatrick   }
453e5dd7070Spatrick 
454ec727ea7Spatrick   /// Finds a token starting at \p L. The token must exist if \p L is valid.
455ec727ea7Spatrick   const syntax::Token *findToken(SourceLocation L) const;
456ec727ea7Spatrick 
457ec727ea7Spatrick   /// Finds the syntax tokens corresponding to the \p SourceRange.
getRange(SourceRange Range) const458a9ac8606Spatrick   ArrayRef<syntax::Token> getRange(SourceRange Range) const {
459ec727ea7Spatrick     assert(Range.isValid());
460ec727ea7Spatrick     return getRange(Range.getBegin(), Range.getEnd());
461ec727ea7Spatrick   }
462ec727ea7Spatrick 
463ec727ea7Spatrick   /// Finds the syntax tokens corresponding to the passed source locations.
464e5dd7070Spatrick   /// \p First is the start position of the first token and \p Last is the start
465e5dd7070Spatrick   /// position of the last token.
getRange(SourceLocation First,SourceLocation Last) const466a9ac8606Spatrick   ArrayRef<syntax::Token> getRange(SourceLocation First,
467e5dd7070Spatrick                                    SourceLocation Last) const {
468e5dd7070Spatrick     assert(First.isValid());
469e5dd7070Spatrick     assert(Last.isValid());
470e5dd7070Spatrick     assert(First == Last ||
471*12c85518Srobert            TBTM.sourceManager().isBeforeInTranslationUnit(First, Last));
472*12c85518Srobert     return llvm::ArrayRef(findToken(First), std::next(findToken(Last)));
473e5dd7070Spatrick   }
474ec727ea7Spatrick 
475a9ac8606Spatrick   ArrayRef<syntax::Token>
getTemplateRange(const ClassTemplateSpecializationDecl * D) const476ec727ea7Spatrick   getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
477ec727ea7Spatrick     auto Tokens = getRange(D->getSourceRange());
478ec727ea7Spatrick     return maybeAppendSemicolon(Tokens, D);
479e5dd7070Spatrick   }
480ec727ea7Spatrick 
481ec727ea7Spatrick   /// Returns true if \p D is the last declarator in a chain and is thus
482ec727ea7Spatrick   /// reponsible for creating SimpleDeclaration for the whole chain.
isResponsibleForCreatingDeclaration(const Decl * D) const483a9ac8606Spatrick   bool isResponsibleForCreatingDeclaration(const Decl *D) const {
484a9ac8606Spatrick     assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
485ec727ea7Spatrick            "only DeclaratorDecl and TypedefNameDecl are supported.");
486ec727ea7Spatrick 
487ec727ea7Spatrick     const Decl *Next = D->getNextDeclInContext();
488ec727ea7Spatrick 
489ec727ea7Spatrick     // There's no next sibling, this one is responsible.
490ec727ea7Spatrick     if (Next == nullptr) {
491ec727ea7Spatrick       return true;
492ec727ea7Spatrick     }
493ec727ea7Spatrick 
494ec727ea7Spatrick     // Next sibling is not the same type, this one is responsible.
495a9ac8606Spatrick     if (D->getKind() != Next->getKind()) {
496ec727ea7Spatrick       return true;
497ec727ea7Spatrick     }
498ec727ea7Spatrick     // Next sibling doesn't begin at the same loc, it must be a different
499ec727ea7Spatrick     // declaration, so this declarator is responsible.
500a9ac8606Spatrick     if (Next->getBeginLoc() != D->getBeginLoc()) {
501ec727ea7Spatrick       return true;
502ec727ea7Spatrick     }
503ec727ea7Spatrick 
504ec727ea7Spatrick     // NextT is a member of the same declaration, and we need the last member to
505ec727ea7Spatrick     // create declaration. This one is not responsible.
506ec727ea7Spatrick     return false;
507ec727ea7Spatrick   }
508ec727ea7Spatrick 
getDeclarationRange(Decl * D)509a9ac8606Spatrick   ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
510a9ac8606Spatrick     ArrayRef<syntax::Token> Tokens;
511ec727ea7Spatrick     // We want to drop the template parameters for specializations.
512a9ac8606Spatrick     if (const auto *S = dyn_cast<TagDecl>(D))
513ec727ea7Spatrick       Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc());
514ec727ea7Spatrick     else
515ec727ea7Spatrick       Tokens = getRange(D->getSourceRange());
516ec727ea7Spatrick     return maybeAppendSemicolon(Tokens, D);
517ec727ea7Spatrick   }
518ec727ea7Spatrick 
getExprRange(const Expr * E) const519a9ac8606Spatrick   ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
520ec727ea7Spatrick     return getRange(E->getSourceRange());
521e5dd7070Spatrick   }
522ec727ea7Spatrick 
523e5dd7070Spatrick   /// Find the adjusted range for the statement, consuming the trailing
524e5dd7070Spatrick   /// semicolon when needed.
getStmtRange(const Stmt * S) const525a9ac8606Spatrick   ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
526ec727ea7Spatrick     auto Tokens = getRange(S->getSourceRange());
527e5dd7070Spatrick     if (isa<CompoundStmt>(S))
528e5dd7070Spatrick       return Tokens;
529e5dd7070Spatrick 
530e5dd7070Spatrick     // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and
531e5dd7070Spatrick     // all statements that end with those. Consume this semicolon here.
532e5dd7070Spatrick     if (Tokens.back().kind() == tok::semi)
533e5dd7070Spatrick       return Tokens;
534e5dd7070Spatrick     return withTrailingSemicolon(Tokens);
535e5dd7070Spatrick   }
536e5dd7070Spatrick 
537e5dd7070Spatrick private:
maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,const Decl * D) const538a9ac8606Spatrick   ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,
539ec727ea7Spatrick                                                const Decl *D) const {
540a9ac8606Spatrick     if (isa<NamespaceDecl>(D))
541ec727ea7Spatrick       return Tokens;
542ec727ea7Spatrick     if (DeclsWithoutSemicolons.count(D))
543ec727ea7Spatrick       return Tokens;
544ec727ea7Spatrick     // FIXME: do not consume trailing semicolon on function definitions.
545ec727ea7Spatrick     // Most declarations own a semicolon in syntax trees, but not in clang AST.
546ec727ea7Spatrick     return withTrailingSemicolon(Tokens);
547ec727ea7Spatrick   }
548ec727ea7Spatrick 
549a9ac8606Spatrick   ArrayRef<syntax::Token>
withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const550a9ac8606Spatrick   withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const {
551e5dd7070Spatrick     assert(!Tokens.empty());
552e5dd7070Spatrick     assert(Tokens.back().kind() != tok::eof);
553ec727ea7Spatrick     // We never consume 'eof', so looking at the next token is ok.
554e5dd7070Spatrick     if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi)
555*12c85518Srobert       return llvm::ArrayRef(Tokens.begin(), Tokens.end() + 1);
556e5dd7070Spatrick     return Tokens;
557e5dd7070Spatrick   }
558e5dd7070Spatrick 
setRole(syntax::Node * N,NodeRole R)559ec727ea7Spatrick   void setRole(syntax::Node *N, NodeRole R) {
560a9ac8606Spatrick     assert(N->getRole() == NodeRole::Detached);
561ec727ea7Spatrick     N->setRole(R);
562ec727ea7Spatrick   }
563e5dd7070Spatrick 
564e5dd7070Spatrick   /// A collection of trees covering the input tokens.
565e5dd7070Spatrick   /// When created, each tree corresponds to a single token in the file.
566e5dd7070Spatrick   /// Clients call 'foldChildren' to attach one or more subtrees to a parent
567e5dd7070Spatrick   /// node and update the list of trees accordingly.
568e5dd7070Spatrick   ///
569e5dd7070Spatrick   /// Ensures that added nodes properly nest and cover the whole token stream.
570e5dd7070Spatrick   struct Forest {
Forestsyntax::TreeBuilder::Forest571*12c85518Srobert     Forest(syntax::Arena &A, const syntax::TokenBuffer &TB) {
572*12c85518Srobert       assert(!TB.expandedTokens().empty());
573*12c85518Srobert       assert(TB.expandedTokens().back().kind() == tok::eof);
574e5dd7070Spatrick       // Create all leaf nodes.
575e5dd7070Spatrick       // Note that we do not have 'eof' in the tree.
576*12c85518Srobert       for (const auto &T : TB.expandedTokens().drop_back()) {
577*12c85518Srobert         auto *L = new (A.getAllocator())
578*12c85518Srobert             syntax::Leaf(reinterpret_cast<TokenManager::Key>(&T));
579e5dd7070Spatrick         L->Original = true;
580*12c85518Srobert         L->CanModify = TB.spelledForExpanded(T).has_value();
581ec727ea7Spatrick         Trees.insert(Trees.end(), {&T, L});
582e5dd7070Spatrick       }
583e5dd7070Spatrick     }
584e5dd7070Spatrick 
assignRolesyntax::TreeBuilder::Forest585a9ac8606Spatrick     void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) {
586e5dd7070Spatrick       assert(!Range.empty());
587e5dd7070Spatrick       auto It = Trees.lower_bound(Range.begin());
588e5dd7070Spatrick       assert(It != Trees.end() && "no node found");
589e5dd7070Spatrick       assert(It->first == Range.begin() && "no child with the specified range");
590e5dd7070Spatrick       assert((std::next(It) == Trees.end() ||
591e5dd7070Spatrick               std::next(It)->first == Range.end()) &&
592e5dd7070Spatrick              "no child with the specified range");
593a9ac8606Spatrick       assert(It->second->getRole() == NodeRole::Detached &&
594ec727ea7Spatrick              "re-assigning role for a child");
595ec727ea7Spatrick       It->second->setRole(Role);
596e5dd7070Spatrick     }
597e5dd7070Spatrick 
598a9ac8606Spatrick     /// Shrink \p Range to a subrange that only contains tokens of a list.
599a9ac8606Spatrick     /// List elements and delimiters should already have correct roles.
shrinkToFitListsyntax::TreeBuilder::Forest600a9ac8606Spatrick     ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) {
601a9ac8606Spatrick       auto BeginChildren = Trees.lower_bound(Range.begin());
602a9ac8606Spatrick       assert((BeginChildren == Trees.end() ||
603a9ac8606Spatrick               BeginChildren->first == Range.begin()) &&
604a9ac8606Spatrick              "Range crosses boundaries of existing subtrees");
605a9ac8606Spatrick 
606a9ac8606Spatrick       auto EndChildren = Trees.lower_bound(Range.end());
607a9ac8606Spatrick       assert(
608a9ac8606Spatrick           (EndChildren == Trees.end() || EndChildren->first == Range.end()) &&
609a9ac8606Spatrick           "Range crosses boundaries of existing subtrees");
610a9ac8606Spatrick 
611a9ac8606Spatrick       auto BelongsToList = [](decltype(Trees)::value_type KV) {
612a9ac8606Spatrick         auto Role = KV.second->getRole();
613a9ac8606Spatrick         return Role == syntax::NodeRole::ListElement ||
614a9ac8606Spatrick                Role == syntax::NodeRole::ListDelimiter;
615a9ac8606Spatrick       };
616a9ac8606Spatrick 
617a9ac8606Spatrick       auto BeginListChildren =
618a9ac8606Spatrick           std::find_if(BeginChildren, EndChildren, BelongsToList);
619a9ac8606Spatrick 
620a9ac8606Spatrick       auto EndListChildren =
621a9ac8606Spatrick           std::find_if_not(BeginListChildren, EndChildren, BelongsToList);
622a9ac8606Spatrick 
623a9ac8606Spatrick       return ArrayRef<syntax::Token>(BeginListChildren->first,
624a9ac8606Spatrick                                      EndListChildren->first);
625a9ac8606Spatrick     }
626a9ac8606Spatrick 
627e5dd7070Spatrick     /// Add \p Node to the forest and attach child nodes based on \p Tokens.
foldChildrensyntax::TreeBuilder::Forest628*12c85518Srobert     void foldChildren(const syntax::TokenBuffer &TB,
629*12c85518Srobert                       ArrayRef<syntax::Token> Tokens, syntax::Tree *Node) {
630e5dd7070Spatrick       // Attach children to `Node`.
631a9ac8606Spatrick       assert(Node->getFirstChild() == nullptr && "node already has children");
632ec727ea7Spatrick 
633ec727ea7Spatrick       auto *FirstToken = Tokens.begin();
634ec727ea7Spatrick       auto BeginChildren = Trees.lower_bound(FirstToken);
635ec727ea7Spatrick 
636ec727ea7Spatrick       assert((BeginChildren == Trees.end() ||
637ec727ea7Spatrick               BeginChildren->first == FirstToken) &&
638ec727ea7Spatrick              "fold crosses boundaries of existing subtrees");
639ec727ea7Spatrick       auto EndChildren = Trees.lower_bound(Tokens.end());
640ec727ea7Spatrick       assert(
641ec727ea7Spatrick           (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) &&
642ec727ea7Spatrick           "fold crosses boundaries of existing subtrees");
643ec727ea7Spatrick 
644a9ac8606Spatrick       for (auto It = BeginChildren; It != EndChildren; ++It) {
645a9ac8606Spatrick         auto *C = It->second;
646a9ac8606Spatrick         if (C->getRole() == NodeRole::Detached)
647ec727ea7Spatrick           C->setRole(NodeRole::Unknown);
648a9ac8606Spatrick         Node->appendChildLowLevel(C);
649e5dd7070Spatrick       }
650e5dd7070Spatrick 
651ec727ea7Spatrick       // Mark that this node came from the AST and is backed by the source code.
652ec727ea7Spatrick       Node->Original = true;
653a9ac8606Spatrick       Node->CanModify =
654*12c85518Srobert           TB.spelledForExpanded(Tokens).has_value();
655e5dd7070Spatrick 
656ec727ea7Spatrick       Trees.erase(BeginChildren, EndChildren);
657ec727ea7Spatrick       Trees.insert({FirstToken, Node});
658e5dd7070Spatrick     }
659e5dd7070Spatrick 
660e5dd7070Spatrick     // EXPECTS: all tokens were consumed and are owned by a single root node.
finalizesyntax::TreeBuilder::Forest661e5dd7070Spatrick     syntax::Node *finalize() && {
662e5dd7070Spatrick       assert(Trees.size() == 1);
663ec727ea7Spatrick       auto *Root = Trees.begin()->second;
664e5dd7070Spatrick       Trees = {};
665e5dd7070Spatrick       return Root;
666e5dd7070Spatrick     }
667e5dd7070Spatrick 
strsyntax::TreeBuilder::Forest668*12c85518Srobert     std::string str(const syntax::TokenBufferTokenManager &STM) const {
669e5dd7070Spatrick       std::string R;
670e5dd7070Spatrick       for (auto It = Trees.begin(); It != Trees.end(); ++It) {
671e5dd7070Spatrick         unsigned CoveredTokens =
672e5dd7070Spatrick             It != Trees.end()
673e5dd7070Spatrick                 ? (std::next(It)->first - It->first)
674*12c85518Srobert                 : STM.tokenBuffer().expandedTokens().end() - It->first;
675e5dd7070Spatrick 
676a9ac8606Spatrick         R += std::string(
677a9ac8606Spatrick             formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(),
678*12c85518Srobert                     It->first->text(STM.sourceManager()), CoveredTokens));
679*12c85518Srobert         R += It->second->dump(STM);
680e5dd7070Spatrick       }
681e5dd7070Spatrick       return R;
682e5dd7070Spatrick     }
683e5dd7070Spatrick 
684e5dd7070Spatrick   private:
685e5dd7070Spatrick     /// Maps from the start token to a subtree starting at that token.
686e5dd7070Spatrick     /// Keys in the map are pointers into the array of expanded tokens, so
687e5dd7070Spatrick     /// pointer order corresponds to the order of preprocessor tokens.
688ec727ea7Spatrick     std::map<const syntax::Token *, syntax::Node *> Trees;
689e5dd7070Spatrick   };
690e5dd7070Spatrick 
691e5dd7070Spatrick   /// For debugging purposes.
str()692*12c85518Srobert   std::string str() { return Pending.str(TBTM); }
693e5dd7070Spatrick 
694e5dd7070Spatrick   syntax::Arena &Arena;
695*12c85518Srobert   TokenBufferTokenManager& TBTM;
696e5dd7070Spatrick   /// To quickly find tokens by their start location.
697a9ac8606Spatrick   llvm::DenseMap<SourceLocation, const syntax::Token *> LocationToToken;
698e5dd7070Spatrick   Forest Pending;
699e5dd7070Spatrick   llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
700ec727ea7Spatrick   ASTToSyntaxMapping Mapping;
701e5dd7070Spatrick };
702e5dd7070Spatrick 
703e5dd7070Spatrick namespace {
704e5dd7070Spatrick class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
705e5dd7070Spatrick public:
BuildTreeVisitor(ASTContext & Context,syntax::TreeBuilder & Builder)706ec727ea7Spatrick   explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
707ec727ea7Spatrick       : Builder(Builder), Context(Context) {}
708e5dd7070Spatrick 
shouldTraversePostOrder() const709e5dd7070Spatrick   bool shouldTraversePostOrder() const { return true; }
710e5dd7070Spatrick 
WalkUpFromDeclaratorDecl(DeclaratorDecl * DD)711ec727ea7Spatrick   bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
712ec727ea7Spatrick     return processDeclaratorAndDeclaration(DD);
713e5dd7070Spatrick   }
714ec727ea7Spatrick 
WalkUpFromTypedefNameDecl(TypedefNameDecl * TD)715ec727ea7Spatrick   bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
716ec727ea7Spatrick     return processDeclaratorAndDeclaration(TD);
717e5dd7070Spatrick   }
718e5dd7070Spatrick 
VisitDecl(Decl * D)719e5dd7070Spatrick   bool VisitDecl(Decl *D) {
720e5dd7070Spatrick     assert(!D->isImplicit());
721ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(D),
722ec727ea7Spatrick                      new (allocator()) syntax::UnknownDeclaration(), D);
723ec727ea7Spatrick     return true;
724ec727ea7Spatrick   }
725ec727ea7Spatrick 
726ec727ea7Spatrick   // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
727ec727ea7Spatrick   // override Traverse.
728ec727ea7Spatrick   // FIXME: make RAV call WalkUpFrom* instead.
729ec727ea7Spatrick   bool
TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * C)730ec727ea7Spatrick   TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
731ec727ea7Spatrick     if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
732ec727ea7Spatrick       return false;
733ec727ea7Spatrick     if (C->isExplicitSpecialization())
734ec727ea7Spatrick       return true; // we are only interested in explicit instantiations.
735ec727ea7Spatrick     auto *Declaration =
736ec727ea7Spatrick         cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
737ec727ea7Spatrick     foldExplicitTemplateInstantiation(
738ec727ea7Spatrick         Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()),
739ec727ea7Spatrick         Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
740ec727ea7Spatrick     return true;
741ec727ea7Spatrick   }
742ec727ea7Spatrick 
WalkUpFromTemplateDecl(TemplateDecl * S)743ec727ea7Spatrick   bool WalkUpFromTemplateDecl(TemplateDecl *S) {
744ec727ea7Spatrick     foldTemplateDeclaration(
745ec727ea7Spatrick         Builder.getDeclarationRange(S),
746ec727ea7Spatrick         Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
747ec727ea7Spatrick         Builder.getDeclarationRange(S->getTemplatedDecl()), S);
748e5dd7070Spatrick     return true;
749e5dd7070Spatrick   }
750e5dd7070Spatrick 
WalkUpFromTagDecl(TagDecl * C)751e5dd7070Spatrick   bool WalkUpFromTagDecl(TagDecl *C) {
752e5dd7070Spatrick     // FIXME: build the ClassSpecifier node.
753ec727ea7Spatrick     if (!C->isFreeStanding()) {
754ec727ea7Spatrick       assert(C->getNumTemplateParameterLists() == 0);
755e5dd7070Spatrick       return true;
756e5dd7070Spatrick     }
757ec727ea7Spatrick     handleFreeStandingTagDecl(C);
758e5dd7070Spatrick     return true;
759e5dd7070Spatrick   }
760e5dd7070Spatrick 
handleFreeStandingTagDecl(TagDecl * C)761ec727ea7Spatrick   syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
762ec727ea7Spatrick     assert(C->isFreeStanding());
763ec727ea7Spatrick     // Class is a declaration specifier and needs a spanning declaration node.
764ec727ea7Spatrick     auto DeclarationRange = Builder.getDeclarationRange(C);
765ec727ea7Spatrick     syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
766ec727ea7Spatrick     Builder.foldNode(DeclarationRange, Result, nullptr);
767ec727ea7Spatrick 
768ec727ea7Spatrick     // Build TemplateDeclaration nodes if we had template parameters.
769ec727ea7Spatrick     auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
770ec727ea7Spatrick       const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
771*12c85518Srobert       auto R = llvm::ArrayRef(TemplateKW, DeclarationRange.end());
772ec727ea7Spatrick       Result =
773ec727ea7Spatrick           foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
774ec727ea7Spatrick       DeclarationRange = R;
775ec727ea7Spatrick     };
776a9ac8606Spatrick     if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
777ec727ea7Spatrick       ConsumeTemplateParameters(*S->getTemplateParameters());
778ec727ea7Spatrick     for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
779ec727ea7Spatrick       ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
780ec727ea7Spatrick     return Result;
781ec727ea7Spatrick   }
782ec727ea7Spatrick 
WalkUpFromTranslationUnitDecl(TranslationUnitDecl * TU)783e5dd7070Spatrick   bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
784ec727ea7Spatrick     // We do not want to call VisitDecl(), the declaration for translation
785e5dd7070Spatrick     // unit is built by finalize().
786e5dd7070Spatrick     return true;
787e5dd7070Spatrick   }
788e5dd7070Spatrick 
WalkUpFromCompoundStmt(CompoundStmt * S)789e5dd7070Spatrick   bool WalkUpFromCompoundStmt(CompoundStmt *S) {
790e5dd7070Spatrick     using NodeRole = syntax::NodeRole;
791e5dd7070Spatrick 
792e5dd7070Spatrick     Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
793e5dd7070Spatrick     for (auto *Child : S->body())
794a9ac8606Spatrick       Builder.markStmtChild(Child, NodeRole::Statement);
795e5dd7070Spatrick     Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
796e5dd7070Spatrick 
797e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
798ec727ea7Spatrick                      new (allocator()) syntax::CompoundStatement, S);
799e5dd7070Spatrick     return true;
800e5dd7070Spatrick   }
801e5dd7070Spatrick 
802e5dd7070Spatrick   // Some statements are not yet handled by syntax trees.
WalkUpFromStmt(Stmt * S)803e5dd7070Spatrick   bool WalkUpFromStmt(Stmt *S) {
804e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
805ec727ea7Spatrick                      new (allocator()) syntax::UnknownStatement, S);
806e5dd7070Spatrick     return true;
807e5dd7070Spatrick   }
808e5dd7070Spatrick 
TraverseIfStmt(IfStmt * S)809a9ac8606Spatrick   bool TraverseIfStmt(IfStmt *S) {
810a9ac8606Spatrick     bool Result = [&, this]() {
811a9ac8606Spatrick       if (S->getInit() && !TraverseStmt(S->getInit())) {
812a9ac8606Spatrick         return false;
813a9ac8606Spatrick       }
814a9ac8606Spatrick       // In cases where the condition is an initialized declaration in a
815a9ac8606Spatrick       // statement, we want to preserve the declaration and ignore the
816a9ac8606Spatrick       // implicit condition expression in the syntax tree.
817a9ac8606Spatrick       if (S->hasVarStorage()) {
818a9ac8606Spatrick         if (!TraverseStmt(S->getConditionVariableDeclStmt()))
819a9ac8606Spatrick           return false;
820a9ac8606Spatrick       } else if (S->getCond() && !TraverseStmt(S->getCond()))
821a9ac8606Spatrick         return false;
822a9ac8606Spatrick 
823a9ac8606Spatrick       if (S->getThen() && !TraverseStmt(S->getThen()))
824a9ac8606Spatrick         return false;
825a9ac8606Spatrick       if (S->getElse() && !TraverseStmt(S->getElse()))
826a9ac8606Spatrick         return false;
827a9ac8606Spatrick       return true;
828a9ac8606Spatrick     }();
829a9ac8606Spatrick     WalkUpFromIfStmt(S);
830a9ac8606Spatrick     return Result;
831a9ac8606Spatrick   }
832a9ac8606Spatrick 
TraverseCXXForRangeStmt(CXXForRangeStmt * S)833e5dd7070Spatrick   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
834e5dd7070Spatrick     // We override to traverse range initializer as VarDecl.
835e5dd7070Spatrick     // RAV traverses it as a statement, we produce invalid node kinds in that
836e5dd7070Spatrick     // case.
837e5dd7070Spatrick     // FIXME: should do this in RAV instead?
838ec727ea7Spatrick     bool Result = [&, this]() {
839e5dd7070Spatrick       if (S->getInit() && !TraverseStmt(S->getInit()))
840e5dd7070Spatrick         return false;
841e5dd7070Spatrick       if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
842e5dd7070Spatrick         return false;
843e5dd7070Spatrick       if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
844e5dd7070Spatrick         return false;
845e5dd7070Spatrick       if (S->getBody() && !TraverseStmt(S->getBody()))
846e5dd7070Spatrick         return false;
847e5dd7070Spatrick       return true;
848ec727ea7Spatrick     }();
849ec727ea7Spatrick     WalkUpFromCXXForRangeStmt(S);
850ec727ea7Spatrick     return Result;
851e5dd7070Spatrick   }
852e5dd7070Spatrick 
TraverseStmt(Stmt * S)853e5dd7070Spatrick   bool TraverseStmt(Stmt *S) {
854a9ac8606Spatrick     if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) {
855e5dd7070Spatrick       // We want to consume the semicolon, make sure SimpleDeclaration does not.
856e5dd7070Spatrick       for (auto *D : DS->decls())
857ec727ea7Spatrick         Builder.noticeDeclWithoutSemicolon(D);
858a9ac8606Spatrick     } else if (auto *E = dyn_cast_or_null<Expr>(S)) {
859a9ac8606Spatrick       return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E));
860e5dd7070Spatrick     }
861e5dd7070Spatrick     return RecursiveASTVisitor::TraverseStmt(S);
862e5dd7070Spatrick   }
863e5dd7070Spatrick 
TraverseOpaqueValueExpr(OpaqueValueExpr * VE)864a9ac8606Spatrick   bool TraverseOpaqueValueExpr(OpaqueValueExpr *VE) {
865a9ac8606Spatrick     // OpaqueValue doesn't correspond to concrete syntax, ignore it.
866a9ac8606Spatrick     return true;
867a9ac8606Spatrick   }
868a9ac8606Spatrick 
869e5dd7070Spatrick   // Some expressions are not yet handled by syntax trees.
WalkUpFromExpr(Expr * E)870e5dd7070Spatrick   bool WalkUpFromExpr(Expr *E) {
871e5dd7070Spatrick     assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
872e5dd7070Spatrick     Builder.foldNode(Builder.getExprRange(E),
873ec727ea7Spatrick                      new (allocator()) syntax::UnknownExpression, E);
874e5dd7070Spatrick     return true;
875e5dd7070Spatrick   }
876e5dd7070Spatrick 
TraverseUserDefinedLiteral(UserDefinedLiteral * S)877ec727ea7Spatrick   bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
878ec727ea7Spatrick     // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
879ec727ea7Spatrick     // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
880ec727ea7Spatrick     // UDL suffix location does not point to the beginning of a token, so we
881ec727ea7Spatrick     // can't represent the UDL suffix as a separate syntax tree node.
882ec727ea7Spatrick 
883ec727ea7Spatrick     return WalkUpFromUserDefinedLiteral(S);
884ec727ea7Spatrick   }
885ec727ea7Spatrick 
886ec727ea7Spatrick   syntax::UserDefinedLiteralExpression *
buildUserDefinedLiteral(UserDefinedLiteral * S)887ec727ea7Spatrick   buildUserDefinedLiteral(UserDefinedLiteral *S) {
888ec727ea7Spatrick     switch (S->getLiteralOperatorKind()) {
889a9ac8606Spatrick     case UserDefinedLiteral::LOK_Integer:
890ec727ea7Spatrick       return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
891a9ac8606Spatrick     case UserDefinedLiteral::LOK_Floating:
892ec727ea7Spatrick       return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
893a9ac8606Spatrick     case UserDefinedLiteral::LOK_Character:
894ec727ea7Spatrick       return new (allocator()) syntax::CharUserDefinedLiteralExpression;
895a9ac8606Spatrick     case UserDefinedLiteral::LOK_String:
896ec727ea7Spatrick       return new (allocator()) syntax::StringUserDefinedLiteralExpression;
897a9ac8606Spatrick     case UserDefinedLiteral::LOK_Raw:
898a9ac8606Spatrick     case UserDefinedLiteral::LOK_Template:
899ec727ea7Spatrick       // For raw literal operator and numeric literal operator template we
900ec727ea7Spatrick       // cannot get the type of the operand in the semantic AST. We get this
901ec727ea7Spatrick       // information from the token. As integer and floating point have the same
902ec727ea7Spatrick       // token kind, we run `NumericLiteralParser` again to distinguish them.
903ec727ea7Spatrick       auto TokLoc = S->getBeginLoc();
904ec727ea7Spatrick       auto TokSpelling =
905ec727ea7Spatrick           Builder.findToken(TokLoc)->text(Context.getSourceManager());
906ec727ea7Spatrick       auto Literal =
907ec727ea7Spatrick           NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
908ec727ea7Spatrick                                Context.getLangOpts(), Context.getTargetInfo(),
909ec727ea7Spatrick                                Context.getDiagnostics());
910ec727ea7Spatrick       if (Literal.isIntegerLiteral())
911ec727ea7Spatrick         return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
912ec727ea7Spatrick       else {
913ec727ea7Spatrick         assert(Literal.isFloatingLiteral());
914ec727ea7Spatrick         return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
915ec727ea7Spatrick       }
916ec727ea7Spatrick     }
917ec727ea7Spatrick     llvm_unreachable("Unknown literal operator kind.");
918ec727ea7Spatrick   }
919ec727ea7Spatrick 
WalkUpFromUserDefinedLiteral(UserDefinedLiteral * S)920ec727ea7Spatrick   bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
921ec727ea7Spatrick     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
922ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
923ec727ea7Spatrick     return true;
924ec727ea7Spatrick   }
925ec727ea7Spatrick 
926a9ac8606Spatrick   // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the
927a9ac8606Spatrick   // `DependentTemplateSpecializationType` case.
928a9ac8606Spatrick   /// Given a nested-name-specifier return the range for the last name
929a9ac8606Spatrick   /// specifier.
930a9ac8606Spatrick   ///
931a9ac8606Spatrick   /// e.g. `std::T::template X<U>::` => `template X<U>::`
getLocalSourceRange(const NestedNameSpecifierLoc & NNSLoc)932a9ac8606Spatrick   SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) {
933a9ac8606Spatrick     auto SR = NNSLoc.getLocalSourceRange();
934ec727ea7Spatrick 
935a9ac8606Spatrick     // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should*
936a9ac8606Spatrick     // return the desired `SourceRange`, but there is a corner case. For a
937a9ac8606Spatrick     // `DependentTemplateSpecializationType` this method returns its
938a9ac8606Spatrick     // qualifiers as well, in other words in the example above this method
939a9ac8606Spatrick     // returns `T::template X<U>::` instead of only `template X<U>::`
940a9ac8606Spatrick     if (auto TL = NNSLoc.getTypeLoc()) {
941a9ac8606Spatrick       if (auto DependentTL =
942a9ac8606Spatrick               TL.getAs<DependentTemplateSpecializationTypeLoc>()) {
943a9ac8606Spatrick         // The 'template' keyword is always present in dependent template
944a9ac8606Spatrick         // specializations. Except in the case of incorrect code
945a9ac8606Spatrick         // TODO: Treat the case of incorrect code.
946a9ac8606Spatrick         SR.setBegin(DependentTL.getTemplateKeywordLoc());
947ec727ea7Spatrick       }
948a9ac8606Spatrick     }
949a9ac8606Spatrick 
950a9ac8606Spatrick     return SR;
951a9ac8606Spatrick   }
952a9ac8606Spatrick 
getNameSpecifierKind(const NestedNameSpecifier & NNS)953a9ac8606Spatrick   syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) {
954a9ac8606Spatrick     switch (NNS.getKind()) {
955a9ac8606Spatrick     case NestedNameSpecifier::Global:
956a9ac8606Spatrick       return syntax::NodeKind::GlobalNameSpecifier;
957a9ac8606Spatrick     case NestedNameSpecifier::Namespace:
958a9ac8606Spatrick     case NestedNameSpecifier::NamespaceAlias:
959a9ac8606Spatrick     case NestedNameSpecifier::Identifier:
960a9ac8606Spatrick       return syntax::NodeKind::IdentifierNameSpecifier;
961a9ac8606Spatrick     case NestedNameSpecifier::TypeSpecWithTemplate:
962a9ac8606Spatrick       return syntax::NodeKind::SimpleTemplateNameSpecifier;
963a9ac8606Spatrick     case NestedNameSpecifier::TypeSpec: {
964a9ac8606Spatrick       const auto *NNSType = NNS.getAsType();
965a9ac8606Spatrick       assert(NNSType);
966a9ac8606Spatrick       if (isa<DecltypeType>(NNSType))
967a9ac8606Spatrick         return syntax::NodeKind::DecltypeNameSpecifier;
968a9ac8606Spatrick       if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>(
969a9ac8606Spatrick               NNSType))
970a9ac8606Spatrick         return syntax::NodeKind::SimpleTemplateNameSpecifier;
971a9ac8606Spatrick       return syntax::NodeKind::IdentifierNameSpecifier;
972a9ac8606Spatrick     }
973a9ac8606Spatrick     default:
974a9ac8606Spatrick       // FIXME: Support Microsoft's __super
975a9ac8606Spatrick       llvm::report_fatal_error("We don't yet support the __super specifier",
976a9ac8606Spatrick                                true);
977a9ac8606Spatrick     }
978a9ac8606Spatrick   }
979a9ac8606Spatrick 
980a9ac8606Spatrick   syntax::NameSpecifier *
buildNameSpecifier(const NestedNameSpecifierLoc & NNSLoc)981a9ac8606Spatrick   buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) {
982a9ac8606Spatrick     assert(NNSLoc.hasQualifier());
983a9ac8606Spatrick     auto NameSpecifierTokens =
984a9ac8606Spatrick         Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back();
985a9ac8606Spatrick     switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) {
986a9ac8606Spatrick     case syntax::NodeKind::GlobalNameSpecifier:
987a9ac8606Spatrick       return new (allocator()) syntax::GlobalNameSpecifier;
988a9ac8606Spatrick     case syntax::NodeKind::IdentifierNameSpecifier: {
989a9ac8606Spatrick       assert(NameSpecifierTokens.size() == 1);
990a9ac8606Spatrick       Builder.markChildToken(NameSpecifierTokens.begin(),
991a9ac8606Spatrick                              syntax::NodeRole::Unknown);
992a9ac8606Spatrick       auto *NS = new (allocator()) syntax::IdentifierNameSpecifier;
993a9ac8606Spatrick       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
994a9ac8606Spatrick       return NS;
995a9ac8606Spatrick     }
996a9ac8606Spatrick     case syntax::NodeKind::SimpleTemplateNameSpecifier: {
997a9ac8606Spatrick       // TODO: Build `SimpleTemplateNameSpecifier` children and implement
998a9ac8606Spatrick       // accessors to them.
999a9ac8606Spatrick       // Be aware, we cannot do that simply by calling `TraverseTypeLoc`,
1000a9ac8606Spatrick       // some `TypeLoc`s have inside them the previous name specifier and
1001a9ac8606Spatrick       // we want to treat them independently.
1002a9ac8606Spatrick       auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier;
1003a9ac8606Spatrick       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1004a9ac8606Spatrick       return NS;
1005a9ac8606Spatrick     }
1006a9ac8606Spatrick     case syntax::NodeKind::DecltypeNameSpecifier: {
1007a9ac8606Spatrick       const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>();
1008a9ac8606Spatrick       if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL))
1009a9ac8606Spatrick         return nullptr;
1010a9ac8606Spatrick       auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
1011a9ac8606Spatrick       // TODO: Implement accessor to `DecltypeNameSpecifier` inner
1012a9ac8606Spatrick       // `DecltypeTypeLoc`.
1013a9ac8606Spatrick       // For that add mapping from `TypeLoc` to `syntax::Node*` then:
1014a9ac8606Spatrick       // Builder.markChild(TypeLoc, syntax::NodeRole);
1015a9ac8606Spatrick       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1016a9ac8606Spatrick       return NS;
1017a9ac8606Spatrick     }
1018a9ac8606Spatrick     default:
1019a9ac8606Spatrick       llvm_unreachable("getChildKind() does not return this value");
1020a9ac8606Spatrick     }
1021a9ac8606Spatrick   }
1022a9ac8606Spatrick 
1023a9ac8606Spatrick   // To build syntax tree nodes for NestedNameSpecifierLoc we override
1024a9ac8606Spatrick   // Traverse instead of WalkUpFrom because we want to traverse the children
1025a9ac8606Spatrick   // ourselves and build a list instead of a nested tree of name specifier
1026a9ac8606Spatrick   // prefixes.
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc)1027a9ac8606Spatrick   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) {
1028a9ac8606Spatrick     if (!QualifierLoc)
1029a9ac8606Spatrick       return true;
1030a9ac8606Spatrick     for (auto It = QualifierLoc; It; It = It.getPrefix()) {
1031a9ac8606Spatrick       auto *NS = buildNameSpecifier(It);
1032a9ac8606Spatrick       if (!NS)
1033a9ac8606Spatrick         return false;
1034a9ac8606Spatrick       Builder.markChild(NS, syntax::NodeRole::ListElement);
1035a9ac8606Spatrick       Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
1036a9ac8606Spatrick     }
1037a9ac8606Spatrick     Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1038a9ac8606Spatrick                      new (allocator()) syntax::NestedNameSpecifier,
1039a9ac8606Spatrick                      QualifierLoc);
1040a9ac8606Spatrick     return true;
1041a9ac8606Spatrick   }
1042a9ac8606Spatrick 
buildIdExpression(NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKeywordLoc,SourceRange UnqualifiedIdLoc,ASTPtr From)1043a9ac8606Spatrick   syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1044a9ac8606Spatrick                                           SourceLocation TemplateKeywordLoc,
1045a9ac8606Spatrick                                           SourceRange UnqualifiedIdLoc,
1046a9ac8606Spatrick                                           ASTPtr From) {
1047a9ac8606Spatrick     if (QualifierLoc) {
1048a9ac8606Spatrick       Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1049a9ac8606Spatrick       if (TemplateKeywordLoc.isValid())
1050a9ac8606Spatrick         Builder.markChildToken(TemplateKeywordLoc,
1051a9ac8606Spatrick                                syntax::NodeRole::TemplateKeyword);
1052a9ac8606Spatrick     }
1053a9ac8606Spatrick 
1054a9ac8606Spatrick     auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1055a9ac8606Spatrick     Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1056a9ac8606Spatrick                      nullptr);
1057a9ac8606Spatrick     Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1058a9ac8606Spatrick 
1059a9ac8606Spatrick     auto IdExpressionBeginLoc =
1060a9ac8606Spatrick         QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1061a9ac8606Spatrick 
1062a9ac8606Spatrick     auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1063a9ac8606Spatrick     Builder.foldNode(
1064a9ac8606Spatrick         Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1065a9ac8606Spatrick         TheIdExpression, From);
1066a9ac8606Spatrick 
1067a9ac8606Spatrick     return TheIdExpression;
1068a9ac8606Spatrick   }
1069a9ac8606Spatrick 
WalkUpFromMemberExpr(MemberExpr * S)1070a9ac8606Spatrick   bool WalkUpFromMemberExpr(MemberExpr *S) {
1071a9ac8606Spatrick     // For `MemberExpr` with implicit `this->` we generate a simple
1072a9ac8606Spatrick     // `id-expression` syntax node, beacuse an implicit `member-expression` is
1073a9ac8606Spatrick     // syntactically undistinguishable from an `id-expression`
1074a9ac8606Spatrick     if (S->isImplicitAccess()) {
1075a9ac8606Spatrick       buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1076a9ac8606Spatrick                         SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1077a9ac8606Spatrick       return true;
1078a9ac8606Spatrick     }
1079a9ac8606Spatrick 
1080a9ac8606Spatrick     auto *TheIdExpression = buildIdExpression(
1081a9ac8606Spatrick         S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1082a9ac8606Spatrick         SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1083a9ac8606Spatrick 
1084a9ac8606Spatrick     Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1085a9ac8606Spatrick 
1086a9ac8606Spatrick     Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1087a9ac8606Spatrick     Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1088ec727ea7Spatrick 
1089ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1090a9ac8606Spatrick                      new (allocator()) syntax::MemberExpression, S);
1091a9ac8606Spatrick     return true;
1092a9ac8606Spatrick   }
1093a9ac8606Spatrick 
WalkUpFromDeclRefExpr(DeclRefExpr * S)1094a9ac8606Spatrick   bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
1095a9ac8606Spatrick     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1096a9ac8606Spatrick                       SourceRange(S->getLocation(), S->getEndLoc()), S);
1097a9ac8606Spatrick 
1098a9ac8606Spatrick     return true;
1099a9ac8606Spatrick   }
1100a9ac8606Spatrick 
1101a9ac8606Spatrick   // Same logic as DeclRefExpr.
WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr * S)1102a9ac8606Spatrick   bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) {
1103a9ac8606Spatrick     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1104a9ac8606Spatrick                       SourceRange(S->getLocation(), S->getEndLoc()), S);
1105a9ac8606Spatrick 
1106a9ac8606Spatrick     return true;
1107a9ac8606Spatrick   }
1108a9ac8606Spatrick 
WalkUpFromCXXThisExpr(CXXThisExpr * S)1109a9ac8606Spatrick   bool WalkUpFromCXXThisExpr(CXXThisExpr *S) {
1110a9ac8606Spatrick     if (!S->isImplicit()) {
1111a9ac8606Spatrick       Builder.markChildToken(S->getLocation(),
1112a9ac8606Spatrick                              syntax::NodeRole::IntroducerKeyword);
1113a9ac8606Spatrick       Builder.foldNode(Builder.getExprRange(S),
1114a9ac8606Spatrick                        new (allocator()) syntax::ThisExpression, S);
1115a9ac8606Spatrick     }
1116ec727ea7Spatrick     return true;
1117ec727ea7Spatrick   }
1118ec727ea7Spatrick 
WalkUpFromParenExpr(ParenExpr * S)1119ec727ea7Spatrick   bool WalkUpFromParenExpr(ParenExpr *S) {
1120ec727ea7Spatrick     Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1121a9ac8606Spatrick     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1122ec727ea7Spatrick     Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1123ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1124ec727ea7Spatrick                      new (allocator()) syntax::ParenExpression, S);
1125ec727ea7Spatrick     return true;
1126ec727ea7Spatrick   }
1127ec727ea7Spatrick 
WalkUpFromIntegerLiteral(IntegerLiteral * S)1128ec727ea7Spatrick   bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
1129ec727ea7Spatrick     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1130ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1131ec727ea7Spatrick                      new (allocator()) syntax::IntegerLiteralExpression, S);
1132ec727ea7Spatrick     return true;
1133ec727ea7Spatrick   }
1134ec727ea7Spatrick 
WalkUpFromCharacterLiteral(CharacterLiteral * S)1135ec727ea7Spatrick   bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
1136ec727ea7Spatrick     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1137ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1138ec727ea7Spatrick                      new (allocator()) syntax::CharacterLiteralExpression, S);
1139ec727ea7Spatrick     return true;
1140ec727ea7Spatrick   }
1141ec727ea7Spatrick 
WalkUpFromFloatingLiteral(FloatingLiteral * S)1142ec727ea7Spatrick   bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
1143ec727ea7Spatrick     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1144ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1145ec727ea7Spatrick                      new (allocator()) syntax::FloatingLiteralExpression, S);
1146ec727ea7Spatrick     return true;
1147ec727ea7Spatrick   }
1148ec727ea7Spatrick 
WalkUpFromStringLiteral(StringLiteral * S)1149ec727ea7Spatrick   bool WalkUpFromStringLiteral(StringLiteral *S) {
1150ec727ea7Spatrick     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1151ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1152ec727ea7Spatrick                      new (allocator()) syntax::StringLiteralExpression, S);
1153ec727ea7Spatrick     return true;
1154ec727ea7Spatrick   }
1155ec727ea7Spatrick 
WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr * S)1156ec727ea7Spatrick   bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
1157ec727ea7Spatrick     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1158ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1159ec727ea7Spatrick                      new (allocator()) syntax::BoolLiteralExpression, S);
1160ec727ea7Spatrick     return true;
1161ec727ea7Spatrick   }
1162ec727ea7Spatrick 
WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr * S)1163ec727ea7Spatrick   bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
1164ec727ea7Spatrick     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1165ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1166ec727ea7Spatrick                      new (allocator()) syntax::CxxNullPtrExpression, S);
1167ec727ea7Spatrick     return true;
1168ec727ea7Spatrick   }
1169ec727ea7Spatrick 
WalkUpFromUnaryOperator(UnaryOperator * S)1170ec727ea7Spatrick   bool WalkUpFromUnaryOperator(UnaryOperator *S) {
1171ec727ea7Spatrick     Builder.markChildToken(S->getOperatorLoc(),
1172a9ac8606Spatrick                            syntax::NodeRole::OperatorToken);
1173a9ac8606Spatrick     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1174ec727ea7Spatrick 
1175ec727ea7Spatrick     if (S->isPostfix())
1176ec727ea7Spatrick       Builder.foldNode(Builder.getExprRange(S),
1177ec727ea7Spatrick                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1178ec727ea7Spatrick                        S);
1179ec727ea7Spatrick     else
1180ec727ea7Spatrick       Builder.foldNode(Builder.getExprRange(S),
1181ec727ea7Spatrick                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1182ec727ea7Spatrick                        S);
1183ec727ea7Spatrick 
1184ec727ea7Spatrick     return true;
1185ec727ea7Spatrick   }
1186ec727ea7Spatrick 
WalkUpFromBinaryOperator(BinaryOperator * S)1187ec727ea7Spatrick   bool WalkUpFromBinaryOperator(BinaryOperator *S) {
1188a9ac8606Spatrick     Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
1189ec727ea7Spatrick     Builder.markChildToken(S->getOperatorLoc(),
1190a9ac8606Spatrick                            syntax::NodeRole::OperatorToken);
1191a9ac8606Spatrick     Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
1192ec727ea7Spatrick     Builder.foldNode(Builder.getExprRange(S),
1193ec727ea7Spatrick                      new (allocator()) syntax::BinaryOperatorExpression, S);
1194ec727ea7Spatrick     return true;
1195ec727ea7Spatrick   }
1196ec727ea7Spatrick 
1197a9ac8606Spatrick   /// Builds `CallArguments` syntax node from arguments that appear in source
1198a9ac8606Spatrick   /// code, i.e. not default arguments.
1199a9ac8606Spatrick   syntax::CallArguments *
buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs)1200a9ac8606Spatrick   buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) {
1201a9ac8606Spatrick     auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1202a9ac8606Spatrick     for (auto *Arg : Args) {
1203a9ac8606Spatrick       Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
1204a9ac8606Spatrick       const auto *DelimiterToken =
1205a9ac8606Spatrick           std::next(Builder.findToken(Arg->getEndLoc()));
1206a9ac8606Spatrick       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1207a9ac8606Spatrick         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1208a9ac8606Spatrick     }
1209a9ac8606Spatrick 
1210a9ac8606Spatrick     auto *Arguments = new (allocator()) syntax::CallArguments;
1211a9ac8606Spatrick     if (!Args.empty())
1212a9ac8606Spatrick       Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
1213a9ac8606Spatrick                                         (*(Args.end() - 1))->getEndLoc()),
1214a9ac8606Spatrick                        Arguments, nullptr);
1215a9ac8606Spatrick 
1216a9ac8606Spatrick     return Arguments;
1217a9ac8606Spatrick   }
1218a9ac8606Spatrick 
WalkUpFromCallExpr(CallExpr * S)1219a9ac8606Spatrick   bool WalkUpFromCallExpr(CallExpr *S) {
1220a9ac8606Spatrick     Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
1221a9ac8606Spatrick 
1222a9ac8606Spatrick     const auto *LParenToken =
1223a9ac8606Spatrick         std::next(Builder.findToken(S->getCallee()->getEndLoc()));
1224a9ac8606Spatrick     // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
1225a9ac8606Spatrick     // the test on decltype desctructors.
1226a9ac8606Spatrick     if (LParenToken->kind() == clang::tok::l_paren)
1227a9ac8606Spatrick       Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1228a9ac8606Spatrick 
1229a9ac8606Spatrick     Builder.markChild(buildCallArguments(S->arguments()),
1230a9ac8606Spatrick                       syntax::NodeRole::Arguments);
1231a9ac8606Spatrick 
1232a9ac8606Spatrick     Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1233a9ac8606Spatrick 
1234a9ac8606Spatrick     Builder.foldNode(Builder.getRange(S->getSourceRange()),
1235a9ac8606Spatrick                      new (allocator()) syntax::CallExpression, S);
1236a9ac8606Spatrick     return true;
1237a9ac8606Spatrick   }
1238a9ac8606Spatrick 
WalkUpFromCXXConstructExpr(CXXConstructExpr * S)1239a9ac8606Spatrick   bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
1240a9ac8606Spatrick     // Ignore the implicit calls to default constructors.
1241a9ac8606Spatrick     if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
1242a9ac8606Spatrick         S->getParenOrBraceRange().isInvalid())
1243a9ac8606Spatrick       return true;
1244a9ac8606Spatrick     return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
1245a9ac8606Spatrick   }
1246a9ac8606Spatrick 
TraverseCXXOperatorCallExpr(CXXOperatorCallExpr * S)1247ec727ea7Spatrick   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1248a9ac8606Spatrick     // To construct a syntax tree of the same shape for calls to built-in and
1249a9ac8606Spatrick     // user-defined operators, ignore the `DeclRefExpr` that refers to the
1250a9ac8606Spatrick     // operator and treat it as a simple token. Do that by traversing
1251a9ac8606Spatrick     // arguments instead of children.
1252a9ac8606Spatrick     for (auto *child : S->arguments()) {
1253ec727ea7Spatrick       // A postfix unary operator is declared as taking two operands. The
1254ec727ea7Spatrick       // second operand is used to distinguish from its prefix counterpart. In
1255ec727ea7Spatrick       // the semantic AST this "phantom" operand is represented as a
1256ec727ea7Spatrick       // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1257ec727ea7Spatrick       // operand because it does not correspond to anything written in source
1258a9ac8606Spatrick       // code.
1259a9ac8606Spatrick       if (child->getSourceRange().isInvalid()) {
1260a9ac8606Spatrick         assert(getOperatorNodeKind(*S) ==
1261a9ac8606Spatrick                syntax::NodeKind::PostfixUnaryOperatorExpression);
1262ec727ea7Spatrick         continue;
1263a9ac8606Spatrick       }
1264ec727ea7Spatrick       if (!TraverseStmt(child))
1265ec727ea7Spatrick         return false;
1266ec727ea7Spatrick     }
1267ec727ea7Spatrick     return WalkUpFromCXXOperatorCallExpr(S);
1268ec727ea7Spatrick   }
1269ec727ea7Spatrick 
WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr * S)1270ec727ea7Spatrick   bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1271ec727ea7Spatrick     switch (getOperatorNodeKind(*S)) {
1272ec727ea7Spatrick     case syntax::NodeKind::BinaryOperatorExpression:
1273a9ac8606Spatrick       Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1274a9ac8606Spatrick       Builder.markChildToken(S->getOperatorLoc(),
1275a9ac8606Spatrick                              syntax::NodeRole::OperatorToken);
1276a9ac8606Spatrick       Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
1277ec727ea7Spatrick       Builder.foldNode(Builder.getExprRange(S),
1278ec727ea7Spatrick                        new (allocator()) syntax::BinaryOperatorExpression, S);
1279ec727ea7Spatrick       return true;
1280ec727ea7Spatrick     case syntax::NodeKind::PrefixUnaryOperatorExpression:
1281a9ac8606Spatrick       Builder.markChildToken(S->getOperatorLoc(),
1282a9ac8606Spatrick                              syntax::NodeRole::OperatorToken);
1283a9ac8606Spatrick       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1284ec727ea7Spatrick       Builder.foldNode(Builder.getExprRange(S),
1285ec727ea7Spatrick                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1286ec727ea7Spatrick                        S);
1287ec727ea7Spatrick       return true;
1288ec727ea7Spatrick     case syntax::NodeKind::PostfixUnaryOperatorExpression:
1289a9ac8606Spatrick       Builder.markChildToken(S->getOperatorLoc(),
1290a9ac8606Spatrick                              syntax::NodeRole::OperatorToken);
1291a9ac8606Spatrick       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1292ec727ea7Spatrick       Builder.foldNode(Builder.getExprRange(S),
1293ec727ea7Spatrick                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1294ec727ea7Spatrick                        S);
1295ec727ea7Spatrick       return true;
1296a9ac8606Spatrick     case syntax::NodeKind::CallExpression: {
1297a9ac8606Spatrick       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
1298a9ac8606Spatrick 
1299a9ac8606Spatrick       const auto *LParenToken =
1300a9ac8606Spatrick           std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
1301a9ac8606Spatrick       // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
1302a9ac8606Spatrick       // fixed the test on decltype desctructors.
1303a9ac8606Spatrick       if (LParenToken->kind() == clang::tok::l_paren)
1304a9ac8606Spatrick         Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1305a9ac8606Spatrick 
1306a9ac8606Spatrick       Builder.markChild(buildCallArguments(CallExpr::arg_range(
1307a9ac8606Spatrick                             S->arg_begin() + 1, S->arg_end())),
1308a9ac8606Spatrick                         syntax::NodeRole::Arguments);
1309a9ac8606Spatrick 
1310a9ac8606Spatrick       Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1311a9ac8606Spatrick 
1312a9ac8606Spatrick       Builder.foldNode(Builder.getRange(S->getSourceRange()),
1313a9ac8606Spatrick                        new (allocator()) syntax::CallExpression, S);
1314a9ac8606Spatrick       return true;
1315a9ac8606Spatrick     }
1316ec727ea7Spatrick     case syntax::NodeKind::UnknownExpression:
1317a9ac8606Spatrick       return WalkUpFromExpr(S);
1318ec727ea7Spatrick     default:
1319ec727ea7Spatrick       llvm_unreachable("getOperatorNodeKind() does not return this value");
1320ec727ea7Spatrick     }
1321ec727ea7Spatrick   }
1322ec727ea7Spatrick 
WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr * S)1323a9ac8606Spatrick   bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; }
1324a9ac8606Spatrick 
WalkUpFromNamespaceDecl(NamespaceDecl * S)1325e5dd7070Spatrick   bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
1326ec727ea7Spatrick     auto Tokens = Builder.getDeclarationRange(S);
1327e5dd7070Spatrick     if (Tokens.front().kind() == tok::coloncolon) {
1328e5dd7070Spatrick       // Handle nested namespace definitions. Those start at '::' token, e.g.
1329e5dd7070Spatrick       // namespace a^::b {}
1330e5dd7070Spatrick       // FIXME: build corresponding nodes for the name of this namespace.
1331e5dd7070Spatrick       return true;
1332e5dd7070Spatrick     }
1333ec727ea7Spatrick     Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1334ec727ea7Spatrick     return true;
1335ec727ea7Spatrick   }
1336ec727ea7Spatrick 
1337a9ac8606Spatrick   // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
1338a9ac8606Spatrick   // results. Find test coverage or remove it.
TraverseParenTypeLoc(ParenTypeLoc L)1339ec727ea7Spatrick   bool TraverseParenTypeLoc(ParenTypeLoc L) {
1340ec727ea7Spatrick     // We reverse order of traversal to get the proper syntax structure.
1341ec727ea7Spatrick     if (!WalkUpFromParenTypeLoc(L))
1342ec727ea7Spatrick       return false;
1343ec727ea7Spatrick     return TraverseTypeLoc(L.getInnerLoc());
1344ec727ea7Spatrick   }
1345ec727ea7Spatrick 
WalkUpFromParenTypeLoc(ParenTypeLoc L)1346ec727ea7Spatrick   bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
1347ec727ea7Spatrick     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1348ec727ea7Spatrick     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1349ec727ea7Spatrick     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1350ec727ea7Spatrick                      new (allocator()) syntax::ParenDeclarator, L);
1351ec727ea7Spatrick     return true;
1352ec727ea7Spatrick   }
1353ec727ea7Spatrick 
1354ec727ea7Spatrick   // Declarator chunks, they are produced by type locs and some clang::Decls.
WalkUpFromArrayTypeLoc(ArrayTypeLoc L)1355ec727ea7Spatrick   bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
1356ec727ea7Spatrick     Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1357a9ac8606Spatrick     Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
1358ec727ea7Spatrick     Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
1359ec727ea7Spatrick     Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1360ec727ea7Spatrick                      new (allocator()) syntax::ArraySubscript, L);
1361ec727ea7Spatrick     return true;
1362ec727ea7Spatrick   }
1363ec727ea7Spatrick 
1364a9ac8606Spatrick   syntax::ParameterDeclarationList *
buildParameterDeclarationList(ArrayRef<ParmVarDecl * > Params)1365a9ac8606Spatrick   buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) {
1366a9ac8606Spatrick     for (auto *P : Params) {
1367a9ac8606Spatrick       Builder.markChild(P, syntax::NodeRole::ListElement);
1368a9ac8606Spatrick       const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1369a9ac8606Spatrick       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1370a9ac8606Spatrick         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1371a9ac8606Spatrick     }
1372a9ac8606Spatrick     auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1373a9ac8606Spatrick     if (!Params.empty())
1374a9ac8606Spatrick       Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1375a9ac8606Spatrick                                         Params.back()->getEndLoc()),
1376a9ac8606Spatrick                        Parameters, nullptr);
1377a9ac8606Spatrick     return Parameters;
1378a9ac8606Spatrick   }
1379a9ac8606Spatrick 
WalkUpFromFunctionTypeLoc(FunctionTypeLoc L)1380ec727ea7Spatrick   bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
1381ec727ea7Spatrick     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1382a9ac8606Spatrick 
1383a9ac8606Spatrick     Builder.markChild(buildParameterDeclarationList(L.getParams()),
1384a9ac8606Spatrick                       syntax::NodeRole::Parameters);
1385a9ac8606Spatrick 
1386ec727ea7Spatrick     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1387ec727ea7Spatrick     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1388ec727ea7Spatrick                      new (allocator()) syntax::ParametersAndQualifiers, L);
1389ec727ea7Spatrick     return true;
1390ec727ea7Spatrick   }
1391ec727ea7Spatrick 
WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L)1392ec727ea7Spatrick   bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
1393ec727ea7Spatrick     if (!L.getTypePtr()->hasTrailingReturn())
1394ec727ea7Spatrick       return WalkUpFromFunctionTypeLoc(L);
1395ec727ea7Spatrick 
1396a9ac8606Spatrick     auto *TrailingReturnTokens = buildTrailingReturn(L);
1397ec727ea7Spatrick     // Finish building the node for parameters.
1398a9ac8606Spatrick     Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
1399ec727ea7Spatrick     return WalkUpFromFunctionTypeLoc(L);
1400ec727ea7Spatrick   }
1401ec727ea7Spatrick 
TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L)1402a9ac8606Spatrick   bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) {
1403a9ac8606Spatrick     // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
1404a9ac8606Spatrick     // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
1405a9ac8606Spatrick     // "(Y::*mp)" We thus reverse the order of traversal to get the proper
1406a9ac8606Spatrick     // syntax structure.
1407a9ac8606Spatrick     if (!WalkUpFromMemberPointerTypeLoc(L))
1408a9ac8606Spatrick       return false;
1409a9ac8606Spatrick     return TraverseTypeLoc(L.getPointeeLoc());
1410a9ac8606Spatrick   }
1411a9ac8606Spatrick 
WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L)1412ec727ea7Spatrick   bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
1413ec727ea7Spatrick     auto SR = L.getLocalSourceRange();
1414ec727ea7Spatrick     Builder.foldNode(Builder.getRange(SR),
1415ec727ea7Spatrick                      new (allocator()) syntax::MemberPointer, L);
1416e5dd7070Spatrick     return true;
1417e5dd7070Spatrick   }
1418e5dd7070Spatrick 
1419e5dd7070Spatrick   // The code below is very regular, it could even be generated with some
1420e5dd7070Spatrick   // preprocessor magic. We merely assign roles to the corresponding children
1421e5dd7070Spatrick   // and fold resulting nodes.
WalkUpFromDeclStmt(DeclStmt * S)1422e5dd7070Spatrick   bool WalkUpFromDeclStmt(DeclStmt *S) {
1423e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1424ec727ea7Spatrick                      new (allocator()) syntax::DeclarationStatement, S);
1425e5dd7070Spatrick     return true;
1426e5dd7070Spatrick   }
1427e5dd7070Spatrick 
WalkUpFromNullStmt(NullStmt * S)1428e5dd7070Spatrick   bool WalkUpFromNullStmt(NullStmt *S) {
1429e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1430ec727ea7Spatrick                      new (allocator()) syntax::EmptyStatement, S);
1431e5dd7070Spatrick     return true;
1432e5dd7070Spatrick   }
1433e5dd7070Spatrick 
WalkUpFromSwitchStmt(SwitchStmt * S)1434e5dd7070Spatrick   bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1435e5dd7070Spatrick     Builder.markChildToken(S->getSwitchLoc(),
1436e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1437e5dd7070Spatrick     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1438e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1439ec727ea7Spatrick                      new (allocator()) syntax::SwitchStatement, S);
1440e5dd7070Spatrick     return true;
1441e5dd7070Spatrick   }
1442e5dd7070Spatrick 
WalkUpFromCaseStmt(CaseStmt * S)1443e5dd7070Spatrick   bool WalkUpFromCaseStmt(CaseStmt *S) {
1444e5dd7070Spatrick     Builder.markChildToken(S->getKeywordLoc(),
1445e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1446a9ac8606Spatrick     Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
1447e5dd7070Spatrick     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1448e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1449ec727ea7Spatrick                      new (allocator()) syntax::CaseStatement, S);
1450e5dd7070Spatrick     return true;
1451e5dd7070Spatrick   }
1452e5dd7070Spatrick 
WalkUpFromDefaultStmt(DefaultStmt * S)1453e5dd7070Spatrick   bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1454e5dd7070Spatrick     Builder.markChildToken(S->getKeywordLoc(),
1455e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1456e5dd7070Spatrick     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1457e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1458ec727ea7Spatrick                      new (allocator()) syntax::DefaultStatement, S);
1459e5dd7070Spatrick     return true;
1460e5dd7070Spatrick   }
1461e5dd7070Spatrick 
WalkUpFromIfStmt(IfStmt * S)1462e5dd7070Spatrick   bool WalkUpFromIfStmt(IfStmt *S) {
1463e5dd7070Spatrick     Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
1464a9ac8606Spatrick     Stmt *ConditionStatement = S->getCond();
1465a9ac8606Spatrick     if (S->hasVarStorage())
1466a9ac8606Spatrick       ConditionStatement = S->getConditionVariableDeclStmt();
1467a9ac8606Spatrick     Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
1468a9ac8606Spatrick     Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1469a9ac8606Spatrick     Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1470a9ac8606Spatrick     Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
1471e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1472ec727ea7Spatrick                      new (allocator()) syntax::IfStatement, S);
1473e5dd7070Spatrick     return true;
1474e5dd7070Spatrick   }
1475e5dd7070Spatrick 
WalkUpFromForStmt(ForStmt * S)1476e5dd7070Spatrick   bool WalkUpFromForStmt(ForStmt *S) {
1477e5dd7070Spatrick     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1478e5dd7070Spatrick     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1479e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1480ec727ea7Spatrick                      new (allocator()) syntax::ForStatement, S);
1481e5dd7070Spatrick     return true;
1482e5dd7070Spatrick   }
1483e5dd7070Spatrick 
WalkUpFromWhileStmt(WhileStmt * S)1484e5dd7070Spatrick   bool WalkUpFromWhileStmt(WhileStmt *S) {
1485e5dd7070Spatrick     Builder.markChildToken(S->getWhileLoc(),
1486e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1487e5dd7070Spatrick     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1488e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1489ec727ea7Spatrick                      new (allocator()) syntax::WhileStatement, S);
1490e5dd7070Spatrick     return true;
1491e5dd7070Spatrick   }
1492e5dd7070Spatrick 
WalkUpFromContinueStmt(ContinueStmt * S)1493e5dd7070Spatrick   bool WalkUpFromContinueStmt(ContinueStmt *S) {
1494e5dd7070Spatrick     Builder.markChildToken(S->getContinueLoc(),
1495e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1496e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1497ec727ea7Spatrick                      new (allocator()) syntax::ContinueStatement, S);
1498e5dd7070Spatrick     return true;
1499e5dd7070Spatrick   }
1500e5dd7070Spatrick 
WalkUpFromBreakStmt(BreakStmt * S)1501e5dd7070Spatrick   bool WalkUpFromBreakStmt(BreakStmt *S) {
1502e5dd7070Spatrick     Builder.markChildToken(S->getBreakLoc(),
1503e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1504e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1505ec727ea7Spatrick                      new (allocator()) syntax::BreakStatement, S);
1506e5dd7070Spatrick     return true;
1507e5dd7070Spatrick   }
1508e5dd7070Spatrick 
WalkUpFromReturnStmt(ReturnStmt * S)1509e5dd7070Spatrick   bool WalkUpFromReturnStmt(ReturnStmt *S) {
1510e5dd7070Spatrick     Builder.markChildToken(S->getReturnLoc(),
1511e5dd7070Spatrick                            syntax::NodeRole::IntroducerKeyword);
1512a9ac8606Spatrick     Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
1513e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1514ec727ea7Spatrick                      new (allocator()) syntax::ReturnStatement, S);
1515e5dd7070Spatrick     return true;
1516e5dd7070Spatrick   }
1517e5dd7070Spatrick 
WalkUpFromCXXForRangeStmt(CXXForRangeStmt * S)1518e5dd7070Spatrick   bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1519e5dd7070Spatrick     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1520e5dd7070Spatrick     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1521e5dd7070Spatrick     Builder.foldNode(Builder.getStmtRange(S),
1522ec727ea7Spatrick                      new (allocator()) syntax::RangeBasedForStatement, S);
1523e5dd7070Spatrick     return true;
1524e5dd7070Spatrick   }
1525e5dd7070Spatrick 
WalkUpFromEmptyDecl(EmptyDecl * S)1526e5dd7070Spatrick   bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1527ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1528ec727ea7Spatrick                      new (allocator()) syntax::EmptyDeclaration, S);
1529e5dd7070Spatrick     return true;
1530e5dd7070Spatrick   }
1531e5dd7070Spatrick 
WalkUpFromStaticAssertDecl(StaticAssertDecl * S)1532e5dd7070Spatrick   bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1533a9ac8606Spatrick     Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1534a9ac8606Spatrick     Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1535ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1536ec727ea7Spatrick                      new (allocator()) syntax::StaticAssertDeclaration, S);
1537e5dd7070Spatrick     return true;
1538e5dd7070Spatrick   }
1539e5dd7070Spatrick 
WalkUpFromLinkageSpecDecl(LinkageSpecDecl * S)1540e5dd7070Spatrick   bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1541ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1542ec727ea7Spatrick                      new (allocator()) syntax::LinkageSpecificationDeclaration,
1543ec727ea7Spatrick                      S);
1544e5dd7070Spatrick     return true;
1545e5dd7070Spatrick   }
1546e5dd7070Spatrick 
WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl * S)1547e5dd7070Spatrick   bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1548ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1549ec727ea7Spatrick                      new (allocator()) syntax::NamespaceAliasDefinition, S);
1550e5dd7070Spatrick     return true;
1551e5dd7070Spatrick   }
1552e5dd7070Spatrick 
WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl * S)1553e5dd7070Spatrick   bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1554ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1555ec727ea7Spatrick                      new (allocator()) syntax::UsingNamespaceDirective, S);
1556e5dd7070Spatrick     return true;
1557e5dd7070Spatrick   }
1558e5dd7070Spatrick 
WalkUpFromUsingDecl(UsingDecl * S)1559e5dd7070Spatrick   bool WalkUpFromUsingDecl(UsingDecl *S) {
1560ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1561ec727ea7Spatrick                      new (allocator()) syntax::UsingDeclaration, S);
1562e5dd7070Spatrick     return true;
1563e5dd7070Spatrick   }
1564e5dd7070Spatrick 
WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * S)1565e5dd7070Spatrick   bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1566ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1567ec727ea7Spatrick                      new (allocator()) syntax::UsingDeclaration, S);
1568e5dd7070Spatrick     return true;
1569e5dd7070Spatrick   }
1570e5dd7070Spatrick 
WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * S)1571e5dd7070Spatrick   bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1572ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1573ec727ea7Spatrick                      new (allocator()) syntax::UsingDeclaration, S);
1574e5dd7070Spatrick     return true;
1575e5dd7070Spatrick   }
1576e5dd7070Spatrick 
WalkUpFromTypeAliasDecl(TypeAliasDecl * S)1577e5dd7070Spatrick   bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1578ec727ea7Spatrick     Builder.foldNode(Builder.getDeclarationRange(S),
1579ec727ea7Spatrick                      new (allocator()) syntax::TypeAliasDeclaration, S);
1580e5dd7070Spatrick     return true;
1581e5dd7070Spatrick   }
1582e5dd7070Spatrick 
1583e5dd7070Spatrick private:
1584ec727ea7Spatrick   /// Folds SimpleDeclarator node (if present) and in case this is the last
1585ec727ea7Spatrick   /// declarator in the chain it also folds SimpleDeclaration node.
processDeclaratorAndDeclaration(T * D)1586ec727ea7Spatrick   template <class T> bool processDeclaratorAndDeclaration(T *D) {
1587a9ac8606Spatrick     auto Range = getDeclaratorRange(
1588a9ac8606Spatrick         Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
1589a9ac8606Spatrick         getQualifiedNameStart(D), getInitializerRange(D));
1590ec727ea7Spatrick 
1591ec727ea7Spatrick     // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1592ec727ea7Spatrick     // declaration, but no declarator).
1593a9ac8606Spatrick     if (!Range.getBegin().isValid()) {
1594a9ac8606Spatrick       Builder.markChild(new (allocator()) syntax::DeclaratorList,
1595a9ac8606Spatrick                         syntax::NodeRole::Declarators);
1596a9ac8606Spatrick       Builder.foldNode(Builder.getDeclarationRange(D),
1597a9ac8606Spatrick                        new (allocator()) syntax::SimpleDeclaration, D);
1598a9ac8606Spatrick       return true;
1599ec727ea7Spatrick     }
1600ec727ea7Spatrick 
1601a9ac8606Spatrick     auto *N = new (allocator()) syntax::SimpleDeclarator;
1602a9ac8606Spatrick     Builder.foldNode(Builder.getRange(Range), N, nullptr);
1603a9ac8606Spatrick     Builder.markChild(N, syntax::NodeRole::ListElement);
1604a9ac8606Spatrick 
1605a9ac8606Spatrick     if (!Builder.isResponsibleForCreatingDeclaration(D)) {
1606a9ac8606Spatrick       // If this is not the last declarator in the declaration we expect a
1607a9ac8606Spatrick       // delimiter after it.
1608a9ac8606Spatrick       const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
1609a9ac8606Spatrick       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1610a9ac8606Spatrick         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1611a9ac8606Spatrick     } else {
1612a9ac8606Spatrick       auto *DL = new (allocator()) syntax::DeclaratorList;
1613a9ac8606Spatrick       auto DeclarationRange = Builder.getDeclarationRange(D);
1614a9ac8606Spatrick       Builder.foldList(DeclarationRange, DL, nullptr);
1615a9ac8606Spatrick 
1616a9ac8606Spatrick       Builder.markChild(DL, syntax::NodeRole::Declarators);
1617a9ac8606Spatrick       Builder.foldNode(DeclarationRange,
1618ec727ea7Spatrick                        new (allocator()) syntax::SimpleDeclaration, D);
1619ec727ea7Spatrick     }
1620ec727ea7Spatrick     return true;
1621ec727ea7Spatrick   }
1622ec727ea7Spatrick 
1623ec727ea7Spatrick   /// Returns the range of the built node.
buildTrailingReturn(FunctionProtoTypeLoc L)1624a9ac8606Spatrick   syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
1625ec727ea7Spatrick     assert(L.getTypePtr()->hasTrailingReturn());
1626ec727ea7Spatrick 
1627ec727ea7Spatrick     auto ReturnedType = L.getReturnLoc();
1628ec727ea7Spatrick     // Build node for the declarator, if any.
1629a9ac8606Spatrick     auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
1630a9ac8606Spatrick                                              ReturnedType.getEndLoc());
1631ec727ea7Spatrick     syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
1632ec727ea7Spatrick     if (ReturnDeclaratorRange.isValid()) {
1633ec727ea7Spatrick       ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1634ec727ea7Spatrick       Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1635ec727ea7Spatrick                        ReturnDeclarator, nullptr);
1636ec727ea7Spatrick     }
1637ec727ea7Spatrick 
1638ec727ea7Spatrick     // Build node for trailing return type.
1639ec727ea7Spatrick     auto Return = Builder.getRange(ReturnedType.getSourceRange());
1640ec727ea7Spatrick     const auto *Arrow = Return.begin() - 1;
1641ec727ea7Spatrick     assert(Arrow->kind() == tok::arrow);
1642*12c85518Srobert     auto Tokens = llvm::ArrayRef(Arrow, Return.end());
1643ec727ea7Spatrick     Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1644ec727ea7Spatrick     if (ReturnDeclarator)
1645a9ac8606Spatrick       Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1646ec727ea7Spatrick     auto *R = new (allocator()) syntax::TrailingReturnType;
1647ec727ea7Spatrick     Builder.foldNode(Tokens, R, L);
1648ec727ea7Spatrick     return R;
1649ec727ea7Spatrick   }
1650ec727ea7Spatrick 
foldExplicitTemplateInstantiation(ArrayRef<syntax::Token> Range,const syntax::Token * ExternKW,const syntax::Token * TemplateKW,syntax::SimpleDeclaration * InnerDeclaration,Decl * From)1651ec727ea7Spatrick   void foldExplicitTemplateInstantiation(
1652ec727ea7Spatrick       ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
1653ec727ea7Spatrick       const syntax::Token *TemplateKW,
1654ec727ea7Spatrick       syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
1655ec727ea7Spatrick     assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
1656ec727ea7Spatrick     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1657ec727ea7Spatrick     Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
1658ec727ea7Spatrick     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1659a9ac8606Spatrick     Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1660ec727ea7Spatrick     Builder.foldNode(
1661ec727ea7Spatrick         Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
1662ec727ea7Spatrick   }
1663ec727ea7Spatrick 
foldTemplateDeclaration(ArrayRef<syntax::Token> Range,const syntax::Token * TemplateKW,ArrayRef<syntax::Token> TemplatedDeclaration,Decl * From)1664ec727ea7Spatrick   syntax::TemplateDeclaration *foldTemplateDeclaration(
1665ec727ea7Spatrick       ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1666ec727ea7Spatrick       ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
1667ec727ea7Spatrick     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1668ec727ea7Spatrick     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1669ec727ea7Spatrick 
1670ec727ea7Spatrick     auto *N = new (allocator()) syntax::TemplateDeclaration;
1671ec727ea7Spatrick     Builder.foldNode(Range, N, From);
1672a9ac8606Spatrick     Builder.markChild(N, syntax::NodeRole::Declaration);
1673ec727ea7Spatrick     return N;
1674ec727ea7Spatrick   }
1675ec727ea7Spatrick 
1676e5dd7070Spatrick   /// A small helper to save some typing.
allocator()1677e5dd7070Spatrick   llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
1678e5dd7070Spatrick 
1679e5dd7070Spatrick   syntax::TreeBuilder &Builder;
1680ec727ea7Spatrick   const ASTContext &Context;
1681e5dd7070Spatrick };
1682e5dd7070Spatrick } // namespace
1683e5dd7070Spatrick 
noticeDeclWithoutSemicolon(Decl * D)1684ec727ea7Spatrick void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1685e5dd7070Spatrick   DeclsWithoutSemicolons.insert(D);
1686e5dd7070Spatrick }
1687e5dd7070Spatrick 
markChildToken(SourceLocation Loc,NodeRole Role)1688e5dd7070Spatrick void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
1689e5dd7070Spatrick   if (Loc.isInvalid())
1690e5dd7070Spatrick     return;
1691e5dd7070Spatrick   Pending.assignRole(*findToken(Loc), Role);
1692e5dd7070Spatrick }
1693e5dd7070Spatrick 
markChildToken(const syntax::Token * T,NodeRole R)1694ec727ea7Spatrick void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
1695ec727ea7Spatrick   if (!T)
1696ec727ea7Spatrick     return;
1697ec727ea7Spatrick   Pending.assignRole(*T, R);
1698ec727ea7Spatrick }
1699ec727ea7Spatrick 
markChild(syntax::Node * N,NodeRole R)1700ec727ea7Spatrick void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1701ec727ea7Spatrick   assert(N);
1702ec727ea7Spatrick   setRole(N, R);
1703ec727ea7Spatrick }
1704ec727ea7Spatrick 
markChild(ASTPtr N,NodeRole R)1705ec727ea7Spatrick void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1706ec727ea7Spatrick   auto *SN = Mapping.find(N);
1707ec727ea7Spatrick   assert(SN != nullptr);
1708ec727ea7Spatrick   setRole(SN, R);
1709ec727ea7Spatrick }
markChild(NestedNameSpecifierLoc NNSLoc,NodeRole R)1710a9ac8606Spatrick void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1711a9ac8606Spatrick   auto *SN = Mapping.find(NNSLoc);
1712a9ac8606Spatrick   assert(SN != nullptr);
1713a9ac8606Spatrick   setRole(SN, R);
1714a9ac8606Spatrick }
1715ec727ea7Spatrick 
markStmtChild(Stmt * Child,NodeRole Role)1716e5dd7070Spatrick void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
1717e5dd7070Spatrick   if (!Child)
1718e5dd7070Spatrick     return;
1719e5dd7070Spatrick 
1720ec727ea7Spatrick   syntax::Tree *ChildNode;
1721ec727ea7Spatrick   if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
1722e5dd7070Spatrick     // This is an expression in a statement position, consume the trailing
1723e5dd7070Spatrick     // semicolon and form an 'ExpressionStatement' node.
1724a9ac8606Spatrick     markExprChild(ChildExpr, NodeRole::Expression);
1725ec727ea7Spatrick     ChildNode = new (allocator()) syntax::ExpressionStatement;
1726ec727ea7Spatrick     // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1727*12c85518Srobert     Pending.foldChildren(TBTM.tokenBuffer(), getStmtRange(Child), ChildNode);
1728ec727ea7Spatrick   } else {
1729ec727ea7Spatrick     ChildNode = Mapping.find(Child);
1730e5dd7070Spatrick   }
1731ec727ea7Spatrick   assert(ChildNode != nullptr);
1732ec727ea7Spatrick   setRole(ChildNode, Role);
1733e5dd7070Spatrick }
1734e5dd7070Spatrick 
markExprChild(Expr * Child,NodeRole Role)1735e5dd7070Spatrick void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1736e5dd7070Spatrick   if (!Child)
1737e5dd7070Spatrick     return;
1738a9ac8606Spatrick   Child = IgnoreImplicit(Child);
1739e5dd7070Spatrick 
1740ec727ea7Spatrick   syntax::Tree *ChildNode = Mapping.find(Child);
1741ec727ea7Spatrick   assert(ChildNode != nullptr);
1742ec727ea7Spatrick   setRole(ChildNode, Role);
1743e5dd7070Spatrick }
1744e5dd7070Spatrick 
findToken(SourceLocation L) const1745e5dd7070Spatrick const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
1746ec727ea7Spatrick   if (L.isInvalid())
1747ec727ea7Spatrick     return nullptr;
1748a9ac8606Spatrick   auto It = LocationToToken.find(L);
1749e5dd7070Spatrick   assert(It != LocationToToken.end());
1750e5dd7070Spatrick   return It->second;
1751e5dd7070Spatrick }
1752e5dd7070Spatrick 
buildSyntaxTree(Arena & A,TokenBufferTokenManager & TBTM,ASTContext & Context)1753a9ac8606Spatrick syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A,
1754*12c85518Srobert                                                  TokenBufferTokenManager& TBTM,
1755a9ac8606Spatrick                                                  ASTContext &Context) {
1756*12c85518Srobert   TreeBuilder Builder(A, TBTM);
1757a9ac8606Spatrick   BuildTreeVisitor(Context, Builder).TraverseAST(Context);
1758e5dd7070Spatrick   return std::move(Builder).finalize();
1759e5dd7070Spatrick }
1760