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) { 15887f0b51dSEduardo Caldas auto FirstDefaultArg = std::find_if(Args.begin(), Args.end(), [](auto It) { 15987f0b51dSEduardo Caldas return isa<CXXDefaultArgExpr>(It); 160f5087d5cSEduardo Caldas }); 16187f0b51dSEduardo 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 if (Name.isValid()) { 2987d382dcdSMarcel Hlopko if (Start.isInvalid()) 2997d382dcdSMarcel Hlopko Start = Name; 300e159a3ceSHaojian Wu // End of TypeLoc could be invalid if the type is invalid, fallback to the 301e159a3ceSHaojian Wu // NameLoc. 302e159a3ceSHaojian Wu if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name)) 3037d382dcdSMarcel Hlopko End = Name; 3047d382dcdSMarcel Hlopko } 3057d382dcdSMarcel Hlopko if (Initializer.isValid()) { 306cdce2fe5SMarcel Hlopko auto InitializerEnd = Initializer.getEnd(); 307f33c2c27SEduardo Caldas assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) || 308f33c2c27SEduardo Caldas End == InitializerEnd); 309cdce2fe5SMarcel Hlopko End = InitializerEnd; 3107d382dcdSMarcel Hlopko } 3117d382dcdSMarcel Hlopko return SourceRange(Start, End); 3127d382dcdSMarcel Hlopko } 3137d382dcdSMarcel Hlopko 314a711a3a4SMarcel Hlopko namespace { 315a711a3a4SMarcel Hlopko /// All AST hierarchy roots that can be represented as pointers. 316a711a3a4SMarcel Hlopko using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>; 317a711a3a4SMarcel Hlopko /// Maintains a mapping from AST to syntax tree nodes. This class will get more 318a711a3a4SMarcel Hlopko /// complicated as we support more kinds of AST nodes, e.g. TypeLocs. 319a711a3a4SMarcel Hlopko /// FIXME: expose this as public API. 320a711a3a4SMarcel Hlopko class ASTToSyntaxMapping { 321a711a3a4SMarcel Hlopko public: 322a711a3a4SMarcel Hlopko void add(ASTPtr From, syntax::Tree *To) { 323a711a3a4SMarcel Hlopko assert(To != nullptr); 324a711a3a4SMarcel Hlopko assert(!From.isNull()); 325a711a3a4SMarcel Hlopko 326a711a3a4SMarcel Hlopko bool Added = Nodes.insert({From, To}).second; 327a711a3a4SMarcel Hlopko (void)Added; 328a711a3a4SMarcel Hlopko assert(Added && "mapping added twice"); 329a711a3a4SMarcel Hlopko } 330a711a3a4SMarcel Hlopko 331f9500cc4SEduardo Caldas void add(NestedNameSpecifierLoc From, syntax::Tree *To) { 332f9500cc4SEduardo Caldas assert(To != nullptr); 333f9500cc4SEduardo Caldas assert(From.hasQualifier()); 334f9500cc4SEduardo Caldas 335f9500cc4SEduardo Caldas bool Added = NNSNodes.insert({From, To}).second; 336f9500cc4SEduardo Caldas (void)Added; 337f9500cc4SEduardo Caldas assert(Added && "mapping added twice"); 338f9500cc4SEduardo Caldas } 339f9500cc4SEduardo Caldas 340a711a3a4SMarcel Hlopko syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); } 341a711a3a4SMarcel Hlopko 342f9500cc4SEduardo Caldas syntax::Tree *find(NestedNameSpecifierLoc P) const { 343f9500cc4SEduardo Caldas return NNSNodes.lookup(P); 344f9500cc4SEduardo Caldas } 345f9500cc4SEduardo Caldas 346a711a3a4SMarcel Hlopko private: 347a711a3a4SMarcel Hlopko llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes; 348f9500cc4SEduardo Caldas llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes; 349a711a3a4SMarcel Hlopko }; 350a711a3a4SMarcel Hlopko } // namespace 351a711a3a4SMarcel Hlopko 3529b3f38f9SIlya Biryukov /// A helper class for constructing the syntax tree while traversing a clang 3539b3f38f9SIlya Biryukov /// AST. 3549b3f38f9SIlya Biryukov /// 3559b3f38f9SIlya Biryukov /// At each point of the traversal we maintain a list of pending nodes. 3569b3f38f9SIlya Biryukov /// Initially all tokens are added as pending nodes. When processing a clang AST 3579b3f38f9SIlya Biryukov /// node, the clients need to: 3589b3f38f9SIlya Biryukov /// - create a corresponding syntax node, 3599b3f38f9SIlya Biryukov /// - assign roles to all pending child nodes with 'markChild' and 3609b3f38f9SIlya Biryukov /// 'markChildToken', 3619b3f38f9SIlya Biryukov /// - replace the child nodes with the new syntax node in the pending list 3629b3f38f9SIlya Biryukov /// with 'foldNode'. 3639b3f38f9SIlya Biryukov /// 3649b3f38f9SIlya Biryukov /// Note that all children are expected to be processed when building a node. 3659b3f38f9SIlya Biryukov /// 3669b3f38f9SIlya Biryukov /// Call finalize() to finish building the tree and consume the root node. 3679b3f38f9SIlya Biryukov class syntax::TreeBuilder { 3689b3f38f9SIlya Biryukov public: 369c1bbefefSIlya Biryukov TreeBuilder(syntax::Arena &Arena) : Arena(Arena), Pending(Arena) { 3704c14ee61SEduardo Caldas for (const auto &T : Arena.getTokenBuffer().expandedTokens()) 37178194118SMikhail Maltsev LocationToToken.insert({T.location(), &T}); 372c1bbefefSIlya Biryukov } 3739b3f38f9SIlya Biryukov 3744c14ee61SEduardo Caldas llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); } 3754c14ee61SEduardo Caldas const SourceManager &sourceManager() const { 3764c14ee61SEduardo Caldas return Arena.getSourceManager(); 3774c14ee61SEduardo Caldas } 3789b3f38f9SIlya Biryukov 3799b3f38f9SIlya Biryukov /// Populate children for \p New node, assuming it covers tokens from \p 3809b3f38f9SIlya Biryukov /// Range. 381ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) { 382a711a3a4SMarcel Hlopko assert(New); 383a711a3a4SMarcel Hlopko Pending.foldChildren(Arena, Range, New); 384a711a3a4SMarcel Hlopko if (From) 385a711a3a4SMarcel Hlopko Mapping.add(From, New); 386a711a3a4SMarcel Hlopko } 387f9500cc4SEduardo Caldas 388ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) { 389a711a3a4SMarcel Hlopko // FIXME: add mapping for TypeLocs 390a711a3a4SMarcel Hlopko foldNode(Range, New, nullptr); 391a711a3a4SMarcel Hlopko } 3929b3f38f9SIlya Biryukov 393f9500cc4SEduardo Caldas void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New, 394f9500cc4SEduardo Caldas NestedNameSpecifierLoc From) { 395f9500cc4SEduardo Caldas assert(New); 396f9500cc4SEduardo Caldas Pending.foldChildren(Arena, Range, New); 397f9500cc4SEduardo Caldas if (From) 398f9500cc4SEduardo Caldas Mapping.add(From, New); 3998abb5fb6SEduardo Caldas } 400f9500cc4SEduardo Caldas 4015011d431SEduardo Caldas /// Populate children for \p New list, assuming it covers tokens from a 4025011d431SEduardo Caldas /// subrange of \p SuperRange. 4035011d431SEduardo Caldas void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New, 4045011d431SEduardo Caldas ASTPtr From) { 4055011d431SEduardo Caldas assert(New); 4065011d431SEduardo Caldas auto ListRange = Pending.shrinkToFitList(SuperRange); 4075011d431SEduardo Caldas Pending.foldChildren(Arena, ListRange, New); 4085011d431SEduardo Caldas if (From) 4095011d431SEduardo Caldas Mapping.add(From, New); 4105011d431SEduardo Caldas } 4115011d431SEduardo Caldas 412e702bdb8SIlya Biryukov /// Notifies that we should not consume trailing semicolon when computing 413e702bdb8SIlya Biryukov /// token range of \p D. 4147d382dcdSMarcel Hlopko void noticeDeclWithoutSemicolon(Decl *D); 415e702bdb8SIlya Biryukov 41658fa50f4SIlya Biryukov /// Mark the \p Child node with a corresponding \p Role. All marked children 41758fa50f4SIlya Biryukov /// should be consumed by foldNode. 4187d382dcdSMarcel Hlopko /// When called on expressions (clang::Expr is derived from clang::Stmt), 41958fa50f4SIlya Biryukov /// wraps expressions into expression statement. 42058fa50f4SIlya Biryukov void markStmtChild(Stmt *Child, NodeRole Role); 42158fa50f4SIlya Biryukov /// Should be called for expressions in non-statement position to avoid 42258fa50f4SIlya Biryukov /// wrapping into expression statement. 42358fa50f4SIlya Biryukov void markExprChild(Expr *Child, NodeRole Role); 4249b3f38f9SIlya Biryukov /// Set role for a token starting at \p Loc. 425def65bb4SIlya Biryukov void markChildToken(SourceLocation Loc, NodeRole R); 4267d382dcdSMarcel Hlopko /// Set role for \p T. 4277d382dcdSMarcel Hlopko void markChildToken(const syntax::Token *T, NodeRole R); 4287d382dcdSMarcel Hlopko 429a711a3a4SMarcel Hlopko /// Set role for \p N. 430a711a3a4SMarcel Hlopko void markChild(syntax::Node *N, NodeRole R); 431a711a3a4SMarcel Hlopko /// Set role for the syntax node matching \p N. 432a711a3a4SMarcel Hlopko void markChild(ASTPtr N, NodeRole R); 433f9500cc4SEduardo Caldas /// Set role for the syntax node matching \p N. 434f9500cc4SEduardo Caldas void markChild(NestedNameSpecifierLoc N, NodeRole R); 4359b3f38f9SIlya Biryukov 4369b3f38f9SIlya Biryukov /// Finish building the tree and consume the root node. 4379b3f38f9SIlya Biryukov syntax::TranslationUnit *finalize() && { 4384c14ee61SEduardo Caldas auto Tokens = Arena.getTokenBuffer().expandedTokens(); 439bfbf6b6cSIlya Biryukov assert(!Tokens.empty()); 440bfbf6b6cSIlya Biryukov assert(Tokens.back().kind() == tok::eof); 441bfbf6b6cSIlya Biryukov 4429b3f38f9SIlya Biryukov // Build the root of the tree, consuming all the children. 4431ad15046SIlya Biryukov Pending.foldChildren(Arena, Tokens.drop_back(), 4444c14ee61SEduardo Caldas new (Arena.getAllocator()) syntax::TranslationUnit); 4459b3f38f9SIlya Biryukov 4463b929fe7SIlya Biryukov auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize()); 4473b929fe7SIlya Biryukov TU->assertInvariantsRecursive(); 4483b929fe7SIlya Biryukov return TU; 4499b3f38f9SIlya Biryukov } 4509b3f38f9SIlya Biryukov 45188bf9b3dSMarcel Hlopko /// Finds a token starting at \p L. The token must exist if \p L is valid. 45288bf9b3dSMarcel Hlopko const syntax::Token *findToken(SourceLocation L) const; 45388bf9b3dSMarcel Hlopko 454a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the \p SourceRange. 455ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceRange Range) const { 456a711a3a4SMarcel Hlopko assert(Range.isValid()); 457a711a3a4SMarcel Hlopko return getRange(Range.getBegin(), Range.getEnd()); 458a711a3a4SMarcel Hlopko } 459a711a3a4SMarcel Hlopko 460a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the passed source locations. 4619b3f38f9SIlya Biryukov /// \p First is the start position of the first token and \p Last is the start 4629b3f38f9SIlya Biryukov /// position of the last token. 463ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceLocation First, 4649b3f38f9SIlya Biryukov SourceLocation Last) const { 4659b3f38f9SIlya Biryukov assert(First.isValid()); 4669b3f38f9SIlya Biryukov assert(Last.isValid()); 4679b3f38f9SIlya Biryukov assert(First == Last || 4684c14ee61SEduardo Caldas Arena.getSourceManager().isBeforeInTranslationUnit(First, Last)); 4699b3f38f9SIlya Biryukov return llvm::makeArrayRef(findToken(First), std::next(findToken(Last))); 4709b3f38f9SIlya Biryukov } 47188bf9b3dSMarcel Hlopko 472ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> 47388bf9b3dSMarcel Hlopko getTemplateRange(const ClassTemplateSpecializationDecl *D) const { 474a711a3a4SMarcel Hlopko auto Tokens = getRange(D->getSourceRange()); 47588bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D); 47688bf9b3dSMarcel Hlopko } 47788bf9b3dSMarcel Hlopko 478cdce2fe5SMarcel Hlopko /// Returns true if \p D is the last declarator in a chain and is thus 479cdce2fe5SMarcel Hlopko /// reponsible for creating SimpleDeclaration for the whole chain. 48038bc0060SEduardo Caldas bool isResponsibleForCreatingDeclaration(const Decl *D) const { 48138bc0060SEduardo Caldas assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) && 482cdce2fe5SMarcel Hlopko "only DeclaratorDecl and TypedefNameDecl are supported."); 483cdce2fe5SMarcel Hlopko 484cdce2fe5SMarcel Hlopko const Decl *Next = D->getNextDeclInContext(); 485cdce2fe5SMarcel Hlopko 486cdce2fe5SMarcel Hlopko // There's no next sibling, this one is responsible. 487cdce2fe5SMarcel Hlopko if (Next == nullptr) { 488cdce2fe5SMarcel Hlopko return true; 489cdce2fe5SMarcel Hlopko } 490cdce2fe5SMarcel Hlopko 491cdce2fe5SMarcel Hlopko // Next sibling is not the same type, this one is responsible. 49238bc0060SEduardo Caldas if (D->getKind() != Next->getKind()) { 493cdce2fe5SMarcel Hlopko return true; 494cdce2fe5SMarcel Hlopko } 495cdce2fe5SMarcel Hlopko // Next sibling doesn't begin at the same loc, it must be a different 496cdce2fe5SMarcel Hlopko // declaration, so this declarator is responsible. 49738bc0060SEduardo Caldas if (Next->getBeginLoc() != D->getBeginLoc()) { 498cdce2fe5SMarcel Hlopko return true; 499cdce2fe5SMarcel Hlopko } 500cdce2fe5SMarcel Hlopko 501cdce2fe5SMarcel Hlopko // NextT is a member of the same declaration, and we need the last member to 502cdce2fe5SMarcel Hlopko // create declaration. This one is not responsible. 503cdce2fe5SMarcel Hlopko return false; 504cdce2fe5SMarcel Hlopko } 505cdce2fe5SMarcel Hlopko 506ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getDeclarationRange(Decl *D) { 507ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> Tokens; 50888bf9b3dSMarcel Hlopko // We want to drop the template parameters for specializations. 509ba41a0f7SEduardo Caldas if (const auto *S = dyn_cast<TagDecl>(D)) 51088bf9b3dSMarcel Hlopko Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc()); 51188bf9b3dSMarcel Hlopko else 512a711a3a4SMarcel Hlopko Tokens = getRange(D->getSourceRange()); 51388bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D); 5149b3f38f9SIlya Biryukov } 515cdce2fe5SMarcel Hlopko 516ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getExprRange(const Expr *E) const { 517a711a3a4SMarcel Hlopko return getRange(E->getSourceRange()); 51858fa50f4SIlya Biryukov } 519cdce2fe5SMarcel Hlopko 52058fa50f4SIlya Biryukov /// Find the adjusted range for the statement, consuming the trailing 52158fa50f4SIlya Biryukov /// semicolon when needed. 522ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const { 523a711a3a4SMarcel Hlopko auto Tokens = getRange(S->getSourceRange()); 52458fa50f4SIlya Biryukov if (isa<CompoundStmt>(S)) 52558fa50f4SIlya Biryukov return Tokens; 52658fa50f4SIlya Biryukov 52758fa50f4SIlya Biryukov // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and 52858fa50f4SIlya Biryukov // all statements that end with those. Consume this semicolon here. 529e702bdb8SIlya Biryukov if (Tokens.back().kind() == tok::semi) 530e702bdb8SIlya Biryukov return Tokens; 531e702bdb8SIlya Biryukov return withTrailingSemicolon(Tokens); 532e702bdb8SIlya Biryukov } 533e702bdb8SIlya Biryukov 534e702bdb8SIlya Biryukov private: 535ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens, 53688bf9b3dSMarcel Hlopko const Decl *D) const { 537ba41a0f7SEduardo Caldas if (isa<NamespaceDecl>(D)) 53888bf9b3dSMarcel Hlopko return Tokens; 53988bf9b3dSMarcel Hlopko if (DeclsWithoutSemicolons.count(D)) 54088bf9b3dSMarcel Hlopko return Tokens; 54188bf9b3dSMarcel Hlopko // FIXME: do not consume trailing semicolon on function definitions. 54288bf9b3dSMarcel Hlopko // Most declarations own a semicolon in syntax trees, but not in clang AST. 54388bf9b3dSMarcel Hlopko return withTrailingSemicolon(Tokens); 54488bf9b3dSMarcel Hlopko } 54588bf9b3dSMarcel Hlopko 546ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> 547ba41a0f7SEduardo Caldas withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const { 548e702bdb8SIlya Biryukov assert(!Tokens.empty()); 549e702bdb8SIlya Biryukov assert(Tokens.back().kind() != tok::eof); 5507d382dcdSMarcel Hlopko // We never consume 'eof', so looking at the next token is ok. 55158fa50f4SIlya Biryukov if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi) 55258fa50f4SIlya Biryukov return llvm::makeArrayRef(Tokens.begin(), Tokens.end() + 1); 55358fa50f4SIlya Biryukov return Tokens; 5549b3f38f9SIlya Biryukov } 5559b3f38f9SIlya Biryukov 556a711a3a4SMarcel Hlopko void setRole(syntax::Node *N, NodeRole R) { 5574c14ee61SEduardo Caldas assert(N->getRole() == NodeRole::Detached); 558a711a3a4SMarcel Hlopko N->setRole(R); 559a711a3a4SMarcel Hlopko } 560a711a3a4SMarcel Hlopko 5619b3f38f9SIlya Biryukov /// A collection of trees covering the input tokens. 5629b3f38f9SIlya Biryukov /// When created, each tree corresponds to a single token in the file. 5639b3f38f9SIlya Biryukov /// Clients call 'foldChildren' to attach one or more subtrees to a parent 5649b3f38f9SIlya Biryukov /// node and update the list of trees accordingly. 5659b3f38f9SIlya Biryukov /// 5669b3f38f9SIlya Biryukov /// Ensures that added nodes properly nest and cover the whole token stream. 5679b3f38f9SIlya Biryukov struct Forest { 5689b3f38f9SIlya Biryukov Forest(syntax::Arena &A) { 5694c14ee61SEduardo Caldas assert(!A.getTokenBuffer().expandedTokens().empty()); 5704c14ee61SEduardo Caldas assert(A.getTokenBuffer().expandedTokens().back().kind() == tok::eof); 5719b3f38f9SIlya Biryukov // Create all leaf nodes. 572bfbf6b6cSIlya Biryukov // Note that we do not have 'eof' in the tree. 573238ae4eeSEduardo Caldas for (const auto &T : A.getTokenBuffer().expandedTokens().drop_back()) { 5744c14ee61SEduardo Caldas auto *L = new (A.getAllocator()) syntax::Leaf(&T); 5751ad15046SIlya Biryukov L->Original = true; 5764c14ee61SEduardo Caldas L->CanModify = A.getTokenBuffer().spelledForExpanded(T).hasValue(); 577a711a3a4SMarcel Hlopko Trees.insert(Trees.end(), {&T, L}); 5781ad15046SIlya Biryukov } 5799b3f38f9SIlya Biryukov } 5809b3f38f9SIlya Biryukov 581ba41a0f7SEduardo Caldas void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) { 5829b3f38f9SIlya Biryukov assert(!Range.empty()); 5839b3f38f9SIlya Biryukov auto It = Trees.lower_bound(Range.begin()); 5849b3f38f9SIlya Biryukov assert(It != Trees.end() && "no node found"); 5859b3f38f9SIlya Biryukov assert(It->first == Range.begin() && "no child with the specified range"); 5869b3f38f9SIlya Biryukov assert((std::next(It) == Trees.end() || 5879b3f38f9SIlya Biryukov std::next(It)->first == Range.end()) && 5889b3f38f9SIlya Biryukov "no child with the specified range"); 5894c14ee61SEduardo Caldas assert(It->second->getRole() == NodeRole::Detached && 590a711a3a4SMarcel Hlopko "re-assigning role for a child"); 591a711a3a4SMarcel Hlopko It->second->setRole(Role); 5929b3f38f9SIlya Biryukov } 5939b3f38f9SIlya Biryukov 5945011d431SEduardo Caldas /// Shrink \p Range to a subrange that only contains tokens of a list. 5955011d431SEduardo Caldas /// List elements and delimiters should already have correct roles. 5965011d431SEduardo Caldas ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) { 5975011d431SEduardo Caldas auto BeginChildren = Trees.lower_bound(Range.begin()); 5985011d431SEduardo Caldas assert((BeginChildren == Trees.end() || 5995011d431SEduardo Caldas BeginChildren->first == Range.begin()) && 6005011d431SEduardo Caldas "Range crosses boundaries of existing subtrees"); 6015011d431SEduardo Caldas 6025011d431SEduardo Caldas auto EndChildren = Trees.lower_bound(Range.end()); 6035011d431SEduardo Caldas assert( 6045011d431SEduardo Caldas (EndChildren == Trees.end() || EndChildren->first == Range.end()) && 6055011d431SEduardo Caldas "Range crosses boundaries of existing subtrees"); 6065011d431SEduardo Caldas 6075011d431SEduardo Caldas auto BelongsToList = [](decltype(Trees)::value_type KV) { 6085011d431SEduardo Caldas auto Role = KV.second->getRole(); 6095011d431SEduardo Caldas return Role == syntax::NodeRole::ListElement || 6105011d431SEduardo Caldas Role == syntax::NodeRole::ListDelimiter; 6115011d431SEduardo Caldas }; 6125011d431SEduardo Caldas 6135011d431SEduardo Caldas auto BeginListChildren = 6145011d431SEduardo Caldas std::find_if(BeginChildren, EndChildren, BelongsToList); 6155011d431SEduardo Caldas 6165011d431SEduardo Caldas auto EndListChildren = 6175011d431SEduardo Caldas std::find_if_not(BeginListChildren, EndChildren, BelongsToList); 6185011d431SEduardo Caldas 6195011d431SEduardo Caldas return ArrayRef<syntax::Token>(BeginListChildren->first, 6205011d431SEduardo Caldas EndListChildren->first); 6215011d431SEduardo Caldas } 6225011d431SEduardo Caldas 623e702bdb8SIlya Biryukov /// Add \p Node to the forest and attach child nodes based on \p Tokens. 624ba41a0f7SEduardo Caldas void foldChildren(const syntax::Arena &A, ArrayRef<syntax::Token> Tokens, 6259b3f38f9SIlya Biryukov syntax::Tree *Node) { 626e702bdb8SIlya Biryukov // Attach children to `Node`. 6274c14ee61SEduardo Caldas assert(Node->getFirstChild() == nullptr && "node already has children"); 628cdce2fe5SMarcel Hlopko 629cdce2fe5SMarcel Hlopko auto *FirstToken = Tokens.begin(); 630cdce2fe5SMarcel Hlopko auto BeginChildren = Trees.lower_bound(FirstToken); 631cdce2fe5SMarcel Hlopko 632cdce2fe5SMarcel Hlopko assert((BeginChildren == Trees.end() || 633cdce2fe5SMarcel Hlopko BeginChildren->first == FirstToken) && 634cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees"); 635cdce2fe5SMarcel Hlopko auto EndChildren = Trees.lower_bound(Tokens.end()); 636cdce2fe5SMarcel Hlopko assert( 637cdce2fe5SMarcel Hlopko (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) && 638cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees"); 639cdce2fe5SMarcel Hlopko 64023657d9cSEduardo Caldas for (auto It = BeginChildren; It != EndChildren; ++It) { 64123657d9cSEduardo Caldas auto *C = It->second; 6424c14ee61SEduardo Caldas if (C->getRole() == NodeRole::Detached) 643cdce2fe5SMarcel Hlopko C->setRole(NodeRole::Unknown); 64423657d9cSEduardo Caldas Node->appendChildLowLevel(C); 645e702bdb8SIlya Biryukov } 6469b3f38f9SIlya Biryukov 647cdce2fe5SMarcel Hlopko // Mark that this node came from the AST and is backed by the source code. 648cdce2fe5SMarcel Hlopko Node->Original = true; 6494c14ee61SEduardo Caldas Node->CanModify = 6504c14ee61SEduardo Caldas A.getTokenBuffer().spelledForExpanded(Tokens).hasValue(); 6519b3f38f9SIlya Biryukov 652cdce2fe5SMarcel Hlopko Trees.erase(BeginChildren, EndChildren); 653cdce2fe5SMarcel Hlopko Trees.insert({FirstToken, Node}); 6549b3f38f9SIlya Biryukov } 6559b3f38f9SIlya Biryukov 6569b3f38f9SIlya Biryukov // EXPECTS: all tokens were consumed and are owned by a single root node. 6579b3f38f9SIlya Biryukov syntax::Node *finalize() && { 6589b3f38f9SIlya Biryukov assert(Trees.size() == 1); 659a711a3a4SMarcel Hlopko auto *Root = Trees.begin()->second; 6609b3f38f9SIlya Biryukov Trees = {}; 6619b3f38f9SIlya Biryukov return Root; 6629b3f38f9SIlya Biryukov } 6639b3f38f9SIlya Biryukov 6649b3f38f9SIlya Biryukov std::string str(const syntax::Arena &A) const { 6659b3f38f9SIlya Biryukov std::string R; 6669b3f38f9SIlya Biryukov for (auto It = Trees.begin(); It != Trees.end(); ++It) { 6679b3f38f9SIlya Biryukov unsigned CoveredTokens = 6689b3f38f9SIlya Biryukov It != Trees.end() 6699b3f38f9SIlya Biryukov ? (std::next(It)->first - It->first) 6704c14ee61SEduardo Caldas : A.getTokenBuffer().expandedTokens().end() - It->first; 6719b3f38f9SIlya Biryukov 672ba41a0f7SEduardo Caldas R += std::string( 6734c14ee61SEduardo Caldas formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(), 6744c14ee61SEduardo Caldas It->first->text(A.getSourceManager()), CoveredTokens)); 6754c14ee61SEduardo Caldas R += It->second->dump(A.getSourceManager()); 6769b3f38f9SIlya Biryukov } 6779b3f38f9SIlya Biryukov return R; 6789b3f38f9SIlya Biryukov } 6799b3f38f9SIlya Biryukov 6809b3f38f9SIlya Biryukov private: 6819b3f38f9SIlya Biryukov /// Maps from the start token to a subtree starting at that token. 682302cb3bcSIlya Biryukov /// Keys in the map are pointers into the array of expanded tokens, so 683302cb3bcSIlya Biryukov /// pointer order corresponds to the order of preprocessor tokens. 684a711a3a4SMarcel Hlopko std::map<const syntax::Token *, syntax::Node *> Trees; 6859b3f38f9SIlya Biryukov }; 6869b3f38f9SIlya Biryukov 6879b3f38f9SIlya Biryukov /// For debugging purposes. 6889b3f38f9SIlya Biryukov std::string str() { return Pending.str(Arena); } 6899b3f38f9SIlya Biryukov 6909b3f38f9SIlya Biryukov syntax::Arena &Arena; 691c1bbefefSIlya Biryukov /// To quickly find tokens by their start location. 69278194118SMikhail Maltsev llvm::DenseMap<SourceLocation, const syntax::Token *> LocationToToken; 6939b3f38f9SIlya Biryukov Forest Pending; 694e702bdb8SIlya Biryukov llvm::DenseSet<Decl *> DeclsWithoutSemicolons; 695a711a3a4SMarcel Hlopko ASTToSyntaxMapping Mapping; 6969b3f38f9SIlya Biryukov }; 6979b3f38f9SIlya Biryukov 6989b3f38f9SIlya Biryukov namespace { 6999b3f38f9SIlya Biryukov class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> { 7009b3f38f9SIlya Biryukov public: 7011db5b348SEduardo Caldas explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder) 7021db5b348SEduardo Caldas : Builder(Builder), Context(Context) {} 7039b3f38f9SIlya Biryukov 7049b3f38f9SIlya Biryukov bool shouldTraversePostOrder() const { return true; } 7059b3f38f9SIlya Biryukov 7067d382dcdSMarcel Hlopko bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) { 707cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(DD); 7087d382dcdSMarcel Hlopko } 7097d382dcdSMarcel Hlopko 710cdce2fe5SMarcel Hlopko bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) { 711cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(TD); 7129b3f38f9SIlya Biryukov } 7139b3f38f9SIlya Biryukov 7149b3f38f9SIlya Biryukov bool VisitDecl(Decl *D) { 7159b3f38f9SIlya Biryukov assert(!D->isImplicit()); 716cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(D), 717a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownDeclaration(), D); 718e702bdb8SIlya Biryukov return true; 719e702bdb8SIlya Biryukov } 720e702bdb8SIlya Biryukov 72188bf9b3dSMarcel Hlopko // RAV does not call WalkUpFrom* on explicit instantiations, so we have to 72288bf9b3dSMarcel Hlopko // override Traverse. 72388bf9b3dSMarcel Hlopko // FIXME: make RAV call WalkUpFrom* instead. 72488bf9b3dSMarcel Hlopko bool 72588bf9b3dSMarcel Hlopko TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) { 72688bf9b3dSMarcel Hlopko if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C)) 72788bf9b3dSMarcel Hlopko return false; 72888bf9b3dSMarcel Hlopko if (C->isExplicitSpecialization()) 72988bf9b3dSMarcel Hlopko return true; // we are only interested in explicit instantiations. 730a711a3a4SMarcel Hlopko auto *Declaration = 731a711a3a4SMarcel Hlopko cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C)); 73288bf9b3dSMarcel Hlopko foldExplicitTemplateInstantiation( 73388bf9b3dSMarcel Hlopko Builder.getTemplateRange(C), Builder.findToken(C->getExternLoc()), 734a711a3a4SMarcel Hlopko Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C); 73588bf9b3dSMarcel Hlopko return true; 73688bf9b3dSMarcel Hlopko } 73788bf9b3dSMarcel Hlopko 73888bf9b3dSMarcel Hlopko bool WalkUpFromTemplateDecl(TemplateDecl *S) { 73988bf9b3dSMarcel Hlopko foldTemplateDeclaration( 740cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S), 74188bf9b3dSMarcel Hlopko Builder.findToken(S->getTemplateParameters()->getTemplateLoc()), 742cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S->getTemplatedDecl()), S); 74388bf9b3dSMarcel Hlopko return true; 74488bf9b3dSMarcel Hlopko } 74588bf9b3dSMarcel Hlopko 746e702bdb8SIlya Biryukov bool WalkUpFromTagDecl(TagDecl *C) { 74704f627f6SIlya Biryukov // FIXME: build the ClassSpecifier node. 74888bf9b3dSMarcel Hlopko if (!C->isFreeStanding()) { 74988bf9b3dSMarcel Hlopko assert(C->getNumTemplateParameterLists() == 0); 75004f627f6SIlya Biryukov return true; 75104f627f6SIlya Biryukov } 752a711a3a4SMarcel Hlopko handleFreeStandingTagDecl(C); 753a711a3a4SMarcel Hlopko return true; 754a711a3a4SMarcel Hlopko } 755a711a3a4SMarcel Hlopko 756a711a3a4SMarcel Hlopko syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) { 757a711a3a4SMarcel Hlopko assert(C->isFreeStanding()); 75888bf9b3dSMarcel Hlopko // Class is a declaration specifier and needs a spanning declaration node. 759cdce2fe5SMarcel Hlopko auto DeclarationRange = Builder.getDeclarationRange(C); 760a711a3a4SMarcel Hlopko syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration; 761a711a3a4SMarcel Hlopko Builder.foldNode(DeclarationRange, Result, nullptr); 76288bf9b3dSMarcel Hlopko 76388bf9b3dSMarcel Hlopko // Build TemplateDeclaration nodes if we had template parameters. 76488bf9b3dSMarcel Hlopko auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) { 76588bf9b3dSMarcel Hlopko const auto *TemplateKW = Builder.findToken(L.getTemplateLoc()); 76688bf9b3dSMarcel Hlopko auto R = llvm::makeArrayRef(TemplateKW, DeclarationRange.end()); 767a711a3a4SMarcel Hlopko Result = 768a711a3a4SMarcel Hlopko foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr); 76988bf9b3dSMarcel Hlopko DeclarationRange = R; 77088bf9b3dSMarcel Hlopko }; 771ba41a0f7SEduardo Caldas if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C)) 77288bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*S->getTemplateParameters()); 77388bf9b3dSMarcel Hlopko for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I) 77488bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1)); 775a711a3a4SMarcel Hlopko return Result; 7769b3f38f9SIlya Biryukov } 7779b3f38f9SIlya Biryukov 7789b3f38f9SIlya Biryukov bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) { 7797d382dcdSMarcel Hlopko // We do not want to call VisitDecl(), the declaration for translation 7809b3f38f9SIlya Biryukov // unit is built by finalize(). 7819b3f38f9SIlya Biryukov return true; 7829b3f38f9SIlya Biryukov } 7839b3f38f9SIlya Biryukov 7849b3f38f9SIlya Biryukov bool WalkUpFromCompoundStmt(CompoundStmt *S) { 78551dad419SIlya Biryukov using NodeRole = syntax::NodeRole; 7869b3f38f9SIlya Biryukov 787def65bb4SIlya Biryukov Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen); 78858fa50f4SIlya Biryukov for (auto *Child : S->body()) 789718e550cSEduardo Caldas Builder.markStmtChild(Child, NodeRole::Statement); 790def65bb4SIlya Biryukov Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen); 7919b3f38f9SIlya Biryukov 79258fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 793a711a3a4SMarcel Hlopko new (allocator()) syntax::CompoundStatement, S); 7949b3f38f9SIlya Biryukov return true; 7959b3f38f9SIlya Biryukov } 7969b3f38f9SIlya Biryukov 79758fa50f4SIlya Biryukov // Some statements are not yet handled by syntax trees. 79858fa50f4SIlya Biryukov bool WalkUpFromStmt(Stmt *S) { 79958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 800a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownStatement, S); 80158fa50f4SIlya Biryukov return true; 80258fa50f4SIlya Biryukov } 80358fa50f4SIlya Biryukov 8046c1a2330SHaojian Wu bool TraverseIfStmt(IfStmt *S) { 8056c1a2330SHaojian Wu bool Result = [&, this]() { 8066c1a2330SHaojian Wu if (S->getInit() && !TraverseStmt(S->getInit())) { 8076c1a2330SHaojian Wu return false; 8086c1a2330SHaojian Wu } 8096c1a2330SHaojian Wu // In cases where the condition is an initialized declaration in a 8106c1a2330SHaojian Wu // statement, we want to preserve the declaration and ignore the 8116c1a2330SHaojian Wu // implicit condition expression in the syntax tree. 8126c1a2330SHaojian Wu if (S->hasVarStorage()) { 8136c1a2330SHaojian Wu if (!TraverseStmt(S->getConditionVariableDeclStmt())) 8146c1a2330SHaojian Wu return false; 8156c1a2330SHaojian Wu } else if (S->getCond() && !TraverseStmt(S->getCond())) 8166c1a2330SHaojian Wu return false; 8176c1a2330SHaojian Wu 8186c1a2330SHaojian Wu if (S->getThen() && !TraverseStmt(S->getThen())) 8196c1a2330SHaojian Wu return false; 8206c1a2330SHaojian Wu if (S->getElse() && !TraverseStmt(S->getElse())) 8216c1a2330SHaojian Wu return false; 8226c1a2330SHaojian Wu return true; 8236c1a2330SHaojian Wu }(); 8246c1a2330SHaojian Wu WalkUpFromIfStmt(S); 8256c1a2330SHaojian Wu return Result; 8266c1a2330SHaojian Wu } 8276c1a2330SHaojian Wu 82858fa50f4SIlya Biryukov bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) { 82958fa50f4SIlya Biryukov // We override to traverse range initializer as VarDecl. 83058fa50f4SIlya Biryukov // RAV traverses it as a statement, we produce invalid node kinds in that 83158fa50f4SIlya Biryukov // case. 83258fa50f4SIlya Biryukov // FIXME: should do this in RAV instead? 8337349479fSDmitri Gribenko bool Result = [&, this]() { 83458fa50f4SIlya Biryukov if (S->getInit() && !TraverseStmt(S->getInit())) 83558fa50f4SIlya Biryukov return false; 83658fa50f4SIlya Biryukov if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable())) 83758fa50f4SIlya Biryukov return false; 83858fa50f4SIlya Biryukov if (S->getRangeInit() && !TraverseStmt(S->getRangeInit())) 83958fa50f4SIlya Biryukov return false; 84058fa50f4SIlya Biryukov if (S->getBody() && !TraverseStmt(S->getBody())) 84158fa50f4SIlya Biryukov return false; 84258fa50f4SIlya Biryukov return true; 8437349479fSDmitri Gribenko }(); 8447349479fSDmitri Gribenko WalkUpFromCXXForRangeStmt(S); 8457349479fSDmitri Gribenko return Result; 84658fa50f4SIlya Biryukov } 84758fa50f4SIlya Biryukov 84858fa50f4SIlya Biryukov bool TraverseStmt(Stmt *S) { 849ba41a0f7SEduardo Caldas if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) { 850e702bdb8SIlya Biryukov // We want to consume the semicolon, make sure SimpleDeclaration does not. 851e702bdb8SIlya Biryukov for (auto *D : DS->decls()) 8527d382dcdSMarcel Hlopko Builder.noticeDeclWithoutSemicolon(D); 853ba41a0f7SEduardo Caldas } else if (auto *E = dyn_cast_or_null<Expr>(S)) { 8542325d6b4SEduardo Caldas return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E)); 85558fa50f4SIlya Biryukov } 85658fa50f4SIlya Biryukov return RecursiveASTVisitor::TraverseStmt(S); 85758fa50f4SIlya Biryukov } 85858fa50f4SIlya Biryukov 859*780ead41SHaojian Wu bool TraverseOpaqueValueExpr(OpaqueValueExpr *VE) { 860*780ead41SHaojian Wu // OpaqueValue doesn't correspond to concrete syntax, ignore it. 861*780ead41SHaojian Wu return true; 862*780ead41SHaojian Wu } 863*780ead41SHaojian Wu 86458fa50f4SIlya Biryukov // Some expressions are not yet handled by syntax trees. 86558fa50f4SIlya Biryukov bool WalkUpFromExpr(Expr *E) { 86658fa50f4SIlya Biryukov assert(!isImplicitExpr(E) && "should be handled by TraverseStmt"); 86758fa50f4SIlya Biryukov Builder.foldNode(Builder.getExprRange(E), 868a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownExpression, E); 86958fa50f4SIlya Biryukov return true; 87058fa50f4SIlya Biryukov } 87158fa50f4SIlya Biryukov 872f33c2c27SEduardo Caldas bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) { 873f33c2c27SEduardo Caldas // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node 874f33c2c27SEduardo Caldas // referencing the location of the UDL suffix (`_w` in `1.2_w`). The 875f33c2c27SEduardo Caldas // UDL suffix location does not point to the beginning of a token, so we 876f33c2c27SEduardo Caldas // can't represent the UDL suffix as a separate syntax tree node. 877f33c2c27SEduardo Caldas 878f33c2c27SEduardo Caldas return WalkUpFromUserDefinedLiteral(S); 879f33c2c27SEduardo Caldas } 880f33c2c27SEduardo Caldas 8811db5b348SEduardo Caldas syntax::UserDefinedLiteralExpression * 8821db5b348SEduardo Caldas buildUserDefinedLiteral(UserDefinedLiteral *S) { 883f33c2c27SEduardo Caldas switch (S->getLiteralOperatorKind()) { 884ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Integer: 8851db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 886ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Floating: 8871db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 888ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Character: 8891db5b348SEduardo Caldas return new (allocator()) syntax::CharUserDefinedLiteralExpression; 890ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_String: 8911db5b348SEduardo Caldas return new (allocator()) syntax::StringUserDefinedLiteralExpression; 892ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Raw: 893ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Template: 8941db5b348SEduardo Caldas // For raw literal operator and numeric literal operator template we 8951db5b348SEduardo Caldas // cannot get the type of the operand in the semantic AST. We get this 8961db5b348SEduardo Caldas // information from the token. As integer and floating point have the same 8971db5b348SEduardo Caldas // token kind, we run `NumericLiteralParser` again to distinguish them. 8981db5b348SEduardo Caldas auto TokLoc = S->getBeginLoc(); 8991db5b348SEduardo Caldas auto TokSpelling = 900a474d5baSEduardo Caldas Builder.findToken(TokLoc)->text(Context.getSourceManager()); 9011db5b348SEduardo Caldas auto Literal = 9021db5b348SEduardo Caldas NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(), 9031db5b348SEduardo Caldas Context.getLangOpts(), Context.getTargetInfo(), 9041db5b348SEduardo Caldas Context.getDiagnostics()); 9051db5b348SEduardo Caldas if (Literal.isIntegerLiteral()) 9061db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 907a474d5baSEduardo Caldas else { 908a474d5baSEduardo Caldas assert(Literal.isFloatingLiteral()); 9091db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 910f33c2c27SEduardo Caldas } 911f33c2c27SEduardo Caldas } 912b8409c03SMichael Liao llvm_unreachable("Unknown literal operator kind."); 913a474d5baSEduardo Caldas } 914f33c2c27SEduardo Caldas 915f33c2c27SEduardo Caldas bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) { 916f33c2c27SEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 9171db5b348SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S); 918f33c2c27SEduardo Caldas return true; 919f33c2c27SEduardo Caldas } 920f33c2c27SEduardo Caldas 9218abb5fb6SEduardo Caldas // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the 9228abb5fb6SEduardo Caldas // `DependentTemplateSpecializationType` case. 923f9500cc4SEduardo Caldas /// Given a nested-name-specifier return the range for the last name 924f9500cc4SEduardo Caldas /// specifier. 9258abb5fb6SEduardo Caldas /// 9268abb5fb6SEduardo Caldas /// e.g. `std::T::template X<U>::` => `template X<U>::` 9278abb5fb6SEduardo Caldas SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) { 9288abb5fb6SEduardo Caldas auto SR = NNSLoc.getLocalSourceRange(); 9298abb5fb6SEduardo Caldas 930f9500cc4SEduardo Caldas // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should* 931f9500cc4SEduardo Caldas // return the desired `SourceRange`, but there is a corner case. For a 932f9500cc4SEduardo Caldas // `DependentTemplateSpecializationType` this method returns its 9338abb5fb6SEduardo Caldas // qualifiers as well, in other words in the example above this method 9348abb5fb6SEduardo Caldas // returns `T::template X<U>::` instead of only `template X<U>::` 9358abb5fb6SEduardo Caldas if (auto TL = NNSLoc.getTypeLoc()) { 9368abb5fb6SEduardo Caldas if (auto DependentTL = 9378abb5fb6SEduardo Caldas TL.getAs<DependentTemplateSpecializationTypeLoc>()) { 9388abb5fb6SEduardo Caldas // The 'template' keyword is always present in dependent template 9398abb5fb6SEduardo Caldas // specializations. Except in the case of incorrect code 9408abb5fb6SEduardo Caldas // TODO: Treat the case of incorrect code. 9418abb5fb6SEduardo Caldas SR.setBegin(DependentTL.getTemplateKeywordLoc()); 9428abb5fb6SEduardo Caldas } 9438abb5fb6SEduardo Caldas } 9448abb5fb6SEduardo Caldas 9458abb5fb6SEduardo Caldas return SR; 9468abb5fb6SEduardo Caldas } 9478abb5fb6SEduardo Caldas 948f9500cc4SEduardo Caldas syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) { 949f9500cc4SEduardo Caldas switch (NNS.getKind()) { 950f9500cc4SEduardo Caldas case NestedNameSpecifier::Global: 951f9500cc4SEduardo Caldas return syntax::NodeKind::GlobalNameSpecifier; 952f9500cc4SEduardo Caldas case NestedNameSpecifier::Namespace: 953f9500cc4SEduardo Caldas case NestedNameSpecifier::NamespaceAlias: 954f9500cc4SEduardo Caldas case NestedNameSpecifier::Identifier: 955f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 956f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpecWithTemplate: 957f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 958f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpec: { 959f9500cc4SEduardo Caldas const auto *NNSType = NNS.getAsType(); 960f9500cc4SEduardo Caldas assert(NNSType); 961f9500cc4SEduardo Caldas if (isa<DecltypeType>(NNSType)) 962f9500cc4SEduardo Caldas return syntax::NodeKind::DecltypeNameSpecifier; 963f9500cc4SEduardo Caldas if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>( 964f9500cc4SEduardo Caldas NNSType)) 965f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 966f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 967f9500cc4SEduardo Caldas } 968f9500cc4SEduardo Caldas default: 969f9500cc4SEduardo Caldas // FIXME: Support Microsoft's __super 970f9500cc4SEduardo Caldas llvm::report_fatal_error("We don't yet support the __super specifier", 971f9500cc4SEduardo Caldas true); 972f9500cc4SEduardo Caldas } 973f9500cc4SEduardo Caldas } 974f9500cc4SEduardo Caldas 975f9500cc4SEduardo Caldas syntax::NameSpecifier * 976ac87a0b5SEduardo Caldas buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) { 977f9500cc4SEduardo Caldas assert(NNSLoc.hasQualifier()); 978f9500cc4SEduardo Caldas auto NameSpecifierTokens = 979f9500cc4SEduardo Caldas Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back(); 980f9500cc4SEduardo Caldas switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) { 981f9500cc4SEduardo Caldas case syntax::NodeKind::GlobalNameSpecifier: 982f9500cc4SEduardo Caldas return new (allocator()) syntax::GlobalNameSpecifier; 983f9500cc4SEduardo Caldas case syntax::NodeKind::IdentifierNameSpecifier: { 984f9500cc4SEduardo Caldas assert(NameSpecifierTokens.size() == 1); 985f9500cc4SEduardo Caldas Builder.markChildToken(NameSpecifierTokens.begin(), 986f9500cc4SEduardo Caldas syntax::NodeRole::Unknown); 987f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::IdentifierNameSpecifier; 988f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 989f9500cc4SEduardo Caldas return NS; 990f9500cc4SEduardo Caldas } 991f9500cc4SEduardo Caldas case syntax::NodeKind::SimpleTemplateNameSpecifier: { 992f9500cc4SEduardo Caldas // TODO: Build `SimpleTemplateNameSpecifier` children and implement 993f9500cc4SEduardo Caldas // accessors to them. 994f9500cc4SEduardo Caldas // Be aware, we cannot do that simply by calling `TraverseTypeLoc`, 995f9500cc4SEduardo Caldas // some `TypeLoc`s have inside them the previous name specifier and 996f9500cc4SEduardo Caldas // we want to treat them independently. 997f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier; 998f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 999f9500cc4SEduardo Caldas return NS; 1000f9500cc4SEduardo Caldas } 1001f9500cc4SEduardo Caldas case syntax::NodeKind::DecltypeNameSpecifier: { 1002f9500cc4SEduardo Caldas const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>(); 1003f9500cc4SEduardo Caldas if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL)) 10048abb5fb6SEduardo Caldas return nullptr; 1005f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::DecltypeNameSpecifier; 1006f9500cc4SEduardo Caldas // TODO: Implement accessor to `DecltypeNameSpecifier` inner 1007f9500cc4SEduardo Caldas // `DecltypeTypeLoc`. 1008f9500cc4SEduardo Caldas // For that add mapping from `TypeLoc` to `syntax::Node*` then: 1009f9500cc4SEduardo Caldas // Builder.markChild(TypeLoc, syntax::NodeRole); 1010f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 1011f9500cc4SEduardo Caldas return NS; 1012f9500cc4SEduardo Caldas } 1013f9500cc4SEduardo Caldas default: 1014f9500cc4SEduardo Caldas llvm_unreachable("getChildKind() does not return this value"); 1015f9500cc4SEduardo Caldas } 1016f9500cc4SEduardo Caldas } 1017f9500cc4SEduardo Caldas 1018f9500cc4SEduardo Caldas // To build syntax tree nodes for NestedNameSpecifierLoc we override 1019f9500cc4SEduardo Caldas // Traverse instead of WalkUpFrom because we want to traverse the children 1020f9500cc4SEduardo Caldas // ourselves and build a list instead of a nested tree of name specifier 1021f9500cc4SEduardo Caldas // prefixes. 1022f9500cc4SEduardo Caldas bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) { 1023f9500cc4SEduardo Caldas if (!QualifierLoc) 1024f9500cc4SEduardo Caldas return true; 102587f0b51dSEduardo Caldas for (auto It = QualifierLoc; It; It = It.getPrefix()) { 102687f0b51dSEduardo Caldas auto *NS = buildNameSpecifier(It); 1027f9500cc4SEduardo Caldas if (!NS) 1028f9500cc4SEduardo Caldas return false; 1029718e550cSEduardo Caldas Builder.markChild(NS, syntax::NodeRole::ListElement); 103087f0b51dSEduardo Caldas Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter); 10318abb5fb6SEduardo Caldas } 1032f9500cc4SEduardo Caldas Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()), 1033f9500cc4SEduardo Caldas new (allocator()) syntax::NestedNameSpecifier, 10348abb5fb6SEduardo Caldas QualifierLoc); 1035f9500cc4SEduardo Caldas return true; 10368abb5fb6SEduardo Caldas } 10378abb5fb6SEduardo Caldas 1038a4ef9e86SEduardo Caldas syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc, 1039a4ef9e86SEduardo Caldas SourceLocation TemplateKeywordLoc, 1040a4ef9e86SEduardo Caldas SourceRange UnqualifiedIdLoc, 1041a4ef9e86SEduardo Caldas ASTPtr From) { 1042a4ef9e86SEduardo Caldas if (QualifierLoc) { 1043718e550cSEduardo Caldas Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier); 1044ba32915dSEduardo Caldas if (TemplateKeywordLoc.isValid()) 1045ba32915dSEduardo Caldas Builder.markChildToken(TemplateKeywordLoc, 1046ba32915dSEduardo Caldas syntax::NodeRole::TemplateKeyword); 1047a4ef9e86SEduardo Caldas } 1048ba32915dSEduardo Caldas 1049ba32915dSEduardo Caldas auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId; 1050a4ef9e86SEduardo Caldas Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId, 1051a4ef9e86SEduardo Caldas nullptr); 1052718e550cSEduardo Caldas Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId); 1053ba32915dSEduardo Caldas 1054a4ef9e86SEduardo Caldas auto IdExpressionBeginLoc = 1055a4ef9e86SEduardo Caldas QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin(); 1056ba32915dSEduardo Caldas 1057a4ef9e86SEduardo Caldas auto *TheIdExpression = new (allocator()) syntax::IdExpression; 1058a4ef9e86SEduardo Caldas Builder.foldNode( 1059a4ef9e86SEduardo Caldas Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()), 1060a4ef9e86SEduardo Caldas TheIdExpression, From); 1061a4ef9e86SEduardo Caldas 1062a4ef9e86SEduardo Caldas return TheIdExpression; 1063a4ef9e86SEduardo Caldas } 1064a4ef9e86SEduardo Caldas 1065a4ef9e86SEduardo Caldas bool WalkUpFromMemberExpr(MemberExpr *S) { 1066ba32915dSEduardo Caldas // For `MemberExpr` with implicit `this->` we generate a simple 1067ba32915dSEduardo Caldas // `id-expression` syntax node, beacuse an implicit `member-expression` is 1068ba32915dSEduardo Caldas // syntactically undistinguishable from an `id-expression` 1069ba32915dSEduardo Caldas if (S->isImplicitAccess()) { 1070a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1071a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), S); 1072ba32915dSEduardo Caldas return true; 1073ba32915dSEduardo Caldas } 1074a4ef9e86SEduardo Caldas 1075a4ef9e86SEduardo Caldas auto *TheIdExpression = buildIdExpression( 1076a4ef9e86SEduardo Caldas S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1077a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr); 1078ba32915dSEduardo Caldas 1079718e550cSEduardo Caldas Builder.markChild(TheIdExpression, syntax::NodeRole::Member); 1080ba32915dSEduardo Caldas 1081718e550cSEduardo Caldas Builder.markExprChild(S->getBase(), syntax::NodeRole::Object); 1082718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken); 1083ba32915dSEduardo Caldas 1084ba32915dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1085ba32915dSEduardo Caldas new (allocator()) syntax::MemberExpression, S); 1086ba32915dSEduardo Caldas return true; 1087ba32915dSEduardo Caldas } 1088ba32915dSEduardo Caldas 10891b2f6b4aSEduardo Caldas bool WalkUpFromDeclRefExpr(DeclRefExpr *S) { 1090a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1091a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 10928abb5fb6SEduardo Caldas 10938abb5fb6SEduardo Caldas return true; 10941b2f6b4aSEduardo Caldas } 10958abb5fb6SEduardo Caldas 10968abb5fb6SEduardo Caldas // Same logic as DeclRefExpr. 10978abb5fb6SEduardo Caldas bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) { 1098a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1099a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 11008abb5fb6SEduardo Caldas 11011b2f6b4aSEduardo Caldas return true; 11021b2f6b4aSEduardo Caldas } 11031b2f6b4aSEduardo Caldas 110485c15f17SEduardo Caldas bool WalkUpFromCXXThisExpr(CXXThisExpr *S) { 110585c15f17SEduardo Caldas if (!S->isImplicit()) { 110685c15f17SEduardo Caldas Builder.markChildToken(S->getLocation(), 110785c15f17SEduardo Caldas syntax::NodeRole::IntroducerKeyword); 110885c15f17SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 110985c15f17SEduardo Caldas new (allocator()) syntax::ThisExpression, S); 111085c15f17SEduardo Caldas } 111185c15f17SEduardo Caldas return true; 111285c15f17SEduardo Caldas } 111385c15f17SEduardo Caldas 1114fdbd7833SEduardo Caldas bool WalkUpFromParenExpr(ParenExpr *S) { 1115fdbd7833SEduardo Caldas Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen); 1116718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression); 1117fdbd7833SEduardo Caldas Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen); 1118fdbd7833SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1119fdbd7833SEduardo Caldas new (allocator()) syntax::ParenExpression, S); 1120fdbd7833SEduardo Caldas return true; 1121fdbd7833SEduardo Caldas } 1122fdbd7833SEduardo Caldas 11233b739690SEduardo Caldas bool WalkUpFromIntegerLiteral(IntegerLiteral *S) { 112442f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11253b739690SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11263b739690SEduardo Caldas new (allocator()) syntax::IntegerLiteralExpression, S); 11273b739690SEduardo Caldas return true; 11283b739690SEduardo Caldas } 11293b739690SEduardo Caldas 1130221d7bbeSEduardo Caldas bool WalkUpFromCharacterLiteral(CharacterLiteral *S) { 1131221d7bbeSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1132221d7bbeSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1133221d7bbeSEduardo Caldas new (allocator()) syntax::CharacterLiteralExpression, S); 1134221d7bbeSEduardo Caldas return true; 1135221d7bbeSEduardo Caldas } 11367b404b6dSEduardo Caldas 11377b404b6dSEduardo Caldas bool WalkUpFromFloatingLiteral(FloatingLiteral *S) { 11387b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11397b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11407b404b6dSEduardo Caldas new (allocator()) syntax::FloatingLiteralExpression, S); 11417b404b6dSEduardo Caldas return true; 11427b404b6dSEduardo Caldas } 11437b404b6dSEduardo Caldas 1144466e8b7eSEduardo Caldas bool WalkUpFromStringLiteral(StringLiteral *S) { 1145466e8b7eSEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 1146466e8b7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1147466e8b7eSEduardo Caldas new (allocator()) syntax::StringLiteralExpression, S); 1148466e8b7eSEduardo Caldas return true; 1149466e8b7eSEduardo Caldas } 1150221d7bbeSEduardo Caldas 11517b404b6dSEduardo Caldas bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) { 11527b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11537b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11547b404b6dSEduardo Caldas new (allocator()) syntax::BoolLiteralExpression, S); 11557b404b6dSEduardo Caldas return true; 11567b404b6dSEduardo Caldas } 11577b404b6dSEduardo Caldas 1158007098d7SEduardo Caldas bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) { 115942f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1160007098d7SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1161007098d7SEduardo Caldas new (allocator()) syntax::CxxNullPtrExpression, S); 1162007098d7SEduardo Caldas return true; 1163007098d7SEduardo Caldas } 1164007098d7SEduardo Caldas 1165461af57dSEduardo Caldas bool WalkUpFromUnaryOperator(UnaryOperator *S) { 116642f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1167718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1168718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand); 1169461af57dSEduardo Caldas 1170461af57dSEduardo Caldas if (S->isPostfix()) 1171461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1172461af57dSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1173461af57dSEduardo Caldas S); 1174461af57dSEduardo Caldas else 1175461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1176461af57dSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1177461af57dSEduardo Caldas S); 1178461af57dSEduardo Caldas 1179461af57dSEduardo Caldas return true; 1180461af57dSEduardo Caldas } 1181461af57dSEduardo Caldas 11823785eb83SEduardo Caldas bool WalkUpFromBinaryOperator(BinaryOperator *S) { 1183718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide); 118442f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1185718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1186718e550cSEduardo Caldas Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide); 11873785eb83SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11883785eb83SEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 11893785eb83SEduardo Caldas return true; 11903785eb83SEduardo Caldas } 11913785eb83SEduardo Caldas 1192f5087d5cSEduardo Caldas /// Builds `CallArguments` syntax node from arguments that appear in source 1193f5087d5cSEduardo Caldas /// code, i.e. not default arguments. 1194f5087d5cSEduardo Caldas syntax::CallArguments * 1195f5087d5cSEduardo Caldas buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) { 1196f5087d5cSEduardo Caldas auto Args = dropDefaultArgs(ArgsAndDefaultArgs); 1197e10df779SDmitri Gribenko for (auto *Arg : Args) { 1198718e550cSEduardo Caldas Builder.markExprChild(Arg, syntax::NodeRole::ListElement); 11992de2ca34SEduardo Caldas const auto *DelimiterToken = 12002de2ca34SEduardo Caldas std::next(Builder.findToken(Arg->getEndLoc())); 12012de2ca34SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1202718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 12032de2ca34SEduardo Caldas } 12042de2ca34SEduardo Caldas 12052de2ca34SEduardo Caldas auto *Arguments = new (allocator()) syntax::CallArguments; 12062de2ca34SEduardo Caldas if (!Args.empty()) 12072de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(), 12082de2ca34SEduardo Caldas (*(Args.end() - 1))->getEndLoc()), 12092de2ca34SEduardo Caldas Arguments, nullptr); 12102de2ca34SEduardo Caldas 12112de2ca34SEduardo Caldas return Arguments; 12122de2ca34SEduardo Caldas } 12132de2ca34SEduardo Caldas 12142de2ca34SEduardo Caldas bool WalkUpFromCallExpr(CallExpr *S) { 1215718e550cSEduardo Caldas Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee); 12162de2ca34SEduardo Caldas 12172de2ca34SEduardo Caldas const auto *LParenToken = 12182de2ca34SEduardo Caldas std::next(Builder.findToken(S->getCallee()->getEndLoc())); 12192de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed 12202de2ca34SEduardo Caldas // the test on decltype desctructors. 12212de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 12222de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 12232de2ca34SEduardo Caldas 12242de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(S->arguments()), 1225718e550cSEduardo Caldas syntax::NodeRole::Arguments); 12262de2ca34SEduardo Caldas 12272de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 12282de2ca34SEduardo Caldas 12292de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 12302de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 12312de2ca34SEduardo Caldas return true; 12322de2ca34SEduardo Caldas } 12332de2ca34SEduardo Caldas 123446f4439dSEduardo Caldas bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) { 123546f4439dSEduardo Caldas // Ignore the implicit calls to default constructors. 123646f4439dSEduardo Caldas if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) && 123746f4439dSEduardo Caldas S->getParenOrBraceRange().isInvalid()) 123846f4439dSEduardo Caldas return true; 123946f4439dSEduardo Caldas return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S); 124046f4439dSEduardo Caldas } 124146f4439dSEduardo Caldas 1242ea8bba7eSEduardo Caldas bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1243ac37afa6SEduardo Caldas // To construct a syntax tree of the same shape for calls to built-in and 1244ac37afa6SEduardo Caldas // user-defined operators, ignore the `DeclRefExpr` that refers to the 1245ac37afa6SEduardo Caldas // operator and treat it as a simple token. Do that by traversing 1246ac37afa6SEduardo Caldas // arguments instead of children. 1247ac37afa6SEduardo Caldas for (auto *child : S->arguments()) { 1248f33c2c27SEduardo Caldas // A postfix unary operator is declared as taking two operands. The 1249f33c2c27SEduardo Caldas // second operand is used to distinguish from its prefix counterpart. In 1250f33c2c27SEduardo Caldas // the semantic AST this "phantom" operand is represented as a 1251ea8bba7eSEduardo Caldas // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this 1252ea8bba7eSEduardo Caldas // operand because it does not correspond to anything written in source 1253ac37afa6SEduardo Caldas // code. 1254ac37afa6SEduardo Caldas if (child->getSourceRange().isInvalid()) { 1255ac37afa6SEduardo Caldas assert(getOperatorNodeKind(*S) == 1256ac37afa6SEduardo Caldas syntax::NodeKind::PostfixUnaryOperatorExpression); 1257ea8bba7eSEduardo Caldas continue; 1258ac37afa6SEduardo Caldas } 1259ea8bba7eSEduardo Caldas if (!TraverseStmt(child)) 1260ea8bba7eSEduardo Caldas return false; 1261ea8bba7eSEduardo Caldas } 1262ea8bba7eSEduardo Caldas return WalkUpFromCXXOperatorCallExpr(S); 1263ea8bba7eSEduardo Caldas } 1264ea8bba7eSEduardo Caldas 12653a574a6cSEduardo Caldas bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1266ea8bba7eSEduardo Caldas switch (getOperatorNodeKind(*S)) { 1267ea8bba7eSEduardo Caldas case syntax::NodeKind::BinaryOperatorExpression: 1268718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide); 1269718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1270718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1271718e550cSEduardo Caldas Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide); 12723a574a6cSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 12733a574a6cSEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 12743a574a6cSEduardo Caldas return true; 1275ea8bba7eSEduardo Caldas case syntax::NodeKind::PrefixUnaryOperatorExpression: 1276718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1277718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1278718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1279ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1280ea8bba7eSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1281ea8bba7eSEduardo Caldas S); 1282ea8bba7eSEduardo Caldas return true; 1283ea8bba7eSEduardo Caldas case syntax::NodeKind::PostfixUnaryOperatorExpression: 1284718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1285718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1286718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1287ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1288ea8bba7eSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1289ea8bba7eSEduardo Caldas S); 1290ea8bba7eSEduardo Caldas return true; 12912de2ca34SEduardo Caldas case syntax::NodeKind::CallExpression: { 1292718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee); 12932de2ca34SEduardo Caldas 12942de2ca34SEduardo Caldas const auto *LParenToken = 12952de2ca34SEduardo Caldas std::next(Builder.findToken(S->getArg(0)->getEndLoc())); 12962de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have 12972de2ca34SEduardo Caldas // fixed the test on decltype desctructors. 12982de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 12992de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 13002de2ca34SEduardo Caldas 13012de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(CallExpr::arg_range( 13022de2ca34SEduardo Caldas S->arg_begin() + 1, S->arg_end())), 1303718e550cSEduardo Caldas syntax::NodeRole::Arguments); 13042de2ca34SEduardo Caldas 13052de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 13062de2ca34SEduardo Caldas 13072de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 13082de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 13092de2ca34SEduardo Caldas return true; 13102de2ca34SEduardo Caldas } 1311ea8bba7eSEduardo Caldas case syntax::NodeKind::UnknownExpression: 13122de2ca34SEduardo Caldas return WalkUpFromExpr(S); 1313ea8bba7eSEduardo Caldas default: 1314ea8bba7eSEduardo Caldas llvm_unreachable("getOperatorNodeKind() does not return this value"); 1315ea8bba7eSEduardo Caldas } 13163a574a6cSEduardo Caldas } 13173a574a6cSEduardo Caldas 1318f5087d5cSEduardo Caldas bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; } 1319f5087d5cSEduardo Caldas 1320be14a22bSIlya Biryukov bool WalkUpFromNamespaceDecl(NamespaceDecl *S) { 1321cdce2fe5SMarcel Hlopko auto Tokens = Builder.getDeclarationRange(S); 1322be14a22bSIlya Biryukov if (Tokens.front().kind() == tok::coloncolon) { 1323be14a22bSIlya Biryukov // Handle nested namespace definitions. Those start at '::' token, e.g. 1324be14a22bSIlya Biryukov // namespace a^::b {} 1325be14a22bSIlya Biryukov // FIXME: build corresponding nodes for the name of this namespace. 1326be14a22bSIlya Biryukov return true; 1327be14a22bSIlya Biryukov } 1328a711a3a4SMarcel Hlopko Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S); 1329be14a22bSIlya Biryukov return true; 1330be14a22bSIlya Biryukov } 1331be14a22bSIlya Biryukov 13328ce15f7eSEduardo Caldas // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test 13338ce15f7eSEduardo Caldas // results. Find test coverage or remove it. 13347d382dcdSMarcel Hlopko bool TraverseParenTypeLoc(ParenTypeLoc L) { 13357d382dcdSMarcel Hlopko // We reverse order of traversal to get the proper syntax structure. 13367d382dcdSMarcel Hlopko if (!WalkUpFromParenTypeLoc(L)) 13377d382dcdSMarcel Hlopko return false; 13387d382dcdSMarcel Hlopko return TraverseTypeLoc(L.getInnerLoc()); 13397d382dcdSMarcel Hlopko } 13407d382dcdSMarcel Hlopko 13417d382dcdSMarcel Hlopko bool WalkUpFromParenTypeLoc(ParenTypeLoc L) { 13427d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 13437d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 13447d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()), 1345a711a3a4SMarcel Hlopko new (allocator()) syntax::ParenDeclarator, L); 13467d382dcdSMarcel Hlopko return true; 13477d382dcdSMarcel Hlopko } 13487d382dcdSMarcel Hlopko 13497d382dcdSMarcel Hlopko // Declarator chunks, they are produced by type locs and some clang::Decls. 13507d382dcdSMarcel Hlopko bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) { 13517d382dcdSMarcel Hlopko Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen); 1352718e550cSEduardo Caldas Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size); 13537d382dcdSMarcel Hlopko Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen); 13547d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()), 1355a711a3a4SMarcel Hlopko new (allocator()) syntax::ArraySubscript, L); 13567d382dcdSMarcel Hlopko return true; 13577d382dcdSMarcel Hlopko } 13587d382dcdSMarcel Hlopko 1359dc3d4743SEduardo Caldas syntax::ParameterDeclarationList * 1360dc3d4743SEduardo Caldas buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) { 1361dc3d4743SEduardo Caldas for (auto *P : Params) { 1362718e550cSEduardo Caldas Builder.markChild(P, syntax::NodeRole::ListElement); 1363dc3d4743SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc())); 1364dc3d4743SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1365718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 1366dc3d4743SEduardo Caldas } 1367dc3d4743SEduardo Caldas auto *Parameters = new (allocator()) syntax::ParameterDeclarationList; 1368dc3d4743SEduardo Caldas if (!Params.empty()) 1369dc3d4743SEduardo Caldas Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(), 1370dc3d4743SEduardo Caldas Params.back()->getEndLoc()), 1371dc3d4743SEduardo Caldas Parameters, nullptr); 1372dc3d4743SEduardo Caldas return Parameters; 1373dc3d4743SEduardo Caldas } 1374dc3d4743SEduardo Caldas 13757d382dcdSMarcel Hlopko bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) { 13767d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 1377dc3d4743SEduardo Caldas 1378dc3d4743SEduardo Caldas Builder.markChild(buildParameterDeclarationList(L.getParams()), 1379718e550cSEduardo Caldas syntax::NodeRole::Parameters); 1380dc3d4743SEduardo Caldas 13817d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 13827d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()), 1383a711a3a4SMarcel Hlopko new (allocator()) syntax::ParametersAndQualifiers, L); 13847d382dcdSMarcel Hlopko return true; 13857d382dcdSMarcel Hlopko } 13867d382dcdSMarcel Hlopko 13877d382dcdSMarcel Hlopko bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) { 13887d382dcdSMarcel Hlopko if (!L.getTypePtr()->hasTrailingReturn()) 13897d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13907d382dcdSMarcel Hlopko 1391ac87a0b5SEduardo Caldas auto *TrailingReturnTokens = buildTrailingReturn(L); 13927d382dcdSMarcel Hlopko // Finish building the node for parameters. 1393718e550cSEduardo Caldas Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn); 13947d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13957d382dcdSMarcel Hlopko } 13967d382dcdSMarcel Hlopko 13978ce15f7eSEduardo Caldas bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) { 13988ce15f7eSEduardo Caldas // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds 13998ce15f7eSEduardo Caldas // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to 14008ce15f7eSEduardo Caldas // "(Y::*mp)" We thus reverse the order of traversal to get the proper 14018ce15f7eSEduardo Caldas // syntax structure. 14028ce15f7eSEduardo Caldas if (!WalkUpFromMemberPointerTypeLoc(L)) 14038ce15f7eSEduardo Caldas return false; 14048ce15f7eSEduardo Caldas return TraverseTypeLoc(L.getPointeeLoc()); 14058ce15f7eSEduardo Caldas } 14068ce15f7eSEduardo Caldas 14077d382dcdSMarcel Hlopko bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) { 14087d382dcdSMarcel Hlopko auto SR = L.getLocalSourceRange(); 1409a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(SR), 1410a711a3a4SMarcel Hlopko new (allocator()) syntax::MemberPointer, L); 14117d382dcdSMarcel Hlopko return true; 14127d382dcdSMarcel Hlopko } 14137d382dcdSMarcel Hlopko 141458fa50f4SIlya Biryukov // The code below is very regular, it could even be generated with some 141558fa50f4SIlya Biryukov // preprocessor magic. We merely assign roles to the corresponding children 141658fa50f4SIlya Biryukov // and fold resulting nodes. 141758fa50f4SIlya Biryukov bool WalkUpFromDeclStmt(DeclStmt *S) { 141858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1419a711a3a4SMarcel Hlopko new (allocator()) syntax::DeclarationStatement, S); 142058fa50f4SIlya Biryukov return true; 142158fa50f4SIlya Biryukov } 142258fa50f4SIlya Biryukov 142358fa50f4SIlya Biryukov bool WalkUpFromNullStmt(NullStmt *S) { 142458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1425a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyStatement, S); 142658fa50f4SIlya Biryukov return true; 142758fa50f4SIlya Biryukov } 142858fa50f4SIlya Biryukov 142958fa50f4SIlya Biryukov bool WalkUpFromSwitchStmt(SwitchStmt *S) { 1430def65bb4SIlya Biryukov Builder.markChildToken(S->getSwitchLoc(), 143158fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 143258fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 143358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1434a711a3a4SMarcel Hlopko new (allocator()) syntax::SwitchStatement, S); 143558fa50f4SIlya Biryukov return true; 143658fa50f4SIlya Biryukov } 143758fa50f4SIlya Biryukov 143858fa50f4SIlya Biryukov bool WalkUpFromCaseStmt(CaseStmt *S) { 1439def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 144058fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1441718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue); 144258fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 144358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1444a711a3a4SMarcel Hlopko new (allocator()) syntax::CaseStatement, S); 144558fa50f4SIlya Biryukov return true; 144658fa50f4SIlya Biryukov } 144758fa50f4SIlya Biryukov 144858fa50f4SIlya Biryukov bool WalkUpFromDefaultStmt(DefaultStmt *S) { 1449def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 145058fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 145158fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 145258fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1453a711a3a4SMarcel Hlopko new (allocator()) syntax::DefaultStatement, S); 145458fa50f4SIlya Biryukov return true; 145558fa50f4SIlya Biryukov } 145658fa50f4SIlya Biryukov 145758fa50f4SIlya Biryukov bool WalkUpFromIfStmt(IfStmt *S) { 1458def65bb4SIlya Biryukov Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword); 14596c1a2330SHaojian Wu Stmt *ConditionStatement = S->getCond(); 14606c1a2330SHaojian Wu if (S->hasVarStorage()) 14616c1a2330SHaojian Wu ConditionStatement = S->getConditionVariableDeclStmt(); 14626c1a2330SHaojian Wu Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition); 1463718e550cSEduardo Caldas Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement); 1464718e550cSEduardo Caldas Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword); 1465718e550cSEduardo Caldas Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement); 146658fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1467a711a3a4SMarcel Hlopko new (allocator()) syntax::IfStatement, S); 146858fa50f4SIlya Biryukov return true; 146958fa50f4SIlya Biryukov } 147058fa50f4SIlya Biryukov 147158fa50f4SIlya Biryukov bool WalkUpFromForStmt(ForStmt *S) { 1472def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 147358fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 147458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1475a711a3a4SMarcel Hlopko new (allocator()) syntax::ForStatement, S); 147658fa50f4SIlya Biryukov return true; 147758fa50f4SIlya Biryukov } 147858fa50f4SIlya Biryukov 147958fa50f4SIlya Biryukov bool WalkUpFromWhileStmt(WhileStmt *S) { 1480def65bb4SIlya Biryukov Builder.markChildToken(S->getWhileLoc(), 148158fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 148258fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 148358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1484a711a3a4SMarcel Hlopko new (allocator()) syntax::WhileStatement, S); 148558fa50f4SIlya Biryukov return true; 148658fa50f4SIlya Biryukov } 148758fa50f4SIlya Biryukov 148858fa50f4SIlya Biryukov bool WalkUpFromContinueStmt(ContinueStmt *S) { 1489def65bb4SIlya Biryukov Builder.markChildToken(S->getContinueLoc(), 149058fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 149158fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1492a711a3a4SMarcel Hlopko new (allocator()) syntax::ContinueStatement, S); 149358fa50f4SIlya Biryukov return true; 149458fa50f4SIlya Biryukov } 149558fa50f4SIlya Biryukov 149658fa50f4SIlya Biryukov bool WalkUpFromBreakStmt(BreakStmt *S) { 1497def65bb4SIlya Biryukov Builder.markChildToken(S->getBreakLoc(), 149858fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 149958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1500a711a3a4SMarcel Hlopko new (allocator()) syntax::BreakStatement, S); 150158fa50f4SIlya Biryukov return true; 150258fa50f4SIlya Biryukov } 150358fa50f4SIlya Biryukov 150458fa50f4SIlya Biryukov bool WalkUpFromReturnStmt(ReturnStmt *S) { 1505def65bb4SIlya Biryukov Builder.markChildToken(S->getReturnLoc(), 150658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1507718e550cSEduardo Caldas Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue); 150858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1509a711a3a4SMarcel Hlopko new (allocator()) syntax::ReturnStatement, S); 151058fa50f4SIlya Biryukov return true; 151158fa50f4SIlya Biryukov } 151258fa50f4SIlya Biryukov 151358fa50f4SIlya Biryukov bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) { 1514def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 151558fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 151658fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1517a711a3a4SMarcel Hlopko new (allocator()) syntax::RangeBasedForStatement, S); 151858fa50f4SIlya Biryukov return true; 151958fa50f4SIlya Biryukov } 152058fa50f4SIlya Biryukov 1521be14a22bSIlya Biryukov bool WalkUpFromEmptyDecl(EmptyDecl *S) { 1522cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1523a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyDeclaration, S); 1524be14a22bSIlya Biryukov return true; 1525be14a22bSIlya Biryukov } 1526be14a22bSIlya Biryukov 1527be14a22bSIlya Biryukov bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) { 1528718e550cSEduardo Caldas Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition); 1529718e550cSEduardo Caldas Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message); 1530cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1531a711a3a4SMarcel Hlopko new (allocator()) syntax::StaticAssertDeclaration, S); 1532be14a22bSIlya Biryukov return true; 1533be14a22bSIlya Biryukov } 1534be14a22bSIlya Biryukov 1535be14a22bSIlya Biryukov bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) { 1536cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1537a711a3a4SMarcel Hlopko new (allocator()) syntax::LinkageSpecificationDeclaration, 1538a711a3a4SMarcel Hlopko S); 1539be14a22bSIlya Biryukov return true; 1540be14a22bSIlya Biryukov } 1541be14a22bSIlya Biryukov 1542be14a22bSIlya Biryukov bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) { 1543cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1544a711a3a4SMarcel Hlopko new (allocator()) syntax::NamespaceAliasDefinition, S); 1545be14a22bSIlya Biryukov return true; 1546be14a22bSIlya Biryukov } 1547be14a22bSIlya Biryukov 1548be14a22bSIlya Biryukov bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) { 1549cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1550a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingNamespaceDirective, S); 1551be14a22bSIlya Biryukov return true; 1552be14a22bSIlya Biryukov } 1553be14a22bSIlya Biryukov 1554be14a22bSIlya Biryukov bool WalkUpFromUsingDecl(UsingDecl *S) { 1555cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1556a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1557be14a22bSIlya Biryukov return true; 1558be14a22bSIlya Biryukov } 1559be14a22bSIlya Biryukov 1560be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) { 1561cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1562a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1563be14a22bSIlya Biryukov return true; 1564be14a22bSIlya Biryukov } 1565be14a22bSIlya Biryukov 1566be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) { 1567cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1568a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1569be14a22bSIlya Biryukov return true; 1570be14a22bSIlya Biryukov } 1571be14a22bSIlya Biryukov 1572be14a22bSIlya Biryukov bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) { 1573cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1574a711a3a4SMarcel Hlopko new (allocator()) syntax::TypeAliasDeclaration, S); 1575be14a22bSIlya Biryukov return true; 1576be14a22bSIlya Biryukov } 1577be14a22bSIlya Biryukov 15789b3f38f9SIlya Biryukov private: 1579cdce2fe5SMarcel Hlopko /// Folds SimpleDeclarator node (if present) and in case this is the last 1580cdce2fe5SMarcel Hlopko /// declarator in the chain it also folds SimpleDeclaration node. 1581cdce2fe5SMarcel Hlopko template <class T> bool processDeclaratorAndDeclaration(T *D) { 158238bc0060SEduardo Caldas auto Range = getDeclaratorRange( 158338bc0060SEduardo Caldas Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(), 158438bc0060SEduardo Caldas getQualifiedNameStart(D), getInitializerRange(D)); 1585cdce2fe5SMarcel Hlopko 1586cdce2fe5SMarcel Hlopko // There doesn't have to be a declarator (e.g. `void foo(int)` only has 1587cdce2fe5SMarcel Hlopko // declaration, but no declarator). 15885011d431SEduardo Caldas if (!Range.getBegin().isValid()) { 15895011d431SEduardo Caldas Builder.markChild(new (allocator()) syntax::DeclaratorList, 15905011d431SEduardo Caldas syntax::NodeRole::Declarators); 15915011d431SEduardo Caldas Builder.foldNode(Builder.getDeclarationRange(D), 15925011d431SEduardo Caldas new (allocator()) syntax::SimpleDeclaration, D); 15935011d431SEduardo Caldas return true; 1594cdce2fe5SMarcel Hlopko } 1595cdce2fe5SMarcel Hlopko 15965011d431SEduardo Caldas auto *N = new (allocator()) syntax::SimpleDeclarator; 15975011d431SEduardo Caldas Builder.foldNode(Builder.getRange(Range), N, nullptr); 15985011d431SEduardo Caldas Builder.markChild(N, syntax::NodeRole::ListElement); 15995011d431SEduardo Caldas 16005011d431SEduardo Caldas if (!Builder.isResponsibleForCreatingDeclaration(D)) { 16015011d431SEduardo Caldas // If this is not the last declarator in the declaration we expect a 16025011d431SEduardo Caldas // delimiter after it. 16035011d431SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd())); 16045011d431SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 16055011d431SEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 16065011d431SEduardo Caldas } else { 16075011d431SEduardo Caldas auto *DL = new (allocator()) syntax::DeclaratorList; 16085011d431SEduardo Caldas auto DeclarationRange = Builder.getDeclarationRange(D); 16095011d431SEduardo Caldas Builder.foldList(DeclarationRange, DL, nullptr); 16105011d431SEduardo Caldas 16115011d431SEduardo Caldas Builder.markChild(DL, syntax::NodeRole::Declarators); 16125011d431SEduardo Caldas Builder.foldNode(DeclarationRange, 1613cdce2fe5SMarcel Hlopko new (allocator()) syntax::SimpleDeclaration, D); 1614cdce2fe5SMarcel Hlopko } 1615cdce2fe5SMarcel Hlopko return true; 1616cdce2fe5SMarcel Hlopko } 1617cdce2fe5SMarcel Hlopko 16187d382dcdSMarcel Hlopko /// Returns the range of the built node. 1619ac87a0b5SEduardo Caldas syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) { 16207d382dcdSMarcel Hlopko assert(L.getTypePtr()->hasTrailingReturn()); 16217d382dcdSMarcel Hlopko 16227d382dcdSMarcel Hlopko auto ReturnedType = L.getReturnLoc(); 16237d382dcdSMarcel Hlopko // Build node for the declarator, if any. 162438bc0060SEduardo Caldas auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType), 162538bc0060SEduardo Caldas ReturnedType.getEndLoc()); 1626a711a3a4SMarcel Hlopko syntax::SimpleDeclarator *ReturnDeclarator = nullptr; 16277d382dcdSMarcel Hlopko if (ReturnDeclaratorRange.isValid()) { 1628a711a3a4SMarcel Hlopko ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator; 1629a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(ReturnDeclaratorRange), 1630a711a3a4SMarcel Hlopko ReturnDeclarator, nullptr); 16317d382dcdSMarcel Hlopko } 16327d382dcdSMarcel Hlopko 16337d382dcdSMarcel Hlopko // Build node for trailing return type. 1634a711a3a4SMarcel Hlopko auto Return = Builder.getRange(ReturnedType.getSourceRange()); 16357d382dcdSMarcel Hlopko const auto *Arrow = Return.begin() - 1; 16367d382dcdSMarcel Hlopko assert(Arrow->kind() == tok::arrow); 16377d382dcdSMarcel Hlopko auto Tokens = llvm::makeArrayRef(Arrow, Return.end()); 163842f6fec3SEduardo Caldas Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken); 1639a711a3a4SMarcel Hlopko if (ReturnDeclarator) 1640718e550cSEduardo Caldas Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator); 1641a711a3a4SMarcel Hlopko auto *R = new (allocator()) syntax::TrailingReturnType; 1642cdce2fe5SMarcel Hlopko Builder.foldNode(Tokens, R, L); 1643a711a3a4SMarcel Hlopko return R; 16447d382dcdSMarcel Hlopko } 164588bf9b3dSMarcel Hlopko 1646a711a3a4SMarcel Hlopko void foldExplicitTemplateInstantiation( 1647a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW, 164888bf9b3dSMarcel Hlopko const syntax::Token *TemplateKW, 1649a711a3a4SMarcel Hlopko syntax::SimpleDeclaration *InnerDeclaration, Decl *From) { 165088bf9b3dSMarcel Hlopko assert(!ExternKW || ExternKW->kind() == tok::kw_extern); 165188bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 165242f6fec3SEduardo Caldas Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword); 165388bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1654718e550cSEduardo Caldas Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration); 1655a711a3a4SMarcel Hlopko Builder.foldNode( 1656a711a3a4SMarcel Hlopko Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From); 165788bf9b3dSMarcel Hlopko } 165888bf9b3dSMarcel Hlopko 1659a711a3a4SMarcel Hlopko syntax::TemplateDeclaration *foldTemplateDeclaration( 1660a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW, 1661a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) { 166288bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 166388bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1664a711a3a4SMarcel Hlopko 1665a711a3a4SMarcel Hlopko auto *N = new (allocator()) syntax::TemplateDeclaration; 1666a711a3a4SMarcel Hlopko Builder.foldNode(Range, N, From); 1667718e550cSEduardo Caldas Builder.markChild(N, syntax::NodeRole::Declaration); 1668a711a3a4SMarcel Hlopko return N; 166988bf9b3dSMarcel Hlopko } 167088bf9b3dSMarcel Hlopko 16719b3f38f9SIlya Biryukov /// A small helper to save some typing. 16729b3f38f9SIlya Biryukov llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } 16739b3f38f9SIlya Biryukov 16749b3f38f9SIlya Biryukov syntax::TreeBuilder &Builder; 16751db5b348SEduardo Caldas const ASTContext &Context; 16769b3f38f9SIlya Biryukov }; 16779b3f38f9SIlya Biryukov } // namespace 16789b3f38f9SIlya Biryukov 16797d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) { 1680e702bdb8SIlya Biryukov DeclsWithoutSemicolons.insert(D); 1681e702bdb8SIlya Biryukov } 1682e702bdb8SIlya Biryukov 1683def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) { 16849b3f38f9SIlya Biryukov if (Loc.isInvalid()) 16859b3f38f9SIlya Biryukov return; 16869b3f38f9SIlya Biryukov Pending.assignRole(*findToken(Loc), Role); 16879b3f38f9SIlya Biryukov } 16889b3f38f9SIlya Biryukov 16897d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) { 16907d382dcdSMarcel Hlopko if (!T) 16917d382dcdSMarcel Hlopko return; 16927d382dcdSMarcel Hlopko Pending.assignRole(*T, R); 16937d382dcdSMarcel Hlopko } 16947d382dcdSMarcel Hlopko 1695a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) { 1696a711a3a4SMarcel Hlopko assert(N); 1697a711a3a4SMarcel Hlopko setRole(N, R); 1698a711a3a4SMarcel Hlopko } 1699a711a3a4SMarcel Hlopko 1700a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) { 1701a711a3a4SMarcel Hlopko auto *SN = Mapping.find(N); 1702a711a3a4SMarcel Hlopko assert(SN != nullptr); 1703a711a3a4SMarcel Hlopko setRole(SN, R); 17047d382dcdSMarcel Hlopko } 1705f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) { 1706f9500cc4SEduardo Caldas auto *SN = Mapping.find(NNSLoc); 1707f9500cc4SEduardo Caldas assert(SN != nullptr); 1708f9500cc4SEduardo Caldas setRole(SN, R); 1709f9500cc4SEduardo Caldas } 17107d382dcdSMarcel Hlopko 171158fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) { 171258fa50f4SIlya Biryukov if (!Child) 171358fa50f4SIlya Biryukov return; 171458fa50f4SIlya Biryukov 1715b34b7691SDmitri Gribenko syntax::Tree *ChildNode; 1716b34b7691SDmitri Gribenko if (Expr *ChildExpr = dyn_cast<Expr>(Child)) { 171758fa50f4SIlya Biryukov // This is an expression in a statement position, consume the trailing 171858fa50f4SIlya Biryukov // semicolon and form an 'ExpressionStatement' node. 1719718e550cSEduardo Caldas markExprChild(ChildExpr, NodeRole::Expression); 1720a711a3a4SMarcel Hlopko ChildNode = new (allocator()) syntax::ExpressionStatement; 1721a711a3a4SMarcel Hlopko // (!) 'getStmtRange()' ensures this covers a trailing semicolon. 1722a711a3a4SMarcel Hlopko Pending.foldChildren(Arena, getStmtRange(Child), ChildNode); 1723b34b7691SDmitri Gribenko } else { 1724b34b7691SDmitri Gribenko ChildNode = Mapping.find(Child); 172558fa50f4SIlya Biryukov } 1726b34b7691SDmitri Gribenko assert(ChildNode != nullptr); 1727a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 172858fa50f4SIlya Biryukov } 172958fa50f4SIlya Biryukov 173058fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) { 1731be14a22bSIlya Biryukov if (!Child) 1732be14a22bSIlya Biryukov return; 17332325d6b4SEduardo Caldas Child = IgnoreImplicit(Child); 1734be14a22bSIlya Biryukov 1735a711a3a4SMarcel Hlopko syntax::Tree *ChildNode = Mapping.find(Child); 1736a711a3a4SMarcel Hlopko assert(ChildNode != nullptr); 1737a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 173858fa50f4SIlya Biryukov } 173958fa50f4SIlya Biryukov 17409b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { 174188bf9b3dSMarcel Hlopko if (L.isInvalid()) 174288bf9b3dSMarcel Hlopko return nullptr; 174378194118SMikhail Maltsev auto It = LocationToToken.find(L); 1744c1bbefefSIlya Biryukov assert(It != LocationToToken.end()); 1745c1bbefefSIlya Biryukov return It->second; 17469b3f38f9SIlya Biryukov } 17479b3f38f9SIlya Biryukov 1748142c6f82SKirill Bobyrev syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A, 1749142c6f82SKirill Bobyrev ASTContext &Context) { 17509b3f38f9SIlya Biryukov TreeBuilder Builder(A); 1751142c6f82SKirill Bobyrev BuildTreeVisitor(Context, Builder).TraverseAST(Context); 17529b3f38f9SIlya Biryukov return std::move(Builder).finalize(); 17539b3f38f9SIlya Biryukov } 1754