xref: /llvm-project/clang/lib/Tooling/Syntax/BuildTree.cpp (revision 5011d43108d1de30a056d66e73fa19062e0e84b7)
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 = std::find_if(Args.begin(), Args.end(), [](auto It) {
159     return isa<CXXDefaultArgExpr>(It);
160   });
161   return llvm::make_range(Args.begin(), FirstDefaultArg);
162 }
163 
164 static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
165   switch (E.getOperator()) {
166   // Comparison
167   case OO_EqualEqual:
168   case OO_ExclaimEqual:
169   case OO_Greater:
170   case OO_GreaterEqual:
171   case OO_Less:
172   case OO_LessEqual:
173   case OO_Spaceship:
174   // Assignment
175   case OO_Equal:
176   case OO_SlashEqual:
177   case OO_PercentEqual:
178   case OO_CaretEqual:
179   case OO_PipeEqual:
180   case OO_LessLessEqual:
181   case OO_GreaterGreaterEqual:
182   case OO_PlusEqual:
183   case OO_MinusEqual:
184   case OO_StarEqual:
185   case OO_AmpEqual:
186   // Binary computation
187   case OO_Slash:
188   case OO_Percent:
189   case OO_Caret:
190   case OO_Pipe:
191   case OO_LessLess:
192   case OO_GreaterGreater:
193   case OO_AmpAmp:
194   case OO_PipePipe:
195   case OO_ArrowStar:
196   case OO_Comma:
197     return syntax::NodeKind::BinaryOperatorExpression;
198   case OO_Tilde:
199   case OO_Exclaim:
200     return syntax::NodeKind::PrefixUnaryOperatorExpression;
201   // Prefix/Postfix increment/decrement
202   case OO_PlusPlus:
203   case OO_MinusMinus:
204     switch (E.getNumArgs()) {
205     case 1:
206       return syntax::NodeKind::PrefixUnaryOperatorExpression;
207     case 2:
208       return syntax::NodeKind::PostfixUnaryOperatorExpression;
209     default:
210       llvm_unreachable("Invalid number of arguments for operator");
211     }
212   // Operators that can be unary or binary
213   case OO_Plus:
214   case OO_Minus:
215   case OO_Star:
216   case OO_Amp:
217     switch (E.getNumArgs()) {
218     case 1:
219       return syntax::NodeKind::PrefixUnaryOperatorExpression;
220     case 2:
221       return syntax::NodeKind::BinaryOperatorExpression;
222     default:
223       llvm_unreachable("Invalid number of arguments for operator");
224     }
225     return syntax::NodeKind::BinaryOperatorExpression;
226   // Not yet supported by SyntaxTree
227   case OO_New:
228   case OO_Delete:
229   case OO_Array_New:
230   case OO_Array_Delete:
231   case OO_Coawait:
232   case OO_Subscript:
233   case OO_Arrow:
234     return syntax::NodeKind::UnknownExpression;
235   case OO_Call:
236     return syntax::NodeKind::CallExpression;
237   case OO_Conditional: // not overloadable
238   case NUM_OVERLOADED_OPERATORS:
239   case OO_None:
240     llvm_unreachable("Not an overloadable operator");
241   }
242   llvm_unreachable("Unknown OverloadedOperatorKind enum");
243 }
244 
245 /// Get the start of the qualified name. In the examples below it gives the
246 /// location of the `^`:
247 ///     `int ^a;`
248 ///     `int *^a;`
249 ///     `int ^a::S::f(){}`
250 static SourceLocation getQualifiedNameStart(NamedDecl *D) {
251   assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
252          "only DeclaratorDecl and TypedefNameDecl are supported.");
253 
254   auto DN = D->getDeclName();
255   bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
256   if (IsAnonymous)
257     return SourceLocation();
258 
259   if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
260     if (DD->getQualifierLoc()) {
261       return DD->getQualifierLoc().getBeginLoc();
262     }
263   }
264 
265   return D->getLocation();
266 }
267 
268 /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl].
269 ///     `int a;` -> range of ``,
270 ///     `int *a = nullptr` -> range of `= nullptr`.
271 ///     `int a{}` -> range of `{}`.
272 ///     `int a()` -> range of `()`.
273 static SourceRange getInitializerRange(Decl *D) {
274   if (auto *V = dyn_cast<VarDecl>(D)) {
275     auto *I = V->getInit();
276     // Initializers in range-based-for are not part of the declarator
277     if (I && !V->isCXXForRangeDecl())
278       return I->getSourceRange();
279   }
280 
281   return SourceRange();
282 }
283 
284 /// Gets the range of declarator as defined by the C++ grammar. E.g.
285 ///     `int a;` -> range of `a`,
286 ///     `int *a;` -> range of `*a`,
287 ///     `int a[10];` -> range of `a[10]`,
288 ///     `int a[1][2][3];` -> range of `a[1][2][3]`,
289 ///     `int *a = nullptr` -> range of `*a = nullptr`.
290 ///     `int S::f(){}` -> range of `S::f()`.
291 /// FIXME: \p Name must be a source range.
292 static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
293                                       SourceLocation Name,
294                                       SourceRange Initializer) {
295   SourceLocation Start = GetStartLoc().Visit(T);
296   SourceLocation End = T.getEndLoc();
297   assert(End.isValid());
298   if (Name.isValid()) {
299     if (Start.isInvalid())
300       Start = Name;
301     if (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().getRawEncoding(), &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       // We need to go in reverse order, because we can only prepend.
640       for (auto It = EndChildren; It != BeginChildren; --It) {
641         auto *C = std::prev(It)->second;
642         if (C->getRole() == NodeRole::Detached)
643           C->setRole(NodeRole::Unknown);
644         Node->prependChildLowLevel(C);
645       }
646 
647       // Mark that this node came from the AST and is backed by the source code.
648       Node->Original = true;
649       Node->CanModify =
650           A.getTokenBuffer().spelledForExpanded(Tokens).hasValue();
651 
652       Trees.erase(BeginChildren, EndChildren);
653       Trees.insert({FirstToken, Node});
654     }
655 
656     // EXPECTS: all tokens were consumed and are owned by a single root node.
657     syntax::Node *finalize() && {
658       assert(Trees.size() == 1);
659       auto *Root = Trees.begin()->second;
660       Trees = {};
661       return Root;
662     }
663 
664     std::string str(const syntax::Arena &A) const {
665       std::string R;
666       for (auto It = Trees.begin(); It != Trees.end(); ++It) {
667         unsigned CoveredTokens =
668             It != Trees.end()
669                 ? (std::next(It)->first - It->first)
670                 : A.getTokenBuffer().expandedTokens().end() - It->first;
671 
672         R += std::string(
673             formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(),
674                     It->first->text(A.getSourceManager()), CoveredTokens));
675         R += It->second->dump(A.getSourceManager());
676       }
677       return R;
678     }
679 
680   private:
681     /// Maps from the start token to a subtree starting at that token.
682     /// Keys in the map are pointers into the array of expanded tokens, so
683     /// pointer order corresponds to the order of preprocessor tokens.
684     std::map<const syntax::Token *, syntax::Node *> Trees;
685   };
686 
687   /// For debugging purposes.
688   std::string str() { return Pending.str(Arena); }
689 
690   syntax::Arena &Arena;
691   /// To quickly find tokens by their start location.
692   llvm::DenseMap</*SourceLocation*/ unsigned, const syntax::Token *>
693       LocationToToken;
694   Forest Pending;
695   llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
696   ASTToSyntaxMapping Mapping;
697 };
698 
699 namespace {
700 class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
701 public:
702   explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
703       : Builder(Builder), Context(Context) {}
704 
705   bool shouldTraversePostOrder() const { return true; }
706 
707   bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
708     return processDeclaratorAndDeclaration(DD);
709   }
710 
711   bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
712     return processDeclaratorAndDeclaration(TD);
713   }
714 
715   bool VisitDecl(Decl *D) {
716     assert(!D->isImplicit());
717     Builder.foldNode(Builder.getDeclarationRange(D),
718                      new (allocator()) syntax::UnknownDeclaration(), D);
719     return true;
720   }
721 
722   // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
723   // override Traverse.
724   // FIXME: make RAV call WalkUpFrom* instead.
725   bool
726   TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
727     if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
728       return false;
729     if (C->isExplicitSpecialization())
730       return true; // we are only interested in explicit instantiations.
731     auto *Declaration =
732         cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
733     foldExplicitTemplateInstantiation(
734         Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()),
735         Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
736     return true;
737   }
738 
739   bool WalkUpFromTemplateDecl(TemplateDecl *S) {
740     foldTemplateDeclaration(
741         Builder.getDeclarationRange(S),
742         Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
743         Builder.getDeclarationRange(S->getTemplatedDecl()), S);
744     return true;
745   }
746 
747   bool WalkUpFromTagDecl(TagDecl *C) {
748     // FIXME: build the ClassSpecifier node.
749     if (!C->isFreeStanding()) {
750       assert(C->getNumTemplateParameterLists() == 0);
751       return true;
752     }
753     handleFreeStandingTagDecl(C);
754     return true;
755   }
756 
757   syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
758     assert(C->isFreeStanding());
759     // Class is a declaration specifier and needs a spanning declaration node.
760     auto DeclarationRange = Builder.getDeclarationRange(C);
761     syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
762     Builder.foldNode(DeclarationRange, Result, nullptr);
763 
764     // Build TemplateDeclaration nodes if we had template parameters.
765     auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
766       const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
767       auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end());
768       Result =
769           foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
770       DeclarationRange = R;
771     };
772     if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
773       ConsumeTemplateParameters(*S->getTemplateParameters());
774     for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
775       ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
776     return Result;
777   }
778 
779   bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
780     // We do not want to call VisitDecl(), the declaration for translation
781     // unit is built by finalize().
782     return true;
783   }
784 
785   bool WalkUpFromCompoundStmt(CompoundStmt *S) {
786     using NodeRole = syntax::NodeRole;
787 
788     Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
789     for (auto *Child : S->body())
790       Builder.markStmtChild(Child, NodeRole::Statement);
791     Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
792 
793     Builder.foldNode(Builder.getStmtRange(S),
794                      new (allocator()) syntax::CompoundStatement, S);
795     return true;
796   }
797 
798   // Some statements are not yet handled by syntax trees.
799   bool WalkUpFromStmt(Stmt *S) {
800     Builder.foldNode(Builder.getStmtRange(S),
801                      new (allocator()) syntax::UnknownStatement, S);
802     return true;
803   }
804 
805   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
806     // We override to traverse range initializer as VarDecl.
807     // RAV traverses it as a statement, we produce invalid node kinds in that
808     // case.
809     // FIXME: should do this in RAV instead?
810     bool Result = [&, this]() {
811       if (S->getInit() && !TraverseStmt(S->getInit()))
812         return false;
813       if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
814         return false;
815       if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
816         return false;
817       if (S->getBody() && !TraverseStmt(S->getBody()))
818         return false;
819       return true;
820     }();
821     WalkUpFromCXXForRangeStmt(S);
822     return Result;
823   }
824 
825   bool TraverseStmt(Stmt *S) {
826     if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) {
827       // We want to consume the semicolon, make sure SimpleDeclaration does not.
828       for (auto *D : DS->decls())
829         Builder.noticeDeclWithoutSemicolon(D);
830     } else if (auto *E = dyn_cast_or_null<Expr>(S)) {
831       return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E));
832     }
833     return RecursiveASTVisitor::TraverseStmt(S);
834   }
835 
836   // Some expressions are not yet handled by syntax trees.
837   bool WalkUpFromExpr(Expr *E) {
838     assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
839     Builder.foldNode(Builder.getExprRange(E),
840                      new (allocator()) syntax::UnknownExpression, E);
841     return true;
842   }
843 
844   bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
845     // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
846     // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
847     // UDL suffix location does not point to the beginning of a token, so we
848     // can't represent the UDL suffix as a separate syntax tree node.
849 
850     return WalkUpFromUserDefinedLiteral(S);
851   }
852 
853   syntax::UserDefinedLiteralExpression *
854   buildUserDefinedLiteral(UserDefinedLiteral *S) {
855     switch (S->getLiteralOperatorKind()) {
856     case UserDefinedLiteral::LOK_Integer:
857       return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
858     case UserDefinedLiteral::LOK_Floating:
859       return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
860     case UserDefinedLiteral::LOK_Character:
861       return new (allocator()) syntax::CharUserDefinedLiteralExpression;
862     case UserDefinedLiteral::LOK_String:
863       return new (allocator()) syntax::StringUserDefinedLiteralExpression;
864     case UserDefinedLiteral::LOK_Raw:
865     case UserDefinedLiteral::LOK_Template:
866       // For raw literal operator and numeric literal operator template we
867       // cannot get the type of the operand in the semantic AST. We get this
868       // information from the token. As integer and floating point have the same
869       // token kind, we run `NumericLiteralParser` again to distinguish them.
870       auto TokLoc = S->getBeginLoc();
871       auto TokSpelling =
872           Builder.findToken(TokLoc)->text(Context.getSourceManager());
873       auto Literal =
874           NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
875                                Context.getLangOpts(), Context.getTargetInfo(),
876                                Context.getDiagnostics());
877       if (Literal.isIntegerLiteral())
878         return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
879       else {
880         assert(Literal.isFloatingLiteral());
881         return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
882       }
883     }
884     llvm_unreachable("Unknown literal operator kind.");
885   }
886 
887   bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
888     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
889     Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
890     return true;
891   }
892 
893   // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the
894   // `DependentTemplateSpecializationType` case.
895   /// Given a nested-name-specifier return the range for the last name
896   /// specifier.
897   ///
898   /// e.g. `std::T::template X<U>::` => `template X<U>::`
899   SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) {
900     auto SR = NNSLoc.getLocalSourceRange();
901 
902     // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should*
903     // return the desired `SourceRange`, but there is a corner case. For a
904     // `DependentTemplateSpecializationType` this method returns its
905     // qualifiers as well, in other words in the example above this method
906     // returns `T::template X<U>::` instead of only `template X<U>::`
907     if (auto TL = NNSLoc.getTypeLoc()) {
908       if (auto DependentTL =
909               TL.getAs<DependentTemplateSpecializationTypeLoc>()) {
910         // The 'template' keyword is always present in dependent template
911         // specializations. Except in the case of incorrect code
912         // TODO: Treat the case of incorrect code.
913         SR.setBegin(DependentTL.getTemplateKeywordLoc());
914       }
915     }
916 
917     return SR;
918   }
919 
920   syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) {
921     switch (NNS.getKind()) {
922     case NestedNameSpecifier::Global:
923       return syntax::NodeKind::GlobalNameSpecifier;
924     case NestedNameSpecifier::Namespace:
925     case NestedNameSpecifier::NamespaceAlias:
926     case NestedNameSpecifier::Identifier:
927       return syntax::NodeKind::IdentifierNameSpecifier;
928     case NestedNameSpecifier::TypeSpecWithTemplate:
929       return syntax::NodeKind::SimpleTemplateNameSpecifier;
930     case NestedNameSpecifier::TypeSpec: {
931       const auto *NNSType = NNS.getAsType();
932       assert(NNSType);
933       if (isa<DecltypeType>(NNSType))
934         return syntax::NodeKind::DecltypeNameSpecifier;
935       if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>(
936               NNSType))
937         return syntax::NodeKind::SimpleTemplateNameSpecifier;
938       return syntax::NodeKind::IdentifierNameSpecifier;
939     }
940     default:
941       // FIXME: Support Microsoft's __super
942       llvm::report_fatal_error("We don't yet support the __super specifier",
943                                true);
944     }
945   }
946 
947   syntax::NameSpecifier *
948   buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) {
949     assert(NNSLoc.hasQualifier());
950     auto NameSpecifierTokens =
951         Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back();
952     switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) {
953     case syntax::NodeKind::GlobalNameSpecifier:
954       return new (allocator()) syntax::GlobalNameSpecifier;
955     case syntax::NodeKind::IdentifierNameSpecifier: {
956       assert(NameSpecifierTokens.size() == 1);
957       Builder.markChildToken(NameSpecifierTokens.begin(),
958                              syntax::NodeRole::Unknown);
959       auto *NS = new (allocator()) syntax::IdentifierNameSpecifier;
960       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
961       return NS;
962     }
963     case syntax::NodeKind::SimpleTemplateNameSpecifier: {
964       // TODO: Build `SimpleTemplateNameSpecifier` children and implement
965       // accessors to them.
966       // Be aware, we cannot do that simply by calling `TraverseTypeLoc`,
967       // some `TypeLoc`s have inside them the previous name specifier and
968       // we want to treat them independently.
969       auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier;
970       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
971       return NS;
972     }
973     case syntax::NodeKind::DecltypeNameSpecifier: {
974       const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>();
975       if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL))
976         return nullptr;
977       auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
978       // TODO: Implement accessor to `DecltypeNameSpecifier` inner
979       // `DecltypeTypeLoc`.
980       // For that add mapping from `TypeLoc` to `syntax::Node*` then:
981       // Builder.markChild(TypeLoc, syntax::NodeRole);
982       Builder.foldNode(NameSpecifierTokens, NS, nullptr);
983       return NS;
984     }
985     default:
986       llvm_unreachable("getChildKind() does not return this value");
987     }
988   }
989 
990   // To build syntax tree nodes for NestedNameSpecifierLoc we override
991   // Traverse instead of WalkUpFrom because we want to traverse the children
992   // ourselves and build a list instead of a nested tree of name specifier
993   // prefixes.
994   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) {
995     if (!QualifierLoc)
996       return true;
997     for (auto It = QualifierLoc; It; It = It.getPrefix()) {
998       auto *NS = buildNameSpecifier(It);
999       if (!NS)
1000         return false;
1001       Builder.markChild(NS, syntax::NodeRole::ListElement);
1002       Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
1003     }
1004     Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1005                      new (allocator()) syntax::NestedNameSpecifier,
1006                      QualifierLoc);
1007     return true;
1008   }
1009 
1010   syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1011                                           SourceLocation TemplateKeywordLoc,
1012                                           SourceRange UnqualifiedIdLoc,
1013                                           ASTPtr From) {
1014     if (QualifierLoc) {
1015       Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1016       if (TemplateKeywordLoc.isValid())
1017         Builder.markChildToken(TemplateKeywordLoc,
1018                                syntax::NodeRole::TemplateKeyword);
1019     }
1020 
1021     auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1022     Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1023                      nullptr);
1024     Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1025 
1026     auto IdExpressionBeginLoc =
1027         QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1028 
1029     auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1030     Builder.foldNode(
1031         Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1032         TheIdExpression, From);
1033 
1034     return TheIdExpression;
1035   }
1036 
1037   bool WalkUpFromMemberExpr(MemberExpr *S) {
1038     // For `MemberExpr` with implicit `this->` we generate a simple
1039     // `id-expression` syntax node, beacuse an implicit `member-expression` is
1040     // syntactically undistinguishable from an `id-expression`
1041     if (S->isImplicitAccess()) {
1042       buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1043                         SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1044       return true;
1045     }
1046 
1047     auto *TheIdExpression = buildIdExpression(
1048         S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1049         SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1050 
1051     Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1052 
1053     Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1054     Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1055 
1056     Builder.foldNode(Builder.getExprRange(S),
1057                      new (allocator()) syntax::MemberExpression, S);
1058     return true;
1059   }
1060 
1061   bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
1062     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1063                       SourceRange(S->getLocation(), S->getEndLoc()), S);
1064 
1065     return true;
1066   }
1067 
1068   // Same logic as DeclRefExpr.
1069   bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) {
1070     buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1071                       SourceRange(S->getLocation(), S->getEndLoc()), S);
1072 
1073     return true;
1074   }
1075 
1076   bool WalkUpFromCXXThisExpr(CXXThisExpr *S) {
1077     if (!S->isImplicit()) {
1078       Builder.markChildToken(S->getLocation(),
1079                              syntax::NodeRole::IntroducerKeyword);
1080       Builder.foldNode(Builder.getExprRange(S),
1081                        new (allocator()) syntax::ThisExpression, S);
1082     }
1083     return true;
1084   }
1085 
1086   bool WalkUpFromParenExpr(ParenExpr *S) {
1087     Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1088     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1089     Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1090     Builder.foldNode(Builder.getExprRange(S),
1091                      new (allocator()) syntax::ParenExpression, S);
1092     return true;
1093   }
1094 
1095   bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
1096     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1097     Builder.foldNode(Builder.getExprRange(S),
1098                      new (allocator()) syntax::IntegerLiteralExpression, S);
1099     return true;
1100   }
1101 
1102   bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
1103     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1104     Builder.foldNode(Builder.getExprRange(S),
1105                      new (allocator()) syntax::CharacterLiteralExpression, S);
1106     return true;
1107   }
1108 
1109   bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
1110     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1111     Builder.foldNode(Builder.getExprRange(S),
1112                      new (allocator()) syntax::FloatingLiteralExpression, S);
1113     return true;
1114   }
1115 
1116   bool WalkUpFromStringLiteral(StringLiteral *S) {
1117     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1118     Builder.foldNode(Builder.getExprRange(S),
1119                      new (allocator()) syntax::StringLiteralExpression, S);
1120     return true;
1121   }
1122 
1123   bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
1124     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1125     Builder.foldNode(Builder.getExprRange(S),
1126                      new (allocator()) syntax::BoolLiteralExpression, S);
1127     return true;
1128   }
1129 
1130   bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
1131     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1132     Builder.foldNode(Builder.getExprRange(S),
1133                      new (allocator()) syntax::CxxNullPtrExpression, S);
1134     return true;
1135   }
1136 
1137   bool WalkUpFromUnaryOperator(UnaryOperator *S) {
1138     Builder.markChildToken(S->getOperatorLoc(),
1139                            syntax::NodeRole::OperatorToken);
1140     Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1141 
1142     if (S->isPostfix())
1143       Builder.foldNode(Builder.getExprRange(S),
1144                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1145                        S);
1146     else
1147       Builder.foldNode(Builder.getExprRange(S),
1148                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1149                        S);
1150 
1151     return true;
1152   }
1153 
1154   bool WalkUpFromBinaryOperator(BinaryOperator *S) {
1155     Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
1156     Builder.markChildToken(S->getOperatorLoc(),
1157                            syntax::NodeRole::OperatorToken);
1158     Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
1159     Builder.foldNode(Builder.getExprRange(S),
1160                      new (allocator()) syntax::BinaryOperatorExpression, S);
1161     return true;
1162   }
1163 
1164   /// Builds `CallArguments` syntax node from arguments that appear in source
1165   /// code, i.e. not default arguments.
1166   syntax::CallArguments *
1167   buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) {
1168     auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1169     for (auto *Arg : Args) {
1170       Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
1171       const auto *DelimiterToken =
1172           std::next(Builder.findToken(Arg->getEndLoc()));
1173       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1174         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1175     }
1176 
1177     auto *Arguments = new (allocator()) syntax::CallArguments;
1178     if (!Args.empty())
1179       Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
1180                                         (*(Args.end() - 1))->getEndLoc()),
1181                        Arguments, nullptr);
1182 
1183     return Arguments;
1184   }
1185 
1186   bool WalkUpFromCallExpr(CallExpr *S) {
1187     Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
1188 
1189     const auto *LParenToken =
1190         std::next(Builder.findToken(S->getCallee()->getEndLoc()));
1191     // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
1192     // the test on decltype desctructors.
1193     if (LParenToken->kind() == clang::tok::l_paren)
1194       Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1195 
1196     Builder.markChild(buildCallArguments(S->arguments()),
1197                       syntax::NodeRole::Arguments);
1198 
1199     Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1200 
1201     Builder.foldNode(Builder.getRange(S->getSourceRange()),
1202                      new (allocator()) syntax::CallExpression, S);
1203     return true;
1204   }
1205 
1206   bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
1207     // Ignore the implicit calls to default constructors.
1208     if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
1209         S->getParenOrBraceRange().isInvalid())
1210       return true;
1211     return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
1212   }
1213 
1214   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1215     // To construct a syntax tree of the same shape for calls to built-in and
1216     // user-defined operators, ignore the `DeclRefExpr` that refers to the
1217     // operator and treat it as a simple token. Do that by traversing
1218     // arguments instead of children.
1219     for (auto *child : S->arguments()) {
1220       // A postfix unary operator is declared as taking two operands. The
1221       // second operand is used to distinguish from its prefix counterpart. In
1222       // the semantic AST this "phantom" operand is represented as a
1223       // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1224       // operand because it does not correspond to anything written in source
1225       // code.
1226       if (child->getSourceRange().isInvalid()) {
1227         assert(getOperatorNodeKind(*S) ==
1228                syntax::NodeKind::PostfixUnaryOperatorExpression);
1229         continue;
1230       }
1231       if (!TraverseStmt(child))
1232         return false;
1233     }
1234     return WalkUpFromCXXOperatorCallExpr(S);
1235   }
1236 
1237   bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1238     switch (getOperatorNodeKind(*S)) {
1239     case syntax::NodeKind::BinaryOperatorExpression:
1240       Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1241       Builder.markChildToken(S->getOperatorLoc(),
1242                              syntax::NodeRole::OperatorToken);
1243       Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
1244       Builder.foldNode(Builder.getExprRange(S),
1245                        new (allocator()) syntax::BinaryOperatorExpression, S);
1246       return true;
1247     case syntax::NodeKind::PrefixUnaryOperatorExpression:
1248       Builder.markChildToken(S->getOperatorLoc(),
1249                              syntax::NodeRole::OperatorToken);
1250       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1251       Builder.foldNode(Builder.getExprRange(S),
1252                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
1253                        S);
1254       return true;
1255     case syntax::NodeKind::PostfixUnaryOperatorExpression:
1256       Builder.markChildToken(S->getOperatorLoc(),
1257                              syntax::NodeRole::OperatorToken);
1258       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1259       Builder.foldNode(Builder.getExprRange(S),
1260                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
1261                        S);
1262       return true;
1263     case syntax::NodeKind::CallExpression: {
1264       Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
1265 
1266       const auto *LParenToken =
1267           std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
1268       // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
1269       // fixed the test on decltype desctructors.
1270       if (LParenToken->kind() == clang::tok::l_paren)
1271         Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1272 
1273       Builder.markChild(buildCallArguments(CallExpr::arg_range(
1274                             S->arg_begin() + 1, S->arg_end())),
1275                         syntax::NodeRole::Arguments);
1276 
1277       Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1278 
1279       Builder.foldNode(Builder.getRange(S->getSourceRange()),
1280                        new (allocator()) syntax::CallExpression, S);
1281       return true;
1282     }
1283     case syntax::NodeKind::UnknownExpression:
1284       return WalkUpFromExpr(S);
1285     default:
1286       llvm_unreachable("getOperatorNodeKind() does not return this value");
1287     }
1288   }
1289 
1290   bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; }
1291 
1292   bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
1293     auto Tokens = Builder.getDeclarationRange(S);
1294     if (Tokens.front().kind() == tok::coloncolon) {
1295       // Handle nested namespace definitions. Those start at '::' token, e.g.
1296       // namespace a^::b {}
1297       // FIXME: build corresponding nodes for the name of this namespace.
1298       return true;
1299     }
1300     Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1301     return true;
1302   }
1303 
1304   // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
1305   // results. Find test coverage or remove it.
1306   bool TraverseParenTypeLoc(ParenTypeLoc L) {
1307     // We reverse order of traversal to get the proper syntax structure.
1308     if (!WalkUpFromParenTypeLoc(L))
1309       return false;
1310     return TraverseTypeLoc(L.getInnerLoc());
1311   }
1312 
1313   bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
1314     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1315     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1316     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1317                      new (allocator()) syntax::ParenDeclarator, L);
1318     return true;
1319   }
1320 
1321   // Declarator chunks, they are produced by type locs and some clang::Decls.
1322   bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
1323     Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1324     Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
1325     Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
1326     Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1327                      new (allocator()) syntax::ArraySubscript, L);
1328     return true;
1329   }
1330 
1331   syntax::ParameterDeclarationList *
1332   buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) {
1333     for (auto *P : Params) {
1334       Builder.markChild(P, syntax::NodeRole::ListElement);
1335       const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1336       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1337         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1338     }
1339     auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1340     if (!Params.empty())
1341       Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1342                                         Params.back()->getEndLoc()),
1343                        Parameters, nullptr);
1344     return Parameters;
1345   }
1346 
1347   bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
1348     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1349 
1350     Builder.markChild(buildParameterDeclarationList(L.getParams()),
1351                       syntax::NodeRole::Parameters);
1352 
1353     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1354     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1355                      new (allocator()) syntax::ParametersAndQualifiers, L);
1356     return true;
1357   }
1358 
1359   bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
1360     if (!L.getTypePtr()->hasTrailingReturn())
1361       return WalkUpFromFunctionTypeLoc(L);
1362 
1363     auto *TrailingReturnTokens = buildTrailingReturn(L);
1364     // Finish building the node for parameters.
1365     Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
1366     return WalkUpFromFunctionTypeLoc(L);
1367   }
1368 
1369   bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) {
1370     // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
1371     // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
1372     // "(Y::*mp)" We thus reverse the order of traversal to get the proper
1373     // syntax structure.
1374     if (!WalkUpFromMemberPointerTypeLoc(L))
1375       return false;
1376     return TraverseTypeLoc(L.getPointeeLoc());
1377   }
1378 
1379   bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
1380     auto SR = L.getLocalSourceRange();
1381     Builder.foldNode(Builder.getRange(SR),
1382                      new (allocator()) syntax::MemberPointer, L);
1383     return true;
1384   }
1385 
1386   // The code below is very regular, it could even be generated with some
1387   // preprocessor magic. We merely assign roles to the corresponding children
1388   // and fold resulting nodes.
1389   bool WalkUpFromDeclStmt(DeclStmt *S) {
1390     Builder.foldNode(Builder.getStmtRange(S),
1391                      new (allocator()) syntax::DeclarationStatement, S);
1392     return true;
1393   }
1394 
1395   bool WalkUpFromNullStmt(NullStmt *S) {
1396     Builder.foldNode(Builder.getStmtRange(S),
1397                      new (allocator()) syntax::EmptyStatement, S);
1398     return true;
1399   }
1400 
1401   bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1402     Builder.markChildToken(S->getSwitchLoc(),
1403                            syntax::NodeRole::IntroducerKeyword);
1404     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1405     Builder.foldNode(Builder.getStmtRange(S),
1406                      new (allocator()) syntax::SwitchStatement, S);
1407     return true;
1408   }
1409 
1410   bool WalkUpFromCaseStmt(CaseStmt *S) {
1411     Builder.markChildToken(S->getKeywordLoc(),
1412                            syntax::NodeRole::IntroducerKeyword);
1413     Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
1414     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1415     Builder.foldNode(Builder.getStmtRange(S),
1416                      new (allocator()) syntax::CaseStatement, S);
1417     return true;
1418   }
1419 
1420   bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1421     Builder.markChildToken(S->getKeywordLoc(),
1422                            syntax::NodeRole::IntroducerKeyword);
1423     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1424     Builder.foldNode(Builder.getStmtRange(S),
1425                      new (allocator()) syntax::DefaultStatement, S);
1426     return true;
1427   }
1428 
1429   bool WalkUpFromIfStmt(IfStmt *S) {
1430     Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
1431     Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1432     Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1433     Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
1434     Builder.foldNode(Builder.getStmtRange(S),
1435                      new (allocator()) syntax::IfStatement, S);
1436     return true;
1437   }
1438 
1439   bool WalkUpFromForStmt(ForStmt *S) {
1440     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1441     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1442     Builder.foldNode(Builder.getStmtRange(S),
1443                      new (allocator()) syntax::ForStatement, S);
1444     return true;
1445   }
1446 
1447   bool WalkUpFromWhileStmt(WhileStmt *S) {
1448     Builder.markChildToken(S->getWhileLoc(),
1449                            syntax::NodeRole::IntroducerKeyword);
1450     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1451     Builder.foldNode(Builder.getStmtRange(S),
1452                      new (allocator()) syntax::WhileStatement, S);
1453     return true;
1454   }
1455 
1456   bool WalkUpFromContinueStmt(ContinueStmt *S) {
1457     Builder.markChildToken(S->getContinueLoc(),
1458                            syntax::NodeRole::IntroducerKeyword);
1459     Builder.foldNode(Builder.getStmtRange(S),
1460                      new (allocator()) syntax::ContinueStatement, S);
1461     return true;
1462   }
1463 
1464   bool WalkUpFromBreakStmt(BreakStmt *S) {
1465     Builder.markChildToken(S->getBreakLoc(),
1466                            syntax::NodeRole::IntroducerKeyword);
1467     Builder.foldNode(Builder.getStmtRange(S),
1468                      new (allocator()) syntax::BreakStatement, S);
1469     return true;
1470   }
1471 
1472   bool WalkUpFromReturnStmt(ReturnStmt *S) {
1473     Builder.markChildToken(S->getReturnLoc(),
1474                            syntax::NodeRole::IntroducerKeyword);
1475     Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
1476     Builder.foldNode(Builder.getStmtRange(S),
1477                      new (allocator()) syntax::ReturnStatement, S);
1478     return true;
1479   }
1480 
1481   bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1482     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1483     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1484     Builder.foldNode(Builder.getStmtRange(S),
1485                      new (allocator()) syntax::RangeBasedForStatement, S);
1486     return true;
1487   }
1488 
1489   bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1490     Builder.foldNode(Builder.getDeclarationRange(S),
1491                      new (allocator()) syntax::EmptyDeclaration, S);
1492     return true;
1493   }
1494 
1495   bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1496     Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1497     Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1498     Builder.foldNode(Builder.getDeclarationRange(S),
1499                      new (allocator()) syntax::StaticAssertDeclaration, S);
1500     return true;
1501   }
1502 
1503   bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1504     Builder.foldNode(Builder.getDeclarationRange(S),
1505                      new (allocator()) syntax::LinkageSpecificationDeclaration,
1506                      S);
1507     return true;
1508   }
1509 
1510   bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1511     Builder.foldNode(Builder.getDeclarationRange(S),
1512                      new (allocator()) syntax::NamespaceAliasDefinition, S);
1513     return true;
1514   }
1515 
1516   bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1517     Builder.foldNode(Builder.getDeclarationRange(S),
1518                      new (allocator()) syntax::UsingNamespaceDirective, S);
1519     return true;
1520   }
1521 
1522   bool WalkUpFromUsingDecl(UsingDecl *S) {
1523     Builder.foldNode(Builder.getDeclarationRange(S),
1524                      new (allocator()) syntax::UsingDeclaration, S);
1525     return true;
1526   }
1527 
1528   bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1529     Builder.foldNode(Builder.getDeclarationRange(S),
1530                      new (allocator()) syntax::UsingDeclaration, S);
1531     return true;
1532   }
1533 
1534   bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1535     Builder.foldNode(Builder.getDeclarationRange(S),
1536                      new (allocator()) syntax::UsingDeclaration, S);
1537     return true;
1538   }
1539 
1540   bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1541     Builder.foldNode(Builder.getDeclarationRange(S),
1542                      new (allocator()) syntax::TypeAliasDeclaration, S);
1543     return true;
1544   }
1545 
1546 private:
1547   /// Folds SimpleDeclarator node (if present) and in case this is the last
1548   /// declarator in the chain it also folds SimpleDeclaration node.
1549   template <class T> bool processDeclaratorAndDeclaration(T *D) {
1550     auto Range = getDeclaratorRange(
1551         Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
1552         getQualifiedNameStart(D), getInitializerRange(D));
1553 
1554     // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1555     // declaration, but no declarator).
1556     if (!Range.getBegin().isValid()) {
1557       Builder.markChild(new (allocator()) syntax::DeclaratorList,
1558                         syntax::NodeRole::Declarators);
1559       Builder.foldNode(Builder.getDeclarationRange(D),
1560                        new (allocator()) syntax::SimpleDeclaration, D);
1561       return true;
1562     }
1563 
1564     auto *N = new (allocator()) syntax::SimpleDeclarator;
1565     Builder.foldNode(Builder.getRange(Range), N, nullptr);
1566     Builder.markChild(N, syntax::NodeRole::ListElement);
1567 
1568     if (!Builder.isResponsibleForCreatingDeclaration(D)) {
1569       // If this is not the last declarator in the declaration we expect a
1570       // delimiter after it.
1571       const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
1572       if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1573         Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1574     } else {
1575       auto *DL = new (allocator()) syntax::DeclaratorList;
1576       auto DeclarationRange = Builder.getDeclarationRange(D);
1577       Builder.foldList(DeclarationRange, DL, nullptr);
1578 
1579       Builder.markChild(DL, syntax::NodeRole::Declarators);
1580       Builder.foldNode(DeclarationRange,
1581                        new (allocator()) syntax::SimpleDeclaration, D);
1582     }
1583     return true;
1584   }
1585 
1586   /// Returns the range of the built node.
1587   syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
1588     assert(L.getTypePtr()->hasTrailingReturn());
1589 
1590     auto ReturnedType = L.getReturnLoc();
1591     // Build node for the declarator, if any.
1592     auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
1593                                              ReturnedType.getEndLoc());
1594     syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
1595     if (ReturnDeclaratorRange.isValid()) {
1596       ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1597       Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1598                        ReturnDeclarator, nullptr);
1599     }
1600 
1601     // Build node for trailing return type.
1602     auto Return = Builder.getRange(ReturnedType.getSourceRange());
1603     const auto *Arrow = Return.begin() - 1;
1604     assert(Arrow->kind() == tok::arrow);
1605     auto Tokens = llvm::makeArrayRef(Arrow, Return.end());
1606     Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1607     if (ReturnDeclarator)
1608       Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1609     auto *R = new (allocator()) syntax::TrailingReturnType;
1610     Builder.foldNode(Tokens, R, L);
1611     return R;
1612   }
1613 
1614   void foldExplicitTemplateInstantiation(
1615       ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
1616       const syntax::Token *TemplateKW,
1617       syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
1618     assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
1619     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1620     Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
1621     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1622     Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1623     Builder.foldNode(
1624         Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
1625   }
1626 
1627   syntax::TemplateDeclaration *foldTemplateDeclaration(
1628       ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1629       ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
1630     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1631     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1632 
1633     auto *N = new (allocator()) syntax::TemplateDeclaration;
1634     Builder.foldNode(Range, N, From);
1635     Builder.markChild(N, syntax::NodeRole::Declaration);
1636     return N;
1637   }
1638 
1639   /// A small helper to save some typing.
1640   llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
1641 
1642   syntax::TreeBuilder &Builder;
1643   const ASTContext &Context;
1644 };
1645 } // namespace
1646 
1647 void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1648   DeclsWithoutSemicolons.insert(D);
1649 }
1650 
1651 void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
1652   if (Loc.isInvalid())
1653     return;
1654   Pending.assignRole(*findToken(Loc), Role);
1655 }
1656 
1657 void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
1658   if (!T)
1659     return;
1660   Pending.assignRole(*T, R);
1661 }
1662 
1663 void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1664   assert(N);
1665   setRole(N, R);
1666 }
1667 
1668 void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1669   auto *SN = Mapping.find(N);
1670   assert(SN != nullptr);
1671   setRole(SN, R);
1672 }
1673 void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1674   auto *SN = Mapping.find(NNSLoc);
1675   assert(SN != nullptr);
1676   setRole(SN, R);
1677 }
1678 
1679 void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
1680   if (!Child)
1681     return;
1682 
1683   syntax::Tree *ChildNode;
1684   if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
1685     // This is an expression in a statement position, consume the trailing
1686     // semicolon and form an 'ExpressionStatement' node.
1687     markExprChild(ChildExpr, NodeRole::Expression);
1688     ChildNode = new (allocator()) syntax::ExpressionStatement;
1689     // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1690     Pending.foldChildren(Arena, getStmtRange(Child), ChildNode);
1691   } else {
1692     ChildNode = Mapping.find(Child);
1693   }
1694   assert(ChildNode != nullptr);
1695   setRole(ChildNode, Role);
1696 }
1697 
1698 void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1699   if (!Child)
1700     return;
1701   Child = IgnoreImplicit(Child);
1702 
1703   syntax::Tree *ChildNode = Mapping.find(Child);
1704   assert(ChildNode != nullptr);
1705   setRole(ChildNode, Role);
1706 }
1707 
1708 const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
1709   if (L.isInvalid())
1710     return nullptr;
1711   auto It = LocationToToken.find(L.getRawEncoding());
1712   assert(It != LocationToToken.end());
1713   return It->second;
1714 }
1715 
1716 syntax::TranslationUnit *
1717 syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) {
1718   TreeBuilder Builder(A);
1719   BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext());
1720   return std::move(Builder).finalize();
1721 }
1722