19b3f38f9SIlya Biryukov //===- BuildTree.cpp ------------------------------------------*- C++ -*-=====// 29b3f38f9SIlya Biryukov // 39b3f38f9SIlya Biryukov // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 49b3f38f9SIlya Biryukov // See https://llvm.org/LICENSE.txt for license information. 59b3f38f9SIlya Biryukov // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 69b3f38f9SIlya Biryukov // 79b3f38f9SIlya Biryukov //===----------------------------------------------------------------------===// 89b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/BuildTree.h" 97d382dcdSMarcel Hlopko #include "clang/AST/ASTFwd.h" 10e702bdb8SIlya Biryukov #include "clang/AST/Decl.h" 11e702bdb8SIlya Biryukov #include "clang/AST/DeclBase.h" 127d382dcdSMarcel Hlopko #include "clang/AST/DeclCXX.h" 137d382dcdSMarcel Hlopko #include "clang/AST/DeclarationName.h" 143785eb83SEduardo Caldas #include "clang/AST/Expr.h" 15ea8bba7eSEduardo Caldas #include "clang/AST/ExprCXX.h" 162325d6b4SEduardo Caldas #include "clang/AST/IgnoreExpr.h" 17134455a0SEduardo Caldas #include "clang/AST/OperationKinds.h" 189b3f38f9SIlya Biryukov #include "clang/AST/RecursiveASTVisitor.h" 199b3f38f9SIlya Biryukov #include "clang/AST/Stmt.h" 207d382dcdSMarcel Hlopko #include "clang/AST/TypeLoc.h" 217d382dcdSMarcel Hlopko #include "clang/AST/TypeLocVisitor.h" 229b3f38f9SIlya Biryukov #include "clang/Basic/LLVM.h" 239b3f38f9SIlya Biryukov #include "clang/Basic/SourceLocation.h" 249b3f38f9SIlya Biryukov #include "clang/Basic/SourceManager.h" 2588bf9b3dSMarcel Hlopko #include "clang/Basic/Specifiers.h" 269b3f38f9SIlya Biryukov #include "clang/Basic/TokenKinds.h" 279b3f38f9SIlya Biryukov #include "clang/Lex/Lexer.h" 281db5b348SEduardo Caldas #include "clang/Lex/LiteralSupport.h" 299b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Nodes.h" 309b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tokens.h" 319b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tree.h" 329b3f38f9SIlya Biryukov #include "llvm/ADT/ArrayRef.h" 33a711a3a4SMarcel Hlopko #include "llvm/ADT/DenseMap.h" 34a711a3a4SMarcel Hlopko #include "llvm/ADT/PointerUnion.h" 359b3f38f9SIlya Biryukov #include "llvm/ADT/STLExtras.h" 367d382dcdSMarcel Hlopko #include "llvm/ADT/ScopeExit.h" 379b3f38f9SIlya Biryukov #include "llvm/ADT/SmallVector.h" 389b3f38f9SIlya Biryukov #include "llvm/Support/Allocator.h" 399b3f38f9SIlya Biryukov #include "llvm/Support/Casting.h" 4096065cf7SIlya Biryukov #include "llvm/Support/Compiler.h" 419b3f38f9SIlya Biryukov #include "llvm/Support/FormatVariadic.h" 421ad15046SIlya Biryukov #include "llvm/Support/MemoryBuffer.h" 439b3f38f9SIlya Biryukov #include "llvm/Support/raw_ostream.h" 44a711a3a4SMarcel Hlopko #include <cstddef> 459b3f38f9SIlya Biryukov #include <map> 469b3f38f9SIlya Biryukov 479b3f38f9SIlya Biryukov using namespace clang; 489b3f38f9SIlya Biryukov 492325d6b4SEduardo Caldas // Ignores the implicit `CXXConstructExpr` for copy/move constructor calls 502325d6b4SEduardo Caldas // generated by the compiler, as well as in implicit conversions like the one 512325d6b4SEduardo Caldas // wrapping `1` in `X x = 1;`. 522325d6b4SEduardo Caldas static Expr *IgnoreImplicitConstructorSingleStep(Expr *E) { 532325d6b4SEduardo Caldas if (auto *C = dyn_cast<CXXConstructExpr>(E)) { 542325d6b4SEduardo Caldas auto NumArgs = C->getNumArgs(); 552325d6b4SEduardo Caldas if (NumArgs == 1 || (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) { 562325d6b4SEduardo Caldas Expr *A = C->getArg(0); 572325d6b4SEduardo Caldas if (C->getParenOrBraceRange().isInvalid()) 582325d6b4SEduardo Caldas return A; 592325d6b4SEduardo Caldas } 602325d6b4SEduardo Caldas } 612325d6b4SEduardo Caldas return E; 622325d6b4SEduardo Caldas } 632325d6b4SEduardo Caldas 64134455a0SEduardo Caldas // In: 65134455a0SEduardo Caldas // struct X { 66134455a0SEduardo Caldas // X(int) 67134455a0SEduardo Caldas // }; 68134455a0SEduardo Caldas // X x = X(1); 69134455a0SEduardo Caldas // Ignores the implicit `CXXFunctionalCastExpr` that wraps 70134455a0SEduardo Caldas // `CXXConstructExpr X(1)`. 71134455a0SEduardo Caldas static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) { 72134455a0SEduardo Caldas if (auto *F = dyn_cast<CXXFunctionalCastExpr>(E)) { 73134455a0SEduardo Caldas if (F->getCastKind() == CK_ConstructorConversion) 74134455a0SEduardo Caldas return F->getSubExpr(); 75134455a0SEduardo Caldas } 76134455a0SEduardo Caldas return E; 77134455a0SEduardo Caldas } 78134455a0SEduardo Caldas 792325d6b4SEduardo Caldas static Expr *IgnoreImplicit(Expr *E) { 802325d6b4SEduardo Caldas return IgnoreExprNodes(E, IgnoreImplicitSingleStep, 81134455a0SEduardo Caldas IgnoreImplicitConstructorSingleStep, 82134455a0SEduardo Caldas IgnoreCXXFunctionalCastExprWrappingConstructor); 832325d6b4SEduardo Caldas } 842325d6b4SEduardo Caldas 8596065cf7SIlya Biryukov LLVM_ATTRIBUTE_UNUSED 862325d6b4SEduardo Caldas static bool isImplicitExpr(Expr *E) { return IgnoreImplicit(E) != E; } 8758fa50f4SIlya Biryukov 887d382dcdSMarcel Hlopko namespace { 897d382dcdSMarcel Hlopko /// Get start location of the Declarator from the TypeLoc. 907d382dcdSMarcel Hlopko /// E.g.: 917d382dcdSMarcel Hlopko /// loc of `(` in `int (a)` 927d382dcdSMarcel Hlopko /// loc of `*` in `int *(a)` 937d382dcdSMarcel Hlopko /// loc of the first `(` in `int (*a)(int)` 947d382dcdSMarcel Hlopko /// loc of the `*` in `int *(a)(int)` 957d382dcdSMarcel Hlopko /// loc of the first `*` in `const int *const *volatile a;` 967d382dcdSMarcel Hlopko /// 977d382dcdSMarcel Hlopko /// It is non-trivial to get the start location because TypeLocs are stored 987d382dcdSMarcel Hlopko /// inside out. In the example above `*volatile` is the TypeLoc returned 997d382dcdSMarcel Hlopko /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()` 1007d382dcdSMarcel Hlopko /// returns. 1017d382dcdSMarcel Hlopko struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> { 1027d382dcdSMarcel Hlopko SourceLocation VisitParenTypeLoc(ParenTypeLoc T) { 1037d382dcdSMarcel Hlopko auto L = Visit(T.getInnerLoc()); 1047d382dcdSMarcel Hlopko if (L.isValid()) 1057d382dcdSMarcel Hlopko return L; 1067d382dcdSMarcel Hlopko return T.getLParenLoc(); 1077d382dcdSMarcel Hlopko } 1087d382dcdSMarcel Hlopko 1097d382dcdSMarcel Hlopko // Types spelled in the prefix part of the declarator. 1107d382dcdSMarcel Hlopko SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) { 1117d382dcdSMarcel Hlopko return HandlePointer(T); 1127d382dcdSMarcel Hlopko } 1137d382dcdSMarcel Hlopko 1147d382dcdSMarcel Hlopko SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) { 1157d382dcdSMarcel Hlopko return HandlePointer(T); 1167d382dcdSMarcel Hlopko } 1177d382dcdSMarcel Hlopko 1187d382dcdSMarcel Hlopko SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) { 1197d382dcdSMarcel Hlopko return HandlePointer(T); 1207d382dcdSMarcel Hlopko } 1217d382dcdSMarcel Hlopko 1227d382dcdSMarcel Hlopko SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) { 1237d382dcdSMarcel Hlopko return HandlePointer(T); 1247d382dcdSMarcel Hlopko } 1257d382dcdSMarcel Hlopko 1267d382dcdSMarcel Hlopko SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) { 1277d382dcdSMarcel Hlopko return HandlePointer(T); 1287d382dcdSMarcel Hlopko } 1297d382dcdSMarcel Hlopko 1307d382dcdSMarcel Hlopko // All other cases are not important, as they are either part of declaration 1317d382dcdSMarcel Hlopko // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on 1327d382dcdSMarcel Hlopko // existing declarators (e.g. QualifiedTypeLoc). They cannot start the 1337d382dcdSMarcel Hlopko // declarator themselves, but their underlying type can. 1347d382dcdSMarcel Hlopko SourceLocation VisitTypeLoc(TypeLoc T) { 1357d382dcdSMarcel Hlopko auto N = T.getNextTypeLoc(); 1367d382dcdSMarcel Hlopko if (!N) 1377d382dcdSMarcel Hlopko return SourceLocation(); 1387d382dcdSMarcel Hlopko return Visit(N); 1397d382dcdSMarcel Hlopko } 1407d382dcdSMarcel Hlopko 1417d382dcdSMarcel Hlopko SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) { 1427d382dcdSMarcel Hlopko if (T.getTypePtr()->hasTrailingReturn()) 1437d382dcdSMarcel Hlopko return SourceLocation(); // avoid recursing into the suffix of declarator. 1447d382dcdSMarcel Hlopko return VisitTypeLoc(T); 1457d382dcdSMarcel Hlopko } 1467d382dcdSMarcel Hlopko 1477d382dcdSMarcel Hlopko private: 1487d382dcdSMarcel Hlopko template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) { 1497d382dcdSMarcel Hlopko auto L = Visit(T.getPointeeLoc()); 1507d382dcdSMarcel Hlopko if (L.isValid()) 1517d382dcdSMarcel Hlopko return L; 1527d382dcdSMarcel Hlopko return T.getLocalSourceRange().getBegin(); 1537d382dcdSMarcel Hlopko } 1547d382dcdSMarcel Hlopko }; 1557d382dcdSMarcel Hlopko } // namespace 1567d382dcdSMarcel Hlopko 157f5087d5cSEduardo Caldas static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args) { 158*87f0b51dSEduardo Caldas auto FirstDefaultArg = std::find_if(Args.begin(), Args.end(), [](auto It) { 159*87f0b51dSEduardo Caldas return isa<CXXDefaultArgExpr>(It); 160f5087d5cSEduardo Caldas }); 161*87f0b51dSEduardo Caldas return llvm::make_range(Args.begin(), FirstDefaultArg); 162f5087d5cSEduardo Caldas } 163f5087d5cSEduardo Caldas 164ea8bba7eSEduardo Caldas static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) { 165ea8bba7eSEduardo Caldas switch (E.getOperator()) { 166ea8bba7eSEduardo Caldas // Comparison 167ea8bba7eSEduardo Caldas case OO_EqualEqual: 168ea8bba7eSEduardo Caldas case OO_ExclaimEqual: 169ea8bba7eSEduardo Caldas case OO_Greater: 170ea8bba7eSEduardo Caldas case OO_GreaterEqual: 171ea8bba7eSEduardo Caldas case OO_Less: 172ea8bba7eSEduardo Caldas case OO_LessEqual: 173ea8bba7eSEduardo Caldas case OO_Spaceship: 174ea8bba7eSEduardo Caldas // Assignment 175ea8bba7eSEduardo Caldas case OO_Equal: 176ea8bba7eSEduardo Caldas case OO_SlashEqual: 177ea8bba7eSEduardo Caldas case OO_PercentEqual: 178ea8bba7eSEduardo Caldas case OO_CaretEqual: 179ea8bba7eSEduardo Caldas case OO_PipeEqual: 180ea8bba7eSEduardo Caldas case OO_LessLessEqual: 181ea8bba7eSEduardo Caldas case OO_GreaterGreaterEqual: 182ea8bba7eSEduardo Caldas case OO_PlusEqual: 183ea8bba7eSEduardo Caldas case OO_MinusEqual: 184ea8bba7eSEduardo Caldas case OO_StarEqual: 185ea8bba7eSEduardo Caldas case OO_AmpEqual: 186ea8bba7eSEduardo Caldas // Binary computation 187ea8bba7eSEduardo Caldas case OO_Slash: 188ea8bba7eSEduardo Caldas case OO_Percent: 189ea8bba7eSEduardo Caldas case OO_Caret: 190ea8bba7eSEduardo Caldas case OO_Pipe: 191ea8bba7eSEduardo Caldas case OO_LessLess: 192ea8bba7eSEduardo Caldas case OO_GreaterGreater: 193ea8bba7eSEduardo Caldas case OO_AmpAmp: 194ea8bba7eSEduardo Caldas case OO_PipePipe: 195ea8bba7eSEduardo Caldas case OO_ArrowStar: 196ea8bba7eSEduardo Caldas case OO_Comma: 197ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression; 198ea8bba7eSEduardo Caldas case OO_Tilde: 199ea8bba7eSEduardo Caldas case OO_Exclaim: 200ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression; 201ea8bba7eSEduardo Caldas // Prefix/Postfix increment/decrement 202ea8bba7eSEduardo Caldas case OO_PlusPlus: 203ea8bba7eSEduardo Caldas case OO_MinusMinus: 204ea8bba7eSEduardo Caldas switch (E.getNumArgs()) { 205ea8bba7eSEduardo Caldas case 1: 206ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression; 207ea8bba7eSEduardo Caldas case 2: 208ea8bba7eSEduardo Caldas return syntax::NodeKind::PostfixUnaryOperatorExpression; 209ea8bba7eSEduardo Caldas default: 210ea8bba7eSEduardo Caldas llvm_unreachable("Invalid number of arguments for operator"); 211ea8bba7eSEduardo Caldas } 212ea8bba7eSEduardo Caldas // Operators that can be unary or binary 213ea8bba7eSEduardo Caldas case OO_Plus: 214ea8bba7eSEduardo Caldas case OO_Minus: 215ea8bba7eSEduardo Caldas case OO_Star: 216ea8bba7eSEduardo Caldas case OO_Amp: 217ea8bba7eSEduardo Caldas switch (E.getNumArgs()) { 218ea8bba7eSEduardo Caldas case 1: 219ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression; 220ea8bba7eSEduardo Caldas case 2: 221ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression; 222ea8bba7eSEduardo Caldas default: 223ea8bba7eSEduardo Caldas llvm_unreachable("Invalid number of arguments for operator"); 224ea8bba7eSEduardo Caldas } 225ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression; 226ea8bba7eSEduardo Caldas // Not yet supported by SyntaxTree 227ea8bba7eSEduardo Caldas case OO_New: 228ea8bba7eSEduardo Caldas case OO_Delete: 229ea8bba7eSEduardo Caldas case OO_Array_New: 230ea8bba7eSEduardo Caldas case OO_Array_Delete: 231ea8bba7eSEduardo Caldas case OO_Coawait: 232ea8bba7eSEduardo Caldas case OO_Subscript: 233ea8bba7eSEduardo Caldas case OO_Arrow: 234ea8bba7eSEduardo Caldas return syntax::NodeKind::UnknownExpression; 2352de2ca34SEduardo Caldas case OO_Call: 2362de2ca34SEduardo Caldas return syntax::NodeKind::CallExpression; 237ea8bba7eSEduardo Caldas case OO_Conditional: // not overloadable 238ea8bba7eSEduardo Caldas case NUM_OVERLOADED_OPERATORS: 239ea8bba7eSEduardo Caldas case OO_None: 240ea8bba7eSEduardo Caldas llvm_unreachable("Not an overloadable operator"); 241ea8bba7eSEduardo Caldas } 242397c6820SSimon Pilgrim llvm_unreachable("Unknown OverloadedOperatorKind enum"); 243ea8bba7eSEduardo Caldas } 244ea8bba7eSEduardo Caldas 24538bc0060SEduardo Caldas /// Get the start of the qualified name. In the examples below it gives the 24638bc0060SEduardo Caldas /// location of the `^`: 24738bc0060SEduardo Caldas /// `int ^a;` 248a1461953SEduardo Caldas /// `int *^a;` 24938bc0060SEduardo Caldas /// `int ^a::S::f(){}` 25038bc0060SEduardo Caldas static SourceLocation getQualifiedNameStart(NamedDecl *D) { 25138bc0060SEduardo Caldas assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) && 25238bc0060SEduardo Caldas "only DeclaratorDecl and TypedefNameDecl are supported."); 25338bc0060SEduardo Caldas 25438bc0060SEduardo Caldas auto DN = D->getDeclName(); 25538bc0060SEduardo Caldas bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo(); 25638bc0060SEduardo Caldas if (IsAnonymous) 25738bc0060SEduardo Caldas return SourceLocation(); 25838bc0060SEduardo Caldas 25938bc0060SEduardo Caldas if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) { 26038bc0060SEduardo Caldas if (DD->getQualifierLoc()) { 26138bc0060SEduardo Caldas return DD->getQualifierLoc().getBeginLoc(); 26238bc0060SEduardo Caldas } 26338bc0060SEduardo Caldas } 26438bc0060SEduardo Caldas 26538bc0060SEduardo Caldas return D->getLocation(); 26638bc0060SEduardo Caldas } 26738bc0060SEduardo Caldas 26838bc0060SEduardo Caldas /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl]. 26938bc0060SEduardo Caldas /// `int a;` -> range of ``, 27038bc0060SEduardo Caldas /// `int *a = nullptr` -> range of `= nullptr`. 27138bc0060SEduardo Caldas /// `int a{}` -> range of `{}`. 27238bc0060SEduardo Caldas /// `int a()` -> range of `()`. 27338bc0060SEduardo Caldas static SourceRange getInitializerRange(Decl *D) { 27438bc0060SEduardo Caldas if (auto *V = dyn_cast<VarDecl>(D)) { 27538bc0060SEduardo Caldas auto *I = V->getInit(); 27638bc0060SEduardo Caldas // Initializers in range-based-for are not part of the declarator 27738bc0060SEduardo Caldas if (I && !V->isCXXForRangeDecl()) 27838bc0060SEduardo Caldas return I->getSourceRange(); 27938bc0060SEduardo Caldas } 28038bc0060SEduardo Caldas 28138bc0060SEduardo Caldas return SourceRange(); 28238bc0060SEduardo Caldas } 28338bc0060SEduardo Caldas 2847d382dcdSMarcel Hlopko /// Gets the range of declarator as defined by the C++ grammar. E.g. 2857d382dcdSMarcel Hlopko /// `int a;` -> range of `a`, 2867d382dcdSMarcel Hlopko /// `int *a;` -> range of `*a`, 2877d382dcdSMarcel Hlopko /// `int a[10];` -> range of `a[10]`, 2887d382dcdSMarcel Hlopko /// `int a[1][2][3];` -> range of `a[1][2][3]`, 2897d382dcdSMarcel Hlopko /// `int *a = nullptr` -> range of `*a = nullptr`. 29038bc0060SEduardo Caldas /// `int S::f(){}` -> range of `S::f()`. 291a1461953SEduardo Caldas /// FIXME: \p Name must be a source range. 2927d382dcdSMarcel Hlopko static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T, 2937d382dcdSMarcel Hlopko SourceLocation Name, 2947d382dcdSMarcel Hlopko SourceRange Initializer) { 2957d382dcdSMarcel Hlopko SourceLocation Start = GetStartLoc().Visit(T); 29638bc0060SEduardo Caldas SourceLocation End = T.getEndLoc(); 2977d382dcdSMarcel Hlopko assert(End.isValid()); 2987d382dcdSMarcel Hlopko if (Name.isValid()) { 2997d382dcdSMarcel Hlopko if (Start.isInvalid()) 3007d382dcdSMarcel Hlopko Start = Name; 3017d382dcdSMarcel Hlopko if (SM.isBeforeInTranslationUnit(End, Name)) 3027d382dcdSMarcel Hlopko End = Name; 3037d382dcdSMarcel Hlopko } 3047d382dcdSMarcel Hlopko if (Initializer.isValid()) { 305cdce2fe5SMarcel Hlopko auto InitializerEnd = Initializer.getEnd(); 306f33c2c27SEduardo Caldas assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) || 307f33c2c27SEduardo Caldas End == InitializerEnd); 308cdce2fe5SMarcel Hlopko End = InitializerEnd; 3097d382dcdSMarcel Hlopko } 3107d382dcdSMarcel Hlopko return SourceRange(Start, End); 3117d382dcdSMarcel Hlopko } 3127d382dcdSMarcel Hlopko 313a711a3a4SMarcel Hlopko namespace { 314a711a3a4SMarcel Hlopko /// All AST hierarchy roots that can be represented as pointers. 315a711a3a4SMarcel Hlopko using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>; 316a711a3a4SMarcel Hlopko /// Maintains a mapping from AST to syntax tree nodes. This class will get more 317a711a3a4SMarcel Hlopko /// complicated as we support more kinds of AST nodes, e.g. TypeLocs. 318a711a3a4SMarcel Hlopko /// FIXME: expose this as public API. 319a711a3a4SMarcel Hlopko class ASTToSyntaxMapping { 320a711a3a4SMarcel Hlopko public: 321a711a3a4SMarcel Hlopko void add(ASTPtr From, syntax::Tree *To) { 322a711a3a4SMarcel Hlopko assert(To != nullptr); 323a711a3a4SMarcel Hlopko assert(!From.isNull()); 324a711a3a4SMarcel Hlopko 325a711a3a4SMarcel Hlopko bool Added = Nodes.insert({From, To}).second; 326a711a3a4SMarcel Hlopko (void)Added; 327a711a3a4SMarcel Hlopko assert(Added && "mapping added twice"); 328a711a3a4SMarcel Hlopko } 329a711a3a4SMarcel Hlopko 330f9500cc4SEduardo Caldas void add(NestedNameSpecifierLoc From, syntax::Tree *To) { 331f9500cc4SEduardo Caldas assert(To != nullptr); 332f9500cc4SEduardo Caldas assert(From.hasQualifier()); 333f9500cc4SEduardo Caldas 334f9500cc4SEduardo Caldas bool Added = NNSNodes.insert({From, To}).second; 335f9500cc4SEduardo Caldas (void)Added; 336f9500cc4SEduardo Caldas assert(Added && "mapping added twice"); 337f9500cc4SEduardo Caldas } 338f9500cc4SEduardo Caldas 339a711a3a4SMarcel Hlopko syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); } 340a711a3a4SMarcel Hlopko 341f9500cc4SEduardo Caldas syntax::Tree *find(NestedNameSpecifierLoc P) const { 342f9500cc4SEduardo Caldas return NNSNodes.lookup(P); 343f9500cc4SEduardo Caldas } 344f9500cc4SEduardo Caldas 345a711a3a4SMarcel Hlopko private: 346a711a3a4SMarcel Hlopko llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes; 347f9500cc4SEduardo Caldas llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes; 348a711a3a4SMarcel Hlopko }; 349a711a3a4SMarcel Hlopko } // namespace 350a711a3a4SMarcel Hlopko 3519b3f38f9SIlya Biryukov /// A helper class for constructing the syntax tree while traversing a clang 3529b3f38f9SIlya Biryukov /// AST. 3539b3f38f9SIlya Biryukov /// 3549b3f38f9SIlya Biryukov /// At each point of the traversal we maintain a list of pending nodes. 3559b3f38f9SIlya Biryukov /// Initially all tokens are added as pending nodes. When processing a clang AST 3569b3f38f9SIlya Biryukov /// node, the clients need to: 3579b3f38f9SIlya Biryukov /// - create a corresponding syntax node, 3589b3f38f9SIlya Biryukov /// - assign roles to all pending child nodes with 'markChild' and 3599b3f38f9SIlya Biryukov /// 'markChildToken', 3609b3f38f9SIlya Biryukov /// - replace the child nodes with the new syntax node in the pending list 3619b3f38f9SIlya Biryukov /// with 'foldNode'. 3629b3f38f9SIlya Biryukov /// 3639b3f38f9SIlya Biryukov /// Note that all children are expected to be processed when building a node. 3649b3f38f9SIlya Biryukov /// 3659b3f38f9SIlya Biryukov /// Call finalize() to finish building the tree and consume the root node. 3669b3f38f9SIlya Biryukov class syntax::TreeBuilder { 3679b3f38f9SIlya Biryukov public: 368c1bbefefSIlya Biryukov TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) { 3694c14ee61SEduardo Caldas for (const auto &T : Arena.getTokenBuffer().expandedTokens()) 370c1bbefefSIlya Biryukov LocationToToken.insert({T.location().getRawEncoding(), &T}); 371c1bbefefSIlya Biryukov } 3729b3f38f9SIlya Biryukov 3734c14ee61SEduardo Caldas llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); } 3744c14ee61SEduardo Caldas const SourceManager &sourceManager() const { 3754c14ee61SEduardo Caldas return Arena.getSourceManager(); 3764c14ee61SEduardo Caldas } 3779b3f38f9SIlya Biryukov 3789b3f38f9SIlya Biryukov /// Populate children for \p New node, assuming it covers tokens from \p 3799b3f38f9SIlya Biryukov /// Range. 380ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) { 381a711a3a4SMarcel Hlopko assert(New); 382a711a3a4SMarcel Hlopko Pending.foldChildren(Arena, Range, New); 383a711a3a4SMarcel Hlopko if (From) 384a711a3a4SMarcel Hlopko Mapping.add(From, New); 385a711a3a4SMarcel Hlopko } 386f9500cc4SEduardo Caldas 387ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) { 388a711a3a4SMarcel Hlopko // FIXME: add mapping for TypeLocs 389a711a3a4SMarcel Hlopko foldNode(Range, New, nullptr); 390a711a3a4SMarcel Hlopko } 3919b3f38f9SIlya Biryukov 392f9500cc4SEduardo Caldas void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New, 393f9500cc4SEduardo Caldas NestedNameSpecifierLoc From) { 394f9500cc4SEduardo Caldas assert(New); 395f9500cc4SEduardo Caldas Pending.foldChildren(Arena, Range, New); 396f9500cc4SEduardo Caldas if (From) 397f9500cc4SEduardo Caldas Mapping.add(From, New); 3988abb5fb6SEduardo Caldas } 399f9500cc4SEduardo Caldas 400e702bdb8SIlya Biryukov /// Notifies that we should not consume trailing semicolon when computing 401e702bdb8SIlya Biryukov /// token range of \p D. 4027d382dcdSMarcel Hlopko void noticeDeclWithoutSemicolon(Decl *D); 403e702bdb8SIlya Biryukov 40458fa50f4SIlya Biryukov /// Mark the \p Child node with a corresponding \p Role. All marked children 40558fa50f4SIlya Biryukov /// should be consumed by foldNode. 4067d382dcdSMarcel Hlopko /// When called on expressions (clang::Expr is derived from clang::Stmt), 40758fa50f4SIlya Biryukov /// wraps expressions into expression statement. 40858fa50f4SIlya Biryukov void markStmtChild(Stmt *Child, NodeRole Role); 40958fa50f4SIlya Biryukov /// Should be called for expressions in non-statement position to avoid 41058fa50f4SIlya Biryukov /// wrapping into expression statement. 41158fa50f4SIlya Biryukov void markExprChild(Expr *Child, NodeRole Role); 4129b3f38f9SIlya Biryukov /// Set role for a token starting at \p Loc. 413def65bb4SIlya Biryukov void markChildToken(SourceLocation Loc, NodeRole R); 4147d382dcdSMarcel Hlopko /// Set role for \p T. 4157d382dcdSMarcel Hlopko void markChildToken(const syntax::Token *T, NodeRole R); 4167d382dcdSMarcel Hlopko 417a711a3a4SMarcel Hlopko /// Set role for \p N. 418a711a3a4SMarcel Hlopko void markChild(syntax::Node *N, NodeRole R); 419a711a3a4SMarcel Hlopko /// Set role for the syntax node matching \p N. 420a711a3a4SMarcel Hlopko void markChild(ASTPtr N, NodeRole R); 421f9500cc4SEduardo Caldas /// Set role for the syntax node matching \p N. 422f9500cc4SEduardo Caldas void markChild(NestedNameSpecifierLoc N, NodeRole R); 4239b3f38f9SIlya Biryukov 4249b3f38f9SIlya Biryukov /// Finish building the tree and consume the root node. 4259b3f38f9SIlya Biryukov syntax::TranslationUnit *finalize() && { 4264c14ee61SEduardo Caldas auto Tokens = Arena.getTokenBuffer().expandedTokens(); 427bfbf6b6cSIlya Biryukov assert(!Tokens.empty()); 428bfbf6b6cSIlya Biryukov assert(Tokens.back().kind() == tok::eof); 429bfbf6b6cSIlya Biryukov 4309b3f38f9SIlya Biryukov // Build the root of the tree, consuming all the children. 4311ad15046SIlya Biryukov Pending.foldChildren(Arena, Tokens.drop_back(), 4324c14ee61SEduardo Caldas new (Arena.getAllocator()) syntax::TranslationUnit); 4339b3f38f9SIlya Biryukov 4343b929fe7SIlya Biryukov auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize()); 4353b929fe7SIlya Biryukov TU->assertInvariantsRecursive(); 4363b929fe7SIlya Biryukov return TU; 4379b3f38f9SIlya Biryukov } 4389b3f38f9SIlya Biryukov 43988bf9b3dSMarcel Hlopko /// Finds a token starting at \p L. The token must exist if \p L is valid. 44088bf9b3dSMarcel Hlopko const syntax::Token *findToken(SourceLocation L) const; 44188bf9b3dSMarcel Hlopko 442a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the \p SourceRange. 443ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceRange Range) const { 444a711a3a4SMarcel Hlopko assert(Range.isValid()); 445a711a3a4SMarcel Hlopko return getRange(Range.getBegin(), Range.getEnd()); 446a711a3a4SMarcel Hlopko } 447a711a3a4SMarcel Hlopko 448a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the passed source locations. 4499b3f38f9SIlya Biryukov /// \p First is the start position of the first token and \p Last is the start 4509b3f38f9SIlya Biryukov /// position of the last token. 451ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceLocation First, 4529b3f38f9SIlya Biryukov SourceLocation Last) const { 4539b3f38f9SIlya Biryukov assert(First.isValid()); 4549b3f38f9SIlya Biryukov assert(Last.isValid()); 4559b3f38f9SIlya Biryukov assert(First == Last || 4564c14ee61SEduardo Caldas Arena.getSourceManager().isBeforeInTranslationUnit(First, Last)); 4579b3f38f9SIlya Biryukov return llvm::makeArrayRef(findToken(First), std::next(findToken(Last))); 4589b3f38f9SIlya Biryukov } 45988bf9b3dSMarcel Hlopko 460ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> 46188bf9b3dSMarcel Hlopko getTemplateRange(const ClassTemplateSpecializationDecl *D) const { 462a711a3a4SMarcel Hlopko auto Tokens = getRange(D->getSourceRange()); 46388bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D); 46488bf9b3dSMarcel Hlopko } 46588bf9b3dSMarcel Hlopko 466cdce2fe5SMarcel Hlopko /// Returns true if \p D is the last declarator in a chain and is thus 467cdce2fe5SMarcel Hlopko /// reponsible for creating SimpleDeclaration for the whole chain. 46838bc0060SEduardo Caldas bool isResponsibleForCreatingDeclaration(const Decl *D) const { 46938bc0060SEduardo Caldas assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) && 470cdce2fe5SMarcel Hlopko "only DeclaratorDecl and TypedefNameDecl are supported."); 471cdce2fe5SMarcel Hlopko 472cdce2fe5SMarcel Hlopko const Decl *Next = D->getNextDeclInContext(); 473cdce2fe5SMarcel Hlopko 474cdce2fe5SMarcel Hlopko // There's no next sibling, this one is responsible. 475cdce2fe5SMarcel Hlopko if (Next == nullptr) { 476cdce2fe5SMarcel Hlopko return true; 477cdce2fe5SMarcel Hlopko } 478cdce2fe5SMarcel Hlopko 479cdce2fe5SMarcel Hlopko // Next sibling is not the same type, this one is responsible. 48038bc0060SEduardo Caldas if (D->getKind() != Next->getKind()) { 481cdce2fe5SMarcel Hlopko return true; 482cdce2fe5SMarcel Hlopko } 483cdce2fe5SMarcel Hlopko // Next sibling doesn't begin at the same loc, it must be a different 484cdce2fe5SMarcel Hlopko // declaration, so this declarator is responsible. 48538bc0060SEduardo Caldas if (Next->getBeginLoc() != D->getBeginLoc()) { 486cdce2fe5SMarcel Hlopko return true; 487cdce2fe5SMarcel Hlopko } 488cdce2fe5SMarcel Hlopko 489cdce2fe5SMarcel Hlopko // NextT is a member of the same declaration, and we need the last member to 490cdce2fe5SMarcel Hlopko // create declaration. This one is not responsible. 491cdce2fe5SMarcel Hlopko return false; 492cdce2fe5SMarcel Hlopko } 493cdce2fe5SMarcel Hlopko 494ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getDeclarationRange(Decl *D) { 495ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> Tokens; 49688bf9b3dSMarcel Hlopko // We want to drop the template parameters for specializations. 497ba41a0f7SEduardo Caldas if (const auto *S = dyn_cast<TagDecl>(D)) 49888bf9b3dSMarcel Hlopko Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc()); 49988bf9b3dSMarcel Hlopko else 500a711a3a4SMarcel Hlopko Tokens = getRange(D->getSourceRange()); 50188bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D); 5029b3f38f9SIlya Biryukov } 503cdce2fe5SMarcel Hlopko 504ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getExprRange(const Expr *E) const { 505a711a3a4SMarcel Hlopko return getRange(E->getSourceRange()); 50658fa50f4SIlya Biryukov } 507cdce2fe5SMarcel Hlopko 50858fa50f4SIlya Biryukov /// Find the adjusted range for the statement, consuming the trailing 50958fa50f4SIlya Biryukov /// semicolon when needed. 510ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const { 511a711a3a4SMarcel Hlopko auto Tokens = getRange(S->getSourceRange()); 51258fa50f4SIlya Biryukov if (isa<CompoundStmt>(S)) 51358fa50f4SIlya Biryukov return Tokens; 51458fa50f4SIlya Biryukov 51558fa50f4SIlya Biryukov // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and 51658fa50f4SIlya Biryukov // all statements that end with those. Consume this semicolon here. 517e702bdb8SIlya Biryukov if (Tokens.back().kind() == tok::semi) 518e702bdb8SIlya Biryukov return Tokens; 519e702bdb8SIlya Biryukov return withTrailingSemicolon(Tokens); 520e702bdb8SIlya Biryukov } 521e702bdb8SIlya Biryukov 522e702bdb8SIlya Biryukov private: 523ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens, 52488bf9b3dSMarcel Hlopko const Decl *D) const { 525ba41a0f7SEduardo Caldas if (isa<NamespaceDecl>(D)) 52688bf9b3dSMarcel Hlopko return Tokens; 52788bf9b3dSMarcel Hlopko if (DeclsWithoutSemicolons.count(D)) 52888bf9b3dSMarcel Hlopko return Tokens; 52988bf9b3dSMarcel Hlopko // FIXME: do not consume trailing semicolon on function definitions. 53088bf9b3dSMarcel Hlopko // Most declarations own a semicolon in syntax trees, but not in clang AST. 53188bf9b3dSMarcel Hlopko return withTrailingSemicolon(Tokens); 53288bf9b3dSMarcel Hlopko } 53388bf9b3dSMarcel Hlopko 534ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> 535ba41a0f7SEduardo Caldas withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const { 536e702bdb8SIlya Biryukov assert(!Tokens.empty()); 537e702bdb8SIlya Biryukov assert(Tokens.back().kind() != tok::eof); 5387d382dcdSMarcel Hlopko // We never consume 'eof', so looking at the next token is ok. 53958fa50f4SIlya Biryukov if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi) 54058fa50f4SIlya Biryukov return llvm::makeArrayRef(Tokens.begin(), Tokens.end() + 1); 54158fa50f4SIlya Biryukov return Tokens; 5429b3f38f9SIlya Biryukov } 5439b3f38f9SIlya Biryukov 544a711a3a4SMarcel Hlopko void setRole(syntax::Node *N, NodeRole R) { 5454c14ee61SEduardo Caldas assert(N->getRole() == NodeRole::Detached); 546a711a3a4SMarcel Hlopko N->setRole(R); 547a711a3a4SMarcel Hlopko } 548a711a3a4SMarcel Hlopko 5499b3f38f9SIlya Biryukov /// A collection of trees covering the input tokens. 5509b3f38f9SIlya Biryukov /// When created, each tree corresponds to a single token in the file. 5519b3f38f9SIlya Biryukov /// Clients call 'foldChildren' to attach one or more subtrees to a parent 5529b3f38f9SIlya Biryukov /// node and update the list of trees accordingly. 5539b3f38f9SIlya Biryukov /// 5549b3f38f9SIlya Biryukov /// Ensures that added nodes properly nest and cover the whole token stream. 5559b3f38f9SIlya Biryukov struct Forest { 5569b3f38f9SIlya Biryukov Forest(syntax::Arena &A) { 5574c14ee61SEduardo Caldas assert(!A.getTokenBuffer().expandedTokens().empty()); 5584c14ee61SEduardo Caldas assert(A.getTokenBuffer().expandedTokens().back().kind() == tok::eof); 5599b3f38f9SIlya Biryukov // Create all leaf nodes. 560bfbf6b6cSIlya Biryukov // Note that we do not have 'eof' in the tree. 561238ae4eeSEduardo Caldas for (const auto &T : A.getTokenBuffer().expandedTokens().drop_back()) { 5624c14ee61SEduardo Caldas auto *L = new (A.getAllocator()) syntax::Leaf(&T); 5631ad15046SIlya Biryukov L->Original = true; 5644c14ee61SEduardo Caldas L->CanModify = A.getTokenBuffer().spelledForExpanded(T).hasValue(); 565a711a3a4SMarcel Hlopko Trees.insert(Trees.end(), {&T, L}); 5661ad15046SIlya Biryukov } 5679b3f38f9SIlya Biryukov } 5689b3f38f9SIlya Biryukov 569ba41a0f7SEduardo Caldas void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) { 5709b3f38f9SIlya Biryukov assert(!Range.empty()); 5719b3f38f9SIlya Biryukov auto It = Trees.lower_bound(Range.begin()); 5729b3f38f9SIlya Biryukov assert(It != Trees.end() && "no node found"); 5739b3f38f9SIlya Biryukov assert(It->first == Range.begin() && "no child with the specified range"); 5749b3f38f9SIlya Biryukov assert((std::next(It) == Trees.end() || 5759b3f38f9SIlya Biryukov std::next(It)->first == Range.end()) && 5769b3f38f9SIlya Biryukov "no child with the specified range"); 5774c14ee61SEduardo Caldas assert(It->second->getRole() == NodeRole::Detached && 578a711a3a4SMarcel Hlopko "re-assigning role for a child"); 579a711a3a4SMarcel Hlopko It->second->setRole(Role); 5809b3f38f9SIlya Biryukov } 5819b3f38f9SIlya Biryukov 582e702bdb8SIlya Biryukov /// Add \p Node to the forest and attach child nodes based on \p Tokens. 583ba41a0f7SEduardo Caldas void foldChildren(const syntax::Arena &A, ArrayRef<syntax::Token> Tokens, 5849b3f38f9SIlya Biryukov syntax::Tree *Node) { 585e702bdb8SIlya Biryukov // Attach children to `Node`. 5864c14ee61SEduardo Caldas assert(Node->getFirstChild() == nullptr && "node already has children"); 587cdce2fe5SMarcel Hlopko 588cdce2fe5SMarcel Hlopko auto *FirstToken = Tokens.begin(); 589cdce2fe5SMarcel Hlopko auto BeginChildren = Trees.lower_bound(FirstToken); 590cdce2fe5SMarcel Hlopko 591cdce2fe5SMarcel Hlopko assert((BeginChildren == Trees.end() || 592cdce2fe5SMarcel Hlopko BeginChildren->first == FirstToken) && 593cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees"); 594cdce2fe5SMarcel Hlopko auto EndChildren = Trees.lower_bound(Tokens.end()); 595cdce2fe5SMarcel Hlopko assert( 596cdce2fe5SMarcel Hlopko (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) && 597cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees"); 598cdce2fe5SMarcel Hlopko 599cdce2fe5SMarcel Hlopko // We need to go in reverse order, because we can only prepend. 600cdce2fe5SMarcel Hlopko for (auto It = EndChildren; It != BeginChildren; --It) { 601cdce2fe5SMarcel Hlopko auto *C = std::prev(It)->second; 6024c14ee61SEduardo Caldas if (C->getRole() == NodeRole::Detached) 603cdce2fe5SMarcel Hlopko C->setRole(NodeRole::Unknown); 604cdce2fe5SMarcel Hlopko Node->prependChildLowLevel(C); 605e702bdb8SIlya Biryukov } 6069b3f38f9SIlya Biryukov 607cdce2fe5SMarcel Hlopko // Mark that this node came from the AST and is backed by the source code. 608cdce2fe5SMarcel Hlopko Node->Original = true; 6094c14ee61SEduardo Caldas Node->CanModify = 6104c14ee61SEduardo Caldas A.getTokenBuffer().spelledForExpanded(Tokens).hasValue(); 6119b3f38f9SIlya Biryukov 612cdce2fe5SMarcel Hlopko Trees.erase(BeginChildren, EndChildren); 613cdce2fe5SMarcel Hlopko Trees.insert({FirstToken, Node}); 6149b3f38f9SIlya Biryukov } 6159b3f38f9SIlya Biryukov 6169b3f38f9SIlya Biryukov // EXPECTS: all tokens were consumed and are owned by a single root node. 6179b3f38f9SIlya Biryukov syntax::Node *finalize() && { 6189b3f38f9SIlya Biryukov assert(Trees.size() == 1); 619a711a3a4SMarcel Hlopko auto *Root = Trees.begin()->second; 6209b3f38f9SIlya Biryukov Trees = {}; 6219b3f38f9SIlya Biryukov return Root; 6229b3f38f9SIlya Biryukov } 6239b3f38f9SIlya Biryukov 6249b3f38f9SIlya Biryukov std::string str(const syntax::Arena &A) const { 6259b3f38f9SIlya Biryukov std::string R; 6269b3f38f9SIlya Biryukov for (auto It = Trees.begin(); It != Trees.end(); ++It) { 6279b3f38f9SIlya Biryukov unsigned CoveredTokens = 6289b3f38f9SIlya Biryukov It != Trees.end() 6299b3f38f9SIlya Biryukov ? (std::next(It)->first - It->first) 6304c14ee61SEduardo Caldas : A.getTokenBuffer().expandedTokens().end() - It->first; 6319b3f38f9SIlya Biryukov 632ba41a0f7SEduardo Caldas R += std::string( 6334c14ee61SEduardo Caldas formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(), 6344c14ee61SEduardo Caldas It->first->text(A.getSourceManager()), CoveredTokens)); 6354c14ee61SEduardo Caldas R += It->second->dump(A.getSourceManager()); 6369b3f38f9SIlya Biryukov } 6379b3f38f9SIlya Biryukov return R; 6389b3f38f9SIlya Biryukov } 6399b3f38f9SIlya Biryukov 6409b3f38f9SIlya Biryukov private: 6419b3f38f9SIlya Biryukov /// Maps from the start token to a subtree starting at that token. 642302cb3bcSIlya Biryukov /// Keys in the map are pointers into the array of expanded tokens, so 643302cb3bcSIlya Biryukov /// pointer order corresponds to the order of preprocessor tokens. 644a711a3a4SMarcel Hlopko std::map<const syntax::Token *, syntax::Node *> Trees; 6459b3f38f9SIlya Biryukov }; 6469b3f38f9SIlya Biryukov 6479b3f38f9SIlya Biryukov /// For debugging purposes. 6489b3f38f9SIlya Biryukov std::string str() { return Pending.str(Arena); } 6499b3f38f9SIlya Biryukov 6509b3f38f9SIlya Biryukov syntax::Arena &Arena; 651c1bbefefSIlya Biryukov /// To quickly find tokens by their start location. 652c1bbefefSIlya Biryukov llvm::DenseMap</*SourceLocation*/ unsigned, const syntax::Token *> 653c1bbefefSIlya Biryukov LocationToToken; 6549b3f38f9SIlya Biryukov Forest Pending; 655e702bdb8SIlya Biryukov llvm::DenseSet<Decl *> DeclsWithoutSemicolons; 656a711a3a4SMarcel Hlopko ASTToSyntaxMapping Mapping; 6579b3f38f9SIlya Biryukov }; 6589b3f38f9SIlya Biryukov 6599b3f38f9SIlya Biryukov namespace { 6609b3f38f9SIlya Biryukov class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> { 6619b3f38f9SIlya Biryukov public: 6621db5b348SEduardo Caldas explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder) 6631db5b348SEduardo Caldas : Builder(Builder), Context(Context) {} 6649b3f38f9SIlya Biryukov 6659b3f38f9SIlya Biryukov bool shouldTraversePostOrder() const { return true; } 6669b3f38f9SIlya Biryukov 6677d382dcdSMarcel Hlopko bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) { 668cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(DD); 6697d382dcdSMarcel Hlopko } 6707d382dcdSMarcel Hlopko 671cdce2fe5SMarcel Hlopko bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) { 672cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(TD); 6739b3f38f9SIlya Biryukov } 6749b3f38f9SIlya Biryukov 6759b3f38f9SIlya Biryukov bool VisitDecl(Decl *D) { 6769b3f38f9SIlya Biryukov assert(!D->isImplicit()); 677cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(D), 678a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownDeclaration(), D); 679e702bdb8SIlya Biryukov return true; 680e702bdb8SIlya Biryukov } 681e702bdb8SIlya Biryukov 68288bf9b3dSMarcel Hlopko // RAV does not call WalkUpFrom* on explicit instantiations, so we have to 68388bf9b3dSMarcel Hlopko // override Traverse. 68488bf9b3dSMarcel Hlopko // FIXME: make RAV call WalkUpFrom* instead. 68588bf9b3dSMarcel Hlopko bool 68688bf9b3dSMarcel Hlopko TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) { 68788bf9b3dSMarcel Hlopko if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C)) 68888bf9b3dSMarcel Hlopko return false; 68988bf9b3dSMarcel Hlopko if (C->isExplicitSpecialization()) 69088bf9b3dSMarcel Hlopko return true; // we are only interested in explicit instantiations. 691a711a3a4SMarcel Hlopko auto *Declaration = 692a711a3a4SMarcel Hlopko cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C)); 69388bf9b3dSMarcel Hlopko foldExplicitTemplateInstantiation( 69488bf9b3dSMarcel Hlopko Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()), 695a711a3a4SMarcel Hlopko Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C); 69688bf9b3dSMarcel Hlopko return true; 69788bf9b3dSMarcel Hlopko } 69888bf9b3dSMarcel Hlopko 69988bf9b3dSMarcel Hlopko bool WalkUpFromTemplateDecl(TemplateDecl *S) { 70088bf9b3dSMarcel Hlopko foldTemplateDeclaration( 701cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S), 70288bf9b3dSMarcel Hlopko Builder.findToken(S->getTemplateParameters()->getTemplateLoc()), 703cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S->getTemplatedDecl()), S); 70488bf9b3dSMarcel Hlopko return true; 70588bf9b3dSMarcel Hlopko } 70688bf9b3dSMarcel Hlopko 707e702bdb8SIlya Biryukov bool WalkUpFromTagDecl(TagDecl *C) { 70804f627f6SIlya Biryukov // FIXME: build the ClassSpecifier node. 70988bf9b3dSMarcel Hlopko if (!C->isFreeStanding()) { 71088bf9b3dSMarcel Hlopko assert(C->getNumTemplateParameterLists() == 0); 71104f627f6SIlya Biryukov return true; 71204f627f6SIlya Biryukov } 713a711a3a4SMarcel Hlopko handleFreeStandingTagDecl(C); 714a711a3a4SMarcel Hlopko return true; 715a711a3a4SMarcel Hlopko } 716a711a3a4SMarcel Hlopko 717a711a3a4SMarcel Hlopko syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) { 718a711a3a4SMarcel Hlopko assert(C->isFreeStanding()); 71988bf9b3dSMarcel Hlopko // Class is a declaration specifier and needs a spanning declaration node. 720cdce2fe5SMarcel Hlopko auto DeclarationRange = Builder.getDeclarationRange(C); 721a711a3a4SMarcel Hlopko syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration; 722a711a3a4SMarcel Hlopko Builder.foldNode(DeclarationRange, Result, nullptr); 72388bf9b3dSMarcel Hlopko 72488bf9b3dSMarcel Hlopko // Build TemplateDeclaration nodes if we had template parameters. 72588bf9b3dSMarcel Hlopko auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) { 72688bf9b3dSMarcel Hlopko const auto *TemplateKW = Builder.findToken(L.getTemplateLoc()); 72788bf9b3dSMarcel Hlopko auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end()); 728a711a3a4SMarcel Hlopko Result = 729a711a3a4SMarcel Hlopko foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr); 73088bf9b3dSMarcel Hlopko DeclarationRange = R; 73188bf9b3dSMarcel Hlopko }; 732ba41a0f7SEduardo Caldas if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C)) 73388bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*S->getTemplateParameters()); 73488bf9b3dSMarcel Hlopko for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I) 73588bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1)); 736a711a3a4SMarcel Hlopko return Result; 7379b3f38f9SIlya Biryukov } 7389b3f38f9SIlya Biryukov 7399b3f38f9SIlya Biryukov bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) { 7407d382dcdSMarcel Hlopko // We do not want to call VisitDecl(), the declaration for translation 7419b3f38f9SIlya Biryukov // unit is built by finalize(). 7429b3f38f9SIlya Biryukov return true; 7439b3f38f9SIlya Biryukov } 7449b3f38f9SIlya Biryukov 7459b3f38f9SIlya Biryukov bool WalkUpFromCompoundStmt(CompoundStmt *S) { 74651dad419SIlya Biryukov using NodeRole = syntax::NodeRole; 7479b3f38f9SIlya Biryukov 748def65bb4SIlya Biryukov Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen); 74958fa50f4SIlya Biryukov for (auto *Child : S->body()) 750718e550cSEduardo Caldas Builder.markStmtChild(Child, NodeRole::Statement); 751def65bb4SIlya Biryukov Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen); 7529b3f38f9SIlya Biryukov 75358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 754a711a3a4SMarcel Hlopko new (allocator()) syntax::CompoundStatement, S); 7559b3f38f9SIlya Biryukov return true; 7569b3f38f9SIlya Biryukov } 7579b3f38f9SIlya Biryukov 75858fa50f4SIlya Biryukov // Some statements are not yet handled by syntax trees. 75958fa50f4SIlya Biryukov bool WalkUpFromStmt(Stmt *S) { 76058fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 761a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownStatement, S); 76258fa50f4SIlya Biryukov return true; 76358fa50f4SIlya Biryukov } 76458fa50f4SIlya Biryukov 76558fa50f4SIlya Biryukov bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) { 76658fa50f4SIlya Biryukov // We override to traverse range initializer as VarDecl. 76758fa50f4SIlya Biryukov // RAV traverses it as a statement, we produce invalid node kinds in that 76858fa50f4SIlya Biryukov // case. 76958fa50f4SIlya Biryukov // FIXME: should do this in RAV instead? 7707349479fSDmitri Gribenko bool Result = [&, this]() { 77158fa50f4SIlya Biryukov if (S->getInit() && !TraverseStmt(S->getInit())) 77258fa50f4SIlya Biryukov return false; 77358fa50f4SIlya Biryukov if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable())) 77458fa50f4SIlya Biryukov return false; 77558fa50f4SIlya Biryukov if (S->getRangeInit() && !TraverseStmt(S->getRangeInit())) 77658fa50f4SIlya Biryukov return false; 77758fa50f4SIlya Biryukov if (S->getBody() && !TraverseStmt(S->getBody())) 77858fa50f4SIlya Biryukov return false; 77958fa50f4SIlya Biryukov return true; 7807349479fSDmitri Gribenko }(); 7817349479fSDmitri Gribenko WalkUpFromCXXForRangeStmt(S); 7827349479fSDmitri Gribenko return Result; 78358fa50f4SIlya Biryukov } 78458fa50f4SIlya Biryukov 78558fa50f4SIlya Biryukov bool TraverseStmt(Stmt *S) { 786ba41a0f7SEduardo Caldas if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) { 787e702bdb8SIlya Biryukov // We want to consume the semicolon, make sure SimpleDeclaration does not. 788e702bdb8SIlya Biryukov for (auto *D : DS->decls()) 7897d382dcdSMarcel Hlopko Builder.noticeDeclWithoutSemicolon(D); 790ba41a0f7SEduardo Caldas } else if (auto *E = dyn_cast_or_null<Expr>(S)) { 7912325d6b4SEduardo Caldas return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E)); 79258fa50f4SIlya Biryukov } 79358fa50f4SIlya Biryukov return RecursiveASTVisitor::TraverseStmt(S); 79458fa50f4SIlya Biryukov } 79558fa50f4SIlya Biryukov 79658fa50f4SIlya Biryukov // Some expressions are not yet handled by syntax trees. 79758fa50f4SIlya Biryukov bool WalkUpFromExpr(Expr *E) { 79858fa50f4SIlya Biryukov assert(!isImplicitExpr(E) && "should be handled by TraverseStmt"); 79958fa50f4SIlya Biryukov Builder.foldNode(Builder.getExprRange(E), 800a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownExpression, E); 80158fa50f4SIlya Biryukov return true; 80258fa50f4SIlya Biryukov } 80358fa50f4SIlya Biryukov 804f33c2c27SEduardo Caldas bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) { 805f33c2c27SEduardo Caldas // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node 806f33c2c27SEduardo Caldas // referencing the location of the UDL suffix (`_w` in `1.2_w`). The 807f33c2c27SEduardo Caldas // UDL suffix location does not point to the beginning of a token, so we 808f33c2c27SEduardo Caldas // can't represent the UDL suffix as a separate syntax tree node. 809f33c2c27SEduardo Caldas 810f33c2c27SEduardo Caldas return WalkUpFromUserDefinedLiteral(S); 811f33c2c27SEduardo Caldas } 812f33c2c27SEduardo Caldas 8131db5b348SEduardo Caldas syntax::UserDefinedLiteralExpression * 8141db5b348SEduardo Caldas buildUserDefinedLiteral(UserDefinedLiteral *S) { 815f33c2c27SEduardo Caldas switch (S->getLiteralOperatorKind()) { 816ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Integer: 8171db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 818ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Floating: 8191db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 820ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Character: 8211db5b348SEduardo Caldas return new (allocator()) syntax::CharUserDefinedLiteralExpression; 822ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_String: 8231db5b348SEduardo Caldas return new (allocator()) syntax::StringUserDefinedLiteralExpression; 824ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Raw: 825ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Template: 8261db5b348SEduardo Caldas // For raw literal operator and numeric literal operator template we 8271db5b348SEduardo Caldas // cannot get the type of the operand in the semantic AST. We get this 8281db5b348SEduardo Caldas // information from the token. As integer and floating point have the same 8291db5b348SEduardo Caldas // token kind, we run `NumericLiteralParser` again to distinguish them. 8301db5b348SEduardo Caldas auto TokLoc = S->getBeginLoc(); 8311db5b348SEduardo Caldas auto TokSpelling = 832a474d5baSEduardo Caldas Builder.findToken(TokLoc)->text(Context.getSourceManager()); 8331db5b348SEduardo Caldas auto Literal = 8341db5b348SEduardo Caldas NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(), 8351db5b348SEduardo Caldas Context.getLangOpts(), Context.getTargetInfo(), 8361db5b348SEduardo Caldas Context.getDiagnostics()); 8371db5b348SEduardo Caldas if (Literal.isIntegerLiteral()) 8381db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 839a474d5baSEduardo Caldas else { 840a474d5baSEduardo Caldas assert(Literal.isFloatingLiteral()); 8411db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 842f33c2c27SEduardo Caldas } 843f33c2c27SEduardo Caldas } 844b8409c03SMichael Liao llvm_unreachable("Unknown literal operator kind."); 845a474d5baSEduardo Caldas } 846f33c2c27SEduardo Caldas 847f33c2c27SEduardo Caldas bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) { 848f33c2c27SEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 8491db5b348SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S); 850f33c2c27SEduardo Caldas return true; 851f33c2c27SEduardo Caldas } 852f33c2c27SEduardo Caldas 8538abb5fb6SEduardo Caldas // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the 8548abb5fb6SEduardo Caldas // `DependentTemplateSpecializationType` case. 855f9500cc4SEduardo Caldas /// Given a nested-name-specifier return the range for the last name 856f9500cc4SEduardo Caldas /// specifier. 8578abb5fb6SEduardo Caldas /// 8588abb5fb6SEduardo Caldas /// e.g. `std::T::template X<U>::` => `template X<U>::` 8598abb5fb6SEduardo Caldas SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) { 8608abb5fb6SEduardo Caldas auto SR = NNSLoc.getLocalSourceRange(); 8618abb5fb6SEduardo Caldas 862f9500cc4SEduardo Caldas // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should* 863f9500cc4SEduardo Caldas // return the desired `SourceRange`, but there is a corner case. For a 864f9500cc4SEduardo Caldas // `DependentTemplateSpecializationType` this method returns its 8658abb5fb6SEduardo Caldas // qualifiers as well, in other words in the example above this method 8668abb5fb6SEduardo Caldas // returns `T::template X<U>::` instead of only `template X<U>::` 8678abb5fb6SEduardo Caldas if (auto TL = NNSLoc.getTypeLoc()) { 8688abb5fb6SEduardo Caldas if (auto DependentTL = 8698abb5fb6SEduardo Caldas TL.getAs<DependentTemplateSpecializationTypeLoc>()) { 8708abb5fb6SEduardo Caldas // The 'template' keyword is always present in dependent template 8718abb5fb6SEduardo Caldas // specializations. Except in the case of incorrect code 8728abb5fb6SEduardo Caldas // TODO: Treat the case of incorrect code. 8738abb5fb6SEduardo Caldas SR.setBegin(DependentTL.getTemplateKeywordLoc()); 8748abb5fb6SEduardo Caldas } 8758abb5fb6SEduardo Caldas } 8768abb5fb6SEduardo Caldas 8778abb5fb6SEduardo Caldas return SR; 8788abb5fb6SEduardo Caldas } 8798abb5fb6SEduardo Caldas 880f9500cc4SEduardo Caldas syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) { 881f9500cc4SEduardo Caldas switch (NNS.getKind()) { 882f9500cc4SEduardo Caldas case NestedNameSpecifier::Global: 883f9500cc4SEduardo Caldas return syntax::NodeKind::GlobalNameSpecifier; 884f9500cc4SEduardo Caldas case NestedNameSpecifier::Namespace: 885f9500cc4SEduardo Caldas case NestedNameSpecifier::NamespaceAlias: 886f9500cc4SEduardo Caldas case NestedNameSpecifier::Identifier: 887f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 888f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpecWithTemplate: 889f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 890f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpec: { 891f9500cc4SEduardo Caldas const auto *NNSType = NNS.getAsType(); 892f9500cc4SEduardo Caldas assert(NNSType); 893f9500cc4SEduardo Caldas if (isa<DecltypeType>(NNSType)) 894f9500cc4SEduardo Caldas return syntax::NodeKind::DecltypeNameSpecifier; 895f9500cc4SEduardo Caldas if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>( 896f9500cc4SEduardo Caldas NNSType)) 897f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 898f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 899f9500cc4SEduardo Caldas } 900f9500cc4SEduardo Caldas default: 901f9500cc4SEduardo Caldas // FIXME: Support Microsoft's __super 902f9500cc4SEduardo Caldas llvm::report_fatal_error("We don't yet support the __super specifier", 903f9500cc4SEduardo Caldas true); 904f9500cc4SEduardo Caldas } 905f9500cc4SEduardo Caldas } 906f9500cc4SEduardo Caldas 907f9500cc4SEduardo Caldas syntax::NameSpecifier * 908ac87a0b5SEduardo Caldas buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) { 909f9500cc4SEduardo Caldas assert(NNSLoc.hasQualifier()); 910f9500cc4SEduardo Caldas auto NameSpecifierTokens = 911f9500cc4SEduardo Caldas Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back(); 912f9500cc4SEduardo Caldas switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) { 913f9500cc4SEduardo Caldas case syntax::NodeKind::GlobalNameSpecifier: 914f9500cc4SEduardo Caldas return new (allocator()) syntax::GlobalNameSpecifier; 915f9500cc4SEduardo Caldas case syntax::NodeKind::IdentifierNameSpecifier: { 916f9500cc4SEduardo Caldas assert(NameSpecifierTokens.size() == 1); 917f9500cc4SEduardo Caldas Builder.markChildToken(NameSpecifierTokens.begin(), 918f9500cc4SEduardo Caldas syntax::NodeRole::Unknown); 919f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::IdentifierNameSpecifier; 920f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 921f9500cc4SEduardo Caldas return NS; 922f9500cc4SEduardo Caldas } 923f9500cc4SEduardo Caldas case syntax::NodeKind::SimpleTemplateNameSpecifier: { 924f9500cc4SEduardo Caldas // TODO: Build `SimpleTemplateNameSpecifier` children and implement 925f9500cc4SEduardo Caldas // accessors to them. 926f9500cc4SEduardo Caldas // Be aware, we cannot do that simply by calling `TraverseTypeLoc`, 927f9500cc4SEduardo Caldas // some `TypeLoc`s have inside them the previous name specifier and 928f9500cc4SEduardo Caldas // we want to treat them independently. 929f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier; 930f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 931f9500cc4SEduardo Caldas return NS; 932f9500cc4SEduardo Caldas } 933f9500cc4SEduardo Caldas case syntax::NodeKind::DecltypeNameSpecifier: { 934f9500cc4SEduardo Caldas const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>(); 935f9500cc4SEduardo Caldas if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL)) 9368abb5fb6SEduardo Caldas return nullptr; 937f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::DecltypeNameSpecifier; 938f9500cc4SEduardo Caldas // TODO: Implement accessor to `DecltypeNameSpecifier` inner 939f9500cc4SEduardo Caldas // `DecltypeTypeLoc`. 940f9500cc4SEduardo Caldas // For that add mapping from `TypeLoc` to `syntax::Node*` then: 941f9500cc4SEduardo Caldas // Builder.markChild(TypeLoc, syntax::NodeRole); 942f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 943f9500cc4SEduardo Caldas return NS; 944f9500cc4SEduardo Caldas } 945f9500cc4SEduardo Caldas default: 946f9500cc4SEduardo Caldas llvm_unreachable("getChildKind() does not return this value"); 947f9500cc4SEduardo Caldas } 948f9500cc4SEduardo Caldas } 949f9500cc4SEduardo Caldas 950f9500cc4SEduardo Caldas // To build syntax tree nodes for NestedNameSpecifierLoc we override 951f9500cc4SEduardo Caldas // Traverse instead of WalkUpFrom because we want to traverse the children 952f9500cc4SEduardo Caldas // ourselves and build a list instead of a nested tree of name specifier 953f9500cc4SEduardo Caldas // prefixes. 954f9500cc4SEduardo Caldas bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) { 955f9500cc4SEduardo Caldas if (!QualifierLoc) 956f9500cc4SEduardo Caldas return true; 957*87f0b51dSEduardo Caldas for (auto It = QualifierLoc; It; It = It.getPrefix()) { 958*87f0b51dSEduardo Caldas auto *NS = buildNameSpecifier(It); 959f9500cc4SEduardo Caldas if (!NS) 960f9500cc4SEduardo Caldas return false; 961718e550cSEduardo Caldas Builder.markChild(NS, syntax::NodeRole::ListElement); 962*87f0b51dSEduardo Caldas Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter); 9638abb5fb6SEduardo Caldas } 964f9500cc4SEduardo Caldas Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()), 965f9500cc4SEduardo Caldas new (allocator()) syntax::NestedNameSpecifier, 9668abb5fb6SEduardo Caldas QualifierLoc); 967f9500cc4SEduardo Caldas return true; 9688abb5fb6SEduardo Caldas } 9698abb5fb6SEduardo Caldas 970a4ef9e86SEduardo Caldas syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc, 971a4ef9e86SEduardo Caldas SourceLocation TemplateKeywordLoc, 972a4ef9e86SEduardo Caldas SourceRange UnqualifiedIdLoc, 973a4ef9e86SEduardo Caldas ASTPtr From) { 974a4ef9e86SEduardo Caldas if (QualifierLoc) { 975718e550cSEduardo Caldas Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier); 976ba32915dSEduardo Caldas if (TemplateKeywordLoc.isValid()) 977ba32915dSEduardo Caldas Builder.markChildToken(TemplateKeywordLoc, 978ba32915dSEduardo Caldas syntax::NodeRole::TemplateKeyword); 979a4ef9e86SEduardo Caldas } 980ba32915dSEduardo Caldas 981ba32915dSEduardo Caldas auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId; 982a4ef9e86SEduardo Caldas Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId, 983a4ef9e86SEduardo Caldas nullptr); 984718e550cSEduardo Caldas Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId); 985ba32915dSEduardo Caldas 986a4ef9e86SEduardo Caldas auto IdExpressionBeginLoc = 987a4ef9e86SEduardo Caldas QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin(); 988ba32915dSEduardo Caldas 989a4ef9e86SEduardo Caldas auto *TheIdExpression = new (allocator()) syntax::IdExpression; 990a4ef9e86SEduardo Caldas Builder.foldNode( 991a4ef9e86SEduardo Caldas Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()), 992a4ef9e86SEduardo Caldas TheIdExpression, From); 993a4ef9e86SEduardo Caldas 994a4ef9e86SEduardo Caldas return TheIdExpression; 995a4ef9e86SEduardo Caldas } 996a4ef9e86SEduardo Caldas 997a4ef9e86SEduardo Caldas bool WalkUpFromMemberExpr(MemberExpr *S) { 998ba32915dSEduardo Caldas // For `MemberExpr` with implicit `this->` we generate a simple 999ba32915dSEduardo Caldas // `id-expression` syntax node, beacuse an implicit `member-expression` is 1000ba32915dSEduardo Caldas // syntactically undistinguishable from an `id-expression` 1001ba32915dSEduardo Caldas if (S->isImplicitAccess()) { 1002a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1003a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), S); 1004ba32915dSEduardo Caldas return true; 1005ba32915dSEduardo Caldas } 1006a4ef9e86SEduardo Caldas 1007a4ef9e86SEduardo Caldas auto *TheIdExpression = buildIdExpression( 1008a4ef9e86SEduardo Caldas S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1009a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr); 1010ba32915dSEduardo Caldas 1011718e550cSEduardo Caldas Builder.markChild(TheIdExpression, syntax::NodeRole::Member); 1012ba32915dSEduardo Caldas 1013718e550cSEduardo Caldas Builder.markExprChild(S->getBase(), syntax::NodeRole::Object); 1014718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken); 1015ba32915dSEduardo Caldas 1016ba32915dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1017ba32915dSEduardo Caldas new (allocator()) syntax::MemberExpression, S); 1018ba32915dSEduardo Caldas return true; 1019ba32915dSEduardo Caldas } 1020ba32915dSEduardo Caldas 10211b2f6b4aSEduardo Caldas bool WalkUpFromDeclRefExpr(DeclRefExpr *S) { 1022a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1023a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 10248abb5fb6SEduardo Caldas 10258abb5fb6SEduardo Caldas return true; 10261b2f6b4aSEduardo Caldas } 10278abb5fb6SEduardo Caldas 10288abb5fb6SEduardo Caldas // Same logic as DeclRefExpr. 10298abb5fb6SEduardo Caldas bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) { 1030a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1031a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 10328abb5fb6SEduardo Caldas 10331b2f6b4aSEduardo Caldas return true; 10341b2f6b4aSEduardo Caldas } 10351b2f6b4aSEduardo Caldas 103685c15f17SEduardo Caldas bool WalkUpFromCXXThisExpr(CXXThisExpr *S) { 103785c15f17SEduardo Caldas if (!S->isImplicit()) { 103885c15f17SEduardo Caldas Builder.markChildToken(S->getLocation(), 103985c15f17SEduardo Caldas syntax::NodeRole::IntroducerKeyword); 104085c15f17SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 104185c15f17SEduardo Caldas new (allocator()) syntax::ThisExpression, S); 104285c15f17SEduardo Caldas } 104385c15f17SEduardo Caldas return true; 104485c15f17SEduardo Caldas } 104585c15f17SEduardo Caldas 1046fdbd7833SEduardo Caldas bool WalkUpFromParenExpr(ParenExpr *S) { 1047fdbd7833SEduardo Caldas Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen); 1048718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression); 1049fdbd7833SEduardo Caldas Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen); 1050fdbd7833SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1051fdbd7833SEduardo Caldas new (allocator()) syntax::ParenExpression, S); 1052fdbd7833SEduardo Caldas return true; 1053fdbd7833SEduardo Caldas } 1054fdbd7833SEduardo Caldas 10553b739690SEduardo Caldas bool WalkUpFromIntegerLiteral(IntegerLiteral *S) { 105642f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 10573b739690SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 10583b739690SEduardo Caldas new (allocator()) syntax::IntegerLiteralExpression, S); 10593b739690SEduardo Caldas return true; 10603b739690SEduardo Caldas } 10613b739690SEduardo Caldas 1062221d7bbeSEduardo Caldas bool WalkUpFromCharacterLiteral(CharacterLiteral *S) { 1063221d7bbeSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1064221d7bbeSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1065221d7bbeSEduardo Caldas new (allocator()) syntax::CharacterLiteralExpression, S); 1066221d7bbeSEduardo Caldas return true; 1067221d7bbeSEduardo Caldas } 10687b404b6dSEduardo Caldas 10697b404b6dSEduardo Caldas bool WalkUpFromFloatingLiteral(FloatingLiteral *S) { 10707b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 10717b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 10727b404b6dSEduardo Caldas new (allocator()) syntax::FloatingLiteralExpression, S); 10737b404b6dSEduardo Caldas return true; 10747b404b6dSEduardo Caldas } 10757b404b6dSEduardo Caldas 1076466e8b7eSEduardo Caldas bool WalkUpFromStringLiteral(StringLiteral *S) { 1077466e8b7eSEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 1078466e8b7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1079466e8b7eSEduardo Caldas new (allocator()) syntax::StringLiteralExpression, S); 1080466e8b7eSEduardo Caldas return true; 1081466e8b7eSEduardo Caldas } 1082221d7bbeSEduardo Caldas 10837b404b6dSEduardo Caldas bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) { 10847b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 10857b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 10867b404b6dSEduardo Caldas new (allocator()) syntax::BoolLiteralExpression, S); 10877b404b6dSEduardo Caldas return true; 10887b404b6dSEduardo Caldas } 10897b404b6dSEduardo Caldas 1090007098d7SEduardo Caldas bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) { 109142f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1092007098d7SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1093007098d7SEduardo Caldas new (allocator()) syntax::CxxNullPtrExpression, S); 1094007098d7SEduardo Caldas return true; 1095007098d7SEduardo Caldas } 1096007098d7SEduardo Caldas 1097461af57dSEduardo Caldas bool WalkUpFromUnaryOperator(UnaryOperator *S) { 109842f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1099718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1100718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand); 1101461af57dSEduardo Caldas 1102461af57dSEduardo Caldas if (S->isPostfix()) 1103461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1104461af57dSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1105461af57dSEduardo Caldas S); 1106461af57dSEduardo Caldas else 1107461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1108461af57dSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1109461af57dSEduardo Caldas S); 1110461af57dSEduardo Caldas 1111461af57dSEduardo Caldas return true; 1112461af57dSEduardo Caldas } 1113461af57dSEduardo Caldas 11143785eb83SEduardo Caldas bool WalkUpFromBinaryOperator(BinaryOperator *S) { 1115718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide); 111642f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1117718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1118718e550cSEduardo Caldas Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide); 11193785eb83SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11203785eb83SEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 11213785eb83SEduardo Caldas return true; 11223785eb83SEduardo Caldas } 11233785eb83SEduardo Caldas 1124f5087d5cSEduardo Caldas /// Builds `CallArguments` syntax node from arguments that appear in source 1125f5087d5cSEduardo Caldas /// code, i.e. not default arguments. 1126f5087d5cSEduardo Caldas syntax::CallArguments * 1127f5087d5cSEduardo Caldas buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) { 1128f5087d5cSEduardo Caldas auto Args = dropDefaultArgs(ArgsAndDefaultArgs); 1129e10df779SDmitri Gribenko for (auto *Arg : Args) { 1130718e550cSEduardo Caldas Builder.markExprChild(Arg, syntax::NodeRole::ListElement); 11312de2ca34SEduardo Caldas const auto *DelimiterToken = 11322de2ca34SEduardo Caldas std::next(Builder.findToken(Arg->getEndLoc())); 11332de2ca34SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1134718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 11352de2ca34SEduardo Caldas } 11362de2ca34SEduardo Caldas 11372de2ca34SEduardo Caldas auto *Arguments = new (allocator()) syntax::CallArguments; 11382de2ca34SEduardo Caldas if (!Args.empty()) 11392de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(), 11402de2ca34SEduardo Caldas (*(Args.end() - 1))->getEndLoc()), 11412de2ca34SEduardo Caldas Arguments, nullptr); 11422de2ca34SEduardo Caldas 11432de2ca34SEduardo Caldas return Arguments; 11442de2ca34SEduardo Caldas } 11452de2ca34SEduardo Caldas 11462de2ca34SEduardo Caldas bool WalkUpFromCallExpr(CallExpr *S) { 1147718e550cSEduardo Caldas Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee); 11482de2ca34SEduardo Caldas 11492de2ca34SEduardo Caldas const auto *LParenToken = 11502de2ca34SEduardo Caldas std::next(Builder.findToken(S->getCallee()->getEndLoc())); 11512de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed 11522de2ca34SEduardo Caldas // the test on decltype desctructors. 11532de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 11542de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 11552de2ca34SEduardo Caldas 11562de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(S->arguments()), 1157718e550cSEduardo Caldas syntax::NodeRole::Arguments); 11582de2ca34SEduardo Caldas 11592de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 11602de2ca34SEduardo Caldas 11612de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 11622de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 11632de2ca34SEduardo Caldas return true; 11642de2ca34SEduardo Caldas } 11652de2ca34SEduardo Caldas 116646f4439dSEduardo Caldas bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) { 116746f4439dSEduardo Caldas // Ignore the implicit calls to default constructors. 116846f4439dSEduardo Caldas if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) && 116946f4439dSEduardo Caldas S->getParenOrBraceRange().isInvalid()) 117046f4439dSEduardo Caldas return true; 117146f4439dSEduardo Caldas return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S); 117246f4439dSEduardo Caldas } 117346f4439dSEduardo Caldas 1174ea8bba7eSEduardo Caldas bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1175ac37afa6SEduardo Caldas // To construct a syntax tree of the same shape for calls to built-in and 1176ac37afa6SEduardo Caldas // user-defined operators, ignore the `DeclRefExpr` that refers to the 1177ac37afa6SEduardo Caldas // operator and treat it as a simple token. Do that by traversing 1178ac37afa6SEduardo Caldas // arguments instead of children. 1179ac37afa6SEduardo Caldas for (auto *child : S->arguments()) { 1180f33c2c27SEduardo Caldas // A postfix unary operator is declared as taking two operands. The 1181f33c2c27SEduardo Caldas // second operand is used to distinguish from its prefix counterpart. In 1182f33c2c27SEduardo Caldas // the semantic AST this "phantom" operand is represented as a 1183ea8bba7eSEduardo Caldas // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this 1184ea8bba7eSEduardo Caldas // operand because it does not correspond to anything written in source 1185ac37afa6SEduardo Caldas // code. 1186ac37afa6SEduardo Caldas if (child->getSourceRange().isInvalid()) { 1187ac37afa6SEduardo Caldas assert(getOperatorNodeKind(*S) == 1188ac37afa6SEduardo Caldas syntax::NodeKind::PostfixUnaryOperatorExpression); 1189ea8bba7eSEduardo Caldas continue; 1190ac37afa6SEduardo Caldas } 1191ea8bba7eSEduardo Caldas if (!TraverseStmt(child)) 1192ea8bba7eSEduardo Caldas return false; 1193ea8bba7eSEduardo Caldas } 1194ea8bba7eSEduardo Caldas return WalkUpFromCXXOperatorCallExpr(S); 1195ea8bba7eSEduardo Caldas } 1196ea8bba7eSEduardo Caldas 11973a574a6cSEduardo Caldas bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1198ea8bba7eSEduardo Caldas switch (getOperatorNodeKind(*S)) { 1199ea8bba7eSEduardo Caldas case syntax::NodeKind::BinaryOperatorExpression: 1200718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide); 1201718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1202718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1203718e550cSEduardo Caldas Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide); 12043a574a6cSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 12053a574a6cSEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 12063a574a6cSEduardo Caldas return true; 1207ea8bba7eSEduardo Caldas case syntax::NodeKind::PrefixUnaryOperatorExpression: 1208718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1209718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1210718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1211ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1212ea8bba7eSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1213ea8bba7eSEduardo Caldas S); 1214ea8bba7eSEduardo Caldas return true; 1215ea8bba7eSEduardo Caldas case syntax::NodeKind::PostfixUnaryOperatorExpression: 1216718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1217718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1218718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1219ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1220ea8bba7eSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1221ea8bba7eSEduardo Caldas S); 1222ea8bba7eSEduardo Caldas return true; 12232de2ca34SEduardo Caldas case syntax::NodeKind::CallExpression: { 1224718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee); 12252de2ca34SEduardo Caldas 12262de2ca34SEduardo Caldas const auto *LParenToken = 12272de2ca34SEduardo Caldas std::next(Builder.findToken(S->getArg(0)->getEndLoc())); 12282de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have 12292de2ca34SEduardo Caldas // fixed the test on decltype desctructors. 12302de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 12312de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 12322de2ca34SEduardo Caldas 12332de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(CallExpr::arg_range( 12342de2ca34SEduardo Caldas S->arg_begin() + 1, S->arg_end())), 1235718e550cSEduardo Caldas syntax::NodeRole::Arguments); 12362de2ca34SEduardo Caldas 12372de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 12382de2ca34SEduardo Caldas 12392de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 12402de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 12412de2ca34SEduardo Caldas return true; 12422de2ca34SEduardo Caldas } 1243ea8bba7eSEduardo Caldas case syntax::NodeKind::UnknownExpression: 12442de2ca34SEduardo Caldas return WalkUpFromExpr(S); 1245ea8bba7eSEduardo Caldas default: 1246ea8bba7eSEduardo Caldas llvm_unreachable("getOperatorNodeKind() does not return this value"); 1247ea8bba7eSEduardo Caldas } 12483a574a6cSEduardo Caldas } 12493a574a6cSEduardo Caldas 1250f5087d5cSEduardo Caldas bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; } 1251f5087d5cSEduardo Caldas 1252be14a22bSIlya Biryukov bool WalkUpFromNamespaceDecl(NamespaceDecl *S) { 1253cdce2fe5SMarcel Hlopko auto Tokens = Builder.getDeclarationRange(S); 1254be14a22bSIlya Biryukov if (Tokens.front().kind() == tok::coloncolon) { 1255be14a22bSIlya Biryukov // Handle nested namespace definitions. Those start at '::' token, e.g. 1256be14a22bSIlya Biryukov // namespace a^::b {} 1257be14a22bSIlya Biryukov // FIXME: build corresponding nodes for the name of this namespace. 1258be14a22bSIlya Biryukov return true; 1259be14a22bSIlya Biryukov } 1260a711a3a4SMarcel Hlopko Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S); 1261be14a22bSIlya Biryukov return true; 1262be14a22bSIlya Biryukov } 1263be14a22bSIlya Biryukov 12648ce15f7eSEduardo Caldas // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test 12658ce15f7eSEduardo Caldas // results. Find test coverage or remove it. 12667d382dcdSMarcel Hlopko bool TraverseParenTypeLoc(ParenTypeLoc L) { 12677d382dcdSMarcel Hlopko // We reverse order of traversal to get the proper syntax structure. 12687d382dcdSMarcel Hlopko if (!WalkUpFromParenTypeLoc(L)) 12697d382dcdSMarcel Hlopko return false; 12707d382dcdSMarcel Hlopko return TraverseTypeLoc(L.getInnerLoc()); 12717d382dcdSMarcel Hlopko } 12727d382dcdSMarcel Hlopko 12737d382dcdSMarcel Hlopko bool WalkUpFromParenTypeLoc(ParenTypeLoc L) { 12747d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 12757d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 12767d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()), 1277a711a3a4SMarcel Hlopko new (allocator()) syntax::ParenDeclarator, L); 12787d382dcdSMarcel Hlopko return true; 12797d382dcdSMarcel Hlopko } 12807d382dcdSMarcel Hlopko 12817d382dcdSMarcel Hlopko // Declarator chunks, they are produced by type locs and some clang::Decls. 12827d382dcdSMarcel Hlopko bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) { 12837d382dcdSMarcel Hlopko Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen); 1284718e550cSEduardo Caldas Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size); 12857d382dcdSMarcel Hlopko Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen); 12867d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()), 1287a711a3a4SMarcel Hlopko new (allocator()) syntax::ArraySubscript, L); 12887d382dcdSMarcel Hlopko return true; 12897d382dcdSMarcel Hlopko } 12907d382dcdSMarcel Hlopko 1291dc3d4743SEduardo Caldas syntax::ParameterDeclarationList * 1292dc3d4743SEduardo Caldas buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) { 1293dc3d4743SEduardo Caldas for (auto *P : Params) { 1294718e550cSEduardo Caldas Builder.markChild(P, syntax::NodeRole::ListElement); 1295dc3d4743SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc())); 1296dc3d4743SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1297718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 1298dc3d4743SEduardo Caldas } 1299dc3d4743SEduardo Caldas auto *Parameters = new (allocator()) syntax::ParameterDeclarationList; 1300dc3d4743SEduardo Caldas if (!Params.empty()) 1301dc3d4743SEduardo Caldas Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(), 1302dc3d4743SEduardo Caldas Params.back()->getEndLoc()), 1303dc3d4743SEduardo Caldas Parameters, nullptr); 1304dc3d4743SEduardo Caldas return Parameters; 1305dc3d4743SEduardo Caldas } 1306dc3d4743SEduardo Caldas 13077d382dcdSMarcel Hlopko bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) { 13087d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 1309dc3d4743SEduardo Caldas 1310dc3d4743SEduardo Caldas Builder.markChild(buildParameterDeclarationList(L.getParams()), 1311718e550cSEduardo Caldas syntax::NodeRole::Parameters); 1312dc3d4743SEduardo Caldas 13137d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 13147d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()), 1315a711a3a4SMarcel Hlopko new (allocator()) syntax::ParametersAndQualifiers, L); 13167d382dcdSMarcel Hlopko return true; 13177d382dcdSMarcel Hlopko } 13187d382dcdSMarcel Hlopko 13197d382dcdSMarcel Hlopko bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) { 13207d382dcdSMarcel Hlopko if (!L.getTypePtr()->hasTrailingReturn()) 13217d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13227d382dcdSMarcel Hlopko 1323ac87a0b5SEduardo Caldas auto *TrailingReturnTokens = buildTrailingReturn(L); 13247d382dcdSMarcel Hlopko // Finish building the node for parameters. 1325718e550cSEduardo Caldas Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn); 13267d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13277d382dcdSMarcel Hlopko } 13287d382dcdSMarcel Hlopko 13298ce15f7eSEduardo Caldas bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) { 13308ce15f7eSEduardo Caldas // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds 13318ce15f7eSEduardo Caldas // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to 13328ce15f7eSEduardo Caldas // "(Y::*mp)" We thus reverse the order of traversal to get the proper 13338ce15f7eSEduardo Caldas // syntax structure. 13348ce15f7eSEduardo Caldas if (!WalkUpFromMemberPointerTypeLoc(L)) 13358ce15f7eSEduardo Caldas return false; 13368ce15f7eSEduardo Caldas return TraverseTypeLoc(L.getPointeeLoc()); 13378ce15f7eSEduardo Caldas } 13388ce15f7eSEduardo Caldas 13397d382dcdSMarcel Hlopko bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) { 13407d382dcdSMarcel Hlopko auto SR = L.getLocalSourceRange(); 1341a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(SR), 1342a711a3a4SMarcel Hlopko new (allocator()) syntax::MemberPointer, L); 13437d382dcdSMarcel Hlopko return true; 13447d382dcdSMarcel Hlopko } 13457d382dcdSMarcel Hlopko 134658fa50f4SIlya Biryukov // The code below is very regular, it could even be generated with some 134758fa50f4SIlya Biryukov // preprocessor magic. We merely assign roles to the corresponding children 134858fa50f4SIlya Biryukov // and fold resulting nodes. 134958fa50f4SIlya Biryukov bool WalkUpFromDeclStmt(DeclStmt *S) { 135058fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1351a711a3a4SMarcel Hlopko new (allocator()) syntax::DeclarationStatement, S); 135258fa50f4SIlya Biryukov return true; 135358fa50f4SIlya Biryukov } 135458fa50f4SIlya Biryukov 135558fa50f4SIlya Biryukov bool WalkUpFromNullStmt(NullStmt *S) { 135658fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1357a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyStatement, S); 135858fa50f4SIlya Biryukov return true; 135958fa50f4SIlya Biryukov } 136058fa50f4SIlya Biryukov 136158fa50f4SIlya Biryukov bool WalkUpFromSwitchStmt(SwitchStmt *S) { 1362def65bb4SIlya Biryukov Builder.markChildToken(S->getSwitchLoc(), 136358fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 136458fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 136558fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1366a711a3a4SMarcel Hlopko new (allocator()) syntax::SwitchStatement, S); 136758fa50f4SIlya Biryukov return true; 136858fa50f4SIlya Biryukov } 136958fa50f4SIlya Biryukov 137058fa50f4SIlya Biryukov bool WalkUpFromCaseStmt(CaseStmt *S) { 1371def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 137258fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1373718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue); 137458fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 137558fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1376a711a3a4SMarcel Hlopko new (allocator()) syntax::CaseStatement, S); 137758fa50f4SIlya Biryukov return true; 137858fa50f4SIlya Biryukov } 137958fa50f4SIlya Biryukov 138058fa50f4SIlya Biryukov bool WalkUpFromDefaultStmt(DefaultStmt *S) { 1381def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 138258fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 138358fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 138458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1385a711a3a4SMarcel Hlopko new (allocator()) syntax::DefaultStatement, S); 138658fa50f4SIlya Biryukov return true; 138758fa50f4SIlya Biryukov } 138858fa50f4SIlya Biryukov 138958fa50f4SIlya Biryukov bool WalkUpFromIfStmt(IfStmt *S) { 1390def65bb4SIlya Biryukov Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword); 1391718e550cSEduardo Caldas Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement); 1392718e550cSEduardo Caldas Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword); 1393718e550cSEduardo Caldas Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement); 139458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1395a711a3a4SMarcel Hlopko new (allocator()) syntax::IfStatement, S); 139658fa50f4SIlya Biryukov return true; 139758fa50f4SIlya Biryukov } 139858fa50f4SIlya Biryukov 139958fa50f4SIlya Biryukov bool WalkUpFromForStmt(ForStmt *S) { 1400def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 140158fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 140258fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1403a711a3a4SMarcel Hlopko new (allocator()) syntax::ForStatement, S); 140458fa50f4SIlya Biryukov return true; 140558fa50f4SIlya Biryukov } 140658fa50f4SIlya Biryukov 140758fa50f4SIlya Biryukov bool WalkUpFromWhileStmt(WhileStmt *S) { 1408def65bb4SIlya Biryukov Builder.markChildToken(S->getWhileLoc(), 140958fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 141058fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 141158fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1412a711a3a4SMarcel Hlopko new (allocator()) syntax::WhileStatement, S); 141358fa50f4SIlya Biryukov return true; 141458fa50f4SIlya Biryukov } 141558fa50f4SIlya Biryukov 141658fa50f4SIlya Biryukov bool WalkUpFromContinueStmt(ContinueStmt *S) { 1417def65bb4SIlya Biryukov Builder.markChildToken(S->getContinueLoc(), 141858fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 141958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1420a711a3a4SMarcel Hlopko new (allocator()) syntax::ContinueStatement, S); 142158fa50f4SIlya Biryukov return true; 142258fa50f4SIlya Biryukov } 142358fa50f4SIlya Biryukov 142458fa50f4SIlya Biryukov bool WalkUpFromBreakStmt(BreakStmt *S) { 1425def65bb4SIlya Biryukov Builder.markChildToken(S->getBreakLoc(), 142658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 142758fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1428a711a3a4SMarcel Hlopko new (allocator()) syntax::BreakStatement, S); 142958fa50f4SIlya Biryukov return true; 143058fa50f4SIlya Biryukov } 143158fa50f4SIlya Biryukov 143258fa50f4SIlya Biryukov bool WalkUpFromReturnStmt(ReturnStmt *S) { 1433def65bb4SIlya Biryukov Builder.markChildToken(S->getReturnLoc(), 143458fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1435718e550cSEduardo Caldas Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue); 143658fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1437a711a3a4SMarcel Hlopko new (allocator()) syntax::ReturnStatement, S); 143858fa50f4SIlya Biryukov return true; 143958fa50f4SIlya Biryukov } 144058fa50f4SIlya Biryukov 144158fa50f4SIlya Biryukov bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) { 1442def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 144358fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 144458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1445a711a3a4SMarcel Hlopko new (allocator()) syntax::RangeBasedForStatement, S); 144658fa50f4SIlya Biryukov return true; 144758fa50f4SIlya Biryukov } 144858fa50f4SIlya Biryukov 1449be14a22bSIlya Biryukov bool WalkUpFromEmptyDecl(EmptyDecl *S) { 1450cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1451a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyDeclaration, S); 1452be14a22bSIlya Biryukov return true; 1453be14a22bSIlya Biryukov } 1454be14a22bSIlya Biryukov 1455be14a22bSIlya Biryukov bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) { 1456718e550cSEduardo Caldas Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition); 1457718e550cSEduardo Caldas Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message); 1458cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1459a711a3a4SMarcel Hlopko new (allocator()) syntax::StaticAssertDeclaration, S); 1460be14a22bSIlya Biryukov return true; 1461be14a22bSIlya Biryukov } 1462be14a22bSIlya Biryukov 1463be14a22bSIlya Biryukov bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) { 1464cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1465a711a3a4SMarcel Hlopko new (allocator()) syntax::LinkageSpecificationDeclaration, 1466a711a3a4SMarcel Hlopko S); 1467be14a22bSIlya Biryukov return true; 1468be14a22bSIlya Biryukov } 1469be14a22bSIlya Biryukov 1470be14a22bSIlya Biryukov bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) { 1471cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1472a711a3a4SMarcel Hlopko new (allocator()) syntax::NamespaceAliasDefinition, S); 1473be14a22bSIlya Biryukov return true; 1474be14a22bSIlya Biryukov } 1475be14a22bSIlya Biryukov 1476be14a22bSIlya Biryukov bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) { 1477cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1478a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingNamespaceDirective, S); 1479be14a22bSIlya Biryukov return true; 1480be14a22bSIlya Biryukov } 1481be14a22bSIlya Biryukov 1482be14a22bSIlya Biryukov bool WalkUpFromUsingDecl(UsingDecl *S) { 1483cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1484a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1485be14a22bSIlya Biryukov return true; 1486be14a22bSIlya Biryukov } 1487be14a22bSIlya Biryukov 1488be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) { 1489cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1490a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1491be14a22bSIlya Biryukov return true; 1492be14a22bSIlya Biryukov } 1493be14a22bSIlya Biryukov 1494be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) { 1495cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1496a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1497be14a22bSIlya Biryukov return true; 1498be14a22bSIlya Biryukov } 1499be14a22bSIlya Biryukov 1500be14a22bSIlya Biryukov bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) { 1501cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1502a711a3a4SMarcel Hlopko new (allocator()) syntax::TypeAliasDeclaration, S); 1503be14a22bSIlya Biryukov return true; 1504be14a22bSIlya Biryukov } 1505be14a22bSIlya Biryukov 15069b3f38f9SIlya Biryukov private: 1507cdce2fe5SMarcel Hlopko /// Folds SimpleDeclarator node (if present) and in case this is the last 1508cdce2fe5SMarcel Hlopko /// declarator in the chain it also folds SimpleDeclaration node. 1509cdce2fe5SMarcel Hlopko template <class T> bool processDeclaratorAndDeclaration(T *D) { 151038bc0060SEduardo Caldas auto Range = getDeclaratorRange( 151138bc0060SEduardo Caldas Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(), 151238bc0060SEduardo Caldas getQualifiedNameStart(D), getInitializerRange(D)); 1513cdce2fe5SMarcel Hlopko 1514cdce2fe5SMarcel Hlopko // There doesn't have to be a declarator (e.g. `void foo(int)` only has 1515cdce2fe5SMarcel Hlopko // declaration, but no declarator). 1516cdce2fe5SMarcel Hlopko if (Range.getBegin().isValid()) { 1517cdce2fe5SMarcel Hlopko auto *N = new (allocator()) syntax::SimpleDeclarator; 1518cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getRange(Range), N, nullptr); 1519718e550cSEduardo Caldas Builder.markChild(N, syntax::NodeRole::Declarator); 1520cdce2fe5SMarcel Hlopko } 1521cdce2fe5SMarcel Hlopko 1522cdce2fe5SMarcel Hlopko if (Builder.isResponsibleForCreatingDeclaration(D)) { 1523cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(D), 1524cdce2fe5SMarcel Hlopko new (allocator()) syntax::SimpleDeclaration, D); 1525cdce2fe5SMarcel Hlopko } 1526cdce2fe5SMarcel Hlopko return true; 1527cdce2fe5SMarcel Hlopko } 1528cdce2fe5SMarcel Hlopko 15297d382dcdSMarcel Hlopko /// Returns the range of the built node. 1530ac87a0b5SEduardo Caldas syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) { 15317d382dcdSMarcel Hlopko assert(L.getTypePtr()->hasTrailingReturn()); 15327d382dcdSMarcel Hlopko 15337d382dcdSMarcel Hlopko auto ReturnedType = L.getReturnLoc(); 15347d382dcdSMarcel Hlopko // Build node for the declarator, if any. 153538bc0060SEduardo Caldas auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType), 153638bc0060SEduardo Caldas ReturnedType.getEndLoc()); 1537a711a3a4SMarcel Hlopko syntax::SimpleDeclarator *ReturnDeclarator = nullptr; 15387d382dcdSMarcel Hlopko if (ReturnDeclaratorRange.isValid()) { 1539a711a3a4SMarcel Hlopko ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator; 1540a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(ReturnDeclaratorRange), 1541a711a3a4SMarcel Hlopko ReturnDeclarator, nullptr); 15427d382dcdSMarcel Hlopko } 15437d382dcdSMarcel Hlopko 15447d382dcdSMarcel Hlopko // Build node for trailing return type. 1545a711a3a4SMarcel Hlopko auto Return = Builder.getRange(ReturnedType.getSourceRange()); 15467d382dcdSMarcel Hlopko const auto *Arrow = Return.begin() - 1; 15477d382dcdSMarcel Hlopko assert(Arrow->kind() == tok::arrow); 15487d382dcdSMarcel Hlopko auto Tokens = llvm::makeArrayRef(Arrow, Return.end()); 154942f6fec3SEduardo Caldas Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken); 1550a711a3a4SMarcel Hlopko if (ReturnDeclarator) 1551718e550cSEduardo Caldas Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator); 1552a711a3a4SMarcel Hlopko auto *R = new (allocator()) syntax::TrailingReturnType; 1553cdce2fe5SMarcel Hlopko Builder.foldNode(Tokens, R, L); 1554a711a3a4SMarcel Hlopko return R; 15557d382dcdSMarcel Hlopko } 155688bf9b3dSMarcel Hlopko 1557a711a3a4SMarcel Hlopko void foldExplicitTemplateInstantiation( 1558a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW, 155988bf9b3dSMarcel Hlopko const syntax::Token *TemplateKW, 1560a711a3a4SMarcel Hlopko syntax::SimpleDeclaration *InnerDeclaration, Decl *From) { 156188bf9b3dSMarcel Hlopko assert(!ExternKW || ExternKW->kind() == tok::kw_extern); 156288bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 156342f6fec3SEduardo Caldas Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword); 156488bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1565718e550cSEduardo Caldas Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration); 1566a711a3a4SMarcel Hlopko Builder.foldNode( 1567a711a3a4SMarcel Hlopko Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From); 156888bf9b3dSMarcel Hlopko } 156988bf9b3dSMarcel Hlopko 1570a711a3a4SMarcel Hlopko syntax::TemplateDeclaration *foldTemplateDeclaration( 1571a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW, 1572a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) { 157388bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 157488bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1575a711a3a4SMarcel Hlopko 1576a711a3a4SMarcel Hlopko auto *N = new (allocator()) syntax::TemplateDeclaration; 1577a711a3a4SMarcel Hlopko Builder.foldNode(Range, N, From); 1578718e550cSEduardo Caldas Builder.markChild(N, syntax::NodeRole::Declaration); 1579a711a3a4SMarcel Hlopko return N; 158088bf9b3dSMarcel Hlopko } 158188bf9b3dSMarcel Hlopko 15829b3f38f9SIlya Biryukov /// A small helper to save some typing. 15839b3f38f9SIlya Biryukov llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } 15849b3f38f9SIlya Biryukov 15859b3f38f9SIlya Biryukov syntax::TreeBuilder &Builder; 15861db5b348SEduardo Caldas const ASTContext &Context; 15879b3f38f9SIlya Biryukov }; 15889b3f38f9SIlya Biryukov } // namespace 15899b3f38f9SIlya Biryukov 15907d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) { 1591e702bdb8SIlya Biryukov DeclsWithoutSemicolons.insert(D); 1592e702bdb8SIlya Biryukov } 1593e702bdb8SIlya Biryukov 1594def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) { 15959b3f38f9SIlya Biryukov if (Loc.isInvalid()) 15969b3f38f9SIlya Biryukov return; 15979b3f38f9SIlya Biryukov Pending.assignRole(*findToken(Loc), Role); 15989b3f38f9SIlya Biryukov } 15999b3f38f9SIlya Biryukov 16007d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) { 16017d382dcdSMarcel Hlopko if (!T) 16027d382dcdSMarcel Hlopko return; 16037d382dcdSMarcel Hlopko Pending.assignRole(*T, R); 16047d382dcdSMarcel Hlopko } 16057d382dcdSMarcel Hlopko 1606a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) { 1607a711a3a4SMarcel Hlopko assert(N); 1608a711a3a4SMarcel Hlopko setRole(N, R); 1609a711a3a4SMarcel Hlopko } 1610a711a3a4SMarcel Hlopko 1611a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) { 1612a711a3a4SMarcel Hlopko auto *SN = Mapping.find(N); 1613a711a3a4SMarcel Hlopko assert(SN != nullptr); 1614a711a3a4SMarcel Hlopko setRole(SN, R); 16157d382dcdSMarcel Hlopko } 1616f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) { 1617f9500cc4SEduardo Caldas auto *SN = Mapping.find(NNSLoc); 1618f9500cc4SEduardo Caldas assert(SN != nullptr); 1619f9500cc4SEduardo Caldas setRole(SN, R); 1620f9500cc4SEduardo Caldas } 16217d382dcdSMarcel Hlopko 162258fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) { 162358fa50f4SIlya Biryukov if (!Child) 162458fa50f4SIlya Biryukov return; 162558fa50f4SIlya Biryukov 1626b34b7691SDmitri Gribenko syntax::Tree *ChildNode; 1627b34b7691SDmitri Gribenko if (Expr *ChildExpr = dyn_cast<Expr>(Child)) { 162858fa50f4SIlya Biryukov // This is an expression in a statement position, consume the trailing 162958fa50f4SIlya Biryukov // semicolon and form an 'ExpressionStatement' node. 1630718e550cSEduardo Caldas markExprChild(ChildExpr, NodeRole::Expression); 1631a711a3a4SMarcel Hlopko ChildNode = new (allocator()) syntax::ExpressionStatement; 1632a711a3a4SMarcel Hlopko // (!) 'getStmtRange()' ensures this covers a trailing semicolon. 1633a711a3a4SMarcel Hlopko Pending.foldChildren(Arena, getStmtRange(Child), ChildNode); 1634b34b7691SDmitri Gribenko } else { 1635b34b7691SDmitri Gribenko ChildNode = Mapping.find(Child); 163658fa50f4SIlya Biryukov } 1637b34b7691SDmitri Gribenko assert(ChildNode != nullptr); 1638a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 163958fa50f4SIlya Biryukov } 164058fa50f4SIlya Biryukov 164158fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) { 1642be14a22bSIlya Biryukov if (!Child) 1643be14a22bSIlya Biryukov return; 16442325d6b4SEduardo Caldas Child = IgnoreImplicit(Child); 1645be14a22bSIlya Biryukov 1646a711a3a4SMarcel Hlopko syntax::Tree *ChildNode = Mapping.find(Child); 1647a711a3a4SMarcel Hlopko assert(ChildNode != nullptr); 1648a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 164958fa50f4SIlya Biryukov } 165058fa50f4SIlya Biryukov 16519b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { 165288bf9b3dSMarcel Hlopko if (L.isInvalid()) 165388bf9b3dSMarcel Hlopko return nullptr; 1654c1bbefefSIlya Biryukov auto It = LocationToToken.find(L.getRawEncoding()); 1655c1bbefefSIlya Biryukov assert(It != LocationToToken.end()); 1656c1bbefefSIlya Biryukov return It->second; 16579b3f38f9SIlya Biryukov } 16589b3f38f9SIlya Biryukov 16599b3f38f9SIlya Biryukov syntax::TranslationUnit * 16609b3f38f9SIlya Biryukov syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) { 16619b3f38f9SIlya Biryukov TreeBuilder Builder(A); 16629b3f38f9SIlya Biryukov BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext()); 16639b3f38f9SIlya Biryukov return std::move(Builder).finalize(); 16649b3f38f9SIlya Biryukov } 1665