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/RecursiveASTVisitor.h"
17 #include "clang/AST/Stmt.h"
18 #include "clang/AST/TypeLoc.h"
19 #include "clang/AST/TypeLocVisitor.h"
20 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/Specifiers.h"
24 #include "clang/Basic/TokenKinds.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Lex/LiteralSupport.h"
27 #include "clang/Tooling/Syntax/Nodes.h"
28 #include "clang/Tooling/Syntax/Tokens.h"
29 #include "clang/Tooling/Syntax/Tree.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/PointerUnion.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/ScopeExit.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/Support/Allocator.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/FormatVariadic.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cstddef>
43 #include <map>
44 
45 using namespace clang;
46 
47 LLVM_ATTRIBUTE_UNUSED
48 static bool isImplicitExpr(clang::Expr *E) { return E->IgnoreImplicit() != E; }
49 
50 namespace {
51 /// Get start location of the Declarator from the TypeLoc.
52 /// E.g.:
53 ///   loc of `(` in `int (a)`
54 ///   loc of `*` in `int *(a)`
55 ///   loc of the first `(` in `int (*a)(int)`
56 ///   loc of the `*` in `int *(a)(int)`
57 ///   loc of the first `*` in `const int *const *volatile a;`
58 ///
59 /// It is non-trivial to get the start location because TypeLocs are stored
60 /// inside out. In the example above `*volatile` is the TypeLoc returned
61 /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()`
62 /// returns.
63 struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> {
64   SourceLocation VisitParenTypeLoc(ParenTypeLoc T) {
65     auto L = Visit(T.getInnerLoc());
66     if (L.isValid())
67       return L;
68     return T.getLParenLoc();
69   }
70 
71   // Types spelled in the prefix part of the declarator.
72   SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) {
73     return HandlePointer(T);
74   }
75 
76   SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
77     return HandlePointer(T);
78   }
79 
80   SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
81     return HandlePointer(T);
82   }
83 
84   SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) {
85     return HandlePointer(T);
86   }
87 
88   SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) {
89     return HandlePointer(T);
90   }
91 
92   // All other cases are not important, as they are either part of declaration
93   // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on
94   // existing declarators (e.g. QualifiedTypeLoc). They cannot start the
95   // declarator themselves, but their underlying type can.
96   SourceLocation VisitTypeLoc(TypeLoc T) {
97     auto N = T.getNextTypeLoc();
98     if (!N)
99       return SourceLocation();
100     return Visit(N);
101   }
102 
103   SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) {
104     if (T.getTypePtr()->hasTrailingReturn())
105       return SourceLocation(); // avoid recursing into the suffix of declarator.
106     return VisitTypeLoc(T);
107   }
108 
109 private:
110   template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) {
111     auto L = Visit(T.getPointeeLoc());
112     if (L.isValid())
113       return L;
114     return T.getLocalSourceRange().getBegin();
115   }
116 };
117 } // namespace
118 
119 static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
120   switch (E.getOperator()) {
121   // Comparison
122   case OO_EqualEqual:
123   case OO_ExclaimEqual:
124   case OO_Greater:
125   case OO_GreaterEqual:
126   case OO_Less:
127   case OO_LessEqual:
128   case OO_Spaceship:
129   // Assignment
130   case OO_Equal:
131   case OO_SlashEqual:
132   case OO_PercentEqual:
133   case OO_CaretEqual:
134   case OO_PipeEqual:
135   case OO_LessLessEqual:
136   case OO_GreaterGreaterEqual:
137   case OO_PlusEqual:
138   case OO_MinusEqual:
139   case OO_StarEqual:
140   case OO_AmpEqual:
141   // Binary computation
142   case OO_Slash:
143   case OO_Percent:
144   case OO_Caret:
145   case OO_Pipe:
146   case OO_LessLess:
147   case OO_GreaterGreater:
148   case OO_AmpAmp:
149   case OO_PipePipe:
150   case OO_ArrowStar:
151   case OO_Comma:
152     return syntax::NodeKind::BinaryOperatorExpression;
153   case OO_Tilde:
154   case OO_Exclaim:
155     return syntax::NodeKind::PrefixUnaryOperatorExpression;
156   // Prefix/Postfix increment/decrement
157   case OO_PlusPlus:
158   case OO_MinusMinus:
159     switch (E.getNumArgs()) {
160     case 1:
161       return syntax::NodeKind::PrefixUnaryOperatorExpression;
162     case 2:
163       return syntax::NodeKind::PostfixUnaryOperatorExpression;
164     default:
165       llvm_unreachable("Invalid number of arguments for operator");
166     }
167   // Operators that can be unary or binary
168   case OO_Plus:
169   case OO_Minus:
170   case OO_Star:
171   case OO_Amp:
172     switch (E.getNumArgs()) {
173     case 1:
174       return syntax::NodeKind::PrefixUnaryOperatorExpression;
175     case 2:
176       return syntax::NodeKind::BinaryOperatorExpression;
177     default:
178       llvm_unreachable("Invalid number of arguments for operator");
179     }
180     return syntax::NodeKind::BinaryOperatorExpression;
181   // Not yet supported by SyntaxTree
182   case OO_New:
183   case OO_Delete:
184   case OO_Array_New:
185   case OO_Array_Delete:
186   case OO_Coawait:
187   case OO_Call:
188   case OO_Subscript:
189   case OO_Arrow:
190     return syntax::NodeKind::UnknownExpression;
191   case OO_Conditional: // not overloadable
192   case NUM_OVERLOADED_OPERATORS:
193   case OO_None:
194     llvm_unreachable("Not an overloadable operator");
195   }
196   llvm_unreachable("Unknown OverloadedOperatorKind enum");
197 }
198 
199 /// Gets the range of declarator as defined by the C++ grammar. E.g.
200 ///     `int a;` -> range of `a`,
201 ///     `int *a;` -> range of `*a`,
202 ///     `int a[10];` -> range of `a[10]`,
203 ///     `int a[1][2][3];` -> range of `a[1][2][3]`,
204 ///     `int *a = nullptr` -> range of `*a = nullptr`.
205 /// FIMXE: \p Name must be a source range, e.g. for `operator+`.
206 static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
207                                       SourceLocation Name,
208                                       SourceRange Initializer) {
209   SourceLocation Start = GetStartLoc().Visit(T);
210   SourceLocation End = T.getSourceRange().getEnd();
211   assert(End.isValid());
212   if (Name.isValid()) {
213     if (Start.isInvalid())
214       Start = Name;
215     if (SM.isBeforeInTranslationUnit(End, Name))
216       End = Name;
217   }
218   if (Initializer.isValid()) {
219     auto InitializerEnd = Initializer.getEnd();
220     assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
221            End == InitializerEnd);
222     End = InitializerEnd;
223   }
224   return SourceRange(Start, End);
225 }
226 
227 namespace {
228 /// All AST hierarchy roots that can be represented as pointers.
229 using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>;
230 /// Maintains a mapping from AST to syntax tree nodes. This class will get more
231 /// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
232 /// FIXME: expose this as public API.
233 class ASTToSyntaxMapping {
234 public:
235   void add(ASTPtr From, syntax::Tree *To) {
236     assert(To != nullptr);
237     assert(!From.isNull());
238 
239     bool Added = Nodes.insert({From, To}).second;
240     (void)Added;
241     assert(Added && "mapping added twice");
242   }
243 
244   syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
245 
246 private:
247   llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes;
248 };
249 } // namespace
250 
251 /// A helper class for constructing the syntax tree while traversing a clang
252 /// AST.
253 ///
254 /// At each point of the traversal we maintain a list of pending nodes.
255 /// Initially all tokens are added as pending nodes. When processing a clang AST
256 /// node, the clients need to:
257 ///   - create a corresponding syntax node,
258 ///   - assign roles to all pending child nodes with 'markChild' and
259 ///     'markChildToken',
260 ///   - replace the child nodes with the new syntax node in the pending list
261 ///     with 'foldNode'.
262 ///
263 /// Note that all children are expected to be processed when building a node.
264 ///
265 /// Call finalize() to finish building the tree and consume the root node.
266 class syntax::TreeBuilder {
267 public:
268   TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) {
269     for (const auto &T : Arena.tokenBuffer().expandedTokens())
270       LocationToToken.insert({T.location().getRawEncoding(), &T});
271   }
272 
273   llvm::BumpPtrAllocator &allocator() { return Arena.allocator(); }
274   const SourceManager &sourceManager() const { return Arena.sourceManager(); }
275 
276   /// Populate children for \p New node, assuming it covers tokens from \p
277   /// Range.
278   void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
279                 ASTPtr From) {
280     assert(New);
281     Pending.foldChildren(Arena, Range, New);
282     if (From)
283       Mapping.add(From, New);
284   }
285   void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
286                 TypeLoc L) {
287     // FIXME: add mapping for TypeLocs
288     foldNode(Range, New, nullptr);
289   }
290 
291   /// Notifies that we should not consume trailing semicolon when computing
292   /// token range of \p D.
293   void noticeDeclWithoutSemicolon(Decl *D);
294 
295   /// Mark the \p Child node with a corresponding \p Role. All marked children
296   /// should be consumed by foldNode.
297   /// When called on expressions (clang::Expr is derived from clang::Stmt),
298   /// wraps expressions into expression statement.
299   void markStmtChild(Stmt *Child, NodeRole Role);
300   /// Should be called for expressions in non-statement position to avoid
301   /// wrapping into expression statement.
302   void markExprChild(Expr *Child, NodeRole Role);
303   /// Set role for a token starting at \p Loc.
304   void markChildToken(SourceLocation Loc, NodeRole R);
305   /// Set role for \p T.
306   void markChildToken(const syntax::Token *T, NodeRole R);
307 
308   /// Set role for \p N.
309   void markChild(syntax::Node *N, NodeRole R);
310   /// Set role for the syntax node matching \p N.
311   void markChild(ASTPtr N, NodeRole R);
312 
313   /// Finish building the tree and consume the root node.
314   syntax::TranslationUnit *finalize() && {
315     auto Tokens = Arena.tokenBuffer().expandedTokens();
316     assert(!Tokens.empty());
317     assert(Tokens.back().kind() == tok::eof);
318 
319     // Build the root of the tree, consuming all the children.
320     Pending.foldChildren(Arena, Tokens.drop_back(),
321                          new (Arena.allocator()) syntax::TranslationUnit);
322 
323     auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize());
324     TU->assertInvariantsRecursive();
325     return TU;
326   }
327 
328   /// Finds a token starting at \p L. The token must exist if \p L is valid.
329   const syntax::Token *findToken(SourceLocation L) const;
330 
331   /// Finds the syntax tokens corresponding to the \p SourceRange.
332   llvm::ArrayRef<syntax::Token> getRange(SourceRange Range) const {
333     assert(Range.isValid());
334     return getRange(Range.getBegin(), Range.getEnd());
335   }
336 
337   /// Finds the syntax tokens corresponding to the passed source locations.
338   /// \p First is the start position of the first token and \p Last is the start
339   /// position of the last token.
340   llvm::ArrayRef<syntax::Token> getRange(SourceLocation First,
341                                          SourceLocation Last) const {
342     assert(First.isValid());
343     assert(Last.isValid());
344     assert(First == Last ||
345            Arena.sourceManager().isBeforeInTranslationUnit(First, Last));
346     return llvm::makeArrayRef(findToken(First), std::next(findToken(Last)));
347   }
348 
349   llvm::ArrayRef<syntax::Token>
350   getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
351     auto Tokens = getRange(D->getSourceRange());
352     return maybeAppendSemicolon(Tokens, D);
353   }
354 
355   /// Returns true if \p D is the last declarator in a chain and is thus
356   /// reponsible for creating SimpleDeclaration for the whole chain.
357   template <class T>
358   bool isResponsibleForCreatingDeclaration(const T *D) const {
359     static_assert((std::is_base_of<DeclaratorDecl, T>::value ||
360                    std::is_base_of<TypedefNameDecl, T>::value),
361                   "only DeclaratorDecl and TypedefNameDecl are supported.");
362 
363     const Decl *Next = D->getNextDeclInContext();
364 
365     // There's no next sibling, this one is responsible.
366     if (Next == nullptr) {
367       return true;
368     }
369     const auto *NextT = llvm::dyn_cast<T>(Next);
370 
371     // Next sibling is not the same type, this one is responsible.
372     if (NextT == nullptr) {
373       return true;
374     }
375     // Next sibling doesn't begin at the same loc, it must be a different
376     // declaration, so this declarator is responsible.
377     if (NextT->getBeginLoc() != D->getBeginLoc()) {
378       return true;
379     }
380 
381     // NextT is a member of the same declaration, and we need the last member to
382     // create declaration. This one is not responsible.
383     return false;
384   }
385 
386   llvm::ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
387     llvm::ArrayRef<clang::syntax::Token> Tokens;
388     // We want to drop the template parameters for specializations.
389     if (const auto *S = llvm::dyn_cast<TagDecl>(D))
390       Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc());
391     else
392       Tokens = getRange(D->getSourceRange());
393     return maybeAppendSemicolon(Tokens, D);
394   }
395 
396   llvm::ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
397     return getRange(E->getSourceRange());
398   }
399 
400   /// Find the adjusted range for the statement, consuming the trailing
401   /// semicolon when needed.
402   llvm::ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
403     auto Tokens = getRange(S->getSourceRange());
404     if (isa<CompoundStmt>(S))
405       return Tokens;
406 
407     // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and
408     // all statements that end with those. Consume this semicolon here.
409     if (Tokens.back().kind() == tok::semi)
410       return Tokens;
411     return withTrailingSemicolon(Tokens);
412   }
413 
414 private:
415   llvm::ArrayRef<syntax::Token>
416   maybeAppendSemicolon(llvm::ArrayRef<syntax::Token> Tokens,
417                        const Decl *D) const {
418     if (llvm::isa<NamespaceDecl>(D))
419       return Tokens;
420     if (DeclsWithoutSemicolons.count(D))
421       return Tokens;
422     // FIXME: do not consume trailing semicolon on function definitions.
423     // Most declarations own a semicolon in syntax trees, but not in clang AST.
424     return withTrailingSemicolon(Tokens);
425   }
426 
427   llvm::ArrayRef<syntax::Token>
428   withTrailingSemicolon(llvm::ArrayRef<syntax::Token> Tokens) const {
429     assert(!Tokens.empty());
430     assert(Tokens.back().kind() != tok::eof);
431     // We never consume 'eof', so looking at the next token is ok.
432     if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi)
433       return llvm::makeArrayRef(Tokens.begin(), Tokens.end() + 1);
434     return Tokens;
435   }
436 
437   void setRole(syntax::Node *N, NodeRole R) {
438     assert(N->role() == NodeRole::Detached);
439     N->setRole(R);
440   }
441 
442   /// A collection of trees covering the input tokens.
443   /// When created, each tree corresponds to a single token in the file.
444   /// Clients call 'foldChildren' to attach one or more subtrees to a parent
445   /// node and update the list of trees accordingly.
446   ///
447   /// Ensures that added nodes properly nest and cover the whole token stream.
448   struct Forest {
449     Forest(syntax::Arena &A) {
450       assert(!A.tokenBuffer().expandedTokens().empty());
451       assert(A.tokenBuffer().expandedTokens().back().kind() == tok::eof);
452       // Create all leaf nodes.
453       // Note that we do not have 'eof' in the tree.
454       for (auto &T : A.tokenBuffer().expandedTokens().drop_back()) {
455         auto *L = new (A.allocator()) syntax::Leaf(&T);
456         L->Original = true;
457         L->CanModify = A.tokenBuffer().spelledForExpanded(T).hasValue();
458         Trees.insert(Trees.end(), {&T, L});
459       }
460     }
461 
462     void assignRole(llvm::ArrayRef<syntax::Token> Range,
463                     syntax::NodeRole Role) {
464       assert(!Range.empty());
465       auto It = Trees.lower_bound(Range.begin());
466       assert(It != Trees.end() && "no node found");
467       assert(It->first == Range.begin() && "no child with the specified range");
468       assert((std::next(It) == Trees.end() ||
469               std::next(It)->first == Range.end()) &&
470              "no child with the specified range");
471       assert(It->second->role() == NodeRole::Detached &&
472              "re-assigning role for a child");
473       It->second->setRole(Role);
474     }
475 
476     /// Add \p Node to the forest and attach child nodes based on \p Tokens.
477     void foldChildren(const syntax::Arena &A,
478                       llvm::ArrayRef<syntax::Token> Tokens,
479                       syntax::Tree *Node) {
480       // Attach children to `Node`.
481       assert(Node->firstChild() == nullptr && "node already has children");
482 
483       auto *FirstToken = Tokens.begin();
484       auto BeginChildren = Trees.lower_bound(FirstToken);
485 
486       assert((BeginChildren == Trees.end() ||
487               BeginChildren->first == FirstToken) &&
488              "fold crosses boundaries of existing subtrees");
489       auto EndChildren = Trees.lower_bound(Tokens.end());
490       assert(
491           (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) &&
492           "fold crosses boundaries of existing subtrees");
493 
494       // We need to go in reverse order, because we can only prepend.
495       for (auto It = EndChildren; It != BeginChildren; --It) {
496         auto *C = std::prev(It)->second;
497         if (C->role() == NodeRole::Detached)
498           C->setRole(NodeRole::Unknown);
499         Node->prependChildLowLevel(C);
500       }
501 
502       // Mark that this node came from the AST and is backed by the source code.
503       Node->Original = true;
504       Node->CanModify = A.tokenBuffer().spelledForExpanded(Tokens).hasValue();
505 
506       Trees.erase(BeginChildren, EndChildren);
507       Trees.insert({FirstToken, Node});
508     }
509 
510     // EXPECTS: all tokens were consumed and are owned by a single root node.
511     syntax::Node *finalize() && {
512       assert(Trees.size() == 1);
513       auto *Root = Trees.begin()->second;
514       Trees = {};
515       return Root;
516     }
517 
518     std::string str(const syntax::Arena &A) const {
519       std::string R;
520       for (auto It = Trees.begin(); It != Trees.end(); ++It) {
521         unsigned CoveredTokens =
522             It != Trees.end()
523                 ? (std::next(It)->first - It->first)
524                 : A.tokenBuffer().expandedTokens().end() - It->first;
525 
526         R += std::string(llvm::formatv(
527             "- '{0}' covers '{1}'+{2} tokens\n", It->second->kind(),
528             It->first->text(A.sourceManager()), CoveredTokens));
529         R += It->second->dump(A);
530       }
531       return R;
532     }
533 
534   private:
535     /// Maps from the start token to a subtree starting at that token.
536     /// Keys in the map are pointers into the array of expanded tokens, so
537     /// pointer order corresponds to the order of preprocessor tokens.
538     std::map<const syntax::Token *, syntax::Node *> Trees;
539   };
540 
541   /// For debugging purposes.
542   std::string str() { return Pending.str(Arena); }
543 
544   syntax::Arena &Arena;
545   /// To quickly find tokens by their start location.
546   llvm::DenseMap</*SourceLocation*/ unsigned, const syntax::Token *>
547       LocationToToken;
548   Forest Pending;
549   llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
550   ASTToSyntaxMapping Mapping;
551 };
552 
553 namespace {
554 class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
555 public:
556   explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
557       : Builder(Builder), Context(Context) {}
558 
559   bool shouldTraversePostOrder() const { return true; }
560 
561   bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
562     return processDeclaratorAndDeclaration(DD);
563   }
564 
565   bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
566     return processDeclaratorAndDeclaration(TD);
567   }
568 
569   bool VisitDecl(Decl *D) {
570     assert(!D->isImplicit());
571     Builder.foldNode(Builder.getDeclarationRange(D),
572                      new (allocator()) syntax::UnknownDeclaration(), D);
573     return true;
574   }
575 
576   // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
577   // override Traverse.
578   // FIXME: make RAV call WalkUpFrom* instead.
579   bool
580   TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
581     if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
582       return false;
583     if (C->isExplicitSpecialization())
584       return true; // we are only interested in explicit instantiations.
585     auto *Declaration =
586         cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
587     foldExplicitTemplateInstantiation(
588         Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()),
589         Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
590     return true;
591   }
592 
593   bool WalkUpFromTemplateDecl(TemplateDecl *S) {
594     foldTemplateDeclaration(
595         Builder.getDeclarationRange(S),
596         Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
597         Builder.getDeclarationRange(S->getTemplatedDecl()), S);
598     return true;
599   }
600 
601   bool WalkUpFromTagDecl(TagDecl *C) {
602     // FIXME: build the ClassSpecifier node.
603     if (!C->isFreeStanding()) {
604       assert(C->getNumTemplateParameterLists() == 0);
605       return true;
606     }
607     handleFreeStandingTagDecl(C);
608     return true;
609   }
610 
611   syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
612     assert(C->isFreeStanding());
613     // Class is a declaration specifier and needs a spanning declaration node.
614     auto DeclarationRange = Builder.getDeclarationRange(C);
615     syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
616     Builder.foldNode(DeclarationRange, Result, nullptr);
617 
618     // Build TemplateDeclaration nodes if we had template parameters.
619     auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
620       const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
621       auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end());
622       Result =
623           foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
624       DeclarationRange = R;
625     };
626     if (auto *S = llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
627       ConsumeTemplateParameters(*S->getTemplateParameters());
628     for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
629       ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
630     return Result;
631   }
632 
633   bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
634     // We do not want to call VisitDecl(), the declaration for translation
635     // unit is built by finalize().
636     return true;
637   }
638 
639   bool WalkUpFromCompoundStmt(CompoundStmt *S) {
640     using NodeRole = syntax::NodeRole;
641 
642     Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
643     for (auto *Child : S->body())
644       Builder.markStmtChild(Child, NodeRole::CompoundStatement_statement);
645     Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
646 
647     Builder.foldNode(Builder.getStmtRange(S),
648                      new (allocator()) syntax::CompoundStatement, S);
649     return true;
650   }
651 
652   // Some statements are not yet handled by syntax trees.
653   bool WalkUpFromStmt(Stmt *S) {
654     Builder.foldNode(Builder.getStmtRange(S),
655                      new (allocator()) syntax::UnknownStatement, S);
656     return true;
657   }
658 
659   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
660     // We override to traverse range initializer as VarDecl.
661     // RAV traverses it as a statement, we produce invalid node kinds in that
662     // case.
663     // FIXME: should do this in RAV instead?
664     bool Result = [&, this]() {
665       if (S->getInit() && !TraverseStmt(S->getInit()))
666         return false;
667       if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
668         return false;
669       if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
670         return false;
671       if (S->getBody() && !TraverseStmt(S->getBody()))
672         return false;
673       return true;
674     }();
675     WalkUpFromCXXForRangeStmt(S);
676     return Result;
677   }
678 
679   bool TraverseStmt(Stmt *S) {
680     if (auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S)) {
681       // We want to consume the semicolon, make sure SimpleDeclaration does not.
682       for (auto *D : DS->decls())
683         Builder.noticeDeclWithoutSemicolon(D);
684     } else if (auto *E = llvm::dyn_cast_or_null<Expr>(S)) {
685       return RecursiveASTVisitor::TraverseStmt(E->IgnoreImplicit());
686     }
687     return RecursiveASTVisitor::TraverseStmt(S);
688   }
689 
690   // Some expressions are not yet handled by syntax trees.
691   bool WalkUpFromExpr(Expr *E) {
692     assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
693     Builder.foldNode(Builder.getExprRange(E),
694                      new (allocator()) syntax::UnknownExpression, E);
695     return true;
696   }
697 
698   syntax::NestedNameSpecifier *
699   BuildNestedNameSpecifier(NestedNameSpecifierLoc QualifierLoc) {
700     if (!QualifierLoc)
701       return nullptr;
702     for (auto it = QualifierLoc; it; it = it.getPrefix()) {
703       auto *NS = new (allocator()) syntax::NameSpecifier;
704       Builder.foldNode(Builder.getRange(it.getLocalSourceRange()), NS, nullptr);
705       Builder.markChild(NS, syntax::NodeRole::NestedNameSpecifier_specifier);
706     }
707     auto *NNS = new (allocator()) syntax::NestedNameSpecifier;
708     Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()), NNS,
709                      nullptr);
710     return NNS;
711   }
712 
713   bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
714     // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
715     // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
716     // UDL suffix location does not point to the beginning of a token, so we
717     // can't represent the UDL suffix as a separate syntax tree node.
718 
719     return WalkUpFromUserDefinedLiteral(S);
720   }
721 
722   syntax::UserDefinedLiteralExpression *
723   buildUserDefinedLiteral(UserDefinedLiteral *S) {
724     switch (S->getLiteralOperatorKind()) {
725     case clang::UserDefinedLiteral::LOK_Integer:
726       return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
727     case clang::UserDefinedLiteral::LOK_Floating:
728       return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
729     case clang::UserDefinedLiteral::LOK_Character:
730       return new (allocator()) syntax::CharUserDefinedLiteralExpression;
731     case clang::UserDefinedLiteral::LOK_String:
732       return new (allocator()) syntax::StringUserDefinedLiteralExpression;
733     case clang::UserDefinedLiteral::LOK_Raw:
734     case clang::UserDefinedLiteral::LOK_Template:
735       // For raw literal operator and numeric literal operator template we
736       // cannot get the type of the operand in the semantic AST. We get this
737       // information from the token. As integer and floating point have the same
738       // token kind, we run `NumericLiteralParser` again to distinguish them.
739       auto TokLoc = S->getBeginLoc();
740       auto TokSpelling =
741           Builder.findToken(TokLoc)->text(Context.getSourceManager());
742       auto Literal =
743           NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
744                                Context.getLangOpts(), Context.getTargetInfo(),
745                                Context.getDiagnostics());
746       if (Literal.isIntegerLiteral())
747         return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
748       else {
749         assert(Literal.isFloatingLiteral());
750         return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
751       }
752     }
753   }
754 
755   bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
756     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
757     Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
758     return true;
759   }
760 
761   bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
762     if (auto *NNS = BuildNestedNameSpecifier(S->getQualifierLoc()))
763       Builder.markChild(NNS, syntax::NodeRole::IdExpression_qualifier);
764 
765     auto *unqualifiedId = new (allocator()) syntax::UnqualifiedId;
766     // Get `UnqualifiedId` from `DeclRefExpr`.
767     // FIXME: Extract this logic so that it can be used by `MemberExpr`,
768     // and other semantic constructs, now it is tied to `DeclRefExpr`.
769     if (!S->hasExplicitTemplateArgs()) {
770       Builder.foldNode(Builder.getRange(S->getNameInfo().getSourceRange()),
771                        unqualifiedId, nullptr);
772     } else {
773       auto templateIdSourceRange =
774           SourceRange(S->getNameInfo().getBeginLoc(), S->getRAngleLoc());
775       Builder.foldNode(Builder.getRange(templateIdSourceRange), unqualifiedId,
776                        nullptr);
777     }
778     Builder.markChild(unqualifiedId, syntax::NodeRole::IdExpression_id);
779 
780     Builder.foldNode(Builder.getExprRange(S),
781                      new (allocator()) syntax::IdExpression, S);
782     return true;
783   }
784 
785   bool WalkUpFromParenExpr(ParenExpr *S) {
786     Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
787     Builder.markExprChild(S->getSubExpr(),
788                           syntax::NodeRole::ParenExpression_subExpression);
789     Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
790     Builder.foldNode(Builder.getExprRange(S),
791                      new (allocator()) syntax::ParenExpression, S);
792     return true;
793   }
794 
795   bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
796     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
797     Builder.foldNode(Builder.getExprRange(S),
798                      new (allocator()) syntax::IntegerLiteralExpression, S);
799     return true;
800   }
801 
802   bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
803     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
804     Builder.foldNode(Builder.getExprRange(S),
805                      new (allocator()) syntax::CharacterLiteralExpression, S);
806     return true;
807   }
808 
809   bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
810     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
811     Builder.foldNode(Builder.getExprRange(S),
812                      new (allocator()) syntax::FloatingLiteralExpression, S);
813     return true;
814   }
815 
816   bool WalkUpFromStringLiteral(StringLiteral *S) {
817     Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
818     Builder.foldNode(Builder.getExprRange(S),
819                      new (allocator()) syntax::StringLiteralExpression, S);
820     return true;
821   }
822 
823   bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
824     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
825     Builder.foldNode(Builder.getExprRange(S),
826                      new (allocator()) syntax::BoolLiteralExpression, S);
827     return true;
828   }
829 
830   bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
831     Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
832     Builder.foldNode(Builder.getExprRange(S),
833                      new (allocator()) syntax::CxxNullPtrExpression, S);
834     return true;
835   }
836 
837   bool WalkUpFromUnaryOperator(UnaryOperator *S) {
838     Builder.markChildToken(S->getOperatorLoc(),
839                            syntax::NodeRole::OperatorExpression_operatorToken);
840     Builder.markExprChild(S->getSubExpr(),
841                           syntax::NodeRole::UnaryOperatorExpression_operand);
842 
843     if (S->isPostfix())
844       Builder.foldNode(Builder.getExprRange(S),
845                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
846                        S);
847     else
848       Builder.foldNode(Builder.getExprRange(S),
849                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
850                        S);
851 
852     return true;
853   }
854 
855   bool WalkUpFromBinaryOperator(BinaryOperator *S) {
856     Builder.markExprChild(
857         S->getLHS(), syntax::NodeRole::BinaryOperatorExpression_leftHandSide);
858     Builder.markChildToken(S->getOperatorLoc(),
859                            syntax::NodeRole::OperatorExpression_operatorToken);
860     Builder.markExprChild(
861         S->getRHS(), syntax::NodeRole::BinaryOperatorExpression_rightHandSide);
862     Builder.foldNode(Builder.getExprRange(S),
863                      new (allocator()) syntax::BinaryOperatorExpression, S);
864     return true;
865   }
866 
867   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
868     if (getOperatorNodeKind(*S) ==
869         syntax::NodeKind::PostfixUnaryOperatorExpression) {
870       // A postfix unary operator is declared as taking two operands. The
871       // second operand is used to distinguish from its prefix counterpart. In
872       // the semantic AST this "phantom" operand is represented as a
873       // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
874       // operand because it does not correspond to anything written in source
875       // code
876       for (auto *child : S->children()) {
877         if (child->getSourceRange().isInvalid())
878           continue;
879         if (!TraverseStmt(child))
880           return false;
881       }
882       return WalkUpFromCXXOperatorCallExpr(S);
883     } else
884       return RecursiveASTVisitor::TraverseCXXOperatorCallExpr(S);
885   }
886 
887   bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
888     switch (getOperatorNodeKind(*S)) {
889     case syntax::NodeKind::BinaryOperatorExpression:
890       Builder.markExprChild(
891           S->getArg(0),
892           syntax::NodeRole::BinaryOperatorExpression_leftHandSide);
893       Builder.markChildToken(
894           S->getOperatorLoc(),
895           syntax::NodeRole::OperatorExpression_operatorToken);
896       Builder.markExprChild(
897           S->getArg(1),
898           syntax::NodeRole::BinaryOperatorExpression_rightHandSide);
899       Builder.foldNode(Builder.getExprRange(S),
900                        new (allocator()) syntax::BinaryOperatorExpression, S);
901       return true;
902     case syntax::NodeKind::PrefixUnaryOperatorExpression:
903       Builder.markChildToken(
904           S->getOperatorLoc(),
905           syntax::NodeRole::OperatorExpression_operatorToken);
906       Builder.markExprChild(S->getArg(0),
907                             syntax::NodeRole::UnaryOperatorExpression_operand);
908       Builder.foldNode(Builder.getExprRange(S),
909                        new (allocator()) syntax::PrefixUnaryOperatorExpression,
910                        S);
911       return true;
912     case syntax::NodeKind::PostfixUnaryOperatorExpression:
913       Builder.markChildToken(
914           S->getOperatorLoc(),
915           syntax::NodeRole::OperatorExpression_operatorToken);
916       Builder.markExprChild(S->getArg(0),
917                             syntax::NodeRole::UnaryOperatorExpression_operand);
918       Builder.foldNode(Builder.getExprRange(S),
919                        new (allocator()) syntax::PostfixUnaryOperatorExpression,
920                        S);
921       return true;
922     case syntax::NodeKind::UnknownExpression:
923       return RecursiveASTVisitor::WalkUpFromCXXOperatorCallExpr(S);
924     default:
925       llvm_unreachable("getOperatorNodeKind() does not return this value");
926     }
927   }
928 
929   bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
930     auto Tokens = Builder.getDeclarationRange(S);
931     if (Tokens.front().kind() == tok::coloncolon) {
932       // Handle nested namespace definitions. Those start at '::' token, e.g.
933       // namespace a^::b {}
934       // FIXME: build corresponding nodes for the name of this namespace.
935       return true;
936     }
937     Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
938     return true;
939   }
940 
941   bool TraverseParenTypeLoc(ParenTypeLoc L) {
942     // We reverse order of traversal to get the proper syntax structure.
943     if (!WalkUpFromParenTypeLoc(L))
944       return false;
945     return TraverseTypeLoc(L.getInnerLoc());
946   }
947 
948   bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
949     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
950     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
951     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
952                      new (allocator()) syntax::ParenDeclarator, L);
953     return true;
954   }
955 
956   // Declarator chunks, they are produced by type locs and some clang::Decls.
957   bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
958     Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
959     Builder.markExprChild(L.getSizeExpr(),
960                           syntax::NodeRole::ArraySubscript_sizeExpression);
961     Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
962     Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
963                      new (allocator()) syntax::ArraySubscript, L);
964     return true;
965   }
966 
967   bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
968     Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
969     for (auto *P : L.getParams()) {
970       Builder.markChild(P, syntax::NodeRole::ParametersAndQualifiers_parameter);
971     }
972     Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
973     Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
974                      new (allocator()) syntax::ParametersAndQualifiers, L);
975     return true;
976   }
977 
978   bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
979     if (!L.getTypePtr()->hasTrailingReturn())
980       return WalkUpFromFunctionTypeLoc(L);
981 
982     auto *TrailingReturnTokens = BuildTrailingReturn(L);
983     // Finish building the node for parameters.
984     Builder.markChild(TrailingReturnTokens,
985                       syntax::NodeRole::ParametersAndQualifiers_trailingReturn);
986     return WalkUpFromFunctionTypeLoc(L);
987   }
988 
989   bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
990     auto SR = L.getLocalSourceRange();
991     Builder.foldNode(Builder.getRange(SR),
992                      new (allocator()) syntax::MemberPointer, L);
993     return true;
994   }
995 
996   // The code below is very regular, it could even be generated with some
997   // preprocessor magic. We merely assign roles to the corresponding children
998   // and fold resulting nodes.
999   bool WalkUpFromDeclStmt(DeclStmt *S) {
1000     Builder.foldNode(Builder.getStmtRange(S),
1001                      new (allocator()) syntax::DeclarationStatement, S);
1002     return true;
1003   }
1004 
1005   bool WalkUpFromNullStmt(NullStmt *S) {
1006     Builder.foldNode(Builder.getStmtRange(S),
1007                      new (allocator()) syntax::EmptyStatement, S);
1008     return true;
1009   }
1010 
1011   bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1012     Builder.markChildToken(S->getSwitchLoc(),
1013                            syntax::NodeRole::IntroducerKeyword);
1014     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1015     Builder.foldNode(Builder.getStmtRange(S),
1016                      new (allocator()) syntax::SwitchStatement, S);
1017     return true;
1018   }
1019 
1020   bool WalkUpFromCaseStmt(CaseStmt *S) {
1021     Builder.markChildToken(S->getKeywordLoc(),
1022                            syntax::NodeRole::IntroducerKeyword);
1023     Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseStatement_value);
1024     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1025     Builder.foldNode(Builder.getStmtRange(S),
1026                      new (allocator()) syntax::CaseStatement, S);
1027     return true;
1028   }
1029 
1030   bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1031     Builder.markChildToken(S->getKeywordLoc(),
1032                            syntax::NodeRole::IntroducerKeyword);
1033     Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1034     Builder.foldNode(Builder.getStmtRange(S),
1035                      new (allocator()) syntax::DefaultStatement, S);
1036     return true;
1037   }
1038 
1039   bool WalkUpFromIfStmt(IfStmt *S) {
1040     Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
1041     Builder.markStmtChild(S->getThen(),
1042                           syntax::NodeRole::IfStatement_thenStatement);
1043     Builder.markChildToken(S->getElseLoc(),
1044                            syntax::NodeRole::IfStatement_elseKeyword);
1045     Builder.markStmtChild(S->getElse(),
1046                           syntax::NodeRole::IfStatement_elseStatement);
1047     Builder.foldNode(Builder.getStmtRange(S),
1048                      new (allocator()) syntax::IfStatement, S);
1049     return true;
1050   }
1051 
1052   bool WalkUpFromForStmt(ForStmt *S) {
1053     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1054     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1055     Builder.foldNode(Builder.getStmtRange(S),
1056                      new (allocator()) syntax::ForStatement, S);
1057     return true;
1058   }
1059 
1060   bool WalkUpFromWhileStmt(WhileStmt *S) {
1061     Builder.markChildToken(S->getWhileLoc(),
1062                            syntax::NodeRole::IntroducerKeyword);
1063     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1064     Builder.foldNode(Builder.getStmtRange(S),
1065                      new (allocator()) syntax::WhileStatement, S);
1066     return true;
1067   }
1068 
1069   bool WalkUpFromContinueStmt(ContinueStmt *S) {
1070     Builder.markChildToken(S->getContinueLoc(),
1071                            syntax::NodeRole::IntroducerKeyword);
1072     Builder.foldNode(Builder.getStmtRange(S),
1073                      new (allocator()) syntax::ContinueStatement, S);
1074     return true;
1075   }
1076 
1077   bool WalkUpFromBreakStmt(BreakStmt *S) {
1078     Builder.markChildToken(S->getBreakLoc(),
1079                            syntax::NodeRole::IntroducerKeyword);
1080     Builder.foldNode(Builder.getStmtRange(S),
1081                      new (allocator()) syntax::BreakStatement, S);
1082     return true;
1083   }
1084 
1085   bool WalkUpFromReturnStmt(ReturnStmt *S) {
1086     Builder.markChildToken(S->getReturnLoc(),
1087                            syntax::NodeRole::IntroducerKeyword);
1088     Builder.markExprChild(S->getRetValue(),
1089                           syntax::NodeRole::ReturnStatement_value);
1090     Builder.foldNode(Builder.getStmtRange(S),
1091                      new (allocator()) syntax::ReturnStatement, S);
1092     return true;
1093   }
1094 
1095   bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1096     Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1097     Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1098     Builder.foldNode(Builder.getStmtRange(S),
1099                      new (allocator()) syntax::RangeBasedForStatement, S);
1100     return true;
1101   }
1102 
1103   bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1104     Builder.foldNode(Builder.getDeclarationRange(S),
1105                      new (allocator()) syntax::EmptyDeclaration, S);
1106     return true;
1107   }
1108 
1109   bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1110     Builder.markExprChild(S->getAssertExpr(),
1111                           syntax::NodeRole::StaticAssertDeclaration_condition);
1112     Builder.markExprChild(S->getMessage(),
1113                           syntax::NodeRole::StaticAssertDeclaration_message);
1114     Builder.foldNode(Builder.getDeclarationRange(S),
1115                      new (allocator()) syntax::StaticAssertDeclaration, S);
1116     return true;
1117   }
1118 
1119   bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1120     Builder.foldNode(Builder.getDeclarationRange(S),
1121                      new (allocator()) syntax::LinkageSpecificationDeclaration,
1122                      S);
1123     return true;
1124   }
1125 
1126   bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1127     Builder.foldNode(Builder.getDeclarationRange(S),
1128                      new (allocator()) syntax::NamespaceAliasDefinition, S);
1129     return true;
1130   }
1131 
1132   bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1133     Builder.foldNode(Builder.getDeclarationRange(S),
1134                      new (allocator()) syntax::UsingNamespaceDirective, S);
1135     return true;
1136   }
1137 
1138   bool WalkUpFromUsingDecl(UsingDecl *S) {
1139     Builder.foldNode(Builder.getDeclarationRange(S),
1140                      new (allocator()) syntax::UsingDeclaration, S);
1141     return true;
1142   }
1143 
1144   bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1145     Builder.foldNode(Builder.getDeclarationRange(S),
1146                      new (allocator()) syntax::UsingDeclaration, S);
1147     return true;
1148   }
1149 
1150   bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1151     Builder.foldNode(Builder.getDeclarationRange(S),
1152                      new (allocator()) syntax::UsingDeclaration, S);
1153     return true;
1154   }
1155 
1156   bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1157     Builder.foldNode(Builder.getDeclarationRange(S),
1158                      new (allocator()) syntax::TypeAliasDeclaration, S);
1159     return true;
1160   }
1161 
1162 private:
1163   template <class T> SourceLocation getQualifiedNameStart(T *D) {
1164     static_assert((std::is_base_of<DeclaratorDecl, T>::value ||
1165                    std::is_base_of<TypedefNameDecl, T>::value),
1166                   "only DeclaratorDecl and TypedefNameDecl are supported.");
1167 
1168     auto DN = D->getDeclName();
1169     bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
1170     if (IsAnonymous)
1171       return SourceLocation();
1172 
1173     if (const auto *DD = llvm::dyn_cast<DeclaratorDecl>(D)) {
1174       if (DD->getQualifierLoc()) {
1175         return DD->getQualifierLoc().getBeginLoc();
1176       }
1177     }
1178 
1179     return D->getLocation();
1180   }
1181 
1182   SourceRange getInitializerRange(Decl *D) {
1183     if (auto *V = llvm::dyn_cast<VarDecl>(D)) {
1184       auto *I = V->getInit();
1185       // Initializers in range-based-for are not part of the declarator
1186       if (I && !V->isCXXForRangeDecl())
1187         return I->getSourceRange();
1188     }
1189 
1190     return SourceRange();
1191   }
1192 
1193   /// Folds SimpleDeclarator node (if present) and in case this is the last
1194   /// declarator in the chain it also folds SimpleDeclaration node.
1195   template <class T> bool processDeclaratorAndDeclaration(T *D) {
1196     SourceRange Initializer = getInitializerRange(D);
1197     auto Range = getDeclaratorRange(Builder.sourceManager(),
1198                                     D->getTypeSourceInfo()->getTypeLoc(),
1199                                     getQualifiedNameStart(D), Initializer);
1200 
1201     // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1202     // declaration, but no declarator).
1203     if (Range.getBegin().isValid()) {
1204       auto *N = new (allocator()) syntax::SimpleDeclarator;
1205       Builder.foldNode(Builder.getRange(Range), N, nullptr);
1206       Builder.markChild(N, syntax::NodeRole::SimpleDeclaration_declarator);
1207     }
1208 
1209     if (Builder.isResponsibleForCreatingDeclaration(D)) {
1210       Builder.foldNode(Builder.getDeclarationRange(D),
1211                        new (allocator()) syntax::SimpleDeclaration, D);
1212     }
1213     return true;
1214   }
1215 
1216   /// Returns the range of the built node.
1217   syntax::TrailingReturnType *BuildTrailingReturn(FunctionProtoTypeLoc L) {
1218     assert(L.getTypePtr()->hasTrailingReturn());
1219 
1220     auto ReturnedType = L.getReturnLoc();
1221     // Build node for the declarator, if any.
1222     auto ReturnDeclaratorRange =
1223         getDeclaratorRange(this->Builder.sourceManager(), ReturnedType,
1224                            /*Name=*/SourceLocation(),
1225                            /*Initializer=*/SourceLocation());
1226     syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
1227     if (ReturnDeclaratorRange.isValid()) {
1228       ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1229       Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1230                        ReturnDeclarator, nullptr);
1231     }
1232 
1233     // Build node for trailing return type.
1234     auto Return = Builder.getRange(ReturnedType.getSourceRange());
1235     const auto *Arrow = Return.begin() - 1;
1236     assert(Arrow->kind() == tok::arrow);
1237     auto Tokens = llvm::makeArrayRef(Arrow, Return.end());
1238     Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1239     if (ReturnDeclarator)
1240       Builder.markChild(ReturnDeclarator,
1241                         syntax::NodeRole::TrailingReturnType_declarator);
1242     auto *R = new (allocator()) syntax::TrailingReturnType;
1243     Builder.foldNode(Tokens, R, L);
1244     return R;
1245   }
1246 
1247   void foldExplicitTemplateInstantiation(
1248       ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
1249       const syntax::Token *TemplateKW,
1250       syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
1251     assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
1252     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1253     Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
1254     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1255     Builder.markChild(
1256         InnerDeclaration,
1257         syntax::NodeRole::ExplicitTemplateInstantiation_declaration);
1258     Builder.foldNode(
1259         Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
1260   }
1261 
1262   syntax::TemplateDeclaration *foldTemplateDeclaration(
1263       ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1264       ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
1265     assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1266     Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1267 
1268     auto *N = new (allocator()) syntax::TemplateDeclaration;
1269     Builder.foldNode(Range, N, From);
1270     Builder.markChild(N, syntax::NodeRole::TemplateDeclaration_declaration);
1271     return N;
1272   }
1273 
1274   /// A small helper to save some typing.
1275   llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
1276 
1277   syntax::TreeBuilder &Builder;
1278   const ASTContext &Context;
1279 };
1280 } // namespace
1281 
1282 void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1283   DeclsWithoutSemicolons.insert(D);
1284 }
1285 
1286 void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
1287   if (Loc.isInvalid())
1288     return;
1289   Pending.assignRole(*findToken(Loc), Role);
1290 }
1291 
1292 void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
1293   if (!T)
1294     return;
1295   Pending.assignRole(*T, R);
1296 }
1297 
1298 void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1299   assert(N);
1300   setRole(N, R);
1301 }
1302 
1303 void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1304   auto *SN = Mapping.find(N);
1305   assert(SN != nullptr);
1306   setRole(SN, R);
1307 }
1308 
1309 void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
1310   if (!Child)
1311     return;
1312 
1313   syntax::Tree *ChildNode;
1314   if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
1315     // This is an expression in a statement position, consume the trailing
1316     // semicolon and form an 'ExpressionStatement' node.
1317     markExprChild(ChildExpr, NodeRole::ExpressionStatement_expression);
1318     ChildNode = new (allocator()) syntax::ExpressionStatement;
1319     // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1320     Pending.foldChildren(Arena, getStmtRange(Child), ChildNode);
1321   } else {
1322     ChildNode = Mapping.find(Child);
1323   }
1324   assert(ChildNode != nullptr);
1325   setRole(ChildNode, Role);
1326 }
1327 
1328 void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1329   if (!Child)
1330     return;
1331   Child = Child->IgnoreImplicit();
1332 
1333   syntax::Tree *ChildNode = Mapping.find(Child);
1334   assert(ChildNode != nullptr);
1335   setRole(ChildNode, Role);
1336 }
1337 
1338 const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
1339   if (L.isInvalid())
1340     return nullptr;
1341   auto It = LocationToToken.find(L.getRawEncoding());
1342   assert(It != LocationToToken.end());
1343   return It->second;
1344 }
1345 
1346 syntax::TranslationUnit *
1347 syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) {
1348   TreeBuilder Builder(A);
1349   BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext());
1350   return std::move(Builder).finalize();
1351 }
1352