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