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
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.
129 SourceLocation VisitTypeLoc(TypeLoc T) {
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(){}`
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 `()`.
267static SourceRange getInitializerRange(Decl *D) {
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.
286static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
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
336 syntax::Tree *find(NestedNameSpecifierLoc P) const {
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.
361class syntax::TreeBuilder {
362public:
363 TreeBuilder(syntax::Arena &Arena, TokenBufferTokenManager& TBTM)
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(); }
372 const SourceManager &sourceManager() const {
373 return TBTM.sourceManager();
374 }
375
376 /// Populate children for \p New node, assuming it covers tokens from \p
377 /// Range.
378 void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) {
379 assert(New);
380 Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
381 if (From)
382 Mapping.add(From, New);
383 }
384
385 void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) {
386 // FIXME: add mapping for TypeLocs
387 foldNode(Range, New, nullptr);
388 }
389
390 void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
391 NestedNameSpecifierLoc From) {
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.
400 void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New,
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.
411 void noticeDeclWithoutSemicolon(Decl *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.
422 void markChildToken(SourceLocation Loc, NodeRole R);
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.
431 void markChild(NestedNameSpecifierLoc N, NodeRole R);
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.
452 ArrayRef<syntax::Token> getRange(SourceRange Range) const {
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.
460 ArrayRef<syntax::Token> getRange(SourceLocation First,
461 SourceLocation Last) const {
462 assert(First.isValid());
463 assert(Last.isValid());
464 assert(First == Last ||
465 TBTM.sourceManager().isBeforeInTranslationUnit(First, Last));
466 return llvm::ArrayRef(findToken(First), std::next(findToken(Last)));
467 }
468
469 ArrayRef<syntax::Token>
470 getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
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.
477 bool isResponsibleForCreatingDeclaration(const Decl *D) const {
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
503 ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
504 ArrayRef<syntax::Token> Tokens;
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
513 ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
514 return getRange(E->getSourceRange());
515 }
516
517 /// Find the adjusted range for the statement, consuming the trailing
518 /// semicolon when needed.
519 ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
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
543 ArrayRef<syntax::Token>
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.
594 ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) {
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 ||
608 Role == syntax::NodeRole::ListDelimiter;
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,
623 ArrayRef<syntax::Token> Tokens, syntax::Tree *Node) {
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()) {
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 }();
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 }();
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()) {
948 case NestedNameSpecifier::Kind::Global:
949 return new (allocator()) syntax::GlobalNameSpecifier;
950
951 case NestedNameSpecifier::Kind::Namespace:
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::Decltype: {
978 const auto DTL = TL.castAs<DecltypeTypeLoc>();
979 if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(
980 DTL, /*TraverseQualifier=*/true))
981 return nullptr;
982 auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
983 // TODO: Implement accessor to `DecltypeNameSpecifier` inner
984 // `DecltypeTypeLoc`.
985 // For that add mapping from `TypeLoc` to `syntax::Node*` then:
986 // Builder.markChild(TypeLoc, syntax::NodeRole);
987 Builder.foldNode(Builder.getRange(DTL.getLocalSourceRange()), NS,
988 nullptr);
989 return NS;
990 }
991 default:
992 return buildIdentifier(TL.getLocalSourceRange());
993 }
994 }
995 default:
996 // FIXME: Support Microsoft's __super
997 llvm::report_fatal_error("We don't yet support the __super specifier",
998 true);
999 }
1000 }
1001
1002 // To build syntax tree nodes for NestedNameSpecifierLoc we override
1003 // Traverse instead of WalkUpFrom because we want to traverse the children
1004 // ourselves and build a list instead of a nested tree of name specifier
1005 // prefixes.
1007 if (!QualifierLoc)
1008 return true;
1009 for (auto It = QualifierLoc; It; /**/) {
1010 auto *NS = buildNameSpecifier(It);
1011 if (!NS)
1012 return false;
1013 Builder.markChild(NS, syntax::NodeRole::ListElement);
1014 Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
1015 if (TypeLoc TL = It.getAsTypeLoc())
1016 It = TL.getPrefix();
1017 else
1018 It = It.getAsNamespaceAndPrefix().Prefix;
1019 }
1020 Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1021 new (allocator()) syntax::NestedNameSpecifier,
1022 QualifierLoc);
1023 return true;
1024 }
1025
1026 syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1027 SourceLocation TemplateKeywordLoc,
1028 SourceRange UnqualifiedIdLoc,
1029 ASTPtr From) {
1030 if (QualifierLoc) {
1031 Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1032 if (TemplateKeywordLoc.isValid())
1033 Builder.markChildToken(TemplateKeywordLoc,
1035 }
1036
1037 auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1038 Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1039 nullptr);
1040 Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1041
1042 auto IdExpressionBeginLoc =
1043 QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1044
1045 auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1046 Builder.foldNode(
1047 Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1048 TheIdExpression, From);
1049
1050 return TheIdExpression;
1051 }
1052
1054 // For `MemberExpr` with implicit `this->` we generate a simple
1055 // `id-expression` syntax node, beacuse an implicit `member-expression` is
1056 // syntactically undistinguishable from an `id-expression`
1057 if (S->isImplicitAccess()) {
1059 SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1060 return true;
1061 }
1062
1063 auto *TheIdExpression = buildIdExpression(
1065 SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1066
1067 Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1068
1069 Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1070 Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1071
1072 Builder.foldNode(Builder.getExprRange(S),
1073 new (allocator()) syntax::MemberExpression, S);
1074 return true;
1075 }
1076
1079 SourceRange(S->getLocation(), S->getEndLoc()), S);
1080
1081 return true;
1082 }
1083
1084 // Same logic as DeclRefExpr.
1091
1093 if (!S->isImplicit()) {
1094 Builder.markChildToken(S->getLocation(),
1096 Builder.foldNode(Builder.getExprRange(S),
1097 new (allocator()) syntax::ThisExpression, S);
1098 }
1099 return true;
1100 }
1101
1103 Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1104 Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1105 Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1106 Builder.foldNode(Builder.getExprRange(S),
1107 new (allocator()) syntax::ParenExpression, S);
1108 return true;
1109 }
1110
1112 Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1113 Builder.foldNode(Builder.getExprRange(S),
1114 new (allocator()) syntax::IntegerLiteralExpression, S);
1115 return true;
1116 }
1117
1119 Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1120 Builder.foldNode(Builder.getExprRange(S),
1121 new (allocator()) syntax::CharacterLiteralExpression, S);
1122 return true;
1123 }
1124
1126 Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1127 Builder.foldNode(Builder.getExprRange(S),
1128 new (allocator()) syntax::FloatingLiteralExpression, S);
1129 return true;
1130 }
1131
1133 Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1134 Builder.foldNode(Builder.getExprRange(S),
1135 new (allocator()) syntax::StringLiteralExpression, S);
1136 return true;
1137 }
1138
1140 Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1141 Builder.foldNode(Builder.getExprRange(S),
1142 new (allocator()) syntax::BoolLiteralExpression, S);
1143 return true;
1144 }
1145
1147 Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1148 Builder.foldNode(Builder.getExprRange(S),
1149 new (allocator()) syntax::CxxNullPtrExpression, S);
1150 return true;
1151 }
1152
1154 Builder.markChildToken(S->getOperatorLoc(),
1156 Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1157
1158 if (S->isPostfix())
1159 Builder.foldNode(Builder.getExprRange(S),
1161 S);
1162 else
1163 Builder.foldNode(Builder.getExprRange(S),
1164 new (allocator()) syntax::PrefixUnaryOperatorExpression,
1165 S);
1166
1167 return true;
1168 }
1169
1171 Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
1172 Builder.markChildToken(S->getOperatorLoc(),
1174 Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
1175 Builder.foldNode(Builder.getExprRange(S),
1176 new (allocator()) syntax::BinaryOperatorExpression, S);
1177 return true;
1178 }
1179
1180 /// Builds `CallArguments` syntax node from arguments that appear in source
1181 /// code, i.e. not default arguments.
1182 syntax::CallArguments *
1184 auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1185 for (auto *Arg : Args) {
1186 Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
1187 const auto *DelimiterToken =
1188 std::next(Builder.findToken(Arg->getEndLoc()));
1189 if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1190 Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1191 }
1192
1193 auto *Arguments = new (allocator()) syntax::CallArguments;
1194 if (!Args.empty())
1195 Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
1196 (*(Args.end() - 1))->getEndLoc()),
1197 Arguments, nullptr);
1198
1199 return Arguments;
1200 }
1201
1203 Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
1204
1205 const auto *LParenToken =
1206 std::next(Builder.findToken(S->getCallee()->getEndLoc()));
1207 // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
1208 // the test on decltype desctructors.
1209 if (LParenToken->kind() == clang::tok::l_paren)
1210 Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1211
1212 Builder.markChild(buildCallArguments(S->arguments()),
1214
1215 Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1216
1217 Builder.foldNode(Builder.getRange(S->getSourceRange()),
1218 new (allocator()) syntax::CallExpression, S);
1219 return true;
1220 }
1221
1223 // Ignore the implicit calls to default constructors.
1224 if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
1226 return true;
1227 return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
1228 }
1229
1231 // To construct a syntax tree of the same shape for calls to built-in and
1232 // user-defined operators, ignore the `DeclRefExpr` that refers to the
1233 // operator and treat it as a simple token. Do that by traversing
1234 // arguments instead of children.
1235 for (auto *child : S->arguments()) {
1236 // A postfix unary operator is declared as taking two operands. The
1237 // second operand is used to distinguish from its prefix counterpart. In
1238 // the semantic AST this "phantom" operand is represented as a
1239 // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1240 // operand because it does not correspond to anything written in source
1241 // code.
1242 if (child->getSourceRange().isInvalid()) {
1243 assert(getOperatorNodeKind(*S) ==
1244 syntax::NodeKind::PostfixUnaryOperatorExpression);
1245 continue;
1246 }
1247 if (!TraverseStmt(child))
1248 return false;
1249 }
1251 }
1252
1254 switch (getOperatorNodeKind(*S)) {
1255 case syntax::NodeKind::BinaryOperatorExpression:
1256 Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1257 Builder.markChildToken(S->getOperatorLoc(),
1259 Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
1260 Builder.foldNode(Builder.getExprRange(S),
1261 new (allocator()) syntax::BinaryOperatorExpression, S);
1262 return true;
1263 case syntax::NodeKind::PrefixUnaryOperatorExpression:
1264 Builder.markChildToken(S->getOperatorLoc(),
1266 Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1267 Builder.foldNode(Builder.getExprRange(S),
1268 new (allocator()) syntax::PrefixUnaryOperatorExpression,
1269 S);
1270 return true;
1271 case syntax::NodeKind::PostfixUnaryOperatorExpression:
1272 Builder.markChildToken(S->getOperatorLoc(),
1274 Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1275 Builder.foldNode(Builder.getExprRange(S),
1277 S);
1278 return true;
1279 case syntax::NodeKind::CallExpression: {
1280 Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
1281
1282 const auto *LParenToken =
1283 std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
1284 // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
1285 // fixed the test on decltype desctructors.
1286 if (LParenToken->kind() == clang::tok::l_paren)
1287 Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
1288
1289 Builder.markChild(buildCallArguments(CallExpr::arg_range(
1290 S->arg_begin() + 1, S->arg_end())),
1292
1293 Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
1294
1295 Builder.foldNode(Builder.getRange(S->getSourceRange()),
1296 new (allocator()) syntax::CallExpression, S);
1297 return true;
1298 }
1299 case syntax::NodeKind::UnknownExpression:
1300 return WalkUpFromExpr(S);
1301 default:
1302 llvm_unreachable("getOperatorNodeKind() does not return this value");
1303 }
1304 }
1305
1307
1309 auto Tokens = Builder.getDeclarationRange(S);
1310 if (Tokens.front().kind() == tok::coloncolon) {
1311 // Handle nested namespace definitions. Those start at '::' token, e.g.
1312 // namespace a^::b {}
1313 // FIXME: build corresponding nodes for the name of this namespace.
1314 return true;
1315 }
1316 Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1317 return true;
1318 }
1319
1320 // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
1321 // results. Find test coverage or remove it.
1322 bool TraverseParenTypeLoc(ParenTypeLoc L, bool TraverseQualifier) {
1323 // We reverse order of traversal to get the proper syntax structure.
1324 if (!WalkUpFromParenTypeLoc(L))
1325 return false;
1326 return TraverseTypeLoc(L.getInnerLoc());
1327 }
1328
1330 Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1331 Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1332 Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1333 new (allocator()) syntax::ParenDeclarator, L);
1334 return true;
1335 }
1336
1337 // Declarator chunks, they are produced by type locs and some clang::Decls.
1339 Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1340 Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
1341 Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
1342 Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1343 new (allocator()) syntax::ArraySubscript, L);
1344 return true;
1345 }
1346
1347 syntax::ParameterDeclarationList *
1349 for (auto *P : Params) {
1350 Builder.markChild(P, syntax::NodeRole::ListElement);
1351 const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1352 if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1353 Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1354 }
1355 auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1356 if (!Params.empty())
1357 Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1358 Params.back()->getEndLoc()),
1359 Parameters, nullptr);
1360 return Parameters;
1361 }
1362
1364 Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1365
1366 Builder.markChild(buildParameterDeclarationList(L.getParams()),
1368
1369 Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
1370 Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1371 new (allocator()) syntax::ParametersAndQualifiers, L);
1372 return true;
1373 }
1374
1376 if (!L.getTypePtr()->hasTrailingReturn())
1377 return WalkUpFromFunctionTypeLoc(L);
1378
1379 auto *TrailingReturnTokens = buildTrailingReturn(L);
1380 // Finish building the node for parameters.
1381 Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
1382 return WalkUpFromFunctionTypeLoc(L);
1383 }
1384
1386 bool TraverseQualifier) {
1387 // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
1388 // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
1389 // "(Y::*mp)" We thus reverse the order of traversal to get the proper
1390 // syntax structure.
1392 return false;
1393 return TraverseTypeLoc(L.getPointeeLoc());
1394 }
1395
1397 auto SR = L.getLocalSourceRange();
1398 Builder.foldNode(Builder.getRange(SR),
1399 new (allocator()) syntax::MemberPointer, L);
1400 return true;
1401 }
1402
1403 // The code below is very regular, it could even be generated with some
1404 // preprocessor magic. We merely assign roles to the corresponding children
1405 // and fold resulting nodes.
1407 Builder.foldNode(Builder.getStmtRange(S),
1408 new (allocator()) syntax::DeclarationStatement, S);
1409 return true;
1410 }
1411
1413 Builder.foldNode(Builder.getStmtRange(S),
1414 new (allocator()) syntax::EmptyStatement, S);
1415 return true;
1416 }
1417
1419 Builder.markChildToken(S->getSwitchLoc(),
1421 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1422 Builder.foldNode(Builder.getStmtRange(S),
1423 new (allocator()) syntax::SwitchStatement, S);
1424 return true;
1425 }
1426
1428 Builder.markChildToken(S->getKeywordLoc(),
1430 Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
1431 Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1432 Builder.foldNode(Builder.getStmtRange(S),
1433 new (allocator()) syntax::CaseStatement, S);
1434 return true;
1435 }
1436
1438 Builder.markChildToken(S->getKeywordLoc(),
1440 Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
1441 Builder.foldNode(Builder.getStmtRange(S),
1442 new (allocator()) syntax::DefaultStatement, S);
1443 return true;
1444 }
1445
1447 Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
1448 Stmt *ConditionStatement = S->getCond();
1449 if (S->hasVarStorage())
1450 ConditionStatement = S->getConditionVariableDeclStmt();
1451 Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
1452 Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1453 Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1454 Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
1455 Builder.foldNode(Builder.getStmtRange(S),
1456 new (allocator()) syntax::IfStatement, S);
1457 return true;
1458 }
1459
1461 Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1462 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1463 Builder.foldNode(Builder.getStmtRange(S),
1464 new (allocator()) syntax::ForStatement, S);
1465 return true;
1466 }
1467
1469 Builder.markChildToken(S->getWhileLoc(),
1471 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1472 Builder.foldNode(Builder.getStmtRange(S),
1473 new (allocator()) syntax::WhileStatement, S);
1474 return true;
1475 }
1476
1478 Builder.markChildToken(S->getKwLoc(), syntax::NodeRole::IntroducerKeyword);
1479 Builder.foldNode(Builder.getStmtRange(S),
1480 new (allocator()) syntax::ContinueStatement, S);
1481 return true;
1482 }
1483
1485 Builder.markChildToken(S->getKwLoc(), syntax::NodeRole::IntroducerKeyword);
1486 Builder.foldNode(Builder.getStmtRange(S),
1487 new (allocator()) syntax::BreakStatement, S);
1488 return true;
1489 }
1490
1492 Builder.markChildToken(S->getReturnLoc(),
1494 Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
1495 Builder.foldNode(Builder.getStmtRange(S),
1496 new (allocator()) syntax::ReturnStatement, S);
1497 return true;
1498 }
1499
1501 Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
1502 Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
1503 Builder.foldNode(Builder.getStmtRange(S),
1504 new (allocator()) syntax::RangeBasedForStatement, S);
1505 return true;
1506 }
1507
1509 Builder.foldNode(Builder.getDeclarationRange(S),
1510 new (allocator()) syntax::EmptyDeclaration, S);
1511 return true;
1512 }
1513
1515 Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1516 Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1517 Builder.foldNode(Builder.getDeclarationRange(S),
1518 new (allocator()) syntax::StaticAssertDeclaration, S);
1519 return true;
1520 }
1521
1523 Builder.foldNode(Builder.getDeclarationRange(S),
1525 S);
1526 return true;
1527 }
1528
1530 Builder.foldNode(Builder.getDeclarationRange(S),
1531 new (allocator()) syntax::NamespaceAliasDefinition, S);
1532 return true;
1533 }
1534
1536 Builder.foldNode(Builder.getDeclarationRange(S),
1537 new (allocator()) syntax::UsingNamespaceDirective, S);
1538 return true;
1539 }
1540
1542 Builder.foldNode(Builder.getDeclarationRange(S),
1543 new (allocator()) syntax::UsingDeclaration, S);
1544 return true;
1545 }
1546
1548 Builder.foldNode(Builder.getDeclarationRange(S),
1549 new (allocator()) syntax::UsingDeclaration, S);
1550 return true;
1551 }
1552
1554 Builder.foldNode(Builder.getDeclarationRange(S),
1555 new (allocator()) syntax::UsingDeclaration, S);
1556 return true;
1557 }
1558
1560 Builder.foldNode(Builder.getDeclarationRange(S),
1561 new (allocator()) syntax::TypeAliasDeclaration, S);
1562 return true;
1563 }
1564
1565private:
1566 /// Folds SimpleDeclarator node (if present) and in case this is the last
1567 /// declarator in the chain it also folds SimpleDeclaration node.
1568 template <class T> bool processDeclaratorAndDeclaration(T *D) {
1569 auto Range = getDeclaratorRange(
1570 Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
1571 getQualifiedNameStart(D), getInitializerRange(D));
1572
1573 // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1574 // declaration, but no declarator).
1575 if (!Range.getBegin().isValid()) {
1576 Builder.markChild(new (allocator()) syntax::DeclaratorList,
1577 syntax::NodeRole::Declarators);
1578 Builder.foldNode(Builder.getDeclarationRange(D),
1579 new (allocator()) syntax::SimpleDeclaration, D);
1580 return true;
1581 }
1582
1583 auto *N = new (allocator()) syntax::SimpleDeclarator;
1584 Builder.foldNode(Builder.getRange(Range), N, nullptr);
1585 Builder.markChild(N, syntax::NodeRole::ListElement);
1586
1587 if (!Builder.isResponsibleForCreatingDeclaration(D)) {
1588 // If this is not the last declarator in the declaration we expect a
1589 // delimiter after it.
1590 const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
1591 if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1592 Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1593 } else {
1594 auto *DL = new (allocator()) syntax::DeclaratorList;
1595 auto DeclarationRange = Builder.getDeclarationRange(D);
1596 Builder.foldList(DeclarationRange, DL, nullptr);
1597
1598 Builder.markChild(DL, syntax::NodeRole::Declarators);
1599 Builder.foldNode(DeclarationRange,
1600 new (allocator()) syntax::SimpleDeclaration, D);
1601 }
1602 return true;
1603 }
1604
1605 /// Returns the range of the built node.
1606 syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
1607 assert(L.getTypePtr()->hasTrailingReturn());
1608
1609 auto ReturnedType = L.getReturnLoc();
1610 // Build node for the declarator, if any.
1611 auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
1612 ReturnedType.getEndLoc());
1613 syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
1614 if (ReturnDeclaratorRange.isValid()) {
1615 ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1616 Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1617 ReturnDeclarator, nullptr);
1618 }
1619
1620 // Build node for trailing return type.
1621 auto Return = Builder.getRange(ReturnedType.getSourceRange());
1622 const auto *Arrow = Return.begin() - 1;
1623 assert(Arrow->kind() == tok::arrow);
1624 auto Tokens = llvm::ArrayRef(Arrow, Return.end());
1625 Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1626 if (ReturnDeclarator)
1627 Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1628 auto *R = new (allocator()) syntax::TrailingReturnType;
1629 Builder.foldNode(Tokens, R, L);
1630 return R;
1631 }
1632
1633 void foldExplicitTemplateInstantiation(
1634 ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
1635 const syntax::Token *TemplateKW,
1636 syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
1637 assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
1638 assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1639 Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
1640 Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1641 Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1642 Builder.foldNode(
1643 Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
1644 }
1645
1646 syntax::TemplateDeclaration *foldTemplateDeclaration(
1647 ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1648 ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
1649 assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
1650 Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1651
1652 auto *N = new (allocator()) syntax::TemplateDeclaration;
1653 Builder.foldNode(Range, N, From);
1654 Builder.markChild(N, syntax::NodeRole::Declaration);
1655 return N;
1656 }
1657
1658 /// A small helper to save some typing.
1659 llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
1660
1661 syntax::TreeBuilder &Builder;
1662 const ASTContext &Context;
1663};
1664} // namespace
1665
1666void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1667 DeclsWithoutSemicolons.insert(D);
1668}
1669
1670void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
1671 if (Loc.isInvalid())
1672 return;
1673 Pending.assignRole(*findToken(Loc), Role);
1674}
1675
1676void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
1677 if (!T)
1678 return;
1679 Pending.assignRole(*T, R);
1680}
1681
1682void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1683 assert(N);
1684 setRole(N, R);
1685}
1686
1687void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1688 auto *SN = Mapping.find(N);
1689 assert(SN != nullptr);
1690 setRole(SN, R);
1691}
1692void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1693 auto *SN = Mapping.find(NNSLoc);
1694 assert(SN != nullptr);
1695 setRole(SN, R);
1696}
1697
1698void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
1699 if (!Child)
1700 return;
1701
1702 syntax::Tree *ChildNode;
1703 if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
1704 // This is an expression in a statement position, consume the trailing
1705 // semicolon and form an 'ExpressionStatement' node.
1706 markExprChild(ChildExpr, NodeRole::Expression);
1707 ChildNode = new (allocator()) syntax::ExpressionStatement;
1708 // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1709 Pending.foldChildren(TBTM.tokenBuffer(), getStmtRange(Child), ChildNode);
1710 } else {
1711 ChildNode = Mapping.find(Child);
1712 }
1713 assert(ChildNode != nullptr);
1714 setRole(ChildNode, Role);
1715}
1716
1717void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1718 if (!Child)
1719 return;
1720 Child = IgnoreImplicit(Child);
1721
1722 syntax::Tree *ChildNode = Mapping.find(Child);
1723 assert(ChildNode != nullptr);
1724 setRole(ChildNode, Role);
1725}
1726
1727const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
1728 if (L.isInvalid())
1729 return nullptr;
1730 auto It = LocationToToken.find(L);
1731 assert(It != LocationToToken.end());
1732 return It->second;
1733}
1734
1735syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A,
1737 ASTContext &Context) {
1738 TreeBuilder Builder(A, TBTM);
1739 BuildTreeVisitor(Context, Builder).TraverseAST(Context);
1740 return std::move(Builder).finalize();
1741}
#define V(N, I)
Forward declaration of all AST node types.
bool WalkUpFromStringLiteral(StringLiteral *S)
bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S)
bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L)
bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S)
bool WalkUpFromParenExpr(ParenExpr *S)
bool WalkUpFromBreakStmt(BreakStmt *S)
bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S)
bool WalkUpFromFloatingLiteral(FloatingLiteral *S)
bool WalkUpFromCaseStmt(CaseStmt *S)
bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S)
syntax::ParameterDeclarationList * buildParameterDeclarationList(ArrayRef< ParmVarDecl * > Params)
bool WalkUpFromParenTypeLoc(ParenTypeLoc L)
bool WalkUpFromBinaryOperator(BinaryOperator *S)
bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S)
bool TraverseParenTypeLoc(ParenTypeLoc L, bool TraverseQualifier)
bool WalkUpFromCXXThisExpr(CXXThisExpr *S)
bool WalkUpFromDeclRefExpr(DeclRefExpr *S)
bool WalkUpFromSwitchStmt(SwitchStmt *S)
bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S)
bool WalkUpFromDeclStmt(DeclStmt *S)
bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S)
bool WalkUpFromWhileStmt(WhileStmt *S)
bool WalkUpFromNamespaceDecl(NamespaceDecl *S)
bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S)
bool WalkUpFromMemberExpr(MemberExpr *S)
bool WalkUpFromCharacterLiteral(CharacterLiteral *S)
static Expr * IgnoreImplicit(Expr *E)
Definition BuildTree.cpp:74
bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S)
bool WalkUpFromNullStmt(NullStmt *S)
syntax::IdExpression * buildIdExpression(NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceRange UnqualifiedIdLoc, ASTPtr From)
bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S)
bool WalkUpFromEmptyDecl(EmptyDecl *S)
bool WalkUpFromIntegerLiteral(IntegerLiteral *S)
static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args)
bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S)
static LLVM_ATTRIBUTE_UNUSED bool isImplicitExpr(Expr *E)
Definition BuildTree.cpp:81
bool WalkUpFromUnaryOperator(UnaryOperator *S)
static Expr * IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E)
Definition BuildTree.cpp:66
bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S)
static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E)
bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S)
bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L)
bool WalkUpFromUsingDecl(UsingDecl *S)
bool WalkUpFromReturnStmt(ReturnStmt *S)
bool WalkUpFromContinueStmt(ContinueStmt *S)
bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S)
bool WalkUpFromIfStmt(IfStmt *S)
bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L, bool TraverseQualifier)
static SourceLocation getQualifiedNameStart(NamedDecl *D)
Get the start of the qualified name.
bool WalkUpFromCallExpr(CallExpr *S)
bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L)
bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L)
bool WalkUpFromDefaultStmt(DefaultStmt *S)
bool WalkUpFromForStmt(ForStmt *S)
static Expr * IgnoreImplicitConstructorSingleStep(Expr *E)
Definition BuildTree.cpp:47
bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S)
syntax::CallArguments * buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs)
Builds CallArguments syntax node from arguments that appear in source code, i.e. not default argument...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
FormatToken * Next
The next token in the unwrapped line.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
#define SM(sm)
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
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:798
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:856
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:3972
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
Expr * getRHS() const
Definition Expr.h:4024
BreakStmt - This represents a break.
Definition Stmt.h:3135
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:723
SourceLocation getLocation() const
Definition ExprCXX.h:746
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
SourceRange getParenOrBraceRange() const
Definition ExprCXX.h:1730
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
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
SourceLocation getForLoc() const
Definition StmtCXX.h:202
VarDecl * getLoopVariable()
Definition StmtCXX.cpp:77
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
SourceLocation getLocation() const
Definition ExprCXX.h:782
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:152
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:114
SourceRange getSourceRange() const
Definition ExprCXX.h:164
Represents the this expression in C++.
Definition ExprCXX.h:1155
bool isImplicit() const
Definition ExprCXX.h:1178
SourceLocation getLocation() const
Definition ExprCXX.h:1172
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
llvm::iterator_range< arg_iterator > arg_range
Definition Expr.h:3126
arg_iterator arg_begin()
Definition Expr.h:3134
arg_iterator arg_end()
Definition Expr.h:3137
Expr * getCallee()
Definition Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
arg_range arguments()
Definition Expr.h:3129
SourceLocation getRParenLoc() const
Definition Expr.h:3208
CaseStmt - Represent a case statement.
Definition Stmt.h:1920
Stmt * getSubStmt()
Definition Stmt.h:2033
Expr * getLHS()
Definition Stmt.h:2003
SourceLocation getLocation() const
Definition Expr.h:1621
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
body_range body()
Definition Stmt.h:1783
SourceLocation getLBracLoc() const
Definition Stmt.h:1857
SourceLocation getRBracLoc() const
Definition Stmt.h:1858
ContinueStmt - This represents a continue.
Definition Stmt.h:3119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1397
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:547
SourceLocation getLocation() const
Definition Expr.h:1346
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
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Stmt * getSubStmt()
Definition Stmt.h:2081
SourceLocation getNameLoc() const
Definition TypeLoc.h:2577
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3504
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier that qualifies the name, with source location information.
Definition ExprCXX.h:3552
SourceLocation getLocation() const
Retrieve the location of the name within the expression.
Definition ExprCXX.h:3548
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprCXX.h:3622
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3562
SourceLocation getNameLoc() const
Definition TypeLoc.h:766
Represents an empty-declaration.
Definition Decl.h:5158
This represents one expression.
Definition Expr.h:112
SourceLocation getLocation() const
Definition Expr.h:1707
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Stmt * getBody()
Definition Stmt.h:2932
SourceLocation getForLoc() const
Definition Stmt.h:2944
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5684
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
Stmt * getThen()
Definition Stmt.h:2348
SourceLocation getIfLoc() const
Definition Stmt.h:2425
bool hasVarStorage() const
True if this IfStmt has storage for a variable declaration.
Definition Stmt.h:2331
SourceLocation getElseLoc() const
Definition Stmt.h:2428
Stmt * getInit()
Definition Stmt.h:2409
Expr * getCond()
Definition Stmt.h:2336
Stmt * getElse()
Definition Stmt.h:2357
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2392
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
SourceLocation getLocation() const
Retrieve the location of the literal.
Definition Expr.h:1536
Represents a linkage specification.
Definition DeclCXX.h:3015
SourceLocation getKwLoc() const
Definition Stmt.h:3082
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
SourceLocation getOperatorLoc() const
Definition Expr.h:3480
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding the member name, if any.
Definition Expr.h:3415
NestedNameSpecifierLoc getQualifierLoc() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name,...
Definition Expr.h:3400
bool isImplicitAccess() const
Determine whether the base of this explicit is implicit.
Definition Expr.h:3496
Expr * getBase() const
Definition Expr.h:3375
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:1804
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
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
Represents a C++ namespace alias.
Definition DeclCXX.h:3201
Represent a C++ namespace.
Definition Decl.h:591
A C++ nested-name-specifier augmented with source location information.
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,...
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1683
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
SourceLocation getLParen() const
Get the location of the left parentheses '('.
Definition Expr.h:2207
const Expr * getSubExpr() const
Definition Expr.h:2199
SourceLocation getRParen() const
Get the location of the right parentheses ')'.
Definition Expr.h:2211
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
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 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
SourceLocation getReturnLoc() const
Definition Stmt.h:3209
Expr * getRetValue()
Definition Stmt.h:3187
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.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4136
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
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:1799
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1973
SourceLocation getKeywordLoc() const
Definition Stmt.h:1897
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2509
SourceLocation getSwitchLoc() const
Definition Stmt.h:2644
Stmt * getBody()
Definition Stmt.h:2584
SourceLocation getNameLoc() const
Definition TypeLoc.h:827
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
SourceLocation getTemplateLoc() const
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3685
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
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
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
static bool isPostfix(Opcode Op)
isPostfix - Return true if this is a postfix operation, like x++.
Definition Expr.h:2314
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2289
Expr * getSubExpr() const
Definition Expr.h:2285
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:4037
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3940
LiteralOperatorKind getLiteralOperatorKind() const
Returns the kind of literal operator invocation which this expression represents.
Definition ExprCXX.cpp:999
SourceLocation getBeginLoc() const
Definition ExprCXX.h:700
@ 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:3591
Represents C++ using-directive.
Definition DeclCXX.h:3096
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:790
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2697
SourceLocation getWhileLoc() const
Definition Stmt.h:2802
Stmt * getBody()
Definition Stmt.h:2761
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
Models arguments of a function call.
Definition Nodes.h:146
E.g. 'int a, b = 10;'.
Definition Nodes.h:224
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
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
extern <string-literal> declaration extern <string-literal> { <decls> }
Definition Nodes.h:386
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
static_assert(<condition>, <message>) static_assert(<condition>)
Definition Nodes.h:376
switch (<cond>) <body>
Definition Nodes.h:238
A TokenBuffer-powered token manager.
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
A token coming directly from a file or from a macro invocation.
Definition Tokens.h:103
tok::TokenKind kind() const
Definition Tokens.h:109
A node that has children and represents a syntactic language construct.
Definition Tree.h:144
Node * getFirstChild()
Definition Tree.h:179
using <name> = <type>
Definition Nodes.h:468
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
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
NodeRole
A relation between a parent and child node, e.g.
Definition Nodes.h:54
@ ListElement
List API roles.
Definition Nodes.h:77
@ LiteralToken
A token that represents a literal, e.g. 'nullptr', '1', 'true', etc.
Definition Nodes.h:67
@ CloseParen
A closing parenthesis in argument lists and blocks, e.g. '}', ')', etc.
Definition Nodes.h:63
@ IntroducerKeyword
A keywords that introduces some grammar construct, e.g. 'if', 'try', etc.
Definition Nodes.h:65
@ BodyStatement
An inner statement for those that have only a single child of kind statement, e.g.
Definition Nodes.h:75
@ OpenParen
An opening parenthesis in argument lists and blocks, e.g. '{', '(', etc.
Definition Nodes.h:61
syntax::TranslationUnit * buildSyntaxTree(Arena &A, TokenBufferTokenManager &TBTM, ASTContext &Context)
Build a syntax tree for the main file.
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.
@ NUM_OVERLOADED_OPERATORS
bool isa(CodeGen::Address addr)
Definition Address.h:330
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.
Definition TypeBase.h:905
const FunctionProtoType * T
Expr * IgnoreImplicitSingleStep(Expr *E)
Definition IgnoreExpr.h:111
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
U cast(CodeGen::Address addr)
Definition Address.h:327