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