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