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