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; 300*e159a3ceSHaojian Wu // End of TypeLoc could be invalid if the type is invalid, fallback to the 301*e159a3ceSHaojian Wu // NameLoc. 302*e159a3ceSHaojian 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 85958fa50f4SIlya Biryukov // Some expressions are not yet handled by syntax trees. 86058fa50f4SIlya Biryukov bool WalkUpFromExpr(Expr *E) { 86158fa50f4SIlya Biryukov assert(!isImplicitExpr(E) && "should be handled by TraverseStmt"); 86258fa50f4SIlya Biryukov Builder.foldNode(Builder.getExprRange(E), 863a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownExpression, E); 86458fa50f4SIlya Biryukov return true; 86558fa50f4SIlya Biryukov } 86658fa50f4SIlya Biryukov 867f33c2c27SEduardo Caldas bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) { 868f33c2c27SEduardo Caldas // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node 869f33c2c27SEduardo Caldas // referencing the location of the UDL suffix (`_w` in `1.2_w`). The 870f33c2c27SEduardo Caldas // UDL suffix location does not point to the beginning of a token, so we 871f33c2c27SEduardo Caldas // can't represent the UDL suffix as a separate syntax tree node. 872f33c2c27SEduardo Caldas 873f33c2c27SEduardo Caldas return WalkUpFromUserDefinedLiteral(S); 874f33c2c27SEduardo Caldas } 875f33c2c27SEduardo Caldas 8761db5b348SEduardo Caldas syntax::UserDefinedLiteralExpression * 8771db5b348SEduardo Caldas buildUserDefinedLiteral(UserDefinedLiteral *S) { 878f33c2c27SEduardo Caldas switch (S->getLiteralOperatorKind()) { 879ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Integer: 8801db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 881ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Floating: 8821db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 883ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Character: 8841db5b348SEduardo Caldas return new (allocator()) syntax::CharUserDefinedLiteralExpression; 885ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_String: 8861db5b348SEduardo Caldas return new (allocator()) syntax::StringUserDefinedLiteralExpression; 887ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Raw: 888ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Template: 8891db5b348SEduardo Caldas // For raw literal operator and numeric literal operator template we 8901db5b348SEduardo Caldas // cannot get the type of the operand in the semantic AST. We get this 8911db5b348SEduardo Caldas // information from the token. As integer and floating point have the same 8921db5b348SEduardo Caldas // token kind, we run `NumericLiteralParser` again to distinguish them. 8931db5b348SEduardo Caldas auto TokLoc = S->getBeginLoc(); 8941db5b348SEduardo Caldas auto TokSpelling = 895a474d5baSEduardo Caldas Builder.findToken(TokLoc)->text(Context.getSourceManager()); 8961db5b348SEduardo Caldas auto Literal = 8971db5b348SEduardo Caldas NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(), 8981db5b348SEduardo Caldas Context.getLangOpts(), Context.getTargetInfo(), 8991db5b348SEduardo Caldas Context.getDiagnostics()); 9001db5b348SEduardo Caldas if (Literal.isIntegerLiteral()) 9011db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression; 902a474d5baSEduardo Caldas else { 903a474d5baSEduardo Caldas assert(Literal.isFloatingLiteral()); 9041db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression; 905f33c2c27SEduardo Caldas } 906f33c2c27SEduardo Caldas } 907b8409c03SMichael Liao llvm_unreachable("Unknown literal operator kind."); 908a474d5baSEduardo Caldas } 909f33c2c27SEduardo Caldas 910f33c2c27SEduardo Caldas bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) { 911f33c2c27SEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 9121db5b348SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S); 913f33c2c27SEduardo Caldas return true; 914f33c2c27SEduardo Caldas } 915f33c2c27SEduardo Caldas 9168abb5fb6SEduardo Caldas // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the 9178abb5fb6SEduardo Caldas // `DependentTemplateSpecializationType` case. 918f9500cc4SEduardo Caldas /// Given a nested-name-specifier return the range for the last name 919f9500cc4SEduardo Caldas /// specifier. 9208abb5fb6SEduardo Caldas /// 9218abb5fb6SEduardo Caldas /// e.g. `std::T::template X<U>::` => `template X<U>::` 9228abb5fb6SEduardo Caldas SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) { 9238abb5fb6SEduardo Caldas auto SR = NNSLoc.getLocalSourceRange(); 9248abb5fb6SEduardo Caldas 925f9500cc4SEduardo Caldas // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should* 926f9500cc4SEduardo Caldas // return the desired `SourceRange`, but there is a corner case. For a 927f9500cc4SEduardo Caldas // `DependentTemplateSpecializationType` this method returns its 9288abb5fb6SEduardo Caldas // qualifiers as well, in other words in the example above this method 9298abb5fb6SEduardo Caldas // returns `T::template X<U>::` instead of only `template X<U>::` 9308abb5fb6SEduardo Caldas if (auto TL = NNSLoc.getTypeLoc()) { 9318abb5fb6SEduardo Caldas if (auto DependentTL = 9328abb5fb6SEduardo Caldas TL.getAs<DependentTemplateSpecializationTypeLoc>()) { 9338abb5fb6SEduardo Caldas // The 'template' keyword is always present in dependent template 9348abb5fb6SEduardo Caldas // specializations. Except in the case of incorrect code 9358abb5fb6SEduardo Caldas // TODO: Treat the case of incorrect code. 9368abb5fb6SEduardo Caldas SR.setBegin(DependentTL.getTemplateKeywordLoc()); 9378abb5fb6SEduardo Caldas } 9388abb5fb6SEduardo Caldas } 9398abb5fb6SEduardo Caldas 9408abb5fb6SEduardo Caldas return SR; 9418abb5fb6SEduardo Caldas } 9428abb5fb6SEduardo Caldas 943f9500cc4SEduardo Caldas syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) { 944f9500cc4SEduardo Caldas switch (NNS.getKind()) { 945f9500cc4SEduardo Caldas case NestedNameSpecifier::Global: 946f9500cc4SEduardo Caldas return syntax::NodeKind::GlobalNameSpecifier; 947f9500cc4SEduardo Caldas case NestedNameSpecifier::Namespace: 948f9500cc4SEduardo Caldas case NestedNameSpecifier::NamespaceAlias: 949f9500cc4SEduardo Caldas case NestedNameSpecifier::Identifier: 950f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 951f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpecWithTemplate: 952f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 953f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpec: { 954f9500cc4SEduardo Caldas const auto *NNSType = NNS.getAsType(); 955f9500cc4SEduardo Caldas assert(NNSType); 956f9500cc4SEduardo Caldas if (isa<DecltypeType>(NNSType)) 957f9500cc4SEduardo Caldas return syntax::NodeKind::DecltypeNameSpecifier; 958f9500cc4SEduardo Caldas if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>( 959f9500cc4SEduardo Caldas NNSType)) 960f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier; 961f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier; 962f9500cc4SEduardo Caldas } 963f9500cc4SEduardo Caldas default: 964f9500cc4SEduardo Caldas // FIXME: Support Microsoft's __super 965f9500cc4SEduardo Caldas llvm::report_fatal_error("We don't yet support the __super specifier", 966f9500cc4SEduardo Caldas true); 967f9500cc4SEduardo Caldas } 968f9500cc4SEduardo Caldas } 969f9500cc4SEduardo Caldas 970f9500cc4SEduardo Caldas syntax::NameSpecifier * 971ac87a0b5SEduardo Caldas buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) { 972f9500cc4SEduardo Caldas assert(NNSLoc.hasQualifier()); 973f9500cc4SEduardo Caldas auto NameSpecifierTokens = 974f9500cc4SEduardo Caldas Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back(); 975f9500cc4SEduardo Caldas switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) { 976f9500cc4SEduardo Caldas case syntax::NodeKind::GlobalNameSpecifier: 977f9500cc4SEduardo Caldas return new (allocator()) syntax::GlobalNameSpecifier; 978f9500cc4SEduardo Caldas case syntax::NodeKind::IdentifierNameSpecifier: { 979f9500cc4SEduardo Caldas assert(NameSpecifierTokens.size() == 1); 980f9500cc4SEduardo Caldas Builder.markChildToken(NameSpecifierTokens.begin(), 981f9500cc4SEduardo Caldas syntax::NodeRole::Unknown); 982f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::IdentifierNameSpecifier; 983f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 984f9500cc4SEduardo Caldas return NS; 985f9500cc4SEduardo Caldas } 986f9500cc4SEduardo Caldas case syntax::NodeKind::SimpleTemplateNameSpecifier: { 987f9500cc4SEduardo Caldas // TODO: Build `SimpleTemplateNameSpecifier` children and implement 988f9500cc4SEduardo Caldas // accessors to them. 989f9500cc4SEduardo Caldas // Be aware, we cannot do that simply by calling `TraverseTypeLoc`, 990f9500cc4SEduardo Caldas // some `TypeLoc`s have inside them the previous name specifier and 991f9500cc4SEduardo Caldas // we want to treat them independently. 992f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier; 993f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 994f9500cc4SEduardo Caldas return NS; 995f9500cc4SEduardo Caldas } 996f9500cc4SEduardo Caldas case syntax::NodeKind::DecltypeNameSpecifier: { 997f9500cc4SEduardo Caldas const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>(); 998f9500cc4SEduardo Caldas if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL)) 9998abb5fb6SEduardo Caldas return nullptr; 1000f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::DecltypeNameSpecifier; 1001f9500cc4SEduardo Caldas // TODO: Implement accessor to `DecltypeNameSpecifier` inner 1002f9500cc4SEduardo Caldas // `DecltypeTypeLoc`. 1003f9500cc4SEduardo Caldas // For that add mapping from `TypeLoc` to `syntax::Node*` then: 1004f9500cc4SEduardo Caldas // Builder.markChild(TypeLoc, syntax::NodeRole); 1005f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr); 1006f9500cc4SEduardo Caldas return NS; 1007f9500cc4SEduardo Caldas } 1008f9500cc4SEduardo Caldas default: 1009f9500cc4SEduardo Caldas llvm_unreachable("getChildKind() does not return this value"); 1010f9500cc4SEduardo Caldas } 1011f9500cc4SEduardo Caldas } 1012f9500cc4SEduardo Caldas 1013f9500cc4SEduardo Caldas // To build syntax tree nodes for NestedNameSpecifierLoc we override 1014f9500cc4SEduardo Caldas // Traverse instead of WalkUpFrom because we want to traverse the children 1015f9500cc4SEduardo Caldas // ourselves and build a list instead of a nested tree of name specifier 1016f9500cc4SEduardo Caldas // prefixes. 1017f9500cc4SEduardo Caldas bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) { 1018f9500cc4SEduardo Caldas if (!QualifierLoc) 1019f9500cc4SEduardo Caldas return true; 102087f0b51dSEduardo Caldas for (auto It = QualifierLoc; It; It = It.getPrefix()) { 102187f0b51dSEduardo Caldas auto *NS = buildNameSpecifier(It); 1022f9500cc4SEduardo Caldas if (!NS) 1023f9500cc4SEduardo Caldas return false; 1024718e550cSEduardo Caldas Builder.markChild(NS, syntax::NodeRole::ListElement); 102587f0b51dSEduardo Caldas Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter); 10268abb5fb6SEduardo Caldas } 1027f9500cc4SEduardo Caldas Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()), 1028f9500cc4SEduardo Caldas new (allocator()) syntax::NestedNameSpecifier, 10298abb5fb6SEduardo Caldas QualifierLoc); 1030f9500cc4SEduardo Caldas return true; 10318abb5fb6SEduardo Caldas } 10328abb5fb6SEduardo Caldas 1033a4ef9e86SEduardo Caldas syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc, 1034a4ef9e86SEduardo Caldas SourceLocation TemplateKeywordLoc, 1035a4ef9e86SEduardo Caldas SourceRange UnqualifiedIdLoc, 1036a4ef9e86SEduardo Caldas ASTPtr From) { 1037a4ef9e86SEduardo Caldas if (QualifierLoc) { 1038718e550cSEduardo Caldas Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier); 1039ba32915dSEduardo Caldas if (TemplateKeywordLoc.isValid()) 1040ba32915dSEduardo Caldas Builder.markChildToken(TemplateKeywordLoc, 1041ba32915dSEduardo Caldas syntax::NodeRole::TemplateKeyword); 1042a4ef9e86SEduardo Caldas } 1043ba32915dSEduardo Caldas 1044ba32915dSEduardo Caldas auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId; 1045a4ef9e86SEduardo Caldas Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId, 1046a4ef9e86SEduardo Caldas nullptr); 1047718e550cSEduardo Caldas Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId); 1048ba32915dSEduardo Caldas 1049a4ef9e86SEduardo Caldas auto IdExpressionBeginLoc = 1050a4ef9e86SEduardo Caldas QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin(); 1051ba32915dSEduardo Caldas 1052a4ef9e86SEduardo Caldas auto *TheIdExpression = new (allocator()) syntax::IdExpression; 1053a4ef9e86SEduardo Caldas Builder.foldNode( 1054a4ef9e86SEduardo Caldas Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()), 1055a4ef9e86SEduardo Caldas TheIdExpression, From); 1056a4ef9e86SEduardo Caldas 1057a4ef9e86SEduardo Caldas return TheIdExpression; 1058a4ef9e86SEduardo Caldas } 1059a4ef9e86SEduardo Caldas 1060a4ef9e86SEduardo Caldas bool WalkUpFromMemberExpr(MemberExpr *S) { 1061ba32915dSEduardo Caldas // For `MemberExpr` with implicit `this->` we generate a simple 1062ba32915dSEduardo Caldas // `id-expression` syntax node, beacuse an implicit `member-expression` is 1063ba32915dSEduardo Caldas // syntactically undistinguishable from an `id-expression` 1064ba32915dSEduardo Caldas if (S->isImplicitAccess()) { 1065a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1066a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), S); 1067ba32915dSEduardo Caldas return true; 1068ba32915dSEduardo Caldas } 1069a4ef9e86SEduardo Caldas 1070a4ef9e86SEduardo Caldas auto *TheIdExpression = buildIdExpression( 1071a4ef9e86SEduardo Caldas S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1072a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr); 1073ba32915dSEduardo Caldas 1074718e550cSEduardo Caldas Builder.markChild(TheIdExpression, syntax::NodeRole::Member); 1075ba32915dSEduardo Caldas 1076718e550cSEduardo Caldas Builder.markExprChild(S->getBase(), syntax::NodeRole::Object); 1077718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken); 1078ba32915dSEduardo Caldas 1079ba32915dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1080ba32915dSEduardo Caldas new (allocator()) syntax::MemberExpression, S); 1081ba32915dSEduardo Caldas return true; 1082ba32915dSEduardo Caldas } 1083ba32915dSEduardo Caldas 10841b2f6b4aSEduardo Caldas bool WalkUpFromDeclRefExpr(DeclRefExpr *S) { 1085a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1086a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 10878abb5fb6SEduardo Caldas 10888abb5fb6SEduardo Caldas return true; 10891b2f6b4aSEduardo Caldas } 10908abb5fb6SEduardo Caldas 10918abb5fb6SEduardo Caldas // Same logic as DeclRefExpr. 10928abb5fb6SEduardo Caldas bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) { 1093a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(), 1094a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S); 10958abb5fb6SEduardo Caldas 10961b2f6b4aSEduardo Caldas return true; 10971b2f6b4aSEduardo Caldas } 10981b2f6b4aSEduardo Caldas 109985c15f17SEduardo Caldas bool WalkUpFromCXXThisExpr(CXXThisExpr *S) { 110085c15f17SEduardo Caldas if (!S->isImplicit()) { 110185c15f17SEduardo Caldas Builder.markChildToken(S->getLocation(), 110285c15f17SEduardo Caldas syntax::NodeRole::IntroducerKeyword); 110385c15f17SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 110485c15f17SEduardo Caldas new (allocator()) syntax::ThisExpression, S); 110585c15f17SEduardo Caldas } 110685c15f17SEduardo Caldas return true; 110785c15f17SEduardo Caldas } 110885c15f17SEduardo Caldas 1109fdbd7833SEduardo Caldas bool WalkUpFromParenExpr(ParenExpr *S) { 1110fdbd7833SEduardo Caldas Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen); 1111718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression); 1112fdbd7833SEduardo Caldas Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen); 1113fdbd7833SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1114fdbd7833SEduardo Caldas new (allocator()) syntax::ParenExpression, S); 1115fdbd7833SEduardo Caldas return true; 1116fdbd7833SEduardo Caldas } 1117fdbd7833SEduardo Caldas 11183b739690SEduardo Caldas bool WalkUpFromIntegerLiteral(IntegerLiteral *S) { 111942f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11203b739690SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11213b739690SEduardo Caldas new (allocator()) syntax::IntegerLiteralExpression, S); 11223b739690SEduardo Caldas return true; 11233b739690SEduardo Caldas } 11243b739690SEduardo Caldas 1125221d7bbeSEduardo Caldas bool WalkUpFromCharacterLiteral(CharacterLiteral *S) { 1126221d7bbeSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1127221d7bbeSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1128221d7bbeSEduardo Caldas new (allocator()) syntax::CharacterLiteralExpression, S); 1129221d7bbeSEduardo Caldas return true; 1130221d7bbeSEduardo Caldas } 11317b404b6dSEduardo Caldas 11327b404b6dSEduardo Caldas bool WalkUpFromFloatingLiteral(FloatingLiteral *S) { 11337b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11347b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11357b404b6dSEduardo Caldas new (allocator()) syntax::FloatingLiteralExpression, S); 11367b404b6dSEduardo Caldas return true; 11377b404b6dSEduardo Caldas } 11387b404b6dSEduardo Caldas 1139466e8b7eSEduardo Caldas bool WalkUpFromStringLiteral(StringLiteral *S) { 1140466e8b7eSEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken); 1141466e8b7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1142466e8b7eSEduardo Caldas new (allocator()) syntax::StringLiteralExpression, S); 1143466e8b7eSEduardo Caldas return true; 1144466e8b7eSEduardo Caldas } 1145221d7bbeSEduardo Caldas 11467b404b6dSEduardo Caldas bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) { 11477b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 11487b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11497b404b6dSEduardo Caldas new (allocator()) syntax::BoolLiteralExpression, S); 11507b404b6dSEduardo Caldas return true; 11517b404b6dSEduardo Caldas } 11527b404b6dSEduardo Caldas 1153007098d7SEduardo Caldas bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) { 115442f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken); 1155007098d7SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1156007098d7SEduardo Caldas new (allocator()) syntax::CxxNullPtrExpression, S); 1157007098d7SEduardo Caldas return true; 1158007098d7SEduardo Caldas } 1159007098d7SEduardo Caldas 1160461af57dSEduardo Caldas bool WalkUpFromUnaryOperator(UnaryOperator *S) { 116142f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1162718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1163718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand); 1164461af57dSEduardo Caldas 1165461af57dSEduardo Caldas if (S->isPostfix()) 1166461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1167461af57dSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1168461af57dSEduardo Caldas S); 1169461af57dSEduardo Caldas else 1170461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1171461af57dSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1172461af57dSEduardo Caldas S); 1173461af57dSEduardo Caldas 1174461af57dSEduardo Caldas return true; 1175461af57dSEduardo Caldas } 1176461af57dSEduardo Caldas 11773785eb83SEduardo Caldas bool WalkUpFromBinaryOperator(BinaryOperator *S) { 1178718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide); 117942f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1180718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1181718e550cSEduardo Caldas Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide); 11823785eb83SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 11833785eb83SEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 11843785eb83SEduardo Caldas return true; 11853785eb83SEduardo Caldas } 11863785eb83SEduardo Caldas 1187f5087d5cSEduardo Caldas /// Builds `CallArguments` syntax node from arguments that appear in source 1188f5087d5cSEduardo Caldas /// code, i.e. not default arguments. 1189f5087d5cSEduardo Caldas syntax::CallArguments * 1190f5087d5cSEduardo Caldas buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) { 1191f5087d5cSEduardo Caldas auto Args = dropDefaultArgs(ArgsAndDefaultArgs); 1192e10df779SDmitri Gribenko for (auto *Arg : Args) { 1193718e550cSEduardo Caldas Builder.markExprChild(Arg, syntax::NodeRole::ListElement); 11942de2ca34SEduardo Caldas const auto *DelimiterToken = 11952de2ca34SEduardo Caldas std::next(Builder.findToken(Arg->getEndLoc())); 11962de2ca34SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1197718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 11982de2ca34SEduardo Caldas } 11992de2ca34SEduardo Caldas 12002de2ca34SEduardo Caldas auto *Arguments = new (allocator()) syntax::CallArguments; 12012de2ca34SEduardo Caldas if (!Args.empty()) 12022de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(), 12032de2ca34SEduardo Caldas (*(Args.end() - 1))->getEndLoc()), 12042de2ca34SEduardo Caldas Arguments, nullptr); 12052de2ca34SEduardo Caldas 12062de2ca34SEduardo Caldas return Arguments; 12072de2ca34SEduardo Caldas } 12082de2ca34SEduardo Caldas 12092de2ca34SEduardo Caldas bool WalkUpFromCallExpr(CallExpr *S) { 1210718e550cSEduardo Caldas Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee); 12112de2ca34SEduardo Caldas 12122de2ca34SEduardo Caldas const auto *LParenToken = 12132de2ca34SEduardo Caldas std::next(Builder.findToken(S->getCallee()->getEndLoc())); 12142de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed 12152de2ca34SEduardo Caldas // the test on decltype desctructors. 12162de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 12172de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 12182de2ca34SEduardo Caldas 12192de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(S->arguments()), 1220718e550cSEduardo Caldas syntax::NodeRole::Arguments); 12212de2ca34SEduardo Caldas 12222de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 12232de2ca34SEduardo Caldas 12242de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 12252de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 12262de2ca34SEduardo Caldas return true; 12272de2ca34SEduardo Caldas } 12282de2ca34SEduardo Caldas 122946f4439dSEduardo Caldas bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) { 123046f4439dSEduardo Caldas // Ignore the implicit calls to default constructors. 123146f4439dSEduardo Caldas if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) && 123246f4439dSEduardo Caldas S->getParenOrBraceRange().isInvalid()) 123346f4439dSEduardo Caldas return true; 123446f4439dSEduardo Caldas return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S); 123546f4439dSEduardo Caldas } 123646f4439dSEduardo Caldas 1237ea8bba7eSEduardo Caldas bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1238ac37afa6SEduardo Caldas // To construct a syntax tree of the same shape for calls to built-in and 1239ac37afa6SEduardo Caldas // user-defined operators, ignore the `DeclRefExpr` that refers to the 1240ac37afa6SEduardo Caldas // operator and treat it as a simple token. Do that by traversing 1241ac37afa6SEduardo Caldas // arguments instead of children. 1242ac37afa6SEduardo Caldas for (auto *child : S->arguments()) { 1243f33c2c27SEduardo Caldas // A postfix unary operator is declared as taking two operands. The 1244f33c2c27SEduardo Caldas // second operand is used to distinguish from its prefix counterpart. In 1245f33c2c27SEduardo Caldas // the semantic AST this "phantom" operand is represented as a 1246ea8bba7eSEduardo Caldas // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this 1247ea8bba7eSEduardo Caldas // operand because it does not correspond to anything written in source 1248ac37afa6SEduardo Caldas // code. 1249ac37afa6SEduardo Caldas if (child->getSourceRange().isInvalid()) { 1250ac37afa6SEduardo Caldas assert(getOperatorNodeKind(*S) == 1251ac37afa6SEduardo Caldas syntax::NodeKind::PostfixUnaryOperatorExpression); 1252ea8bba7eSEduardo Caldas continue; 1253ac37afa6SEduardo Caldas } 1254ea8bba7eSEduardo Caldas if (!TraverseStmt(child)) 1255ea8bba7eSEduardo Caldas return false; 1256ea8bba7eSEduardo Caldas } 1257ea8bba7eSEduardo Caldas return WalkUpFromCXXOperatorCallExpr(S); 1258ea8bba7eSEduardo Caldas } 1259ea8bba7eSEduardo Caldas 12603a574a6cSEduardo Caldas bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1261ea8bba7eSEduardo Caldas switch (getOperatorNodeKind(*S)) { 1262ea8bba7eSEduardo Caldas case syntax::NodeKind::BinaryOperatorExpression: 1263718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide); 1264718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1265718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1266718e550cSEduardo Caldas Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide); 12673a574a6cSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 12683a574a6cSEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S); 12693a574a6cSEduardo Caldas return true; 1270ea8bba7eSEduardo Caldas case syntax::NodeKind::PrefixUnaryOperatorExpression: 1271718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1272718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1273718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1274ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1275ea8bba7eSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression, 1276ea8bba7eSEduardo Caldas S); 1277ea8bba7eSEduardo Caldas return true; 1278ea8bba7eSEduardo Caldas case syntax::NodeKind::PostfixUnaryOperatorExpression: 1279718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), 1280718e550cSEduardo Caldas syntax::NodeRole::OperatorToken); 1281718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1282ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S), 1283ea8bba7eSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression, 1284ea8bba7eSEduardo Caldas S); 1285ea8bba7eSEduardo Caldas return true; 12862de2ca34SEduardo Caldas case syntax::NodeKind::CallExpression: { 1287718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee); 12882de2ca34SEduardo Caldas 12892de2ca34SEduardo Caldas const auto *LParenToken = 12902de2ca34SEduardo Caldas std::next(Builder.findToken(S->getArg(0)->getEndLoc())); 12912de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have 12922de2ca34SEduardo Caldas // fixed the test on decltype desctructors. 12932de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren) 12942de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 12952de2ca34SEduardo Caldas 12962de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(CallExpr::arg_range( 12972de2ca34SEduardo Caldas S->arg_begin() + 1, S->arg_end())), 1298718e550cSEduardo Caldas syntax::NodeRole::Arguments); 12992de2ca34SEduardo Caldas 13002de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 13012de2ca34SEduardo Caldas 13022de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()), 13032de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S); 13042de2ca34SEduardo Caldas return true; 13052de2ca34SEduardo Caldas } 1306ea8bba7eSEduardo Caldas case syntax::NodeKind::UnknownExpression: 13072de2ca34SEduardo Caldas return WalkUpFromExpr(S); 1308ea8bba7eSEduardo Caldas default: 1309ea8bba7eSEduardo Caldas llvm_unreachable("getOperatorNodeKind() does not return this value"); 1310ea8bba7eSEduardo Caldas } 13113a574a6cSEduardo Caldas } 13123a574a6cSEduardo Caldas 1313f5087d5cSEduardo Caldas bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; } 1314f5087d5cSEduardo Caldas 1315be14a22bSIlya Biryukov bool WalkUpFromNamespaceDecl(NamespaceDecl *S) { 1316cdce2fe5SMarcel Hlopko auto Tokens = Builder.getDeclarationRange(S); 1317be14a22bSIlya Biryukov if (Tokens.front().kind() == tok::coloncolon) { 1318be14a22bSIlya Biryukov // Handle nested namespace definitions. Those start at '::' token, e.g. 1319be14a22bSIlya Biryukov // namespace a^::b {} 1320be14a22bSIlya Biryukov // FIXME: build corresponding nodes for the name of this namespace. 1321be14a22bSIlya Biryukov return true; 1322be14a22bSIlya Biryukov } 1323a711a3a4SMarcel Hlopko Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S); 1324be14a22bSIlya Biryukov return true; 1325be14a22bSIlya Biryukov } 1326be14a22bSIlya Biryukov 13278ce15f7eSEduardo Caldas // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test 13288ce15f7eSEduardo Caldas // results. Find test coverage or remove it. 13297d382dcdSMarcel Hlopko bool TraverseParenTypeLoc(ParenTypeLoc L) { 13307d382dcdSMarcel Hlopko // We reverse order of traversal to get the proper syntax structure. 13317d382dcdSMarcel Hlopko if (!WalkUpFromParenTypeLoc(L)) 13327d382dcdSMarcel Hlopko return false; 13337d382dcdSMarcel Hlopko return TraverseTypeLoc(L.getInnerLoc()); 13347d382dcdSMarcel Hlopko } 13357d382dcdSMarcel Hlopko 13367d382dcdSMarcel Hlopko bool WalkUpFromParenTypeLoc(ParenTypeLoc L) { 13377d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 13387d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 13397d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()), 1340a711a3a4SMarcel Hlopko new (allocator()) syntax::ParenDeclarator, L); 13417d382dcdSMarcel Hlopko return true; 13427d382dcdSMarcel Hlopko } 13437d382dcdSMarcel Hlopko 13447d382dcdSMarcel Hlopko // Declarator chunks, they are produced by type locs and some clang::Decls. 13457d382dcdSMarcel Hlopko bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) { 13467d382dcdSMarcel Hlopko Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen); 1347718e550cSEduardo Caldas Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size); 13487d382dcdSMarcel Hlopko Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen); 13497d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()), 1350a711a3a4SMarcel Hlopko new (allocator()) syntax::ArraySubscript, L); 13517d382dcdSMarcel Hlopko return true; 13527d382dcdSMarcel Hlopko } 13537d382dcdSMarcel Hlopko 1354dc3d4743SEduardo Caldas syntax::ParameterDeclarationList * 1355dc3d4743SEduardo Caldas buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) { 1356dc3d4743SEduardo Caldas for (auto *P : Params) { 1357718e550cSEduardo Caldas Builder.markChild(P, syntax::NodeRole::ListElement); 1358dc3d4743SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc())); 1359dc3d4743SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1360718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 1361dc3d4743SEduardo Caldas } 1362dc3d4743SEduardo Caldas auto *Parameters = new (allocator()) syntax::ParameterDeclarationList; 1363dc3d4743SEduardo Caldas if (!Params.empty()) 1364dc3d4743SEduardo Caldas Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(), 1365dc3d4743SEduardo Caldas Params.back()->getEndLoc()), 1366dc3d4743SEduardo Caldas Parameters, nullptr); 1367dc3d4743SEduardo Caldas return Parameters; 1368dc3d4743SEduardo Caldas } 1369dc3d4743SEduardo Caldas 13707d382dcdSMarcel Hlopko bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) { 13717d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 1372dc3d4743SEduardo Caldas 1373dc3d4743SEduardo Caldas Builder.markChild(buildParameterDeclarationList(L.getParams()), 1374718e550cSEduardo Caldas syntax::NodeRole::Parameters); 1375dc3d4743SEduardo Caldas 13767d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 13777d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()), 1378a711a3a4SMarcel Hlopko new (allocator()) syntax::ParametersAndQualifiers, L); 13797d382dcdSMarcel Hlopko return true; 13807d382dcdSMarcel Hlopko } 13817d382dcdSMarcel Hlopko 13827d382dcdSMarcel Hlopko bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) { 13837d382dcdSMarcel Hlopko if (!L.getTypePtr()->hasTrailingReturn()) 13847d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13857d382dcdSMarcel Hlopko 1386ac87a0b5SEduardo Caldas auto *TrailingReturnTokens = buildTrailingReturn(L); 13877d382dcdSMarcel Hlopko // Finish building the node for parameters. 1388718e550cSEduardo Caldas Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn); 13897d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L); 13907d382dcdSMarcel Hlopko } 13917d382dcdSMarcel Hlopko 13928ce15f7eSEduardo Caldas bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) { 13938ce15f7eSEduardo Caldas // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds 13948ce15f7eSEduardo Caldas // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to 13958ce15f7eSEduardo Caldas // "(Y::*mp)" We thus reverse the order of traversal to get the proper 13968ce15f7eSEduardo Caldas // syntax structure. 13978ce15f7eSEduardo Caldas if (!WalkUpFromMemberPointerTypeLoc(L)) 13988ce15f7eSEduardo Caldas return false; 13998ce15f7eSEduardo Caldas return TraverseTypeLoc(L.getPointeeLoc()); 14008ce15f7eSEduardo Caldas } 14018ce15f7eSEduardo Caldas 14027d382dcdSMarcel Hlopko bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) { 14037d382dcdSMarcel Hlopko auto SR = L.getLocalSourceRange(); 1404a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(SR), 1405a711a3a4SMarcel Hlopko new (allocator()) syntax::MemberPointer, L); 14067d382dcdSMarcel Hlopko return true; 14077d382dcdSMarcel Hlopko } 14087d382dcdSMarcel Hlopko 140958fa50f4SIlya Biryukov // The code below is very regular, it could even be generated with some 141058fa50f4SIlya Biryukov // preprocessor magic. We merely assign roles to the corresponding children 141158fa50f4SIlya Biryukov // and fold resulting nodes. 141258fa50f4SIlya Biryukov bool WalkUpFromDeclStmt(DeclStmt *S) { 141358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1414a711a3a4SMarcel Hlopko new (allocator()) syntax::DeclarationStatement, S); 141558fa50f4SIlya Biryukov return true; 141658fa50f4SIlya Biryukov } 141758fa50f4SIlya Biryukov 141858fa50f4SIlya Biryukov bool WalkUpFromNullStmt(NullStmt *S) { 141958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1420a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyStatement, S); 142158fa50f4SIlya Biryukov return true; 142258fa50f4SIlya Biryukov } 142358fa50f4SIlya Biryukov 142458fa50f4SIlya Biryukov bool WalkUpFromSwitchStmt(SwitchStmt *S) { 1425def65bb4SIlya Biryukov Builder.markChildToken(S->getSwitchLoc(), 142658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 142758fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 142858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1429a711a3a4SMarcel Hlopko new (allocator()) syntax::SwitchStatement, S); 143058fa50f4SIlya Biryukov return true; 143158fa50f4SIlya Biryukov } 143258fa50f4SIlya Biryukov 143358fa50f4SIlya Biryukov bool WalkUpFromCaseStmt(CaseStmt *S) { 1434def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 143558fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1436718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue); 143758fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 143858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1439a711a3a4SMarcel Hlopko new (allocator()) syntax::CaseStatement, S); 144058fa50f4SIlya Biryukov return true; 144158fa50f4SIlya Biryukov } 144258fa50f4SIlya Biryukov 144358fa50f4SIlya Biryukov bool WalkUpFromDefaultStmt(DefaultStmt *S) { 1444def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(), 144558fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 144658fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 144758fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1448a711a3a4SMarcel Hlopko new (allocator()) syntax::DefaultStatement, S); 144958fa50f4SIlya Biryukov return true; 145058fa50f4SIlya Biryukov } 145158fa50f4SIlya Biryukov 145258fa50f4SIlya Biryukov bool WalkUpFromIfStmt(IfStmt *S) { 1453def65bb4SIlya Biryukov Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword); 14546c1a2330SHaojian Wu Stmt *ConditionStatement = S->getCond(); 14556c1a2330SHaojian Wu if (S->hasVarStorage()) 14566c1a2330SHaojian Wu ConditionStatement = S->getConditionVariableDeclStmt(); 14576c1a2330SHaojian Wu Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition); 1458718e550cSEduardo Caldas Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement); 1459718e550cSEduardo Caldas Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword); 1460718e550cSEduardo Caldas Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement); 146158fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1462a711a3a4SMarcel Hlopko new (allocator()) syntax::IfStatement, S); 146358fa50f4SIlya Biryukov return true; 146458fa50f4SIlya Biryukov } 146558fa50f4SIlya Biryukov 146658fa50f4SIlya Biryukov bool WalkUpFromForStmt(ForStmt *S) { 1467def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 146858fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 146958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1470a711a3a4SMarcel Hlopko new (allocator()) syntax::ForStatement, S); 147158fa50f4SIlya Biryukov return true; 147258fa50f4SIlya Biryukov } 147358fa50f4SIlya Biryukov 147458fa50f4SIlya Biryukov bool WalkUpFromWhileStmt(WhileStmt *S) { 1475def65bb4SIlya Biryukov Builder.markChildToken(S->getWhileLoc(), 147658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 147758fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 147858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1479a711a3a4SMarcel Hlopko new (allocator()) syntax::WhileStatement, S); 148058fa50f4SIlya Biryukov return true; 148158fa50f4SIlya Biryukov } 148258fa50f4SIlya Biryukov 148358fa50f4SIlya Biryukov bool WalkUpFromContinueStmt(ContinueStmt *S) { 1484def65bb4SIlya Biryukov Builder.markChildToken(S->getContinueLoc(), 148558fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 148658fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1487a711a3a4SMarcel Hlopko new (allocator()) syntax::ContinueStatement, S); 148858fa50f4SIlya Biryukov return true; 148958fa50f4SIlya Biryukov } 149058fa50f4SIlya Biryukov 149158fa50f4SIlya Biryukov bool WalkUpFromBreakStmt(BreakStmt *S) { 1492def65bb4SIlya Biryukov Builder.markChildToken(S->getBreakLoc(), 149358fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 149458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1495a711a3a4SMarcel Hlopko new (allocator()) syntax::BreakStatement, S); 149658fa50f4SIlya Biryukov return true; 149758fa50f4SIlya Biryukov } 149858fa50f4SIlya Biryukov 149958fa50f4SIlya Biryukov bool WalkUpFromReturnStmt(ReturnStmt *S) { 1500def65bb4SIlya Biryukov Builder.markChildToken(S->getReturnLoc(), 150158fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword); 1502718e550cSEduardo Caldas Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue); 150358fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1504a711a3a4SMarcel Hlopko new (allocator()) syntax::ReturnStatement, S); 150558fa50f4SIlya Biryukov return true; 150658fa50f4SIlya Biryukov } 150758fa50f4SIlya Biryukov 150858fa50f4SIlya Biryukov bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) { 1509def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 151058fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 151158fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S), 1512a711a3a4SMarcel Hlopko new (allocator()) syntax::RangeBasedForStatement, S); 151358fa50f4SIlya Biryukov return true; 151458fa50f4SIlya Biryukov } 151558fa50f4SIlya Biryukov 1516be14a22bSIlya Biryukov bool WalkUpFromEmptyDecl(EmptyDecl *S) { 1517cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1518a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyDeclaration, S); 1519be14a22bSIlya Biryukov return true; 1520be14a22bSIlya Biryukov } 1521be14a22bSIlya Biryukov 1522be14a22bSIlya Biryukov bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) { 1523718e550cSEduardo Caldas Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition); 1524718e550cSEduardo Caldas Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message); 1525cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1526a711a3a4SMarcel Hlopko new (allocator()) syntax::StaticAssertDeclaration, S); 1527be14a22bSIlya Biryukov return true; 1528be14a22bSIlya Biryukov } 1529be14a22bSIlya Biryukov 1530be14a22bSIlya Biryukov bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) { 1531cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1532a711a3a4SMarcel Hlopko new (allocator()) syntax::LinkageSpecificationDeclaration, 1533a711a3a4SMarcel Hlopko S); 1534be14a22bSIlya Biryukov return true; 1535be14a22bSIlya Biryukov } 1536be14a22bSIlya Biryukov 1537be14a22bSIlya Biryukov bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) { 1538cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1539a711a3a4SMarcel Hlopko new (allocator()) syntax::NamespaceAliasDefinition, S); 1540be14a22bSIlya Biryukov return true; 1541be14a22bSIlya Biryukov } 1542be14a22bSIlya Biryukov 1543be14a22bSIlya Biryukov bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) { 1544cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1545a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingNamespaceDirective, S); 1546be14a22bSIlya Biryukov return true; 1547be14a22bSIlya Biryukov } 1548be14a22bSIlya Biryukov 1549be14a22bSIlya Biryukov bool WalkUpFromUsingDecl(UsingDecl *S) { 1550cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1551a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1552be14a22bSIlya Biryukov return true; 1553be14a22bSIlya Biryukov } 1554be14a22bSIlya Biryukov 1555be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) { 1556cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1557a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1558be14a22bSIlya Biryukov return true; 1559be14a22bSIlya Biryukov } 1560be14a22bSIlya Biryukov 1561be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) { 1562cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1563a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S); 1564be14a22bSIlya Biryukov return true; 1565be14a22bSIlya Biryukov } 1566be14a22bSIlya Biryukov 1567be14a22bSIlya Biryukov bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) { 1568cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S), 1569a711a3a4SMarcel Hlopko new (allocator()) syntax::TypeAliasDeclaration, S); 1570be14a22bSIlya Biryukov return true; 1571be14a22bSIlya Biryukov } 1572be14a22bSIlya Biryukov 15739b3f38f9SIlya Biryukov private: 1574cdce2fe5SMarcel Hlopko /// Folds SimpleDeclarator node (if present) and in case this is the last 1575cdce2fe5SMarcel Hlopko /// declarator in the chain it also folds SimpleDeclaration node. 1576cdce2fe5SMarcel Hlopko template <class T> bool processDeclaratorAndDeclaration(T *D) { 157738bc0060SEduardo Caldas auto Range = getDeclaratorRange( 157838bc0060SEduardo Caldas Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(), 157938bc0060SEduardo Caldas getQualifiedNameStart(D), getInitializerRange(D)); 1580cdce2fe5SMarcel Hlopko 1581cdce2fe5SMarcel Hlopko // There doesn't have to be a declarator (e.g. `void foo(int)` only has 1582cdce2fe5SMarcel Hlopko // declaration, but no declarator). 15835011d431SEduardo Caldas if (!Range.getBegin().isValid()) { 15845011d431SEduardo Caldas Builder.markChild(new (allocator()) syntax::DeclaratorList, 15855011d431SEduardo Caldas syntax::NodeRole::Declarators); 15865011d431SEduardo Caldas Builder.foldNode(Builder.getDeclarationRange(D), 15875011d431SEduardo Caldas new (allocator()) syntax::SimpleDeclaration, D); 15885011d431SEduardo Caldas return true; 1589cdce2fe5SMarcel Hlopko } 1590cdce2fe5SMarcel Hlopko 15915011d431SEduardo Caldas auto *N = new (allocator()) syntax::SimpleDeclarator; 15925011d431SEduardo Caldas Builder.foldNode(Builder.getRange(Range), N, nullptr); 15935011d431SEduardo Caldas Builder.markChild(N, syntax::NodeRole::ListElement); 15945011d431SEduardo Caldas 15955011d431SEduardo Caldas if (!Builder.isResponsibleForCreatingDeclaration(D)) { 15965011d431SEduardo Caldas // If this is not the last declarator in the declaration we expect a 15975011d431SEduardo Caldas // delimiter after it. 15985011d431SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd())); 15995011d431SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 16005011d431SEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 16015011d431SEduardo Caldas } else { 16025011d431SEduardo Caldas auto *DL = new (allocator()) syntax::DeclaratorList; 16035011d431SEduardo Caldas auto DeclarationRange = Builder.getDeclarationRange(D); 16045011d431SEduardo Caldas Builder.foldList(DeclarationRange, DL, nullptr); 16055011d431SEduardo Caldas 16065011d431SEduardo Caldas Builder.markChild(DL, syntax::NodeRole::Declarators); 16075011d431SEduardo Caldas Builder.foldNode(DeclarationRange, 1608cdce2fe5SMarcel Hlopko new (allocator()) syntax::SimpleDeclaration, D); 1609cdce2fe5SMarcel Hlopko } 1610cdce2fe5SMarcel Hlopko return true; 1611cdce2fe5SMarcel Hlopko } 1612cdce2fe5SMarcel Hlopko 16137d382dcdSMarcel Hlopko /// Returns the range of the built node. 1614ac87a0b5SEduardo Caldas syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) { 16157d382dcdSMarcel Hlopko assert(L.getTypePtr()->hasTrailingReturn()); 16167d382dcdSMarcel Hlopko 16177d382dcdSMarcel Hlopko auto ReturnedType = L.getReturnLoc(); 16187d382dcdSMarcel Hlopko // Build node for the declarator, if any. 161938bc0060SEduardo Caldas auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType), 162038bc0060SEduardo Caldas ReturnedType.getEndLoc()); 1621a711a3a4SMarcel Hlopko syntax::SimpleDeclarator *ReturnDeclarator = nullptr; 16227d382dcdSMarcel Hlopko if (ReturnDeclaratorRange.isValid()) { 1623a711a3a4SMarcel Hlopko ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator; 1624a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(ReturnDeclaratorRange), 1625a711a3a4SMarcel Hlopko ReturnDeclarator, nullptr); 16267d382dcdSMarcel Hlopko } 16277d382dcdSMarcel Hlopko 16287d382dcdSMarcel Hlopko // Build node for trailing return type. 1629a711a3a4SMarcel Hlopko auto Return = Builder.getRange(ReturnedType.getSourceRange()); 16307d382dcdSMarcel Hlopko const auto *Arrow = Return.begin() - 1; 16317d382dcdSMarcel Hlopko assert(Arrow->kind() == tok::arrow); 16327d382dcdSMarcel Hlopko auto Tokens = llvm::makeArrayRef(Arrow, Return.end()); 163342f6fec3SEduardo Caldas Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken); 1634a711a3a4SMarcel Hlopko if (ReturnDeclarator) 1635718e550cSEduardo Caldas Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator); 1636a711a3a4SMarcel Hlopko auto *R = new (allocator()) syntax::TrailingReturnType; 1637cdce2fe5SMarcel Hlopko Builder.foldNode(Tokens, R, L); 1638a711a3a4SMarcel Hlopko return R; 16397d382dcdSMarcel Hlopko } 164088bf9b3dSMarcel Hlopko 1641a711a3a4SMarcel Hlopko void foldExplicitTemplateInstantiation( 1642a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW, 164388bf9b3dSMarcel Hlopko const syntax::Token *TemplateKW, 1644a711a3a4SMarcel Hlopko syntax::SimpleDeclaration *InnerDeclaration, Decl *From) { 164588bf9b3dSMarcel Hlopko assert(!ExternKW || ExternKW->kind() == tok::kw_extern); 164688bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 164742f6fec3SEduardo Caldas Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword); 164888bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1649718e550cSEduardo Caldas Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration); 1650a711a3a4SMarcel Hlopko Builder.foldNode( 1651a711a3a4SMarcel Hlopko Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From); 165288bf9b3dSMarcel Hlopko } 165388bf9b3dSMarcel Hlopko 1654a711a3a4SMarcel Hlopko syntax::TemplateDeclaration *foldTemplateDeclaration( 1655a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW, 1656a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) { 165788bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 165888bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1659a711a3a4SMarcel Hlopko 1660a711a3a4SMarcel Hlopko auto *N = new (allocator()) syntax::TemplateDeclaration; 1661a711a3a4SMarcel Hlopko Builder.foldNode(Range, N, From); 1662718e550cSEduardo Caldas Builder.markChild(N, syntax::NodeRole::Declaration); 1663a711a3a4SMarcel Hlopko return N; 166488bf9b3dSMarcel Hlopko } 166588bf9b3dSMarcel Hlopko 16669b3f38f9SIlya Biryukov /// A small helper to save some typing. 16679b3f38f9SIlya Biryukov llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } 16689b3f38f9SIlya Biryukov 16699b3f38f9SIlya Biryukov syntax::TreeBuilder &Builder; 16701db5b348SEduardo Caldas const ASTContext &Context; 16719b3f38f9SIlya Biryukov }; 16729b3f38f9SIlya Biryukov } // namespace 16739b3f38f9SIlya Biryukov 16747d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) { 1675e702bdb8SIlya Biryukov DeclsWithoutSemicolons.insert(D); 1676e702bdb8SIlya Biryukov } 1677e702bdb8SIlya Biryukov 1678def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) { 16799b3f38f9SIlya Biryukov if (Loc.isInvalid()) 16809b3f38f9SIlya Biryukov return; 16819b3f38f9SIlya Biryukov Pending.assignRole(*findToken(Loc), Role); 16829b3f38f9SIlya Biryukov } 16839b3f38f9SIlya Biryukov 16847d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) { 16857d382dcdSMarcel Hlopko if (!T) 16867d382dcdSMarcel Hlopko return; 16877d382dcdSMarcel Hlopko Pending.assignRole(*T, R); 16887d382dcdSMarcel Hlopko } 16897d382dcdSMarcel Hlopko 1690a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) { 1691a711a3a4SMarcel Hlopko assert(N); 1692a711a3a4SMarcel Hlopko setRole(N, R); 1693a711a3a4SMarcel Hlopko } 1694a711a3a4SMarcel Hlopko 1695a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) { 1696a711a3a4SMarcel Hlopko auto *SN = Mapping.find(N); 1697a711a3a4SMarcel Hlopko assert(SN != nullptr); 1698a711a3a4SMarcel Hlopko setRole(SN, R); 16997d382dcdSMarcel Hlopko } 1700f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) { 1701f9500cc4SEduardo Caldas auto *SN = Mapping.find(NNSLoc); 1702f9500cc4SEduardo Caldas assert(SN != nullptr); 1703f9500cc4SEduardo Caldas setRole(SN, R); 1704f9500cc4SEduardo Caldas } 17057d382dcdSMarcel Hlopko 170658fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) { 170758fa50f4SIlya Biryukov if (!Child) 170858fa50f4SIlya Biryukov return; 170958fa50f4SIlya Biryukov 1710b34b7691SDmitri Gribenko syntax::Tree *ChildNode; 1711b34b7691SDmitri Gribenko if (Expr *ChildExpr = dyn_cast<Expr>(Child)) { 171258fa50f4SIlya Biryukov // This is an expression in a statement position, consume the trailing 171358fa50f4SIlya Biryukov // semicolon and form an 'ExpressionStatement' node. 1714718e550cSEduardo Caldas markExprChild(ChildExpr, NodeRole::Expression); 1715a711a3a4SMarcel Hlopko ChildNode = new (allocator()) syntax::ExpressionStatement; 1716a711a3a4SMarcel Hlopko // (!) 'getStmtRange()' ensures this covers a trailing semicolon. 1717a711a3a4SMarcel Hlopko Pending.foldChildren(Arena, getStmtRange(Child), ChildNode); 1718b34b7691SDmitri Gribenko } else { 1719b34b7691SDmitri Gribenko ChildNode = Mapping.find(Child); 172058fa50f4SIlya Biryukov } 1721b34b7691SDmitri Gribenko assert(ChildNode != nullptr); 1722a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 172358fa50f4SIlya Biryukov } 172458fa50f4SIlya Biryukov 172558fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) { 1726be14a22bSIlya Biryukov if (!Child) 1727be14a22bSIlya Biryukov return; 17282325d6b4SEduardo Caldas Child = IgnoreImplicit(Child); 1729be14a22bSIlya Biryukov 1730a711a3a4SMarcel Hlopko syntax::Tree *ChildNode = Mapping.find(Child); 1731a711a3a4SMarcel Hlopko assert(ChildNode != nullptr); 1732a711a3a4SMarcel Hlopko setRole(ChildNode, Role); 173358fa50f4SIlya Biryukov } 173458fa50f4SIlya Biryukov 17359b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { 173688bf9b3dSMarcel Hlopko if (L.isInvalid()) 173788bf9b3dSMarcel Hlopko return nullptr; 173878194118SMikhail Maltsev auto It = LocationToToken.find(L); 1739c1bbefefSIlya Biryukov assert(It != LocationToToken.end()); 1740c1bbefefSIlya Biryukov return It->second; 17419b3f38f9SIlya Biryukov } 17429b3f38f9SIlya Biryukov 1743142c6f82SKirill Bobyrev syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A, 1744142c6f82SKirill Bobyrev ASTContext &Context) { 17459b3f38f9SIlya Biryukov TreeBuilder Builder(A); 1746142c6f82SKirill Bobyrev BuildTreeVisitor(Context, Builder).TraverseAST(Context); 17479b3f38f9SIlya Biryukov return std::move(Builder).finalize(); 17489b3f38f9SIlya Biryukov } 1749