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