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 TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1136 // To construct a syntax tree of the same shape for calls to built-in and 1137 // user-defined operators, ignore the `DeclRefExpr` that refers to the 1138 // operator and treat it as a simple token. Do that by traversing 1139 // arguments instead of children. 1140 for (auto *child : S->arguments()) { 1141 // A postfix unary operator is declared as taking two operands. The 1142 // second operand is used to distinguish from its prefix counterpart. In 1143 // the semantic AST this "phantom" operand is represented as a 1144 // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this 1145 // operand because it does not correspond to anything written in source 1146 // code. 1147 if (child->getSourceRange().isInvalid()) { 1148 assert(getOperatorNodeKind(*S) == 1149 syntax::NodeKind::PostfixUnaryOperatorExpression); 1150 continue; 1151 } 1152 if (!TraverseStmt(child)) 1153 return false; 1154 } 1155 return WalkUpFromCXXOperatorCallExpr(S); 1156 } 1157 1158 bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) { 1159 switch (getOperatorNodeKind(*S)) { 1160 case syntax::NodeKind::BinaryOperatorExpression: 1161 Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide); 1162 Builder.markChildToken(S->getOperatorLoc(), 1163 syntax::NodeRole::OperatorToken); 1164 Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide); 1165 Builder.foldNode(Builder.getExprRange(S), 1166 new (allocator()) syntax::BinaryOperatorExpression, S); 1167 return true; 1168 case syntax::NodeKind::PrefixUnaryOperatorExpression: 1169 Builder.markChildToken(S->getOperatorLoc(), 1170 syntax::NodeRole::OperatorToken); 1171 Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand); 1172 Builder.foldNode(Builder.getExprRange(S), 1173 new (allocator()) syntax::PrefixUnaryOperatorExpression, 1174 S); 1175 return true; 1176 case syntax::NodeKind::PostfixUnaryOperatorExpression: 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::PostfixUnaryOperatorExpression, 1182 S); 1183 return true; 1184 case syntax::NodeKind::CallExpression: { 1185 Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee); 1186 1187 const auto *LParenToken = 1188 std::next(Builder.findToken(S->getArg(0)->getEndLoc())); 1189 // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have 1190 // fixed the test on decltype desctructors. 1191 if (LParenToken->kind() == clang::tok::l_paren) 1192 Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen); 1193 1194 Builder.markChild(buildCallArguments(CallExpr::arg_range( 1195 S->arg_begin() + 1, S->arg_end())), 1196 syntax::NodeRole::Arguments); 1197 1198 Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen); 1199 1200 Builder.foldNode(Builder.getRange(S->getSourceRange()), 1201 new (allocator()) syntax::CallExpression, S); 1202 return true; 1203 } 1204 case syntax::NodeKind::UnknownExpression: 1205 return WalkUpFromExpr(S); 1206 default: 1207 llvm_unreachable("getOperatorNodeKind() does not return this value"); 1208 } 1209 } 1210 1211 bool WalkUpFromNamespaceDecl(NamespaceDecl *S) { 1212 auto Tokens = Builder.getDeclarationRange(S); 1213 if (Tokens.front().kind() == tok::coloncolon) { 1214 // Handle nested namespace definitions. Those start at '::' token, e.g. 1215 // namespace a^::b {} 1216 // FIXME: build corresponding nodes for the name of this namespace. 1217 return true; 1218 } 1219 Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S); 1220 return true; 1221 } 1222 1223 // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test 1224 // results. Find test coverage or remove it. 1225 bool TraverseParenTypeLoc(ParenTypeLoc L) { 1226 // We reverse order of traversal to get the proper syntax structure. 1227 if (!WalkUpFromParenTypeLoc(L)) 1228 return false; 1229 return TraverseTypeLoc(L.getInnerLoc()); 1230 } 1231 1232 bool WalkUpFromParenTypeLoc(ParenTypeLoc L) { 1233 Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 1234 Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 1235 Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()), 1236 new (allocator()) syntax::ParenDeclarator, L); 1237 return true; 1238 } 1239 1240 // Declarator chunks, they are produced by type locs and some clang::Decls. 1241 bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) { 1242 Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen); 1243 Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size); 1244 Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen); 1245 Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()), 1246 new (allocator()) syntax::ArraySubscript, L); 1247 return true; 1248 } 1249 1250 syntax::ParameterDeclarationList * 1251 buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) { 1252 for (auto *P : Params) { 1253 Builder.markChild(P, syntax::NodeRole::ListElement); 1254 const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc())); 1255 if (DelimiterToken->kind() == clang::tok::TokenKind::comma) 1256 Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter); 1257 } 1258 auto *Parameters = new (allocator()) syntax::ParameterDeclarationList; 1259 if (!Params.empty()) 1260 Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(), 1261 Params.back()->getEndLoc()), 1262 Parameters, nullptr); 1263 return Parameters; 1264 } 1265 1266 bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) { 1267 Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen); 1268 1269 Builder.markChild(buildParameterDeclarationList(L.getParams()), 1270 syntax::NodeRole::Parameters); 1271 1272 Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen); 1273 Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()), 1274 new (allocator()) syntax::ParametersAndQualifiers, L); 1275 return true; 1276 } 1277 1278 bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) { 1279 if (!L.getTypePtr()->hasTrailingReturn()) 1280 return WalkUpFromFunctionTypeLoc(L); 1281 1282 auto *TrailingReturnTokens = buildTrailingReturn(L); 1283 // Finish building the node for parameters. 1284 Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn); 1285 return WalkUpFromFunctionTypeLoc(L); 1286 } 1287 1288 bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) { 1289 // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds 1290 // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to 1291 // "(Y::*mp)" We thus reverse the order of traversal to get the proper 1292 // syntax structure. 1293 if (!WalkUpFromMemberPointerTypeLoc(L)) 1294 return false; 1295 return TraverseTypeLoc(L.getPointeeLoc()); 1296 } 1297 1298 bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) { 1299 auto SR = L.getLocalSourceRange(); 1300 Builder.foldNode(Builder.getRange(SR), 1301 new (allocator()) syntax::MemberPointer, L); 1302 return true; 1303 } 1304 1305 // The code below is very regular, it could even be generated with some 1306 // preprocessor magic. We merely assign roles to the corresponding children 1307 // and fold resulting nodes. 1308 bool WalkUpFromDeclStmt(DeclStmt *S) { 1309 Builder.foldNode(Builder.getStmtRange(S), 1310 new (allocator()) syntax::DeclarationStatement, S); 1311 return true; 1312 } 1313 1314 bool WalkUpFromNullStmt(NullStmt *S) { 1315 Builder.foldNode(Builder.getStmtRange(S), 1316 new (allocator()) syntax::EmptyStatement, S); 1317 return true; 1318 } 1319 1320 bool WalkUpFromSwitchStmt(SwitchStmt *S) { 1321 Builder.markChildToken(S->getSwitchLoc(), 1322 syntax::NodeRole::IntroducerKeyword); 1323 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 1324 Builder.foldNode(Builder.getStmtRange(S), 1325 new (allocator()) syntax::SwitchStatement, S); 1326 return true; 1327 } 1328 1329 bool WalkUpFromCaseStmt(CaseStmt *S) { 1330 Builder.markChildToken(S->getKeywordLoc(), 1331 syntax::NodeRole::IntroducerKeyword); 1332 Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue); 1333 Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 1334 Builder.foldNode(Builder.getStmtRange(S), 1335 new (allocator()) syntax::CaseStatement, S); 1336 return true; 1337 } 1338 1339 bool WalkUpFromDefaultStmt(DefaultStmt *S) { 1340 Builder.markChildToken(S->getKeywordLoc(), 1341 syntax::NodeRole::IntroducerKeyword); 1342 Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement); 1343 Builder.foldNode(Builder.getStmtRange(S), 1344 new (allocator()) syntax::DefaultStatement, S); 1345 return true; 1346 } 1347 1348 bool WalkUpFromIfStmt(IfStmt *S) { 1349 Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword); 1350 Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement); 1351 Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword); 1352 Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement); 1353 Builder.foldNode(Builder.getStmtRange(S), 1354 new (allocator()) syntax::IfStatement, S); 1355 return true; 1356 } 1357 1358 bool WalkUpFromForStmt(ForStmt *S) { 1359 Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 1360 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 1361 Builder.foldNode(Builder.getStmtRange(S), 1362 new (allocator()) syntax::ForStatement, S); 1363 return true; 1364 } 1365 1366 bool WalkUpFromWhileStmt(WhileStmt *S) { 1367 Builder.markChildToken(S->getWhileLoc(), 1368 syntax::NodeRole::IntroducerKeyword); 1369 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 1370 Builder.foldNode(Builder.getStmtRange(S), 1371 new (allocator()) syntax::WhileStatement, S); 1372 return true; 1373 } 1374 1375 bool WalkUpFromContinueStmt(ContinueStmt *S) { 1376 Builder.markChildToken(S->getContinueLoc(), 1377 syntax::NodeRole::IntroducerKeyword); 1378 Builder.foldNode(Builder.getStmtRange(S), 1379 new (allocator()) syntax::ContinueStatement, S); 1380 return true; 1381 } 1382 1383 bool WalkUpFromBreakStmt(BreakStmt *S) { 1384 Builder.markChildToken(S->getBreakLoc(), 1385 syntax::NodeRole::IntroducerKeyword); 1386 Builder.foldNode(Builder.getStmtRange(S), 1387 new (allocator()) syntax::BreakStatement, S); 1388 return true; 1389 } 1390 1391 bool WalkUpFromReturnStmt(ReturnStmt *S) { 1392 Builder.markChildToken(S->getReturnLoc(), 1393 syntax::NodeRole::IntroducerKeyword); 1394 Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue); 1395 Builder.foldNode(Builder.getStmtRange(S), 1396 new (allocator()) syntax::ReturnStatement, S); 1397 return true; 1398 } 1399 1400 bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) { 1401 Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword); 1402 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement); 1403 Builder.foldNode(Builder.getStmtRange(S), 1404 new (allocator()) syntax::RangeBasedForStatement, S); 1405 return true; 1406 } 1407 1408 bool WalkUpFromEmptyDecl(EmptyDecl *S) { 1409 Builder.foldNode(Builder.getDeclarationRange(S), 1410 new (allocator()) syntax::EmptyDeclaration, S); 1411 return true; 1412 } 1413 1414 bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) { 1415 Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition); 1416 Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message); 1417 Builder.foldNode(Builder.getDeclarationRange(S), 1418 new (allocator()) syntax::StaticAssertDeclaration, S); 1419 return true; 1420 } 1421 1422 bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) { 1423 Builder.foldNode(Builder.getDeclarationRange(S), 1424 new (allocator()) syntax::LinkageSpecificationDeclaration, 1425 S); 1426 return true; 1427 } 1428 1429 bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) { 1430 Builder.foldNode(Builder.getDeclarationRange(S), 1431 new (allocator()) syntax::NamespaceAliasDefinition, S); 1432 return true; 1433 } 1434 1435 bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) { 1436 Builder.foldNode(Builder.getDeclarationRange(S), 1437 new (allocator()) syntax::UsingNamespaceDirective, S); 1438 return true; 1439 } 1440 1441 bool WalkUpFromUsingDecl(UsingDecl *S) { 1442 Builder.foldNode(Builder.getDeclarationRange(S), 1443 new (allocator()) syntax::UsingDeclaration, S); 1444 return true; 1445 } 1446 1447 bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) { 1448 Builder.foldNode(Builder.getDeclarationRange(S), 1449 new (allocator()) syntax::UsingDeclaration, S); 1450 return true; 1451 } 1452 1453 bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) { 1454 Builder.foldNode(Builder.getDeclarationRange(S), 1455 new (allocator()) syntax::UsingDeclaration, S); 1456 return true; 1457 } 1458 1459 bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) { 1460 Builder.foldNode(Builder.getDeclarationRange(S), 1461 new (allocator()) syntax::TypeAliasDeclaration, S); 1462 return true; 1463 } 1464 1465 private: 1466 /// Folds SimpleDeclarator node (if present) and in case this is the last 1467 /// declarator in the chain it also folds SimpleDeclaration node. 1468 template <class T> bool processDeclaratorAndDeclaration(T *D) { 1469 auto Range = getDeclaratorRange( 1470 Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(), 1471 getQualifiedNameStart(D), getInitializerRange(D)); 1472 1473 // There doesn't have to be a declarator (e.g. `void foo(int)` only has 1474 // declaration, but no declarator). 1475 if (Range.getBegin().isValid()) { 1476 auto *N = new (allocator()) syntax::SimpleDeclarator; 1477 Builder.foldNode(Builder.getRange(Range), N, nullptr); 1478 Builder.markChild(N, syntax::NodeRole::Declarator); 1479 } 1480 1481 if (Builder.isResponsibleForCreatingDeclaration(D)) { 1482 Builder.foldNode(Builder.getDeclarationRange(D), 1483 new (allocator()) syntax::SimpleDeclaration, D); 1484 } 1485 return true; 1486 } 1487 1488 /// Returns the range of the built node. 1489 syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) { 1490 assert(L.getTypePtr()->hasTrailingReturn()); 1491 1492 auto ReturnedType = L.getReturnLoc(); 1493 // Build node for the declarator, if any. 1494 auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType), 1495 ReturnedType.getEndLoc()); 1496 syntax::SimpleDeclarator *ReturnDeclarator = nullptr; 1497 if (ReturnDeclaratorRange.isValid()) { 1498 ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator; 1499 Builder.foldNode(Builder.getRange(ReturnDeclaratorRange), 1500 ReturnDeclarator, nullptr); 1501 } 1502 1503 // Build node for trailing return type. 1504 auto Return = Builder.getRange(ReturnedType.getSourceRange()); 1505 const auto *Arrow = Return.begin() - 1; 1506 assert(Arrow->kind() == tok::arrow); 1507 auto Tokens = llvm::makeArrayRef(Arrow, Return.end()); 1508 Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken); 1509 if (ReturnDeclarator) 1510 Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator); 1511 auto *R = new (allocator()) syntax::TrailingReturnType; 1512 Builder.foldNode(Tokens, R, L); 1513 return R; 1514 } 1515 1516 void foldExplicitTemplateInstantiation( 1517 ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW, 1518 const syntax::Token *TemplateKW, 1519 syntax::SimpleDeclaration *InnerDeclaration, Decl *From) { 1520 assert(!ExternKW || ExternKW->kind() == tok::kw_extern); 1521 assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 1522 Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword); 1523 Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1524 Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration); 1525 Builder.foldNode( 1526 Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From); 1527 } 1528 1529 syntax::TemplateDeclaration *foldTemplateDeclaration( 1530 ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW, 1531 ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) { 1532 assert(TemplateKW && TemplateKW->kind() == tok::kw_template); 1533 Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword); 1534 1535 auto *N = new (allocator()) syntax::TemplateDeclaration; 1536 Builder.foldNode(Range, N, From); 1537 Builder.markChild(N, syntax::NodeRole::Declaration); 1538 return N; 1539 } 1540 1541 /// A small helper to save some typing. 1542 llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); } 1543 1544 syntax::TreeBuilder &Builder; 1545 const ASTContext &Context; 1546 }; 1547 } // namespace 1548 1549 void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) { 1550 DeclsWithoutSemicolons.insert(D); 1551 } 1552 1553 void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) { 1554 if (Loc.isInvalid()) 1555 return; 1556 Pending.assignRole(*findToken(Loc), Role); 1557 } 1558 1559 void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) { 1560 if (!T) 1561 return; 1562 Pending.assignRole(*T, R); 1563 } 1564 1565 void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) { 1566 assert(N); 1567 setRole(N, R); 1568 } 1569 1570 void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) { 1571 auto *SN = Mapping.find(N); 1572 assert(SN != nullptr); 1573 setRole(SN, R); 1574 } 1575 void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) { 1576 auto *SN = Mapping.find(NNSLoc); 1577 assert(SN != nullptr); 1578 setRole(SN, R); 1579 } 1580 1581 void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) { 1582 if (!Child) 1583 return; 1584 1585 syntax::Tree *ChildNode; 1586 if (Expr *ChildExpr = dyn_cast<Expr>(Child)) { 1587 // This is an expression in a statement position, consume the trailing 1588 // semicolon and form an 'ExpressionStatement' node. 1589 markExprChild(ChildExpr, NodeRole::Expression); 1590 ChildNode = new (allocator()) syntax::ExpressionStatement; 1591 // (!) 'getStmtRange()' ensures this covers a trailing semicolon. 1592 Pending.foldChildren(Arena, getStmtRange(Child), ChildNode); 1593 } else { 1594 ChildNode = Mapping.find(Child); 1595 } 1596 assert(ChildNode != nullptr); 1597 setRole(ChildNode, Role); 1598 } 1599 1600 void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) { 1601 if (!Child) 1602 return; 1603 Child = IgnoreImplicit(Child); 1604 1605 syntax::Tree *ChildNode = Mapping.find(Child); 1606 assert(ChildNode != nullptr); 1607 setRole(ChildNode, Role); 1608 } 1609 1610 const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const { 1611 if (L.isInvalid()) 1612 return nullptr; 1613 auto It = LocationToToken.find(L.getRawEncoding()); 1614 assert(It != LocationToToken.end()); 1615 return It->second; 1616 } 1617 1618 syntax::TranslationUnit * 1619 syntax::buildSyntaxTree(Arena &A, const TranslationUnitDecl &TU) { 1620 TreeBuilder Builder(A); 1621 BuildTreeVisitor(TU.getASTContext(), Builder).TraverseAST(TU.getASTContext()); 1622 return std::move(Builder).finalize(); 1623 } 1624