19b3f38f9SIlya Biryukov //===- BuildTree.cpp ------------------------------------------*- C++ -*-=====//
29b3f38f9SIlya Biryukov //
39b3f38f9SIlya Biryukov // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
49b3f38f9SIlya Biryukov // See https://llvm.org/LICENSE.txt for license information.
59b3f38f9SIlya Biryukov // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69b3f38f9SIlya Biryukov //
79b3f38f9SIlya Biryukov //===----------------------------------------------------------------------===//
89b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/BuildTree.h"
97d382dcdSMarcel Hlopko #include "clang/AST/ASTFwd.h"
10e702bdb8SIlya Biryukov #include "clang/AST/Decl.h"
11e702bdb8SIlya Biryukov #include "clang/AST/DeclBase.h"
127d382dcdSMarcel Hlopko #include "clang/AST/DeclCXX.h"
137d382dcdSMarcel Hlopko #include "clang/AST/DeclarationName.h"
143785eb83SEduardo Caldas #include "clang/AST/Expr.h"
15ea8bba7eSEduardo Caldas #include "clang/AST/ExprCXX.h"
162325d6b4SEduardo Caldas #include "clang/AST/IgnoreExpr.h"
17134455a0SEduardo Caldas #include "clang/AST/OperationKinds.h"
189b3f38f9SIlya Biryukov #include "clang/AST/RecursiveASTVisitor.h"
199b3f38f9SIlya Biryukov #include "clang/AST/Stmt.h"
207d382dcdSMarcel Hlopko #include "clang/AST/TypeLoc.h"
217d382dcdSMarcel Hlopko #include "clang/AST/TypeLocVisitor.h"
229b3f38f9SIlya Biryukov #include "clang/Basic/LLVM.h"
239b3f38f9SIlya Biryukov #include "clang/Basic/SourceLocation.h"
249b3f38f9SIlya Biryukov #include "clang/Basic/SourceManager.h"
2588bf9b3dSMarcel Hlopko #include "clang/Basic/Specifiers.h"
269b3f38f9SIlya Biryukov #include "clang/Basic/TokenKinds.h"
279b3f38f9SIlya Biryukov #include "clang/Lex/Lexer.h"
281db5b348SEduardo Caldas #include "clang/Lex/LiteralSupport.h"
299b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Nodes.h"
30263dcf45SHaojian Wu #include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
319b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tokens.h"
329b3f38f9SIlya Biryukov #include "clang/Tooling/Syntax/Tree.h"
339b3f38f9SIlya Biryukov #include "llvm/ADT/ArrayRef.h"
34a711a3a4SMarcel Hlopko #include "llvm/ADT/DenseMap.h"
35a711a3a4SMarcel Hlopko #include "llvm/ADT/PointerUnion.h"
369b3f38f9SIlya Biryukov #include "llvm/ADT/STLExtras.h"
377d382dcdSMarcel Hlopko #include "llvm/ADT/ScopeExit.h"
389b3f38f9SIlya Biryukov #include "llvm/ADT/SmallVector.h"
399b3f38f9SIlya Biryukov #include "llvm/Support/Allocator.h"
409b3f38f9SIlya Biryukov #include "llvm/Support/Casting.h"
4196065cf7SIlya Biryukov #include "llvm/Support/Compiler.h"
429b3f38f9SIlya Biryukov #include "llvm/Support/FormatVariadic.h"
431ad15046SIlya Biryukov #include "llvm/Support/MemoryBuffer.h"
449b3f38f9SIlya Biryukov #include "llvm/Support/raw_ostream.h"
45a711a3a4SMarcel Hlopko #include <cstddef>
469b3f38f9SIlya Biryukov #include <map>
479b3f38f9SIlya Biryukov
489b3f38f9SIlya Biryukov using namespace clang;
499b3f38f9SIlya Biryukov
502325d6b4SEduardo Caldas // Ignores the implicit `CXXConstructExpr` for copy/move constructor calls
512325d6b4SEduardo Caldas // generated by the compiler, as well as in implicit conversions like the one
522325d6b4SEduardo Caldas // wrapping `1` in `X x = 1;`.
IgnoreImplicitConstructorSingleStep(Expr * E)532325d6b4SEduardo Caldas static Expr *IgnoreImplicitConstructorSingleStep(Expr *E) {
542325d6b4SEduardo Caldas if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
552325d6b4SEduardo Caldas auto NumArgs = C->getNumArgs();
562325d6b4SEduardo Caldas if (NumArgs == 1 || (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
572325d6b4SEduardo Caldas Expr *A = C->getArg(0);
582325d6b4SEduardo Caldas if (C->getParenOrBraceRange().isInvalid())
592325d6b4SEduardo Caldas return A;
602325d6b4SEduardo Caldas }
612325d6b4SEduardo Caldas }
622325d6b4SEduardo Caldas return E;
632325d6b4SEduardo Caldas }
642325d6b4SEduardo Caldas
65134455a0SEduardo Caldas // In:
66134455a0SEduardo Caldas // struct X {
67134455a0SEduardo Caldas // X(int)
68134455a0SEduardo Caldas // };
69134455a0SEduardo Caldas // X x = X(1);
70134455a0SEduardo Caldas // Ignores the implicit `CXXFunctionalCastExpr` that wraps
71134455a0SEduardo Caldas // `CXXConstructExpr X(1)`.
IgnoreCXXFunctionalCastExprWrappingConstructor(Expr * E)72134455a0SEduardo Caldas static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
73134455a0SEduardo Caldas if (auto *F = dyn_cast<CXXFunctionalCastExpr>(E)) {
74134455a0SEduardo Caldas if (F->getCastKind() == CK_ConstructorConversion)
75134455a0SEduardo Caldas return F->getSubExpr();
76134455a0SEduardo Caldas }
77134455a0SEduardo Caldas return E;
78134455a0SEduardo Caldas }
79134455a0SEduardo Caldas
IgnoreImplicit(Expr * E)802325d6b4SEduardo Caldas static Expr *IgnoreImplicit(Expr *E) {
812325d6b4SEduardo Caldas return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
82134455a0SEduardo Caldas IgnoreImplicitConstructorSingleStep,
83134455a0SEduardo Caldas IgnoreCXXFunctionalCastExprWrappingConstructor);
842325d6b4SEduardo Caldas }
852325d6b4SEduardo Caldas
8696065cf7SIlya Biryukov LLVM_ATTRIBUTE_UNUSED
isImplicitExpr(Expr * E)872325d6b4SEduardo Caldas static bool isImplicitExpr(Expr *E) { return IgnoreImplicit(E) != E; }
8858fa50f4SIlya Biryukov
897d382dcdSMarcel Hlopko namespace {
907d382dcdSMarcel Hlopko /// Get start location of the Declarator from the TypeLoc.
917d382dcdSMarcel Hlopko /// E.g.:
927d382dcdSMarcel Hlopko /// loc of `(` in `int (a)`
937d382dcdSMarcel Hlopko /// loc of `*` in `int *(a)`
947d382dcdSMarcel Hlopko /// loc of the first `(` in `int (*a)(int)`
957d382dcdSMarcel Hlopko /// loc of the `*` in `int *(a)(int)`
967d382dcdSMarcel Hlopko /// loc of the first `*` in `const int *const *volatile a;`
977d382dcdSMarcel Hlopko ///
987d382dcdSMarcel Hlopko /// It is non-trivial to get the start location because TypeLocs are stored
997d382dcdSMarcel Hlopko /// inside out. In the example above `*volatile` is the TypeLoc returned
1007d382dcdSMarcel Hlopko /// by `Decl.getTypeSourceInfo()`, and `*const` is what `.getPointeeLoc()`
1017d382dcdSMarcel Hlopko /// returns.
1027d382dcdSMarcel Hlopko struct GetStartLoc : TypeLocVisitor<GetStartLoc, SourceLocation> {
VisitParenTypeLoc__anonfe6d26ee0111::GetStartLoc1037d382dcdSMarcel Hlopko SourceLocation VisitParenTypeLoc(ParenTypeLoc T) {
1047d382dcdSMarcel Hlopko auto L = Visit(T.getInnerLoc());
1057d382dcdSMarcel Hlopko if (L.isValid())
1067d382dcdSMarcel Hlopko return L;
1077d382dcdSMarcel Hlopko return T.getLParenLoc();
1087d382dcdSMarcel Hlopko }
1097d382dcdSMarcel Hlopko
1107d382dcdSMarcel Hlopko // Types spelled in the prefix part of the declarator.
VisitPointerTypeLoc__anonfe6d26ee0111::GetStartLoc1117d382dcdSMarcel Hlopko SourceLocation VisitPointerTypeLoc(PointerTypeLoc T) {
1127d382dcdSMarcel Hlopko return HandlePointer(T);
1137d382dcdSMarcel Hlopko }
1147d382dcdSMarcel Hlopko
VisitMemberPointerTypeLoc__anonfe6d26ee0111::GetStartLoc1157d382dcdSMarcel Hlopko SourceLocation VisitMemberPointerTypeLoc(MemberPointerTypeLoc T) {
1167d382dcdSMarcel Hlopko return HandlePointer(T);
1177d382dcdSMarcel Hlopko }
1187d382dcdSMarcel Hlopko
VisitBlockPointerTypeLoc__anonfe6d26ee0111::GetStartLoc1197d382dcdSMarcel Hlopko SourceLocation VisitBlockPointerTypeLoc(BlockPointerTypeLoc T) {
1207d382dcdSMarcel Hlopko return HandlePointer(T);
1217d382dcdSMarcel Hlopko }
1227d382dcdSMarcel Hlopko
VisitReferenceTypeLoc__anonfe6d26ee0111::GetStartLoc1237d382dcdSMarcel Hlopko SourceLocation VisitReferenceTypeLoc(ReferenceTypeLoc T) {
1247d382dcdSMarcel Hlopko return HandlePointer(T);
1257d382dcdSMarcel Hlopko }
1267d382dcdSMarcel Hlopko
VisitObjCObjectPointerTypeLoc__anonfe6d26ee0111::GetStartLoc1277d382dcdSMarcel Hlopko SourceLocation VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc T) {
1287d382dcdSMarcel Hlopko return HandlePointer(T);
1297d382dcdSMarcel Hlopko }
1307d382dcdSMarcel Hlopko
1317d382dcdSMarcel Hlopko // All other cases are not important, as they are either part of declaration
1327d382dcdSMarcel Hlopko // specifiers (e.g. inheritors of TypeSpecTypeLoc) or introduce modifiers on
1337d382dcdSMarcel Hlopko // existing declarators (e.g. QualifiedTypeLoc). They cannot start the
1347d382dcdSMarcel Hlopko // declarator themselves, but their underlying type can.
VisitTypeLoc__anonfe6d26ee0111::GetStartLoc1357d382dcdSMarcel Hlopko SourceLocation VisitTypeLoc(TypeLoc T) {
1367d382dcdSMarcel Hlopko auto N = T.getNextTypeLoc();
1377d382dcdSMarcel Hlopko if (!N)
1387d382dcdSMarcel Hlopko return SourceLocation();
1397d382dcdSMarcel Hlopko return Visit(N);
1407d382dcdSMarcel Hlopko }
1417d382dcdSMarcel Hlopko
VisitFunctionProtoTypeLoc__anonfe6d26ee0111::GetStartLoc1427d382dcdSMarcel Hlopko SourceLocation VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc T) {
1437d382dcdSMarcel Hlopko if (T.getTypePtr()->hasTrailingReturn())
1447d382dcdSMarcel Hlopko return SourceLocation(); // avoid recursing into the suffix of declarator.
1457d382dcdSMarcel Hlopko return VisitTypeLoc(T);
1467d382dcdSMarcel Hlopko }
1477d382dcdSMarcel Hlopko
1487d382dcdSMarcel Hlopko private:
HandlePointer__anonfe6d26ee0111::GetStartLoc1497d382dcdSMarcel Hlopko template <class PtrLoc> SourceLocation HandlePointer(PtrLoc T) {
1507d382dcdSMarcel Hlopko auto L = Visit(T.getPointeeLoc());
1517d382dcdSMarcel Hlopko if (L.isValid())
1527d382dcdSMarcel Hlopko return L;
1537d382dcdSMarcel Hlopko return T.getLocalSourceRange().getBegin();
1547d382dcdSMarcel Hlopko }
1557d382dcdSMarcel Hlopko };
1567d382dcdSMarcel Hlopko } // namespace
1577d382dcdSMarcel Hlopko
dropDefaultArgs(CallExpr::arg_range Args)158f5087d5cSEduardo Caldas static CallExpr::arg_range dropDefaultArgs(CallExpr::arg_range Args) {
15916ceb44eSKazu Hirata auto FirstDefaultArg =
16016ceb44eSKazu Hirata llvm::find_if(Args, [](auto It) { return isa<CXXDefaultArgExpr>(It); });
16187f0b51dSEduardo Caldas return llvm::make_range(Args.begin(), FirstDefaultArg);
162f5087d5cSEduardo Caldas }
163f5087d5cSEduardo Caldas
getOperatorNodeKind(const CXXOperatorCallExpr & E)164ea8bba7eSEduardo Caldas static syntax::NodeKind getOperatorNodeKind(const CXXOperatorCallExpr &E) {
165ea8bba7eSEduardo Caldas switch (E.getOperator()) {
166ea8bba7eSEduardo Caldas // Comparison
167ea8bba7eSEduardo Caldas case OO_EqualEqual:
168ea8bba7eSEduardo Caldas case OO_ExclaimEqual:
169ea8bba7eSEduardo Caldas case OO_Greater:
170ea8bba7eSEduardo Caldas case OO_GreaterEqual:
171ea8bba7eSEduardo Caldas case OO_Less:
172ea8bba7eSEduardo Caldas case OO_LessEqual:
173ea8bba7eSEduardo Caldas case OO_Spaceship:
174ea8bba7eSEduardo Caldas // Assignment
175ea8bba7eSEduardo Caldas case OO_Equal:
176ea8bba7eSEduardo Caldas case OO_SlashEqual:
177ea8bba7eSEduardo Caldas case OO_PercentEqual:
178ea8bba7eSEduardo Caldas case OO_CaretEqual:
179ea8bba7eSEduardo Caldas case OO_PipeEqual:
180ea8bba7eSEduardo Caldas case OO_LessLessEqual:
181ea8bba7eSEduardo Caldas case OO_GreaterGreaterEqual:
182ea8bba7eSEduardo Caldas case OO_PlusEqual:
183ea8bba7eSEduardo Caldas case OO_MinusEqual:
184ea8bba7eSEduardo Caldas case OO_StarEqual:
185ea8bba7eSEduardo Caldas case OO_AmpEqual:
186ea8bba7eSEduardo Caldas // Binary computation
187ea8bba7eSEduardo Caldas case OO_Slash:
188ea8bba7eSEduardo Caldas case OO_Percent:
189ea8bba7eSEduardo Caldas case OO_Caret:
190ea8bba7eSEduardo Caldas case OO_Pipe:
191ea8bba7eSEduardo Caldas case OO_LessLess:
192ea8bba7eSEduardo Caldas case OO_GreaterGreater:
193ea8bba7eSEduardo Caldas case OO_AmpAmp:
194ea8bba7eSEduardo Caldas case OO_PipePipe:
195ea8bba7eSEduardo Caldas case OO_ArrowStar:
196ea8bba7eSEduardo Caldas case OO_Comma:
197ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression;
198ea8bba7eSEduardo Caldas case OO_Tilde:
199ea8bba7eSEduardo Caldas case OO_Exclaim:
200ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression;
201ea8bba7eSEduardo Caldas // Prefix/Postfix increment/decrement
202ea8bba7eSEduardo Caldas case OO_PlusPlus:
203ea8bba7eSEduardo Caldas case OO_MinusMinus:
204ea8bba7eSEduardo Caldas switch (E.getNumArgs()) {
205ea8bba7eSEduardo Caldas case 1:
206ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression;
207ea8bba7eSEduardo Caldas case 2:
208ea8bba7eSEduardo Caldas return syntax::NodeKind::PostfixUnaryOperatorExpression;
209ea8bba7eSEduardo Caldas default:
210ea8bba7eSEduardo Caldas llvm_unreachable("Invalid number of arguments for operator");
211ea8bba7eSEduardo Caldas }
212ea8bba7eSEduardo Caldas // Operators that can be unary or binary
213ea8bba7eSEduardo Caldas case OO_Plus:
214ea8bba7eSEduardo Caldas case OO_Minus:
215ea8bba7eSEduardo Caldas case OO_Star:
216ea8bba7eSEduardo Caldas case OO_Amp:
217ea8bba7eSEduardo Caldas switch (E.getNumArgs()) {
218ea8bba7eSEduardo Caldas case 1:
219ea8bba7eSEduardo Caldas return syntax::NodeKind::PrefixUnaryOperatorExpression;
220ea8bba7eSEduardo Caldas case 2:
221ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression;
222ea8bba7eSEduardo Caldas default:
223ea8bba7eSEduardo Caldas llvm_unreachable("Invalid number of arguments for operator");
224ea8bba7eSEduardo Caldas }
225ea8bba7eSEduardo Caldas return syntax::NodeKind::BinaryOperatorExpression;
226ea8bba7eSEduardo Caldas // Not yet supported by SyntaxTree
227ea8bba7eSEduardo Caldas case OO_New:
228ea8bba7eSEduardo Caldas case OO_Delete:
229ea8bba7eSEduardo Caldas case OO_Array_New:
230ea8bba7eSEduardo Caldas case OO_Array_Delete:
231ea8bba7eSEduardo Caldas case OO_Coawait:
232ea8bba7eSEduardo Caldas case OO_Subscript:
233ea8bba7eSEduardo Caldas case OO_Arrow:
234ea8bba7eSEduardo Caldas return syntax::NodeKind::UnknownExpression;
2352de2ca34SEduardo Caldas case OO_Call:
2362de2ca34SEduardo Caldas return syntax::NodeKind::CallExpression;
237ea8bba7eSEduardo Caldas case OO_Conditional: // not overloadable
238ea8bba7eSEduardo Caldas case NUM_OVERLOADED_OPERATORS:
239ea8bba7eSEduardo Caldas case OO_None:
240ea8bba7eSEduardo Caldas llvm_unreachable("Not an overloadable operator");
241ea8bba7eSEduardo Caldas }
242397c6820SSimon Pilgrim llvm_unreachable("Unknown OverloadedOperatorKind enum");
243ea8bba7eSEduardo Caldas }
244ea8bba7eSEduardo Caldas
24538bc0060SEduardo Caldas /// Get the start of the qualified name. In the examples below it gives the
24638bc0060SEduardo Caldas /// location of the `^`:
24738bc0060SEduardo Caldas /// `int ^a;`
248a1461953SEduardo Caldas /// `int *^a;`
24938bc0060SEduardo Caldas /// `int ^a::S::f(){}`
getQualifiedNameStart(NamedDecl * D)25038bc0060SEduardo Caldas static SourceLocation getQualifiedNameStart(NamedDecl *D) {
25138bc0060SEduardo Caldas assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
25238bc0060SEduardo Caldas "only DeclaratorDecl and TypedefNameDecl are supported.");
25338bc0060SEduardo Caldas
25438bc0060SEduardo Caldas auto DN = D->getDeclName();
25538bc0060SEduardo Caldas bool IsAnonymous = DN.isIdentifier() && !DN.getAsIdentifierInfo();
25638bc0060SEduardo Caldas if (IsAnonymous)
25738bc0060SEduardo Caldas return SourceLocation();
25838bc0060SEduardo Caldas
25938bc0060SEduardo Caldas if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
26038bc0060SEduardo Caldas if (DD->getQualifierLoc()) {
26138bc0060SEduardo Caldas return DD->getQualifierLoc().getBeginLoc();
26238bc0060SEduardo Caldas }
26338bc0060SEduardo Caldas }
26438bc0060SEduardo Caldas
26538bc0060SEduardo Caldas return D->getLocation();
26638bc0060SEduardo Caldas }
26738bc0060SEduardo Caldas
26838bc0060SEduardo Caldas /// Gets the range of the initializer inside an init-declarator C++ [dcl.decl].
26938bc0060SEduardo Caldas /// `int a;` -> range of ``,
27038bc0060SEduardo Caldas /// `int *a = nullptr` -> range of `= nullptr`.
27138bc0060SEduardo Caldas /// `int a{}` -> range of `{}`.
27238bc0060SEduardo Caldas /// `int a()` -> range of `()`.
getInitializerRange(Decl * D)27338bc0060SEduardo Caldas static SourceRange getInitializerRange(Decl *D) {
27438bc0060SEduardo Caldas if (auto *V = dyn_cast<VarDecl>(D)) {
27538bc0060SEduardo Caldas auto *I = V->getInit();
27638bc0060SEduardo Caldas // Initializers in range-based-for are not part of the declarator
27738bc0060SEduardo Caldas if (I && !V->isCXXForRangeDecl())
27838bc0060SEduardo Caldas return I->getSourceRange();
27938bc0060SEduardo Caldas }
28038bc0060SEduardo Caldas
28138bc0060SEduardo Caldas return SourceRange();
28238bc0060SEduardo Caldas }
28338bc0060SEduardo Caldas
2847d382dcdSMarcel Hlopko /// Gets the range of declarator as defined by the C++ grammar. E.g.
2857d382dcdSMarcel Hlopko /// `int a;` -> range of `a`,
2867d382dcdSMarcel Hlopko /// `int *a;` -> range of `*a`,
2877d382dcdSMarcel Hlopko /// `int a[10];` -> range of `a[10]`,
2887d382dcdSMarcel Hlopko /// `int a[1][2][3];` -> range of `a[1][2][3]`,
2897d382dcdSMarcel Hlopko /// `int *a = nullptr` -> range of `*a = nullptr`.
29038bc0060SEduardo Caldas /// `int S::f(){}` -> range of `S::f()`.
291a1461953SEduardo Caldas /// FIXME: \p Name must be a source range.
getDeclaratorRange(const SourceManager & SM,TypeLoc T,SourceLocation Name,SourceRange Initializer)2927d382dcdSMarcel Hlopko static SourceRange getDeclaratorRange(const SourceManager &SM, TypeLoc T,
2937d382dcdSMarcel Hlopko SourceLocation Name,
2947d382dcdSMarcel Hlopko SourceRange Initializer) {
2957d382dcdSMarcel Hlopko SourceLocation Start = GetStartLoc().Visit(T);
29638bc0060SEduardo Caldas SourceLocation End = T.getEndLoc();
2977d382dcdSMarcel Hlopko if (Name.isValid()) {
2987d382dcdSMarcel Hlopko if (Start.isInvalid())
2997d382dcdSMarcel Hlopko Start = Name;
300e159a3ceSHaojian Wu // End of TypeLoc could be invalid if the type is invalid, fallback to the
301e159a3ceSHaojian Wu // NameLoc.
302e159a3ceSHaojian Wu if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name))
3037d382dcdSMarcel Hlopko End = Name;
3047d382dcdSMarcel Hlopko }
3057d382dcdSMarcel Hlopko if (Initializer.isValid()) {
306cdce2fe5SMarcel Hlopko auto InitializerEnd = Initializer.getEnd();
307f33c2c27SEduardo Caldas assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
308f33c2c27SEduardo Caldas End == InitializerEnd);
309cdce2fe5SMarcel Hlopko End = InitializerEnd;
3107d382dcdSMarcel Hlopko }
3117d382dcdSMarcel Hlopko return SourceRange(Start, End);
3127d382dcdSMarcel Hlopko }
3137d382dcdSMarcel Hlopko
314a711a3a4SMarcel Hlopko namespace {
315a711a3a4SMarcel Hlopko /// All AST hierarchy roots that can be represented as pointers.
316a711a3a4SMarcel Hlopko using ASTPtr = llvm::PointerUnion<Stmt *, Decl *>;
317a711a3a4SMarcel Hlopko /// Maintains a mapping from AST to syntax tree nodes. This class will get more
318a711a3a4SMarcel Hlopko /// complicated as we support more kinds of AST nodes, e.g. TypeLocs.
319a711a3a4SMarcel Hlopko /// FIXME: expose this as public API.
320a711a3a4SMarcel Hlopko class ASTToSyntaxMapping {
321a711a3a4SMarcel Hlopko public:
add(ASTPtr From,syntax::Tree * To)322a711a3a4SMarcel Hlopko void add(ASTPtr From, syntax::Tree *To) {
323a711a3a4SMarcel Hlopko assert(To != nullptr);
324a711a3a4SMarcel Hlopko assert(!From.isNull());
325a711a3a4SMarcel Hlopko
326a711a3a4SMarcel Hlopko bool Added = Nodes.insert({From, To}).second;
327a711a3a4SMarcel Hlopko (void)Added;
328a711a3a4SMarcel Hlopko assert(Added && "mapping added twice");
329a711a3a4SMarcel Hlopko }
330a711a3a4SMarcel Hlopko
add(NestedNameSpecifierLoc From,syntax::Tree * To)331f9500cc4SEduardo Caldas void add(NestedNameSpecifierLoc From, syntax::Tree *To) {
332f9500cc4SEduardo Caldas assert(To != nullptr);
333f9500cc4SEduardo Caldas assert(From.hasQualifier());
334f9500cc4SEduardo Caldas
335f9500cc4SEduardo Caldas bool Added = NNSNodes.insert({From, To}).second;
336f9500cc4SEduardo Caldas (void)Added;
337f9500cc4SEduardo Caldas assert(Added && "mapping added twice");
338f9500cc4SEduardo Caldas }
339f9500cc4SEduardo Caldas
find(ASTPtr P) const340a711a3a4SMarcel Hlopko syntax::Tree *find(ASTPtr P) const { return Nodes.lookup(P); }
341a711a3a4SMarcel Hlopko
find(NestedNameSpecifierLoc P) const342f9500cc4SEduardo Caldas syntax::Tree *find(NestedNameSpecifierLoc P) const {
343f9500cc4SEduardo Caldas return NNSNodes.lookup(P);
344f9500cc4SEduardo Caldas }
345f9500cc4SEduardo Caldas
346a711a3a4SMarcel Hlopko private:
347a711a3a4SMarcel Hlopko llvm::DenseMap<ASTPtr, syntax::Tree *> Nodes;
348f9500cc4SEduardo Caldas llvm::DenseMap<NestedNameSpecifierLoc, syntax::Tree *> NNSNodes;
349a711a3a4SMarcel Hlopko };
350a711a3a4SMarcel Hlopko } // namespace
351a711a3a4SMarcel Hlopko
3529b3f38f9SIlya Biryukov /// A helper class for constructing the syntax tree while traversing a clang
3539b3f38f9SIlya Biryukov /// AST.
3549b3f38f9SIlya Biryukov ///
3559b3f38f9SIlya Biryukov /// At each point of the traversal we maintain a list of pending nodes.
3569b3f38f9SIlya Biryukov /// Initially all tokens are added as pending nodes. When processing a clang AST
3579b3f38f9SIlya Biryukov /// node, the clients need to:
3589b3f38f9SIlya Biryukov /// - create a corresponding syntax node,
3599b3f38f9SIlya Biryukov /// - assign roles to all pending child nodes with 'markChild' and
3609b3f38f9SIlya Biryukov /// 'markChildToken',
3619b3f38f9SIlya Biryukov /// - replace the child nodes with the new syntax node in the pending list
3629b3f38f9SIlya Biryukov /// with 'foldNode'.
3639b3f38f9SIlya Biryukov ///
3649b3f38f9SIlya Biryukov /// Note that all children are expected to be processed when building a node.
3659b3f38f9SIlya Biryukov ///
3669b3f38f9SIlya Biryukov /// Call finalize() to finish building the tree and consume the root node.
3679b3f38f9SIlya Biryukov class syntax::TreeBuilder {
3689b3f38f9SIlya Biryukov public:
TreeBuilder(syntax::Arena & Arena,TokenBufferTokenManager & TBTM)369263dcf45SHaojian Wu TreeBuilder(syntax::Arena &Arena, TokenBufferTokenManager& TBTM)
370263dcf45SHaojian Wu : Arena(Arena),
371263dcf45SHaojian Wu TBTM(TBTM),
372263dcf45SHaojian Wu Pending(Arena, TBTM.tokenBuffer()) {
373263dcf45SHaojian Wu for (const auto &T : TBTM.tokenBuffer().expandedTokens())
37478194118SMikhail Maltsev LocationToToken.insert({T.location(), &T});
375c1bbefefSIlya Biryukov }
3769b3f38f9SIlya Biryukov
allocator()3774c14ee61SEduardo Caldas llvm::BumpPtrAllocator &allocator() { return Arena.getAllocator(); }
sourceManager() const3784c14ee61SEduardo Caldas const SourceManager &sourceManager() const {
379263dcf45SHaojian Wu return TBTM.sourceManager();
3804c14ee61SEduardo Caldas }
3819b3f38f9SIlya Biryukov
3829b3f38f9SIlya Biryukov /// Populate children for \p New node, assuming it covers tokens from \p
3839b3f38f9SIlya Biryukov /// Range.
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,ASTPtr From)384ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, ASTPtr From) {
385a711a3a4SMarcel Hlopko assert(New);
386263dcf45SHaojian Wu Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
387a711a3a4SMarcel Hlopko if (From)
388a711a3a4SMarcel Hlopko Mapping.add(From, New);
389a711a3a4SMarcel Hlopko }
390f9500cc4SEduardo Caldas
foldNode(ArrayRef<syntax::Token> Range,syntax::Tree * New,TypeLoc L)391ba41a0f7SEduardo Caldas void foldNode(ArrayRef<syntax::Token> Range, syntax::Tree *New, TypeLoc L) {
392a711a3a4SMarcel Hlopko // FIXME: add mapping for TypeLocs
393a711a3a4SMarcel Hlopko foldNode(Range, New, nullptr);
394a711a3a4SMarcel Hlopko }
3959b3f38f9SIlya Biryukov
foldNode(llvm::ArrayRef<syntax::Token> Range,syntax::Tree * New,NestedNameSpecifierLoc From)396f9500cc4SEduardo Caldas void foldNode(llvm::ArrayRef<syntax::Token> Range, syntax::Tree *New,
397f9500cc4SEduardo Caldas NestedNameSpecifierLoc From) {
398f9500cc4SEduardo Caldas assert(New);
399263dcf45SHaojian Wu Pending.foldChildren(TBTM.tokenBuffer(), Range, New);
400f9500cc4SEduardo Caldas if (From)
401f9500cc4SEduardo Caldas Mapping.add(From, New);
4028abb5fb6SEduardo Caldas }
403f9500cc4SEduardo Caldas
4045011d431SEduardo Caldas /// Populate children for \p New list, assuming it covers tokens from a
4055011d431SEduardo Caldas /// subrange of \p SuperRange.
foldList(ArrayRef<syntax::Token> SuperRange,syntax::List * New,ASTPtr From)4065011d431SEduardo Caldas void foldList(ArrayRef<syntax::Token> SuperRange, syntax::List *New,
4075011d431SEduardo Caldas ASTPtr From) {
4085011d431SEduardo Caldas assert(New);
4095011d431SEduardo Caldas auto ListRange = Pending.shrinkToFitList(SuperRange);
410263dcf45SHaojian Wu Pending.foldChildren(TBTM.tokenBuffer(), ListRange, New);
4115011d431SEduardo Caldas if (From)
4125011d431SEduardo Caldas Mapping.add(From, New);
4135011d431SEduardo Caldas }
4145011d431SEduardo Caldas
415e702bdb8SIlya Biryukov /// Notifies that we should not consume trailing semicolon when computing
416e702bdb8SIlya Biryukov /// token range of \p D.
4177d382dcdSMarcel Hlopko void noticeDeclWithoutSemicolon(Decl *D);
418e702bdb8SIlya Biryukov
41958fa50f4SIlya Biryukov /// Mark the \p Child node with a corresponding \p Role. All marked children
42058fa50f4SIlya Biryukov /// should be consumed by foldNode.
4217d382dcdSMarcel Hlopko /// When called on expressions (clang::Expr is derived from clang::Stmt),
42258fa50f4SIlya Biryukov /// wraps expressions into expression statement.
42358fa50f4SIlya Biryukov void markStmtChild(Stmt *Child, NodeRole Role);
42458fa50f4SIlya Biryukov /// Should be called for expressions in non-statement position to avoid
42558fa50f4SIlya Biryukov /// wrapping into expression statement.
42658fa50f4SIlya Biryukov void markExprChild(Expr *Child, NodeRole Role);
4279b3f38f9SIlya Biryukov /// Set role for a token starting at \p Loc.
428def65bb4SIlya Biryukov void markChildToken(SourceLocation Loc, NodeRole R);
4297d382dcdSMarcel Hlopko /// Set role for \p T.
4307d382dcdSMarcel Hlopko void markChildToken(const syntax::Token *T, NodeRole R);
4317d382dcdSMarcel Hlopko
432a711a3a4SMarcel Hlopko /// Set role for \p N.
433a711a3a4SMarcel Hlopko void markChild(syntax::Node *N, NodeRole R);
434a711a3a4SMarcel Hlopko /// Set role for the syntax node matching \p N.
435a711a3a4SMarcel Hlopko void markChild(ASTPtr N, NodeRole R);
436f9500cc4SEduardo Caldas /// Set role for the syntax node matching \p N.
437f9500cc4SEduardo Caldas void markChild(NestedNameSpecifierLoc N, NodeRole R);
4389b3f38f9SIlya Biryukov
4399b3f38f9SIlya Biryukov /// Finish building the tree and consume the root node.
finalize()4409b3f38f9SIlya Biryukov syntax::TranslationUnit *finalize() && {
441263dcf45SHaojian Wu auto Tokens = TBTM.tokenBuffer().expandedTokens();
442bfbf6b6cSIlya Biryukov assert(!Tokens.empty());
443bfbf6b6cSIlya Biryukov assert(Tokens.back().kind() == tok::eof);
444bfbf6b6cSIlya Biryukov
4459b3f38f9SIlya Biryukov // Build the root of the tree, consuming all the children.
446263dcf45SHaojian Wu Pending.foldChildren(TBTM.tokenBuffer(), Tokens.drop_back(),
4474c14ee61SEduardo Caldas new (Arena.getAllocator()) syntax::TranslationUnit);
4489b3f38f9SIlya Biryukov
4493b929fe7SIlya Biryukov auto *TU = cast<syntax::TranslationUnit>(std::move(Pending).finalize());
4503b929fe7SIlya Biryukov TU->assertInvariantsRecursive();
4513b929fe7SIlya Biryukov return TU;
4529b3f38f9SIlya Biryukov }
4539b3f38f9SIlya Biryukov
45488bf9b3dSMarcel Hlopko /// Finds a token starting at \p L. The token must exist if \p L is valid.
45588bf9b3dSMarcel Hlopko const syntax::Token *findToken(SourceLocation L) const;
45688bf9b3dSMarcel Hlopko
457a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the \p SourceRange.
getRange(SourceRange Range) const458ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceRange Range) const {
459a711a3a4SMarcel Hlopko assert(Range.isValid());
460a711a3a4SMarcel Hlopko return getRange(Range.getBegin(), Range.getEnd());
461a711a3a4SMarcel Hlopko }
462a711a3a4SMarcel Hlopko
463a711a3a4SMarcel Hlopko /// Finds the syntax tokens corresponding to the passed source locations.
4649b3f38f9SIlya Biryukov /// \p First is the start position of the first token and \p Last is the start
4659b3f38f9SIlya Biryukov /// position of the last token.
getRange(SourceLocation First,SourceLocation Last) const466ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getRange(SourceLocation First,
4679b3f38f9SIlya Biryukov SourceLocation Last) const {
4689b3f38f9SIlya Biryukov assert(First.isValid());
4699b3f38f9SIlya Biryukov assert(Last.isValid());
4709b3f38f9SIlya Biryukov assert(First == Last ||
471263dcf45SHaojian Wu TBTM.sourceManager().isBeforeInTranslationUnit(First, Last));
472a3c248dbSserge-sans-paille return llvm::ArrayRef(findToken(First), std::next(findToken(Last)));
4739b3f38f9SIlya Biryukov }
47488bf9b3dSMarcel Hlopko
475ba41a0f7SEduardo Caldas ArrayRef<syntax::Token>
getTemplateRange(const ClassTemplateSpecializationDecl * D) const47688bf9b3dSMarcel Hlopko getTemplateRange(const ClassTemplateSpecializationDecl *D) const {
477a711a3a4SMarcel Hlopko auto Tokens = getRange(D->getSourceRange());
47888bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D);
47988bf9b3dSMarcel Hlopko }
48088bf9b3dSMarcel Hlopko
481cdce2fe5SMarcel Hlopko /// Returns true if \p D is the last declarator in a chain and is thus
482cdce2fe5SMarcel Hlopko /// reponsible for creating SimpleDeclaration for the whole chain.
isResponsibleForCreatingDeclaration(const Decl * D) const48338bc0060SEduardo Caldas bool isResponsibleForCreatingDeclaration(const Decl *D) const {
48438bc0060SEduardo Caldas assert((isa<DeclaratorDecl, TypedefNameDecl>(D)) &&
485cdce2fe5SMarcel Hlopko "only DeclaratorDecl and TypedefNameDecl are supported.");
486cdce2fe5SMarcel Hlopko
487cdce2fe5SMarcel Hlopko const Decl *Next = D->getNextDeclInContext();
488cdce2fe5SMarcel Hlopko
489cdce2fe5SMarcel Hlopko // There's no next sibling, this one is responsible.
490cdce2fe5SMarcel Hlopko if (Next == nullptr) {
491cdce2fe5SMarcel Hlopko return true;
492cdce2fe5SMarcel Hlopko }
493cdce2fe5SMarcel Hlopko
494cdce2fe5SMarcel Hlopko // Next sibling is not the same type, this one is responsible.
49538bc0060SEduardo Caldas if (D->getKind() != Next->getKind()) {
496cdce2fe5SMarcel Hlopko return true;
497cdce2fe5SMarcel Hlopko }
498cdce2fe5SMarcel Hlopko // Next sibling doesn't begin at the same loc, it must be a different
499cdce2fe5SMarcel Hlopko // declaration, so this declarator is responsible.
50038bc0060SEduardo Caldas if (Next->getBeginLoc() != D->getBeginLoc()) {
501cdce2fe5SMarcel Hlopko return true;
502cdce2fe5SMarcel Hlopko }
503cdce2fe5SMarcel Hlopko
504cdce2fe5SMarcel Hlopko // NextT is a member of the same declaration, and we need the last member to
505cdce2fe5SMarcel Hlopko // create declaration. This one is not responsible.
506cdce2fe5SMarcel Hlopko return false;
507cdce2fe5SMarcel Hlopko }
508cdce2fe5SMarcel Hlopko
getDeclarationRange(Decl * D)509ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getDeclarationRange(Decl *D) {
510ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> Tokens;
51188bf9b3dSMarcel Hlopko // We want to drop the template parameters for specializations.
512ba41a0f7SEduardo Caldas if (const auto *S = dyn_cast<TagDecl>(D))
51388bf9b3dSMarcel Hlopko Tokens = getRange(S->TypeDecl::getBeginLoc(), S->getEndLoc());
51488bf9b3dSMarcel Hlopko else
515a711a3a4SMarcel Hlopko Tokens = getRange(D->getSourceRange());
51688bf9b3dSMarcel Hlopko return maybeAppendSemicolon(Tokens, D);
5179b3f38f9SIlya Biryukov }
518cdce2fe5SMarcel Hlopko
getExprRange(const Expr * E) const519ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getExprRange(const Expr *E) const {
520a711a3a4SMarcel Hlopko return getRange(E->getSourceRange());
52158fa50f4SIlya Biryukov }
522cdce2fe5SMarcel Hlopko
52358fa50f4SIlya Biryukov /// Find the adjusted range for the statement, consuming the trailing
52458fa50f4SIlya Biryukov /// semicolon when needed.
getStmtRange(const Stmt * S) const525ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> getStmtRange(const Stmt *S) const {
526a711a3a4SMarcel Hlopko auto Tokens = getRange(S->getSourceRange());
52758fa50f4SIlya Biryukov if (isa<CompoundStmt>(S))
52858fa50f4SIlya Biryukov return Tokens;
52958fa50f4SIlya Biryukov
53058fa50f4SIlya Biryukov // Some statements miss a trailing semicolon, e.g. 'return', 'continue' and
53158fa50f4SIlya Biryukov // all statements that end with those. Consume this semicolon here.
532e702bdb8SIlya Biryukov if (Tokens.back().kind() == tok::semi)
533e702bdb8SIlya Biryukov return Tokens;
534e702bdb8SIlya Biryukov return withTrailingSemicolon(Tokens);
535e702bdb8SIlya Biryukov }
536e702bdb8SIlya Biryukov
537e702bdb8SIlya Biryukov private:
maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,const Decl * D) const538ba41a0f7SEduardo Caldas ArrayRef<syntax::Token> maybeAppendSemicolon(ArrayRef<syntax::Token> Tokens,
53988bf9b3dSMarcel Hlopko const Decl *D) const {
540ba41a0f7SEduardo Caldas if (isa<NamespaceDecl>(D))
54188bf9b3dSMarcel Hlopko return Tokens;
54288bf9b3dSMarcel Hlopko if (DeclsWithoutSemicolons.count(D))
54388bf9b3dSMarcel Hlopko return Tokens;
54488bf9b3dSMarcel Hlopko // FIXME: do not consume trailing semicolon on function definitions.
54588bf9b3dSMarcel Hlopko // Most declarations own a semicolon in syntax trees, but not in clang AST.
54688bf9b3dSMarcel Hlopko return withTrailingSemicolon(Tokens);
54788bf9b3dSMarcel Hlopko }
54888bf9b3dSMarcel Hlopko
549ba41a0f7SEduardo Caldas ArrayRef<syntax::Token>
withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const550ba41a0f7SEduardo Caldas withTrailingSemicolon(ArrayRef<syntax::Token> Tokens) const {
551e702bdb8SIlya Biryukov assert(!Tokens.empty());
552e702bdb8SIlya Biryukov assert(Tokens.back().kind() != tok::eof);
5537d382dcdSMarcel Hlopko // We never consume 'eof', so looking at the next token is ok.
55458fa50f4SIlya Biryukov if (Tokens.back().kind() != tok::semi && Tokens.end()->kind() == tok::semi)
555a3c248dbSserge-sans-paille return llvm::ArrayRef(Tokens.begin(), Tokens.end() + 1);
55658fa50f4SIlya Biryukov return Tokens;
5579b3f38f9SIlya Biryukov }
5589b3f38f9SIlya Biryukov
setRole(syntax::Node * N,NodeRole R)559a711a3a4SMarcel Hlopko void setRole(syntax::Node *N, NodeRole R) {
5604c14ee61SEduardo Caldas assert(N->getRole() == NodeRole::Detached);
561a711a3a4SMarcel Hlopko N->setRole(R);
562a711a3a4SMarcel Hlopko }
563a711a3a4SMarcel Hlopko
5649b3f38f9SIlya Biryukov /// A collection of trees covering the input tokens.
5659b3f38f9SIlya Biryukov /// When created, each tree corresponds to a single token in the file.
5669b3f38f9SIlya Biryukov /// Clients call 'foldChildren' to attach one or more subtrees to a parent
5679b3f38f9SIlya Biryukov /// node and update the list of trees accordingly.
5689b3f38f9SIlya Biryukov ///
5699b3f38f9SIlya Biryukov /// Ensures that added nodes properly nest and cover the whole token stream.
5709b3f38f9SIlya Biryukov struct Forest {
Forestsyntax::TreeBuilder::Forest571263dcf45SHaojian Wu Forest(syntax::Arena &A, const syntax::TokenBuffer &TB) {
572263dcf45SHaojian Wu assert(!TB.expandedTokens().empty());
573263dcf45SHaojian Wu assert(TB.expandedTokens().back().kind() == tok::eof);
5749b3f38f9SIlya Biryukov // Create all leaf nodes.
575bfbf6b6cSIlya Biryukov // Note that we do not have 'eof' in the tree.
576263dcf45SHaojian Wu for (const auto &T : TB.expandedTokens().drop_back()) {
577263dcf45SHaojian Wu auto *L = new (A.getAllocator())
578263dcf45SHaojian Wu syntax::Leaf(reinterpret_cast<TokenManager::Key>(&T));
5791ad15046SIlya Biryukov L->Original = true;
580263dcf45SHaojian Wu L->CanModify = TB.spelledForExpanded(T).has_value();
581a711a3a4SMarcel Hlopko Trees.insert(Trees.end(), {&T, L});
5821ad15046SIlya Biryukov }
5839b3f38f9SIlya Biryukov }
5849b3f38f9SIlya Biryukov
assignRolesyntax::TreeBuilder::Forest585ba41a0f7SEduardo Caldas void assignRole(ArrayRef<syntax::Token> Range, syntax::NodeRole Role) {
5869b3f38f9SIlya Biryukov assert(!Range.empty());
5879b3f38f9SIlya Biryukov auto It = Trees.lower_bound(Range.begin());
5889b3f38f9SIlya Biryukov assert(It != Trees.end() && "no node found");
5899b3f38f9SIlya Biryukov assert(It->first == Range.begin() && "no child with the specified range");
5909b3f38f9SIlya Biryukov assert((std::next(It) == Trees.end() ||
5919b3f38f9SIlya Biryukov std::next(It)->first == Range.end()) &&
5929b3f38f9SIlya Biryukov "no child with the specified range");
5934c14ee61SEduardo Caldas assert(It->second->getRole() == NodeRole::Detached &&
594a711a3a4SMarcel Hlopko "re-assigning role for a child");
595a711a3a4SMarcel Hlopko It->second->setRole(Role);
5969b3f38f9SIlya Biryukov }
5979b3f38f9SIlya Biryukov
5985011d431SEduardo Caldas /// Shrink \p Range to a subrange that only contains tokens of a list.
5995011d431SEduardo Caldas /// List elements and delimiters should already have correct roles.
shrinkToFitListsyntax::TreeBuilder::Forest6005011d431SEduardo Caldas ArrayRef<syntax::Token> shrinkToFitList(ArrayRef<syntax::Token> Range) {
6015011d431SEduardo Caldas auto BeginChildren = Trees.lower_bound(Range.begin());
6025011d431SEduardo Caldas assert((BeginChildren == Trees.end() ||
6035011d431SEduardo Caldas BeginChildren->first == Range.begin()) &&
6045011d431SEduardo Caldas "Range crosses boundaries of existing subtrees");
6055011d431SEduardo Caldas
6065011d431SEduardo Caldas auto EndChildren = Trees.lower_bound(Range.end());
6075011d431SEduardo Caldas assert(
6085011d431SEduardo Caldas (EndChildren == Trees.end() || EndChildren->first == Range.end()) &&
6095011d431SEduardo Caldas "Range crosses boundaries of existing subtrees");
6105011d431SEduardo Caldas
6115011d431SEduardo Caldas auto BelongsToList = [](decltype(Trees)::value_type KV) {
6125011d431SEduardo Caldas auto Role = KV.second->getRole();
6135011d431SEduardo Caldas return Role == syntax::NodeRole::ListElement ||
6145011d431SEduardo Caldas Role == syntax::NodeRole::ListDelimiter;
6155011d431SEduardo Caldas };
6165011d431SEduardo Caldas
6175011d431SEduardo Caldas auto BeginListChildren =
6185011d431SEduardo Caldas std::find_if(BeginChildren, EndChildren, BelongsToList);
6195011d431SEduardo Caldas
6205011d431SEduardo Caldas auto EndListChildren =
6215011d431SEduardo Caldas std::find_if_not(BeginListChildren, EndChildren, BelongsToList);
6225011d431SEduardo Caldas
6235011d431SEduardo Caldas return ArrayRef<syntax::Token>(BeginListChildren->first,
6245011d431SEduardo Caldas EndListChildren->first);
6255011d431SEduardo Caldas }
6265011d431SEduardo Caldas
627e702bdb8SIlya Biryukov /// Add \p Node to the forest and attach child nodes based on \p Tokens.
foldChildrensyntax::TreeBuilder::Forest628263dcf45SHaojian Wu void foldChildren(const syntax::TokenBuffer &TB,
629263dcf45SHaojian Wu ArrayRef<syntax::Token> Tokens, syntax::Tree *Node) {
630e702bdb8SIlya Biryukov // Attach children to `Node`.
6314c14ee61SEduardo Caldas assert(Node->getFirstChild() == nullptr && "node already has children");
632cdce2fe5SMarcel Hlopko
633cdce2fe5SMarcel Hlopko auto *FirstToken = Tokens.begin();
634cdce2fe5SMarcel Hlopko auto BeginChildren = Trees.lower_bound(FirstToken);
635cdce2fe5SMarcel Hlopko
636cdce2fe5SMarcel Hlopko assert((BeginChildren == Trees.end() ||
637cdce2fe5SMarcel Hlopko BeginChildren->first == FirstToken) &&
638cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees");
639cdce2fe5SMarcel Hlopko auto EndChildren = Trees.lower_bound(Tokens.end());
640cdce2fe5SMarcel Hlopko assert(
641cdce2fe5SMarcel Hlopko (EndChildren == Trees.end() || EndChildren->first == Tokens.end()) &&
642cdce2fe5SMarcel Hlopko "fold crosses boundaries of existing subtrees");
643cdce2fe5SMarcel Hlopko
64423657d9cSEduardo Caldas for (auto It = BeginChildren; It != EndChildren; ++It) {
64523657d9cSEduardo Caldas auto *C = It->second;
6464c14ee61SEduardo Caldas if (C->getRole() == NodeRole::Detached)
647cdce2fe5SMarcel Hlopko C->setRole(NodeRole::Unknown);
64823657d9cSEduardo Caldas Node->appendChildLowLevel(C);
649e702bdb8SIlya Biryukov }
6509b3f38f9SIlya Biryukov
651cdce2fe5SMarcel Hlopko // Mark that this node came from the AST and is backed by the source code.
652cdce2fe5SMarcel Hlopko Node->Original = true;
6534c14ee61SEduardo Caldas Node->CanModify =
654263dcf45SHaojian Wu TB.spelledForExpanded(Tokens).has_value();
6559b3f38f9SIlya Biryukov
656cdce2fe5SMarcel Hlopko Trees.erase(BeginChildren, EndChildren);
657cdce2fe5SMarcel Hlopko Trees.insert({FirstToken, Node});
6589b3f38f9SIlya Biryukov }
6599b3f38f9SIlya Biryukov
6609b3f38f9SIlya Biryukov // EXPECTS: all tokens were consumed and are owned by a single root node.
finalizesyntax::TreeBuilder::Forest6619b3f38f9SIlya Biryukov syntax::Node *finalize() && {
6629b3f38f9SIlya Biryukov assert(Trees.size() == 1);
663a711a3a4SMarcel Hlopko auto *Root = Trees.begin()->second;
6649b3f38f9SIlya Biryukov Trees = {};
6659b3f38f9SIlya Biryukov return Root;
6669b3f38f9SIlya Biryukov }
6679b3f38f9SIlya Biryukov
strsyntax::TreeBuilder::Forest668263dcf45SHaojian Wu std::string str(const syntax::TokenBufferTokenManager &STM) const {
6699b3f38f9SIlya Biryukov std::string R;
6709b3f38f9SIlya Biryukov for (auto It = Trees.begin(); It != Trees.end(); ++It) {
6719b3f38f9SIlya Biryukov unsigned CoveredTokens =
6729b3f38f9SIlya Biryukov It != Trees.end()
6739b3f38f9SIlya Biryukov ? (std::next(It)->first - It->first)
674263dcf45SHaojian Wu : STM.tokenBuffer().expandedTokens().end() - It->first;
6759b3f38f9SIlya Biryukov
676ba41a0f7SEduardo Caldas R += std::string(
6774c14ee61SEduardo Caldas formatv("- '{0}' covers '{1}'+{2} tokens\n", It->second->getKind(),
678263dcf45SHaojian Wu It->first->text(STM.sourceManager()), CoveredTokens));
679263dcf45SHaojian Wu R += It->second->dump(STM);
6809b3f38f9SIlya Biryukov }
6819b3f38f9SIlya Biryukov return R;
6829b3f38f9SIlya Biryukov }
6839b3f38f9SIlya Biryukov
6849b3f38f9SIlya Biryukov private:
6859b3f38f9SIlya Biryukov /// Maps from the start token to a subtree starting at that token.
686302cb3bcSIlya Biryukov /// Keys in the map are pointers into the array of expanded tokens, so
687302cb3bcSIlya Biryukov /// pointer order corresponds to the order of preprocessor tokens.
688a711a3a4SMarcel Hlopko std::map<const syntax::Token *, syntax::Node *> Trees;
6899b3f38f9SIlya Biryukov };
6909b3f38f9SIlya Biryukov
6919b3f38f9SIlya Biryukov /// For debugging purposes.
str()692263dcf45SHaojian Wu std::string str() { return Pending.str(TBTM); }
6939b3f38f9SIlya Biryukov
6949b3f38f9SIlya Biryukov syntax::Arena &Arena;
695263dcf45SHaojian Wu TokenBufferTokenManager& TBTM;
696c1bbefefSIlya Biryukov /// To quickly find tokens by their start location.
69778194118SMikhail Maltsev llvm::DenseMap<SourceLocation, const syntax::Token *> LocationToToken;
6989b3f38f9SIlya Biryukov Forest Pending;
699e702bdb8SIlya Biryukov llvm::DenseSet<Decl *> DeclsWithoutSemicolons;
700a711a3a4SMarcel Hlopko ASTToSyntaxMapping Mapping;
7019b3f38f9SIlya Biryukov };
7029b3f38f9SIlya Biryukov
7039b3f38f9SIlya Biryukov namespace {
7049b3f38f9SIlya Biryukov class BuildTreeVisitor : public RecursiveASTVisitor<BuildTreeVisitor> {
7059b3f38f9SIlya Biryukov public:
BuildTreeVisitor(ASTContext & Context,syntax::TreeBuilder & Builder)7061db5b348SEduardo Caldas explicit BuildTreeVisitor(ASTContext &Context, syntax::TreeBuilder &Builder)
7071db5b348SEduardo Caldas : Builder(Builder), Context(Context) {}
7089b3f38f9SIlya Biryukov
shouldTraversePostOrder() const7099b3f38f9SIlya Biryukov bool shouldTraversePostOrder() const { return true; }
7109b3f38f9SIlya Biryukov
WalkUpFromDeclaratorDecl(DeclaratorDecl * DD)7117d382dcdSMarcel Hlopko bool WalkUpFromDeclaratorDecl(DeclaratorDecl *DD) {
712cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(DD);
7137d382dcdSMarcel Hlopko }
7147d382dcdSMarcel Hlopko
WalkUpFromTypedefNameDecl(TypedefNameDecl * TD)715cdce2fe5SMarcel Hlopko bool WalkUpFromTypedefNameDecl(TypedefNameDecl *TD) {
716cdce2fe5SMarcel Hlopko return processDeclaratorAndDeclaration(TD);
7179b3f38f9SIlya Biryukov }
7189b3f38f9SIlya Biryukov
VisitDecl(Decl * D)7199b3f38f9SIlya Biryukov bool VisitDecl(Decl *D) {
7209b3f38f9SIlya Biryukov assert(!D->isImplicit());
721cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(D),
722a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownDeclaration(), D);
723e702bdb8SIlya Biryukov return true;
724e702bdb8SIlya Biryukov }
725e702bdb8SIlya Biryukov
72688bf9b3dSMarcel Hlopko // RAV does not call WalkUpFrom* on explicit instantiations, so we have to
72788bf9b3dSMarcel Hlopko // override Traverse.
72888bf9b3dSMarcel Hlopko // FIXME: make RAV call WalkUpFrom* instead.
72988bf9b3dSMarcel Hlopko bool
TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * C)73088bf9b3dSMarcel Hlopko TraverseClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *C) {
73188bf9b3dSMarcel Hlopko if (!RecursiveASTVisitor::TraverseClassTemplateSpecializationDecl(C))
73288bf9b3dSMarcel Hlopko return false;
73388bf9b3dSMarcel Hlopko if (C->isExplicitSpecialization())
73488bf9b3dSMarcel Hlopko return true; // we are only interested in explicit instantiations.
735a711a3a4SMarcel Hlopko auto *Declaration =
736a711a3a4SMarcel Hlopko cast<syntax::SimpleDeclaration>(handleFreeStandingTagDecl(C));
73788bf9b3dSMarcel Hlopko foldExplicitTemplateInstantiation(
738*12028373SKrystian Stasiowski Builder.getTemplateRange(C),
739*12028373SKrystian Stasiowski Builder.findToken(C->getExternKeywordLoc()),
740a711a3a4SMarcel Hlopko Builder.findToken(C->getTemplateKeywordLoc()), Declaration, C);
74188bf9b3dSMarcel Hlopko return true;
74288bf9b3dSMarcel Hlopko }
74388bf9b3dSMarcel Hlopko
WalkUpFromTemplateDecl(TemplateDecl * S)74488bf9b3dSMarcel Hlopko bool WalkUpFromTemplateDecl(TemplateDecl *S) {
74588bf9b3dSMarcel Hlopko foldTemplateDeclaration(
746cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S),
74788bf9b3dSMarcel Hlopko Builder.findToken(S->getTemplateParameters()->getTemplateLoc()),
748cdce2fe5SMarcel Hlopko Builder.getDeclarationRange(S->getTemplatedDecl()), S);
74988bf9b3dSMarcel Hlopko return true;
75088bf9b3dSMarcel Hlopko }
75188bf9b3dSMarcel Hlopko
WalkUpFromTagDecl(TagDecl * C)752e702bdb8SIlya Biryukov bool WalkUpFromTagDecl(TagDecl *C) {
75304f627f6SIlya Biryukov // FIXME: build the ClassSpecifier node.
75488bf9b3dSMarcel Hlopko if (!C->isFreeStanding()) {
75588bf9b3dSMarcel Hlopko assert(C->getNumTemplateParameterLists() == 0);
75604f627f6SIlya Biryukov return true;
75704f627f6SIlya Biryukov }
758a711a3a4SMarcel Hlopko handleFreeStandingTagDecl(C);
759a711a3a4SMarcel Hlopko return true;
760a711a3a4SMarcel Hlopko }
761a711a3a4SMarcel Hlopko
handleFreeStandingTagDecl(TagDecl * C)762a711a3a4SMarcel Hlopko syntax::Declaration *handleFreeStandingTagDecl(TagDecl *C) {
763a711a3a4SMarcel Hlopko assert(C->isFreeStanding());
76488bf9b3dSMarcel Hlopko // Class is a declaration specifier and needs a spanning declaration node.
765cdce2fe5SMarcel Hlopko auto DeclarationRange = Builder.getDeclarationRange(C);
766a711a3a4SMarcel Hlopko syntax::Declaration *Result = new (allocator()) syntax::SimpleDeclaration;
767a711a3a4SMarcel Hlopko Builder.foldNode(DeclarationRange, Result, nullptr);
76888bf9b3dSMarcel Hlopko
76988bf9b3dSMarcel Hlopko // Build TemplateDeclaration nodes if we had template parameters.
77088bf9b3dSMarcel Hlopko auto ConsumeTemplateParameters = [&](const TemplateParameterList &L) {
77188bf9b3dSMarcel Hlopko const auto *TemplateKW = Builder.findToken(L.getTemplateLoc());
772a3c248dbSserge-sans-paille auto R = llvm::ArrayRef(TemplateKW, DeclarationRange.end());
773a711a3a4SMarcel Hlopko Result =
774a711a3a4SMarcel Hlopko foldTemplateDeclaration(R, TemplateKW, DeclarationRange, nullptr);
77588bf9b3dSMarcel Hlopko DeclarationRange = R;
77688bf9b3dSMarcel Hlopko };
777ba41a0f7SEduardo Caldas if (auto *S = dyn_cast<ClassTemplatePartialSpecializationDecl>(C))
77888bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*S->getTemplateParameters());
77988bf9b3dSMarcel Hlopko for (unsigned I = C->getNumTemplateParameterLists(); 0 < I; --I)
78088bf9b3dSMarcel Hlopko ConsumeTemplateParameters(*C->getTemplateParameterList(I - 1));
781a711a3a4SMarcel Hlopko return Result;
7829b3f38f9SIlya Biryukov }
7839b3f38f9SIlya Biryukov
WalkUpFromTranslationUnitDecl(TranslationUnitDecl * TU)7849b3f38f9SIlya Biryukov bool WalkUpFromTranslationUnitDecl(TranslationUnitDecl *TU) {
7857d382dcdSMarcel Hlopko // We do not want to call VisitDecl(), the declaration for translation
7869b3f38f9SIlya Biryukov // unit is built by finalize().
7879b3f38f9SIlya Biryukov return true;
7889b3f38f9SIlya Biryukov }
7899b3f38f9SIlya Biryukov
WalkUpFromCompoundStmt(CompoundStmt * S)7909b3f38f9SIlya Biryukov bool WalkUpFromCompoundStmt(CompoundStmt *S) {
79151dad419SIlya Biryukov using NodeRole = syntax::NodeRole;
7929b3f38f9SIlya Biryukov
793def65bb4SIlya Biryukov Builder.markChildToken(S->getLBracLoc(), NodeRole::OpenParen);
79458fa50f4SIlya Biryukov for (auto *Child : S->body())
795718e550cSEduardo Caldas Builder.markStmtChild(Child, NodeRole::Statement);
796def65bb4SIlya Biryukov Builder.markChildToken(S->getRBracLoc(), NodeRole::CloseParen);
7979b3f38f9SIlya Biryukov
79858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
799a711a3a4SMarcel Hlopko new (allocator()) syntax::CompoundStatement, S);
8009b3f38f9SIlya Biryukov return true;
8019b3f38f9SIlya Biryukov }
8029b3f38f9SIlya Biryukov
80358fa50f4SIlya Biryukov // Some statements are not yet handled by syntax trees.
WalkUpFromStmt(Stmt * S)80458fa50f4SIlya Biryukov bool WalkUpFromStmt(Stmt *S) {
80558fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
806a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownStatement, S);
80758fa50f4SIlya Biryukov return true;
80858fa50f4SIlya Biryukov }
80958fa50f4SIlya Biryukov
TraverseIfStmt(IfStmt * S)8106c1a2330SHaojian Wu bool TraverseIfStmt(IfStmt *S) {
8116c1a2330SHaojian Wu bool Result = [&, this]() {
8126c1a2330SHaojian Wu if (S->getInit() && !TraverseStmt(S->getInit())) {
8136c1a2330SHaojian Wu return false;
8146c1a2330SHaojian Wu }
8156c1a2330SHaojian Wu // In cases where the condition is an initialized declaration in a
8166c1a2330SHaojian Wu // statement, we want to preserve the declaration and ignore the
8176c1a2330SHaojian Wu // implicit condition expression in the syntax tree.
8186c1a2330SHaojian Wu if (S->hasVarStorage()) {
8196c1a2330SHaojian Wu if (!TraverseStmt(S->getConditionVariableDeclStmt()))
8206c1a2330SHaojian Wu return false;
8216c1a2330SHaojian Wu } else if (S->getCond() && !TraverseStmt(S->getCond()))
8226c1a2330SHaojian Wu return false;
8236c1a2330SHaojian Wu
8246c1a2330SHaojian Wu if (S->getThen() && !TraverseStmt(S->getThen()))
8256c1a2330SHaojian Wu return false;
8266c1a2330SHaojian Wu if (S->getElse() && !TraverseStmt(S->getElse()))
8276c1a2330SHaojian Wu return false;
8286c1a2330SHaojian Wu return true;
8296c1a2330SHaojian Wu }();
8306c1a2330SHaojian Wu WalkUpFromIfStmt(S);
8316c1a2330SHaojian Wu return Result;
8326c1a2330SHaojian Wu }
8336c1a2330SHaojian Wu
TraverseCXXForRangeStmt(CXXForRangeStmt * S)83458fa50f4SIlya Biryukov bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
83558fa50f4SIlya Biryukov // We override to traverse range initializer as VarDecl.
83658fa50f4SIlya Biryukov // RAV traverses it as a statement, we produce invalid node kinds in that
83758fa50f4SIlya Biryukov // case.
83858fa50f4SIlya Biryukov // FIXME: should do this in RAV instead?
8397349479fSDmitri Gribenko bool Result = [&, this]() {
84058fa50f4SIlya Biryukov if (S->getInit() && !TraverseStmt(S->getInit()))
84158fa50f4SIlya Biryukov return false;
84258fa50f4SIlya Biryukov if (S->getLoopVariable() && !TraverseDecl(S->getLoopVariable()))
84358fa50f4SIlya Biryukov return false;
84458fa50f4SIlya Biryukov if (S->getRangeInit() && !TraverseStmt(S->getRangeInit()))
84558fa50f4SIlya Biryukov return false;
84658fa50f4SIlya Biryukov if (S->getBody() && !TraverseStmt(S->getBody()))
84758fa50f4SIlya Biryukov return false;
84858fa50f4SIlya Biryukov return true;
8497349479fSDmitri Gribenko }();
8507349479fSDmitri Gribenko WalkUpFromCXXForRangeStmt(S);
8517349479fSDmitri Gribenko return Result;
85258fa50f4SIlya Biryukov }
85358fa50f4SIlya Biryukov
TraverseStmt(Stmt * S)85458fa50f4SIlya Biryukov bool TraverseStmt(Stmt *S) {
855ba41a0f7SEduardo Caldas if (auto *DS = dyn_cast_or_null<DeclStmt>(S)) {
856e702bdb8SIlya Biryukov // We want to consume the semicolon, make sure SimpleDeclaration does not.
857e702bdb8SIlya Biryukov for (auto *D : DS->decls())
8587d382dcdSMarcel Hlopko Builder.noticeDeclWithoutSemicolon(D);
859ba41a0f7SEduardo Caldas } else if (auto *E = dyn_cast_or_null<Expr>(S)) {
8602325d6b4SEduardo Caldas return RecursiveASTVisitor::TraverseStmt(IgnoreImplicit(E));
86158fa50f4SIlya Biryukov }
86258fa50f4SIlya Biryukov return RecursiveASTVisitor::TraverseStmt(S);
86358fa50f4SIlya Biryukov }
86458fa50f4SIlya Biryukov
TraverseOpaqueValueExpr(OpaqueValueExpr * VE)865780ead41SHaojian Wu bool TraverseOpaqueValueExpr(OpaqueValueExpr *VE) {
866780ead41SHaojian Wu // OpaqueValue doesn't correspond to concrete syntax, ignore it.
867780ead41SHaojian Wu return true;
868780ead41SHaojian Wu }
869780ead41SHaojian Wu
87058fa50f4SIlya Biryukov // Some expressions are not yet handled by syntax trees.
WalkUpFromExpr(Expr * E)87158fa50f4SIlya Biryukov bool WalkUpFromExpr(Expr *E) {
87258fa50f4SIlya Biryukov assert(!isImplicitExpr(E) && "should be handled by TraverseStmt");
87358fa50f4SIlya Biryukov Builder.foldNode(Builder.getExprRange(E),
874a711a3a4SMarcel Hlopko new (allocator()) syntax::UnknownExpression, E);
87558fa50f4SIlya Biryukov return true;
87658fa50f4SIlya Biryukov }
87758fa50f4SIlya Biryukov
TraverseUserDefinedLiteral(UserDefinedLiteral * S)878f33c2c27SEduardo Caldas bool TraverseUserDefinedLiteral(UserDefinedLiteral *S) {
879f33c2c27SEduardo Caldas // The semantic AST node `UserDefinedLiteral` (UDL) may have one child node
880f33c2c27SEduardo Caldas // referencing the location of the UDL suffix (`_w` in `1.2_w`). The
881f33c2c27SEduardo Caldas // UDL suffix location does not point to the beginning of a token, so we
882f33c2c27SEduardo Caldas // can't represent the UDL suffix as a separate syntax tree node.
883f33c2c27SEduardo Caldas
884f33c2c27SEduardo Caldas return WalkUpFromUserDefinedLiteral(S);
885f33c2c27SEduardo Caldas }
886f33c2c27SEduardo Caldas
8871db5b348SEduardo Caldas syntax::UserDefinedLiteralExpression *
buildUserDefinedLiteral(UserDefinedLiteral * S)8881db5b348SEduardo Caldas buildUserDefinedLiteral(UserDefinedLiteral *S) {
889f33c2c27SEduardo Caldas switch (S->getLiteralOperatorKind()) {
890ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Integer:
8911db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
892ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Floating:
8931db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
894ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Character:
8951db5b348SEduardo Caldas return new (allocator()) syntax::CharUserDefinedLiteralExpression;
896ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_String:
8971db5b348SEduardo Caldas return new (allocator()) syntax::StringUserDefinedLiteralExpression;
898ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Raw:
899ba41a0f7SEduardo Caldas case UserDefinedLiteral::LOK_Template:
9001db5b348SEduardo Caldas // For raw literal operator and numeric literal operator template we
9011db5b348SEduardo Caldas // cannot get the type of the operand in the semantic AST. We get this
9021db5b348SEduardo Caldas // information from the token. As integer and floating point have the same
9031db5b348SEduardo Caldas // token kind, we run `NumericLiteralParser` again to distinguish them.
9041db5b348SEduardo Caldas auto TokLoc = S->getBeginLoc();
9051db5b348SEduardo Caldas auto TokSpelling =
906a474d5baSEduardo Caldas Builder.findToken(TokLoc)->text(Context.getSourceManager());
9071db5b348SEduardo Caldas auto Literal =
9081db5b348SEduardo Caldas NumericLiteralParser(TokSpelling, TokLoc, Context.getSourceManager(),
9091db5b348SEduardo Caldas Context.getLangOpts(), Context.getTargetInfo(),
9101db5b348SEduardo Caldas Context.getDiagnostics());
9111db5b348SEduardo Caldas if (Literal.isIntegerLiteral())
9121db5b348SEduardo Caldas return new (allocator()) syntax::IntegerUserDefinedLiteralExpression;
913a474d5baSEduardo Caldas else {
914a474d5baSEduardo Caldas assert(Literal.isFloatingLiteral());
9151db5b348SEduardo Caldas return new (allocator()) syntax::FloatUserDefinedLiteralExpression;
916f33c2c27SEduardo Caldas }
917f33c2c27SEduardo Caldas }
918b8409c03SMichael Liao llvm_unreachable("Unknown literal operator kind.");
919a474d5baSEduardo Caldas }
920f33c2c27SEduardo Caldas
WalkUpFromUserDefinedLiteral(UserDefinedLiteral * S)921f33c2c27SEduardo Caldas bool WalkUpFromUserDefinedLiteral(UserDefinedLiteral *S) {
922f33c2c27SEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
9231db5b348SEduardo Caldas Builder.foldNode(Builder.getExprRange(S), buildUserDefinedLiteral(S), S);
924f33c2c27SEduardo Caldas return true;
925f33c2c27SEduardo Caldas }
926f33c2c27SEduardo Caldas
9278abb5fb6SEduardo Caldas // FIXME: Fix `NestedNameSpecifierLoc::getLocalSourceRange` for the
9288abb5fb6SEduardo Caldas // `DependentTemplateSpecializationType` case.
929f9500cc4SEduardo Caldas /// Given a nested-name-specifier return the range for the last name
930f9500cc4SEduardo Caldas /// specifier.
9318abb5fb6SEduardo Caldas ///
9328abb5fb6SEduardo Caldas /// e.g. `std::T::template X<U>::` => `template X<U>::`
getLocalSourceRange(const NestedNameSpecifierLoc & NNSLoc)9338abb5fb6SEduardo Caldas SourceRange getLocalSourceRange(const NestedNameSpecifierLoc &NNSLoc) {
9348abb5fb6SEduardo Caldas auto SR = NNSLoc.getLocalSourceRange();
9358abb5fb6SEduardo Caldas
936f9500cc4SEduardo Caldas // The method `NestedNameSpecifierLoc::getLocalSourceRange` *should*
937f9500cc4SEduardo Caldas // return the desired `SourceRange`, but there is a corner case. For a
938f9500cc4SEduardo Caldas // `DependentTemplateSpecializationType` this method returns its
9398abb5fb6SEduardo Caldas // qualifiers as well, in other words in the example above this method
9408abb5fb6SEduardo Caldas // returns `T::template X<U>::` instead of only `template X<U>::`
9418abb5fb6SEduardo Caldas if (auto TL = NNSLoc.getTypeLoc()) {
9428abb5fb6SEduardo Caldas if (auto DependentTL =
9438abb5fb6SEduardo Caldas TL.getAs<DependentTemplateSpecializationTypeLoc>()) {
9448abb5fb6SEduardo Caldas // The 'template' keyword is always present in dependent template
9458abb5fb6SEduardo Caldas // specializations. Except in the case of incorrect code
9468abb5fb6SEduardo Caldas // TODO: Treat the case of incorrect code.
9478abb5fb6SEduardo Caldas SR.setBegin(DependentTL.getTemplateKeywordLoc());
9488abb5fb6SEduardo Caldas }
9498abb5fb6SEduardo Caldas }
9508abb5fb6SEduardo Caldas
9518abb5fb6SEduardo Caldas return SR;
9528abb5fb6SEduardo Caldas }
9538abb5fb6SEduardo Caldas
getNameSpecifierKind(const NestedNameSpecifier & NNS)954f9500cc4SEduardo Caldas syntax::NodeKind getNameSpecifierKind(const NestedNameSpecifier &NNS) {
955f9500cc4SEduardo Caldas switch (NNS.getKind()) {
956f9500cc4SEduardo Caldas case NestedNameSpecifier::Global:
957f9500cc4SEduardo Caldas return syntax::NodeKind::GlobalNameSpecifier;
958f9500cc4SEduardo Caldas case NestedNameSpecifier::Namespace:
959f9500cc4SEduardo Caldas case NestedNameSpecifier::NamespaceAlias:
960f9500cc4SEduardo Caldas case NestedNameSpecifier::Identifier:
961f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier;
962f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpecWithTemplate:
963f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier;
964f9500cc4SEduardo Caldas case NestedNameSpecifier::TypeSpec: {
965f9500cc4SEduardo Caldas const auto *NNSType = NNS.getAsType();
966f9500cc4SEduardo Caldas assert(NNSType);
967f9500cc4SEduardo Caldas if (isa<DecltypeType>(NNSType))
968f9500cc4SEduardo Caldas return syntax::NodeKind::DecltypeNameSpecifier;
969f9500cc4SEduardo Caldas if (isa<TemplateSpecializationType, DependentTemplateSpecializationType>(
970f9500cc4SEduardo Caldas NNSType))
971f9500cc4SEduardo Caldas return syntax::NodeKind::SimpleTemplateNameSpecifier;
972f9500cc4SEduardo Caldas return syntax::NodeKind::IdentifierNameSpecifier;
973f9500cc4SEduardo Caldas }
974f9500cc4SEduardo Caldas default:
975f9500cc4SEduardo Caldas // FIXME: Support Microsoft's __super
976f9500cc4SEduardo Caldas llvm::report_fatal_error("We don't yet support the __super specifier",
977f9500cc4SEduardo Caldas true);
978f9500cc4SEduardo Caldas }
979f9500cc4SEduardo Caldas }
980f9500cc4SEduardo Caldas
981f9500cc4SEduardo Caldas syntax::NameSpecifier *
buildNameSpecifier(const NestedNameSpecifierLoc & NNSLoc)982ac87a0b5SEduardo Caldas buildNameSpecifier(const NestedNameSpecifierLoc &NNSLoc) {
983f9500cc4SEduardo Caldas assert(NNSLoc.hasQualifier());
984f9500cc4SEduardo Caldas auto NameSpecifierTokens =
985f9500cc4SEduardo Caldas Builder.getRange(getLocalSourceRange(NNSLoc)).drop_back();
986f9500cc4SEduardo Caldas switch (getNameSpecifierKind(*NNSLoc.getNestedNameSpecifier())) {
987f9500cc4SEduardo Caldas case syntax::NodeKind::GlobalNameSpecifier:
988f9500cc4SEduardo Caldas return new (allocator()) syntax::GlobalNameSpecifier;
989f9500cc4SEduardo Caldas case syntax::NodeKind::IdentifierNameSpecifier: {
990f9500cc4SEduardo Caldas assert(NameSpecifierTokens.size() == 1);
991f9500cc4SEduardo Caldas Builder.markChildToken(NameSpecifierTokens.begin(),
992f9500cc4SEduardo Caldas syntax::NodeRole::Unknown);
993f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::IdentifierNameSpecifier;
994f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr);
995f9500cc4SEduardo Caldas return NS;
996f9500cc4SEduardo Caldas }
997f9500cc4SEduardo Caldas case syntax::NodeKind::SimpleTemplateNameSpecifier: {
998f9500cc4SEduardo Caldas // TODO: Build `SimpleTemplateNameSpecifier` children and implement
999f9500cc4SEduardo Caldas // accessors to them.
1000f9500cc4SEduardo Caldas // Be aware, we cannot do that simply by calling `TraverseTypeLoc`,
1001f9500cc4SEduardo Caldas // some `TypeLoc`s have inside them the previous name specifier and
1002f9500cc4SEduardo Caldas // we want to treat them independently.
1003f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::SimpleTemplateNameSpecifier;
1004f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1005f9500cc4SEduardo Caldas return NS;
1006f9500cc4SEduardo Caldas }
1007f9500cc4SEduardo Caldas case syntax::NodeKind::DecltypeNameSpecifier: {
1008f9500cc4SEduardo Caldas const auto TL = NNSLoc.getTypeLoc().castAs<DecltypeTypeLoc>();
1009f9500cc4SEduardo Caldas if (!RecursiveASTVisitor::TraverseDecltypeTypeLoc(TL))
10108abb5fb6SEduardo Caldas return nullptr;
1011f9500cc4SEduardo Caldas auto *NS = new (allocator()) syntax::DecltypeNameSpecifier;
1012f9500cc4SEduardo Caldas // TODO: Implement accessor to `DecltypeNameSpecifier` inner
1013f9500cc4SEduardo Caldas // `DecltypeTypeLoc`.
1014f9500cc4SEduardo Caldas // For that add mapping from `TypeLoc` to `syntax::Node*` then:
1015f9500cc4SEduardo Caldas // Builder.markChild(TypeLoc, syntax::NodeRole);
1016f9500cc4SEduardo Caldas Builder.foldNode(NameSpecifierTokens, NS, nullptr);
1017f9500cc4SEduardo Caldas return NS;
1018f9500cc4SEduardo Caldas }
1019f9500cc4SEduardo Caldas default:
1020f9500cc4SEduardo Caldas llvm_unreachable("getChildKind() does not return this value");
1021f9500cc4SEduardo Caldas }
1022f9500cc4SEduardo Caldas }
1023f9500cc4SEduardo Caldas
1024f9500cc4SEduardo Caldas // To build syntax tree nodes for NestedNameSpecifierLoc we override
1025f9500cc4SEduardo Caldas // Traverse instead of WalkUpFrom because we want to traverse the children
1026f9500cc4SEduardo Caldas // ourselves and build a list instead of a nested tree of name specifier
1027f9500cc4SEduardo Caldas // prefixes.
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc)1028f9500cc4SEduardo Caldas bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc QualifierLoc) {
1029f9500cc4SEduardo Caldas if (!QualifierLoc)
1030f9500cc4SEduardo Caldas return true;
103187f0b51dSEduardo Caldas for (auto It = QualifierLoc; It; It = It.getPrefix()) {
103287f0b51dSEduardo Caldas auto *NS = buildNameSpecifier(It);
1033f9500cc4SEduardo Caldas if (!NS)
1034f9500cc4SEduardo Caldas return false;
1035718e550cSEduardo Caldas Builder.markChild(NS, syntax::NodeRole::ListElement);
103687f0b51dSEduardo Caldas Builder.markChildToken(It.getEndLoc(), syntax::NodeRole::ListDelimiter);
10378abb5fb6SEduardo Caldas }
1038f9500cc4SEduardo Caldas Builder.foldNode(Builder.getRange(QualifierLoc.getSourceRange()),
1039f9500cc4SEduardo Caldas new (allocator()) syntax::NestedNameSpecifier,
10408abb5fb6SEduardo Caldas QualifierLoc);
1041f9500cc4SEduardo Caldas return true;
10428abb5fb6SEduardo Caldas }
10438abb5fb6SEduardo Caldas
buildIdExpression(NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKeywordLoc,SourceRange UnqualifiedIdLoc,ASTPtr From)1044a4ef9e86SEduardo Caldas syntax::IdExpression *buildIdExpression(NestedNameSpecifierLoc QualifierLoc,
1045a4ef9e86SEduardo Caldas SourceLocation TemplateKeywordLoc,
1046a4ef9e86SEduardo Caldas SourceRange UnqualifiedIdLoc,
1047a4ef9e86SEduardo Caldas ASTPtr From) {
1048a4ef9e86SEduardo Caldas if (QualifierLoc) {
1049718e550cSEduardo Caldas Builder.markChild(QualifierLoc, syntax::NodeRole::Qualifier);
1050ba32915dSEduardo Caldas if (TemplateKeywordLoc.isValid())
1051ba32915dSEduardo Caldas Builder.markChildToken(TemplateKeywordLoc,
1052ba32915dSEduardo Caldas syntax::NodeRole::TemplateKeyword);
1053a4ef9e86SEduardo Caldas }
1054ba32915dSEduardo Caldas
1055ba32915dSEduardo Caldas auto *TheUnqualifiedId = new (allocator()) syntax::UnqualifiedId;
1056a4ef9e86SEduardo Caldas Builder.foldNode(Builder.getRange(UnqualifiedIdLoc), TheUnqualifiedId,
1057a4ef9e86SEduardo Caldas nullptr);
1058718e550cSEduardo Caldas Builder.markChild(TheUnqualifiedId, syntax::NodeRole::UnqualifiedId);
1059ba32915dSEduardo Caldas
1060a4ef9e86SEduardo Caldas auto IdExpressionBeginLoc =
1061a4ef9e86SEduardo Caldas QualifierLoc ? QualifierLoc.getBeginLoc() : UnqualifiedIdLoc.getBegin();
1062ba32915dSEduardo Caldas
1063a4ef9e86SEduardo Caldas auto *TheIdExpression = new (allocator()) syntax::IdExpression;
1064a4ef9e86SEduardo Caldas Builder.foldNode(
1065a4ef9e86SEduardo Caldas Builder.getRange(IdExpressionBeginLoc, UnqualifiedIdLoc.getEnd()),
1066a4ef9e86SEduardo Caldas TheIdExpression, From);
1067a4ef9e86SEduardo Caldas
1068a4ef9e86SEduardo Caldas return TheIdExpression;
1069a4ef9e86SEduardo Caldas }
1070a4ef9e86SEduardo Caldas
WalkUpFromMemberExpr(MemberExpr * S)1071a4ef9e86SEduardo Caldas bool WalkUpFromMemberExpr(MemberExpr *S) {
1072ba32915dSEduardo Caldas // For `MemberExpr` with implicit `this->` we generate a simple
1073ba32915dSEduardo Caldas // `id-expression` syntax node, beacuse an implicit `member-expression` is
1074ba32915dSEduardo Caldas // syntactically undistinguishable from an `id-expression`
1075ba32915dSEduardo Caldas if (S->isImplicitAccess()) {
1076a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1077a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), S);
1078ba32915dSEduardo Caldas return true;
1079ba32915dSEduardo Caldas }
1080a4ef9e86SEduardo Caldas
1081a4ef9e86SEduardo Caldas auto *TheIdExpression = buildIdExpression(
1082a4ef9e86SEduardo Caldas S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1083a4ef9e86SEduardo Caldas SourceRange(S->getMemberLoc(), S->getEndLoc()), nullptr);
1084ba32915dSEduardo Caldas
1085718e550cSEduardo Caldas Builder.markChild(TheIdExpression, syntax::NodeRole::Member);
1086ba32915dSEduardo Caldas
1087718e550cSEduardo Caldas Builder.markExprChild(S->getBase(), syntax::NodeRole::Object);
1088718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(), syntax::NodeRole::AccessToken);
1089ba32915dSEduardo Caldas
1090ba32915dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1091ba32915dSEduardo Caldas new (allocator()) syntax::MemberExpression, S);
1092ba32915dSEduardo Caldas return true;
1093ba32915dSEduardo Caldas }
1094ba32915dSEduardo Caldas
WalkUpFromDeclRefExpr(DeclRefExpr * S)10951b2f6b4aSEduardo Caldas bool WalkUpFromDeclRefExpr(DeclRefExpr *S) {
1096a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1097a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S);
10988abb5fb6SEduardo Caldas
10998abb5fb6SEduardo Caldas return true;
11001b2f6b4aSEduardo Caldas }
11018abb5fb6SEduardo Caldas
11028abb5fb6SEduardo Caldas // Same logic as DeclRefExpr.
WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr * S)11038abb5fb6SEduardo Caldas bool WalkUpFromDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *S) {
1104a4ef9e86SEduardo Caldas buildIdExpression(S->getQualifierLoc(), S->getTemplateKeywordLoc(),
1105a4ef9e86SEduardo Caldas SourceRange(S->getLocation(), S->getEndLoc()), S);
11068abb5fb6SEduardo Caldas
11071b2f6b4aSEduardo Caldas return true;
11081b2f6b4aSEduardo Caldas }
11091b2f6b4aSEduardo Caldas
WalkUpFromCXXThisExpr(CXXThisExpr * S)111085c15f17SEduardo Caldas bool WalkUpFromCXXThisExpr(CXXThisExpr *S) {
111185c15f17SEduardo Caldas if (!S->isImplicit()) {
111285c15f17SEduardo Caldas Builder.markChildToken(S->getLocation(),
111385c15f17SEduardo Caldas syntax::NodeRole::IntroducerKeyword);
111485c15f17SEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
111585c15f17SEduardo Caldas new (allocator()) syntax::ThisExpression, S);
111685c15f17SEduardo Caldas }
111785c15f17SEduardo Caldas return true;
111885c15f17SEduardo Caldas }
111985c15f17SEduardo Caldas
WalkUpFromParenExpr(ParenExpr * S)1120fdbd7833SEduardo Caldas bool WalkUpFromParenExpr(ParenExpr *S) {
1121fdbd7833SEduardo Caldas Builder.markChildToken(S->getLParen(), syntax::NodeRole::OpenParen);
1122718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::SubExpression);
1123fdbd7833SEduardo Caldas Builder.markChildToken(S->getRParen(), syntax::NodeRole::CloseParen);
1124fdbd7833SEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1125fdbd7833SEduardo Caldas new (allocator()) syntax::ParenExpression, S);
1126fdbd7833SEduardo Caldas return true;
1127fdbd7833SEduardo Caldas }
1128fdbd7833SEduardo Caldas
WalkUpFromIntegerLiteral(IntegerLiteral * S)11293b739690SEduardo Caldas bool WalkUpFromIntegerLiteral(IntegerLiteral *S) {
113042f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11313b739690SEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
11323b739690SEduardo Caldas new (allocator()) syntax::IntegerLiteralExpression, S);
11333b739690SEduardo Caldas return true;
11343b739690SEduardo Caldas }
11353b739690SEduardo Caldas
WalkUpFromCharacterLiteral(CharacterLiteral * S)1136221d7bbeSEduardo Caldas bool WalkUpFromCharacterLiteral(CharacterLiteral *S) {
1137221d7bbeSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1138221d7bbeSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1139221d7bbeSEduardo Caldas new (allocator()) syntax::CharacterLiteralExpression, S);
1140221d7bbeSEduardo Caldas return true;
1141221d7bbeSEduardo Caldas }
11427b404b6dSEduardo Caldas
WalkUpFromFloatingLiteral(FloatingLiteral * S)11437b404b6dSEduardo Caldas bool WalkUpFromFloatingLiteral(FloatingLiteral *S) {
11447b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11457b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
11467b404b6dSEduardo Caldas new (allocator()) syntax::FloatingLiteralExpression, S);
11477b404b6dSEduardo Caldas return true;
11487b404b6dSEduardo Caldas }
11497b404b6dSEduardo Caldas
WalkUpFromStringLiteral(StringLiteral * S)1150466e8b7eSEduardo Caldas bool WalkUpFromStringLiteral(StringLiteral *S) {
1151466e8b7eSEduardo Caldas Builder.markChildToken(S->getBeginLoc(), syntax::NodeRole::LiteralToken);
1152466e8b7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1153466e8b7eSEduardo Caldas new (allocator()) syntax::StringLiteralExpression, S);
1154466e8b7eSEduardo Caldas return true;
1155466e8b7eSEduardo Caldas }
1156221d7bbeSEduardo Caldas
WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr * S)11577b404b6dSEduardo Caldas bool WalkUpFromCXXBoolLiteralExpr(CXXBoolLiteralExpr *S) {
11587b404b6dSEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
11597b404b6dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
11607b404b6dSEduardo Caldas new (allocator()) syntax::BoolLiteralExpression, S);
11617b404b6dSEduardo Caldas return true;
11627b404b6dSEduardo Caldas }
11637b404b6dSEduardo Caldas
WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr * S)1164007098d7SEduardo Caldas bool WalkUpFromCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *S) {
116542f6fec3SEduardo Caldas Builder.markChildToken(S->getLocation(), syntax::NodeRole::LiteralToken);
1166007098d7SEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1167007098d7SEduardo Caldas new (allocator()) syntax::CxxNullPtrExpression, S);
1168007098d7SEduardo Caldas return true;
1169007098d7SEduardo Caldas }
1170007098d7SEduardo Caldas
WalkUpFromUnaryOperator(UnaryOperator * S)1171461af57dSEduardo Caldas bool WalkUpFromUnaryOperator(UnaryOperator *S) {
117242f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(),
1173718e550cSEduardo Caldas syntax::NodeRole::OperatorToken);
1174718e550cSEduardo Caldas Builder.markExprChild(S->getSubExpr(), syntax::NodeRole::Operand);
1175461af57dSEduardo Caldas
1176461af57dSEduardo Caldas if (S->isPostfix())
1177461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1178461af57dSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression,
1179461af57dSEduardo Caldas S);
1180461af57dSEduardo Caldas else
1181461af57dSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1182461af57dSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression,
1183461af57dSEduardo Caldas S);
1184461af57dSEduardo Caldas
1185461af57dSEduardo Caldas return true;
1186461af57dSEduardo Caldas }
1187461af57dSEduardo Caldas
WalkUpFromBinaryOperator(BinaryOperator * S)11883785eb83SEduardo Caldas bool WalkUpFromBinaryOperator(BinaryOperator *S) {
1189718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::LeftHandSide);
119042f6fec3SEduardo Caldas Builder.markChildToken(S->getOperatorLoc(),
1191718e550cSEduardo Caldas syntax::NodeRole::OperatorToken);
1192718e550cSEduardo Caldas Builder.markExprChild(S->getRHS(), syntax::NodeRole::RightHandSide);
11933785eb83SEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
11943785eb83SEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S);
11953785eb83SEduardo Caldas return true;
11963785eb83SEduardo Caldas }
11973785eb83SEduardo Caldas
1198f5087d5cSEduardo Caldas /// Builds `CallArguments` syntax node from arguments that appear in source
1199f5087d5cSEduardo Caldas /// code, i.e. not default arguments.
1200f5087d5cSEduardo Caldas syntax::CallArguments *
buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs)1201f5087d5cSEduardo Caldas buildCallArguments(CallExpr::arg_range ArgsAndDefaultArgs) {
1202f5087d5cSEduardo Caldas auto Args = dropDefaultArgs(ArgsAndDefaultArgs);
1203e10df779SDmitri Gribenko for (auto *Arg : Args) {
1204718e550cSEduardo Caldas Builder.markExprChild(Arg, syntax::NodeRole::ListElement);
12052de2ca34SEduardo Caldas const auto *DelimiterToken =
12062de2ca34SEduardo Caldas std::next(Builder.findToken(Arg->getEndLoc()));
12072de2ca34SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1208718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
12092de2ca34SEduardo Caldas }
12102de2ca34SEduardo Caldas
12112de2ca34SEduardo Caldas auto *Arguments = new (allocator()) syntax::CallArguments;
12122de2ca34SEduardo Caldas if (!Args.empty())
12132de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange((*Args.begin())->getBeginLoc(),
12142de2ca34SEduardo Caldas (*(Args.end() - 1))->getEndLoc()),
12152de2ca34SEduardo Caldas Arguments, nullptr);
12162de2ca34SEduardo Caldas
12172de2ca34SEduardo Caldas return Arguments;
12182de2ca34SEduardo Caldas }
12192de2ca34SEduardo Caldas
WalkUpFromCallExpr(CallExpr * S)12202de2ca34SEduardo Caldas bool WalkUpFromCallExpr(CallExpr *S) {
1221718e550cSEduardo Caldas Builder.markExprChild(S->getCallee(), syntax::NodeRole::Callee);
12222de2ca34SEduardo Caldas
12232de2ca34SEduardo Caldas const auto *LParenToken =
12242de2ca34SEduardo Caldas std::next(Builder.findToken(S->getCallee()->getEndLoc()));
12252de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have fixed
12262de2ca34SEduardo Caldas // the test on decltype desctructors.
12272de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren)
12282de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
12292de2ca34SEduardo Caldas
12302de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(S->arguments()),
1231718e550cSEduardo Caldas syntax::NodeRole::Arguments);
12322de2ca34SEduardo Caldas
12332de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
12342de2ca34SEduardo Caldas
12352de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()),
12362de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S);
12372de2ca34SEduardo Caldas return true;
12382de2ca34SEduardo Caldas }
12392de2ca34SEduardo Caldas
WalkUpFromCXXConstructExpr(CXXConstructExpr * S)124046f4439dSEduardo Caldas bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
124146f4439dSEduardo Caldas // Ignore the implicit calls to default constructors.
124246f4439dSEduardo Caldas if ((S->getNumArgs() == 0 || isa<CXXDefaultArgExpr>(S->getArg(0))) &&
124346f4439dSEduardo Caldas S->getParenOrBraceRange().isInvalid())
124446f4439dSEduardo Caldas return true;
124546f4439dSEduardo Caldas return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
124646f4439dSEduardo Caldas }
124746f4439dSEduardo Caldas
TraverseCXXOperatorCallExpr(CXXOperatorCallExpr * S)1248ea8bba7eSEduardo Caldas bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1249ac37afa6SEduardo Caldas // To construct a syntax tree of the same shape for calls to built-in and
1250ac37afa6SEduardo Caldas // user-defined operators, ignore the `DeclRefExpr` that refers to the
1251ac37afa6SEduardo Caldas // operator and treat it as a simple token. Do that by traversing
1252ac37afa6SEduardo Caldas // arguments instead of children.
1253ac37afa6SEduardo Caldas for (auto *child : S->arguments()) {
1254f33c2c27SEduardo Caldas // A postfix unary operator is declared as taking two operands. The
1255f33c2c27SEduardo Caldas // second operand is used to distinguish from its prefix counterpart. In
1256f33c2c27SEduardo Caldas // the semantic AST this "phantom" operand is represented as a
1257ea8bba7eSEduardo Caldas // `IntegerLiteral` with invalid `SourceLocation`. We skip visiting this
1258ea8bba7eSEduardo Caldas // operand because it does not correspond to anything written in source
1259ac37afa6SEduardo Caldas // code.
1260ac37afa6SEduardo Caldas if (child->getSourceRange().isInvalid()) {
1261ac37afa6SEduardo Caldas assert(getOperatorNodeKind(*S) ==
1262ac37afa6SEduardo Caldas syntax::NodeKind::PostfixUnaryOperatorExpression);
1263ea8bba7eSEduardo Caldas continue;
1264ac37afa6SEduardo Caldas }
1265ea8bba7eSEduardo Caldas if (!TraverseStmt(child))
1266ea8bba7eSEduardo Caldas return false;
1267ea8bba7eSEduardo Caldas }
1268ea8bba7eSEduardo Caldas return WalkUpFromCXXOperatorCallExpr(S);
1269ea8bba7eSEduardo Caldas }
1270ea8bba7eSEduardo Caldas
WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr * S)12713a574a6cSEduardo Caldas bool WalkUpFromCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
1272ea8bba7eSEduardo Caldas switch (getOperatorNodeKind(*S)) {
1273ea8bba7eSEduardo Caldas case syntax::NodeKind::BinaryOperatorExpression:
1274718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::LeftHandSide);
1275718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(),
1276718e550cSEduardo Caldas syntax::NodeRole::OperatorToken);
1277718e550cSEduardo Caldas Builder.markExprChild(S->getArg(1), syntax::NodeRole::RightHandSide);
12783a574a6cSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
12793a574a6cSEduardo Caldas new (allocator()) syntax::BinaryOperatorExpression, S);
12803a574a6cSEduardo Caldas return true;
1281ea8bba7eSEduardo Caldas case syntax::NodeKind::PrefixUnaryOperatorExpression:
1282718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(),
1283718e550cSEduardo Caldas syntax::NodeRole::OperatorToken);
1284718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1285ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1286ea8bba7eSEduardo Caldas new (allocator()) syntax::PrefixUnaryOperatorExpression,
1287ea8bba7eSEduardo Caldas S);
1288ea8bba7eSEduardo Caldas return true;
1289ea8bba7eSEduardo Caldas case syntax::NodeKind::PostfixUnaryOperatorExpression:
1290718e550cSEduardo Caldas Builder.markChildToken(S->getOperatorLoc(),
1291718e550cSEduardo Caldas syntax::NodeRole::OperatorToken);
1292718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Operand);
1293ea8bba7eSEduardo Caldas Builder.foldNode(Builder.getExprRange(S),
1294ea8bba7eSEduardo Caldas new (allocator()) syntax::PostfixUnaryOperatorExpression,
1295ea8bba7eSEduardo Caldas S);
1296ea8bba7eSEduardo Caldas return true;
12972de2ca34SEduardo Caldas case syntax::NodeKind::CallExpression: {
1298718e550cSEduardo Caldas Builder.markExprChild(S->getArg(0), syntax::NodeRole::Callee);
12992de2ca34SEduardo Caldas
13002de2ca34SEduardo Caldas const auto *LParenToken =
13012de2ca34SEduardo Caldas std::next(Builder.findToken(S->getArg(0)->getEndLoc()));
13022de2ca34SEduardo Caldas // FIXME: Assert that `LParenToken` is indeed a `l_paren` once we have
13032de2ca34SEduardo Caldas // fixed the test on decltype desctructors.
13042de2ca34SEduardo Caldas if (LParenToken->kind() == clang::tok::l_paren)
13052de2ca34SEduardo Caldas Builder.markChildToken(LParenToken, syntax::NodeRole::OpenParen);
13062de2ca34SEduardo Caldas
13072de2ca34SEduardo Caldas Builder.markChild(buildCallArguments(CallExpr::arg_range(
13082de2ca34SEduardo Caldas S->arg_begin() + 1, S->arg_end())),
1309718e550cSEduardo Caldas syntax::NodeRole::Arguments);
13102de2ca34SEduardo Caldas
13112de2ca34SEduardo Caldas Builder.markChildToken(S->getRParenLoc(), syntax::NodeRole::CloseParen);
13122de2ca34SEduardo Caldas
13132de2ca34SEduardo Caldas Builder.foldNode(Builder.getRange(S->getSourceRange()),
13142de2ca34SEduardo Caldas new (allocator()) syntax::CallExpression, S);
13152de2ca34SEduardo Caldas return true;
13162de2ca34SEduardo Caldas }
1317ea8bba7eSEduardo Caldas case syntax::NodeKind::UnknownExpression:
13182de2ca34SEduardo Caldas return WalkUpFromExpr(S);
1319ea8bba7eSEduardo Caldas default:
1320ea8bba7eSEduardo Caldas llvm_unreachable("getOperatorNodeKind() does not return this value");
1321ea8bba7eSEduardo Caldas }
13223a574a6cSEduardo Caldas }
13233a574a6cSEduardo Caldas
WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr * S)1324f5087d5cSEduardo Caldas bool WalkUpFromCXXDefaultArgExpr(CXXDefaultArgExpr *S) { return true; }
1325f5087d5cSEduardo Caldas
WalkUpFromNamespaceDecl(NamespaceDecl * S)1326be14a22bSIlya Biryukov bool WalkUpFromNamespaceDecl(NamespaceDecl *S) {
1327cdce2fe5SMarcel Hlopko auto Tokens = Builder.getDeclarationRange(S);
1328be14a22bSIlya Biryukov if (Tokens.front().kind() == tok::coloncolon) {
1329be14a22bSIlya Biryukov // Handle nested namespace definitions. Those start at '::' token, e.g.
1330be14a22bSIlya Biryukov // namespace a^::b {}
1331be14a22bSIlya Biryukov // FIXME: build corresponding nodes for the name of this namespace.
1332be14a22bSIlya Biryukov return true;
1333be14a22bSIlya Biryukov }
1334a711a3a4SMarcel Hlopko Builder.foldNode(Tokens, new (allocator()) syntax::NamespaceDefinition, S);
1335be14a22bSIlya Biryukov return true;
1336be14a22bSIlya Biryukov }
1337be14a22bSIlya Biryukov
13388ce15f7eSEduardo Caldas // FIXME: Deleting the `TraverseParenTypeLoc` override doesn't change test
13398ce15f7eSEduardo Caldas // results. Find test coverage or remove it.
TraverseParenTypeLoc(ParenTypeLoc L)13407d382dcdSMarcel Hlopko bool TraverseParenTypeLoc(ParenTypeLoc L) {
13417d382dcdSMarcel Hlopko // We reverse order of traversal to get the proper syntax structure.
13427d382dcdSMarcel Hlopko if (!WalkUpFromParenTypeLoc(L))
13437d382dcdSMarcel Hlopko return false;
13447d382dcdSMarcel Hlopko return TraverseTypeLoc(L.getInnerLoc());
13457d382dcdSMarcel Hlopko }
13467d382dcdSMarcel Hlopko
WalkUpFromParenTypeLoc(ParenTypeLoc L)13477d382dcdSMarcel Hlopko bool WalkUpFromParenTypeLoc(ParenTypeLoc L) {
13487d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
13497d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13507d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getRParenLoc()),
1351a711a3a4SMarcel Hlopko new (allocator()) syntax::ParenDeclarator, L);
13527d382dcdSMarcel Hlopko return true;
13537d382dcdSMarcel Hlopko }
13547d382dcdSMarcel Hlopko
13557d382dcdSMarcel Hlopko // Declarator chunks, they are produced by type locs and some clang::Decls.
WalkUpFromArrayTypeLoc(ArrayTypeLoc L)13567d382dcdSMarcel Hlopko bool WalkUpFromArrayTypeLoc(ArrayTypeLoc L) {
13577d382dcdSMarcel Hlopko Builder.markChildToken(L.getLBracketLoc(), syntax::NodeRole::OpenParen);
1358718e550cSEduardo Caldas Builder.markExprChild(L.getSizeExpr(), syntax::NodeRole::Size);
13597d382dcdSMarcel Hlopko Builder.markChildToken(L.getRBracketLoc(), syntax::NodeRole::CloseParen);
13607d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLBracketLoc(), L.getRBracketLoc()),
1361a711a3a4SMarcel Hlopko new (allocator()) syntax::ArraySubscript, L);
13627d382dcdSMarcel Hlopko return true;
13637d382dcdSMarcel Hlopko }
13647d382dcdSMarcel Hlopko
1365dc3d4743SEduardo Caldas syntax::ParameterDeclarationList *
buildParameterDeclarationList(ArrayRef<ParmVarDecl * > Params)1366dc3d4743SEduardo Caldas buildParameterDeclarationList(ArrayRef<ParmVarDecl *> Params) {
1367dc3d4743SEduardo Caldas for (auto *P : Params) {
1368718e550cSEduardo Caldas Builder.markChild(P, syntax::NodeRole::ListElement);
1369dc3d4743SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(P->getEndLoc()));
1370dc3d4743SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
1371718e550cSEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
1372dc3d4743SEduardo Caldas }
1373dc3d4743SEduardo Caldas auto *Parameters = new (allocator()) syntax::ParameterDeclarationList;
1374dc3d4743SEduardo Caldas if (!Params.empty())
1375dc3d4743SEduardo Caldas Builder.foldNode(Builder.getRange(Params.front()->getBeginLoc(),
1376dc3d4743SEduardo Caldas Params.back()->getEndLoc()),
1377dc3d4743SEduardo Caldas Parameters, nullptr);
1378dc3d4743SEduardo Caldas return Parameters;
1379dc3d4743SEduardo Caldas }
1380dc3d4743SEduardo Caldas
WalkUpFromFunctionTypeLoc(FunctionTypeLoc L)13817d382dcdSMarcel Hlopko bool WalkUpFromFunctionTypeLoc(FunctionTypeLoc L) {
13827d382dcdSMarcel Hlopko Builder.markChildToken(L.getLParenLoc(), syntax::NodeRole::OpenParen);
1383dc3d4743SEduardo Caldas
1384dc3d4743SEduardo Caldas Builder.markChild(buildParameterDeclarationList(L.getParams()),
1385718e550cSEduardo Caldas syntax::NodeRole::Parameters);
1386dc3d4743SEduardo Caldas
13877d382dcdSMarcel Hlopko Builder.markChildToken(L.getRParenLoc(), syntax::NodeRole::CloseParen);
13887d382dcdSMarcel Hlopko Builder.foldNode(Builder.getRange(L.getLParenLoc(), L.getEndLoc()),
1389a711a3a4SMarcel Hlopko new (allocator()) syntax::ParametersAndQualifiers, L);
13907d382dcdSMarcel Hlopko return true;
13917d382dcdSMarcel Hlopko }
13927d382dcdSMarcel Hlopko
WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L)13937d382dcdSMarcel Hlopko bool WalkUpFromFunctionProtoTypeLoc(FunctionProtoTypeLoc L) {
13947d382dcdSMarcel Hlopko if (!L.getTypePtr()->hasTrailingReturn())
13957d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L);
13967d382dcdSMarcel Hlopko
1397ac87a0b5SEduardo Caldas auto *TrailingReturnTokens = buildTrailingReturn(L);
13987d382dcdSMarcel Hlopko // Finish building the node for parameters.
1399718e550cSEduardo Caldas Builder.markChild(TrailingReturnTokens, syntax::NodeRole::TrailingReturn);
14007d382dcdSMarcel Hlopko return WalkUpFromFunctionTypeLoc(L);
14017d382dcdSMarcel Hlopko }
14027d382dcdSMarcel Hlopko
TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L)14038ce15f7eSEduardo Caldas bool TraverseMemberPointerTypeLoc(MemberPointerTypeLoc L) {
14048ce15f7eSEduardo Caldas // In the source code "void (Y::*mp)()" `MemberPointerTypeLoc` corresponds
14058ce15f7eSEduardo Caldas // to "Y::*" but it points to a `ParenTypeLoc` that corresponds to
14068ce15f7eSEduardo Caldas // "(Y::*mp)" We thus reverse the order of traversal to get the proper
14078ce15f7eSEduardo Caldas // syntax structure.
14088ce15f7eSEduardo Caldas if (!WalkUpFromMemberPointerTypeLoc(L))
14098ce15f7eSEduardo Caldas return false;
14108ce15f7eSEduardo Caldas return TraverseTypeLoc(L.getPointeeLoc());
14118ce15f7eSEduardo Caldas }
14128ce15f7eSEduardo Caldas
WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L)14137d382dcdSMarcel Hlopko bool WalkUpFromMemberPointerTypeLoc(MemberPointerTypeLoc L) {
14147d382dcdSMarcel Hlopko auto SR = L.getLocalSourceRange();
1415a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(SR),
1416a711a3a4SMarcel Hlopko new (allocator()) syntax::MemberPointer, L);
14177d382dcdSMarcel Hlopko return true;
14187d382dcdSMarcel Hlopko }
14197d382dcdSMarcel Hlopko
142058fa50f4SIlya Biryukov // The code below is very regular, it could even be generated with some
142158fa50f4SIlya Biryukov // preprocessor magic. We merely assign roles to the corresponding children
142258fa50f4SIlya Biryukov // and fold resulting nodes.
WalkUpFromDeclStmt(DeclStmt * S)142358fa50f4SIlya Biryukov bool WalkUpFromDeclStmt(DeclStmt *S) {
142458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1425a711a3a4SMarcel Hlopko new (allocator()) syntax::DeclarationStatement, S);
142658fa50f4SIlya Biryukov return true;
142758fa50f4SIlya Biryukov }
142858fa50f4SIlya Biryukov
WalkUpFromNullStmt(NullStmt * S)142958fa50f4SIlya Biryukov bool WalkUpFromNullStmt(NullStmt *S) {
143058fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1431a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyStatement, S);
143258fa50f4SIlya Biryukov return true;
143358fa50f4SIlya Biryukov }
143458fa50f4SIlya Biryukov
WalkUpFromSwitchStmt(SwitchStmt * S)143558fa50f4SIlya Biryukov bool WalkUpFromSwitchStmt(SwitchStmt *S) {
1436def65bb4SIlya Biryukov Builder.markChildToken(S->getSwitchLoc(),
143758fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
143858fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
143958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1440a711a3a4SMarcel Hlopko new (allocator()) syntax::SwitchStatement, S);
144158fa50f4SIlya Biryukov return true;
144258fa50f4SIlya Biryukov }
144358fa50f4SIlya Biryukov
WalkUpFromCaseStmt(CaseStmt * S)144458fa50f4SIlya Biryukov bool WalkUpFromCaseStmt(CaseStmt *S) {
1445def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(),
144658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
1447718e550cSEduardo Caldas Builder.markExprChild(S->getLHS(), syntax::NodeRole::CaseValue);
144858fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
144958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1450a711a3a4SMarcel Hlopko new (allocator()) syntax::CaseStatement, S);
145158fa50f4SIlya Biryukov return true;
145258fa50f4SIlya Biryukov }
145358fa50f4SIlya Biryukov
WalkUpFromDefaultStmt(DefaultStmt * S)145458fa50f4SIlya Biryukov bool WalkUpFromDefaultStmt(DefaultStmt *S) {
1455def65bb4SIlya Biryukov Builder.markChildToken(S->getKeywordLoc(),
145658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
145758fa50f4SIlya Biryukov Builder.markStmtChild(S->getSubStmt(), syntax::NodeRole::BodyStatement);
145858fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1459a711a3a4SMarcel Hlopko new (allocator()) syntax::DefaultStatement, S);
146058fa50f4SIlya Biryukov return true;
146158fa50f4SIlya Biryukov }
146258fa50f4SIlya Biryukov
WalkUpFromIfStmt(IfStmt * S)146358fa50f4SIlya Biryukov bool WalkUpFromIfStmt(IfStmt *S) {
1464def65bb4SIlya Biryukov Builder.markChildToken(S->getIfLoc(), syntax::NodeRole::IntroducerKeyword);
14656c1a2330SHaojian Wu Stmt *ConditionStatement = S->getCond();
14666c1a2330SHaojian Wu if (S->hasVarStorage())
14676c1a2330SHaojian Wu ConditionStatement = S->getConditionVariableDeclStmt();
14686c1a2330SHaojian Wu Builder.markStmtChild(ConditionStatement, syntax::NodeRole::Condition);
1469718e550cSEduardo Caldas Builder.markStmtChild(S->getThen(), syntax::NodeRole::ThenStatement);
1470718e550cSEduardo Caldas Builder.markChildToken(S->getElseLoc(), syntax::NodeRole::ElseKeyword);
1471718e550cSEduardo Caldas Builder.markStmtChild(S->getElse(), syntax::NodeRole::ElseStatement);
147258fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1473a711a3a4SMarcel Hlopko new (allocator()) syntax::IfStatement, S);
147458fa50f4SIlya Biryukov return true;
147558fa50f4SIlya Biryukov }
147658fa50f4SIlya Biryukov
WalkUpFromForStmt(ForStmt * S)147758fa50f4SIlya Biryukov bool WalkUpFromForStmt(ForStmt *S) {
1478def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
147958fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
148058fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1481a711a3a4SMarcel Hlopko new (allocator()) syntax::ForStatement, S);
148258fa50f4SIlya Biryukov return true;
148358fa50f4SIlya Biryukov }
148458fa50f4SIlya Biryukov
WalkUpFromWhileStmt(WhileStmt * S)148558fa50f4SIlya Biryukov bool WalkUpFromWhileStmt(WhileStmt *S) {
1486def65bb4SIlya Biryukov Builder.markChildToken(S->getWhileLoc(),
148758fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
148858fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
148958fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1490a711a3a4SMarcel Hlopko new (allocator()) syntax::WhileStatement, S);
149158fa50f4SIlya Biryukov return true;
149258fa50f4SIlya Biryukov }
149358fa50f4SIlya Biryukov
WalkUpFromContinueStmt(ContinueStmt * S)149458fa50f4SIlya Biryukov bool WalkUpFromContinueStmt(ContinueStmt *S) {
1495def65bb4SIlya Biryukov Builder.markChildToken(S->getContinueLoc(),
149658fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
149758fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1498a711a3a4SMarcel Hlopko new (allocator()) syntax::ContinueStatement, S);
149958fa50f4SIlya Biryukov return true;
150058fa50f4SIlya Biryukov }
150158fa50f4SIlya Biryukov
WalkUpFromBreakStmt(BreakStmt * S)150258fa50f4SIlya Biryukov bool WalkUpFromBreakStmt(BreakStmt *S) {
1503def65bb4SIlya Biryukov Builder.markChildToken(S->getBreakLoc(),
150458fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
150558fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1506a711a3a4SMarcel Hlopko new (allocator()) syntax::BreakStatement, S);
150758fa50f4SIlya Biryukov return true;
150858fa50f4SIlya Biryukov }
150958fa50f4SIlya Biryukov
WalkUpFromReturnStmt(ReturnStmt * S)151058fa50f4SIlya Biryukov bool WalkUpFromReturnStmt(ReturnStmt *S) {
1511def65bb4SIlya Biryukov Builder.markChildToken(S->getReturnLoc(),
151258fa50f4SIlya Biryukov syntax::NodeRole::IntroducerKeyword);
1513718e550cSEduardo Caldas Builder.markExprChild(S->getRetValue(), syntax::NodeRole::ReturnValue);
151458fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1515a711a3a4SMarcel Hlopko new (allocator()) syntax::ReturnStatement, S);
151658fa50f4SIlya Biryukov return true;
151758fa50f4SIlya Biryukov }
151858fa50f4SIlya Biryukov
WalkUpFromCXXForRangeStmt(CXXForRangeStmt * S)151958fa50f4SIlya Biryukov bool WalkUpFromCXXForRangeStmt(CXXForRangeStmt *S) {
1520def65bb4SIlya Biryukov Builder.markChildToken(S->getForLoc(), syntax::NodeRole::IntroducerKeyword);
152158fa50f4SIlya Biryukov Builder.markStmtChild(S->getBody(), syntax::NodeRole::BodyStatement);
152258fa50f4SIlya Biryukov Builder.foldNode(Builder.getStmtRange(S),
1523a711a3a4SMarcel Hlopko new (allocator()) syntax::RangeBasedForStatement, S);
152458fa50f4SIlya Biryukov return true;
152558fa50f4SIlya Biryukov }
152658fa50f4SIlya Biryukov
WalkUpFromEmptyDecl(EmptyDecl * S)1527be14a22bSIlya Biryukov bool WalkUpFromEmptyDecl(EmptyDecl *S) {
1528cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1529a711a3a4SMarcel Hlopko new (allocator()) syntax::EmptyDeclaration, S);
1530be14a22bSIlya Biryukov return true;
1531be14a22bSIlya Biryukov }
1532be14a22bSIlya Biryukov
WalkUpFromStaticAssertDecl(StaticAssertDecl * S)1533be14a22bSIlya Biryukov bool WalkUpFromStaticAssertDecl(StaticAssertDecl *S) {
1534718e550cSEduardo Caldas Builder.markExprChild(S->getAssertExpr(), syntax::NodeRole::Condition);
1535718e550cSEduardo Caldas Builder.markExprChild(S->getMessage(), syntax::NodeRole::Message);
1536cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1537a711a3a4SMarcel Hlopko new (allocator()) syntax::StaticAssertDeclaration, S);
1538be14a22bSIlya Biryukov return true;
1539be14a22bSIlya Biryukov }
1540be14a22bSIlya Biryukov
WalkUpFromLinkageSpecDecl(LinkageSpecDecl * S)1541be14a22bSIlya Biryukov bool WalkUpFromLinkageSpecDecl(LinkageSpecDecl *S) {
1542cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1543a711a3a4SMarcel Hlopko new (allocator()) syntax::LinkageSpecificationDeclaration,
1544a711a3a4SMarcel Hlopko S);
1545be14a22bSIlya Biryukov return true;
1546be14a22bSIlya Biryukov }
1547be14a22bSIlya Biryukov
WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl * S)1548be14a22bSIlya Biryukov bool WalkUpFromNamespaceAliasDecl(NamespaceAliasDecl *S) {
1549cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1550a711a3a4SMarcel Hlopko new (allocator()) syntax::NamespaceAliasDefinition, S);
1551be14a22bSIlya Biryukov return true;
1552be14a22bSIlya Biryukov }
1553be14a22bSIlya Biryukov
WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl * S)1554be14a22bSIlya Biryukov bool WalkUpFromUsingDirectiveDecl(UsingDirectiveDecl *S) {
1555cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1556a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingNamespaceDirective, S);
1557be14a22bSIlya Biryukov return true;
1558be14a22bSIlya Biryukov }
1559be14a22bSIlya Biryukov
WalkUpFromUsingDecl(UsingDecl * S)1560be14a22bSIlya Biryukov bool WalkUpFromUsingDecl(UsingDecl *S) {
1561cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1562a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S);
1563be14a22bSIlya Biryukov return true;
1564be14a22bSIlya Biryukov }
1565be14a22bSIlya Biryukov
WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * S)1566be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *S) {
1567cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1568a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S);
1569be14a22bSIlya Biryukov return true;
1570be14a22bSIlya Biryukov }
1571be14a22bSIlya Biryukov
WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * S)1572be14a22bSIlya Biryukov bool WalkUpFromUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *S) {
1573cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1574a711a3a4SMarcel Hlopko new (allocator()) syntax::UsingDeclaration, S);
1575be14a22bSIlya Biryukov return true;
1576be14a22bSIlya Biryukov }
1577be14a22bSIlya Biryukov
WalkUpFromTypeAliasDecl(TypeAliasDecl * S)1578be14a22bSIlya Biryukov bool WalkUpFromTypeAliasDecl(TypeAliasDecl *S) {
1579cdce2fe5SMarcel Hlopko Builder.foldNode(Builder.getDeclarationRange(S),
1580a711a3a4SMarcel Hlopko new (allocator()) syntax::TypeAliasDeclaration, S);
1581be14a22bSIlya Biryukov return true;
1582be14a22bSIlya Biryukov }
1583be14a22bSIlya Biryukov
15849b3f38f9SIlya Biryukov private:
1585cdce2fe5SMarcel Hlopko /// Folds SimpleDeclarator node (if present) and in case this is the last
1586cdce2fe5SMarcel Hlopko /// declarator in the chain it also folds SimpleDeclaration node.
processDeclaratorAndDeclaration(T * D)1587cdce2fe5SMarcel Hlopko template <class T> bool processDeclaratorAndDeclaration(T *D) {
158838bc0060SEduardo Caldas auto Range = getDeclaratorRange(
158938bc0060SEduardo Caldas Builder.sourceManager(), D->getTypeSourceInfo()->getTypeLoc(),
159038bc0060SEduardo Caldas getQualifiedNameStart(D), getInitializerRange(D));
1591cdce2fe5SMarcel Hlopko
1592cdce2fe5SMarcel Hlopko // There doesn't have to be a declarator (e.g. `void foo(int)` only has
1593cdce2fe5SMarcel Hlopko // declaration, but no declarator).
15945011d431SEduardo Caldas if (!Range.getBegin().isValid()) {
15955011d431SEduardo Caldas Builder.markChild(new (allocator()) syntax::DeclaratorList,
15965011d431SEduardo Caldas syntax::NodeRole::Declarators);
15975011d431SEduardo Caldas Builder.foldNode(Builder.getDeclarationRange(D),
15985011d431SEduardo Caldas new (allocator()) syntax::SimpleDeclaration, D);
15995011d431SEduardo Caldas return true;
1600cdce2fe5SMarcel Hlopko }
1601cdce2fe5SMarcel Hlopko
16025011d431SEduardo Caldas auto *N = new (allocator()) syntax::SimpleDeclarator;
16035011d431SEduardo Caldas Builder.foldNode(Builder.getRange(Range), N, nullptr);
16045011d431SEduardo Caldas Builder.markChild(N, syntax::NodeRole::ListElement);
16055011d431SEduardo Caldas
16065011d431SEduardo Caldas if (!Builder.isResponsibleForCreatingDeclaration(D)) {
16075011d431SEduardo Caldas // If this is not the last declarator in the declaration we expect a
16085011d431SEduardo Caldas // delimiter after it.
16095011d431SEduardo Caldas const auto *DelimiterToken = std::next(Builder.findToken(Range.getEnd()));
16105011d431SEduardo Caldas if (DelimiterToken->kind() == clang::tok::TokenKind::comma)
16115011d431SEduardo Caldas Builder.markChildToken(DelimiterToken, syntax::NodeRole::ListDelimiter);
16125011d431SEduardo Caldas } else {
16135011d431SEduardo Caldas auto *DL = new (allocator()) syntax::DeclaratorList;
16145011d431SEduardo Caldas auto DeclarationRange = Builder.getDeclarationRange(D);
16155011d431SEduardo Caldas Builder.foldList(DeclarationRange, DL, nullptr);
16165011d431SEduardo Caldas
16175011d431SEduardo Caldas Builder.markChild(DL, syntax::NodeRole::Declarators);
16185011d431SEduardo Caldas Builder.foldNode(DeclarationRange,
1619cdce2fe5SMarcel Hlopko new (allocator()) syntax::SimpleDeclaration, D);
1620cdce2fe5SMarcel Hlopko }
1621cdce2fe5SMarcel Hlopko return true;
1622cdce2fe5SMarcel Hlopko }
1623cdce2fe5SMarcel Hlopko
16247d382dcdSMarcel Hlopko /// Returns the range of the built node.
buildTrailingReturn(FunctionProtoTypeLoc L)1625ac87a0b5SEduardo Caldas syntax::TrailingReturnType *buildTrailingReturn(FunctionProtoTypeLoc L) {
16267d382dcdSMarcel Hlopko assert(L.getTypePtr()->hasTrailingReturn());
16277d382dcdSMarcel Hlopko
16287d382dcdSMarcel Hlopko auto ReturnedType = L.getReturnLoc();
16297d382dcdSMarcel Hlopko // Build node for the declarator, if any.
163038bc0060SEduardo Caldas auto ReturnDeclaratorRange = SourceRange(GetStartLoc().Visit(ReturnedType),
163138bc0060SEduardo Caldas ReturnedType.getEndLoc());
1632a711a3a4SMarcel Hlopko syntax::SimpleDeclarator *ReturnDeclarator = nullptr;
16337d382dcdSMarcel Hlopko if (ReturnDeclaratorRange.isValid()) {
1634a711a3a4SMarcel Hlopko ReturnDeclarator = new (allocator()) syntax::SimpleDeclarator;
1635a711a3a4SMarcel Hlopko Builder.foldNode(Builder.getRange(ReturnDeclaratorRange),
1636a711a3a4SMarcel Hlopko ReturnDeclarator, nullptr);
16377d382dcdSMarcel Hlopko }
16387d382dcdSMarcel Hlopko
16397d382dcdSMarcel Hlopko // Build node for trailing return type.
1640a711a3a4SMarcel Hlopko auto Return = Builder.getRange(ReturnedType.getSourceRange());
16417d382dcdSMarcel Hlopko const auto *Arrow = Return.begin() - 1;
16427d382dcdSMarcel Hlopko assert(Arrow->kind() == tok::arrow);
1643a3c248dbSserge-sans-paille auto Tokens = llvm::ArrayRef(Arrow, Return.end());
164442f6fec3SEduardo Caldas Builder.markChildToken(Arrow, syntax::NodeRole::ArrowToken);
1645a711a3a4SMarcel Hlopko if (ReturnDeclarator)
1646718e550cSEduardo Caldas Builder.markChild(ReturnDeclarator, syntax::NodeRole::Declarator);
1647a711a3a4SMarcel Hlopko auto *R = new (allocator()) syntax::TrailingReturnType;
1648cdce2fe5SMarcel Hlopko Builder.foldNode(Tokens, R, L);
1649a711a3a4SMarcel Hlopko return R;
16507d382dcdSMarcel Hlopko }
165188bf9b3dSMarcel Hlopko
foldExplicitTemplateInstantiation(ArrayRef<syntax::Token> Range,const syntax::Token * ExternKW,const syntax::Token * TemplateKW,syntax::SimpleDeclaration * InnerDeclaration,Decl * From)1652a711a3a4SMarcel Hlopko void foldExplicitTemplateInstantiation(
1653a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *ExternKW,
165488bf9b3dSMarcel Hlopko const syntax::Token *TemplateKW,
1655a711a3a4SMarcel Hlopko syntax::SimpleDeclaration *InnerDeclaration, Decl *From) {
165688bf9b3dSMarcel Hlopko assert(!ExternKW || ExternKW->kind() == tok::kw_extern);
165788bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
165842f6fec3SEduardo Caldas Builder.markChildToken(ExternKW, syntax::NodeRole::ExternKeyword);
165988bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1660718e550cSEduardo Caldas Builder.markChild(InnerDeclaration, syntax::NodeRole::Declaration);
1661a711a3a4SMarcel Hlopko Builder.foldNode(
1662a711a3a4SMarcel Hlopko Range, new (allocator()) syntax::ExplicitTemplateInstantiation, From);
166388bf9b3dSMarcel Hlopko }
166488bf9b3dSMarcel Hlopko
foldTemplateDeclaration(ArrayRef<syntax::Token> Range,const syntax::Token * TemplateKW,ArrayRef<syntax::Token> TemplatedDeclaration,Decl * From)1665a711a3a4SMarcel Hlopko syntax::TemplateDeclaration *foldTemplateDeclaration(
1666a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> Range, const syntax::Token *TemplateKW,
1667a711a3a4SMarcel Hlopko ArrayRef<syntax::Token> TemplatedDeclaration, Decl *From) {
166888bf9b3dSMarcel Hlopko assert(TemplateKW && TemplateKW->kind() == tok::kw_template);
166988bf9b3dSMarcel Hlopko Builder.markChildToken(TemplateKW, syntax::NodeRole::IntroducerKeyword);
1670a711a3a4SMarcel Hlopko
1671a711a3a4SMarcel Hlopko auto *N = new (allocator()) syntax::TemplateDeclaration;
1672a711a3a4SMarcel Hlopko Builder.foldNode(Range, N, From);
1673718e550cSEduardo Caldas Builder.markChild(N, syntax::NodeRole::Declaration);
1674a711a3a4SMarcel Hlopko return N;
167588bf9b3dSMarcel Hlopko }
167688bf9b3dSMarcel Hlopko
16779b3f38f9SIlya Biryukov /// A small helper to save some typing.
allocator()16789b3f38f9SIlya Biryukov llvm::BumpPtrAllocator &allocator() { return Builder.allocator(); }
16799b3f38f9SIlya Biryukov
16809b3f38f9SIlya Biryukov syntax::TreeBuilder &Builder;
16811db5b348SEduardo Caldas const ASTContext &Context;
16829b3f38f9SIlya Biryukov };
16839b3f38f9SIlya Biryukov } // namespace
16849b3f38f9SIlya Biryukov
noticeDeclWithoutSemicolon(Decl * D)16857d382dcdSMarcel Hlopko void syntax::TreeBuilder::noticeDeclWithoutSemicolon(Decl *D) {
1686e702bdb8SIlya Biryukov DeclsWithoutSemicolons.insert(D);
1687e702bdb8SIlya Biryukov }
1688e702bdb8SIlya Biryukov
markChildToken(SourceLocation Loc,NodeRole Role)1689def65bb4SIlya Biryukov void syntax::TreeBuilder::markChildToken(SourceLocation Loc, NodeRole Role) {
16909b3f38f9SIlya Biryukov if (Loc.isInvalid())
16919b3f38f9SIlya Biryukov return;
16929b3f38f9SIlya Biryukov Pending.assignRole(*findToken(Loc), Role);
16939b3f38f9SIlya Biryukov }
16949b3f38f9SIlya Biryukov
markChildToken(const syntax::Token * T,NodeRole R)16957d382dcdSMarcel Hlopko void syntax::TreeBuilder::markChildToken(const syntax::Token *T, NodeRole R) {
16967d382dcdSMarcel Hlopko if (!T)
16977d382dcdSMarcel Hlopko return;
16987d382dcdSMarcel Hlopko Pending.assignRole(*T, R);
16997d382dcdSMarcel Hlopko }
17007d382dcdSMarcel Hlopko
markChild(syntax::Node * N,NodeRole R)1701a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(syntax::Node *N, NodeRole R) {
1702a711a3a4SMarcel Hlopko assert(N);
1703a711a3a4SMarcel Hlopko setRole(N, R);
1704a711a3a4SMarcel Hlopko }
1705a711a3a4SMarcel Hlopko
markChild(ASTPtr N,NodeRole R)1706a711a3a4SMarcel Hlopko void syntax::TreeBuilder::markChild(ASTPtr N, NodeRole R) {
1707a711a3a4SMarcel Hlopko auto *SN = Mapping.find(N);
1708a711a3a4SMarcel Hlopko assert(SN != nullptr);
1709a711a3a4SMarcel Hlopko setRole(SN, R);
17107d382dcdSMarcel Hlopko }
markChild(NestedNameSpecifierLoc NNSLoc,NodeRole R)1711f9500cc4SEduardo Caldas void syntax::TreeBuilder::markChild(NestedNameSpecifierLoc NNSLoc, NodeRole R) {
1712f9500cc4SEduardo Caldas auto *SN = Mapping.find(NNSLoc);
1713f9500cc4SEduardo Caldas assert(SN != nullptr);
1714f9500cc4SEduardo Caldas setRole(SN, R);
1715f9500cc4SEduardo Caldas }
17167d382dcdSMarcel Hlopko
markStmtChild(Stmt * Child,NodeRole Role)171758fa50f4SIlya Biryukov void syntax::TreeBuilder::markStmtChild(Stmt *Child, NodeRole Role) {
171858fa50f4SIlya Biryukov if (!Child)
171958fa50f4SIlya Biryukov return;
172058fa50f4SIlya Biryukov
1721b34b7691SDmitri Gribenko syntax::Tree *ChildNode;
1722b34b7691SDmitri Gribenko if (Expr *ChildExpr = dyn_cast<Expr>(Child)) {
172358fa50f4SIlya Biryukov // This is an expression in a statement position, consume the trailing
172458fa50f4SIlya Biryukov // semicolon and form an 'ExpressionStatement' node.
1725718e550cSEduardo Caldas markExprChild(ChildExpr, NodeRole::Expression);
1726a711a3a4SMarcel Hlopko ChildNode = new (allocator()) syntax::ExpressionStatement;
1727a711a3a4SMarcel Hlopko // (!) 'getStmtRange()' ensures this covers a trailing semicolon.
1728263dcf45SHaojian Wu Pending.foldChildren(TBTM.tokenBuffer(), getStmtRange(Child), ChildNode);
1729b34b7691SDmitri Gribenko } else {
1730b34b7691SDmitri Gribenko ChildNode = Mapping.find(Child);
173158fa50f4SIlya Biryukov }
1732b34b7691SDmitri Gribenko assert(ChildNode != nullptr);
1733a711a3a4SMarcel Hlopko setRole(ChildNode, Role);
173458fa50f4SIlya Biryukov }
173558fa50f4SIlya Biryukov
markExprChild(Expr * Child,NodeRole Role)173658fa50f4SIlya Biryukov void syntax::TreeBuilder::markExprChild(Expr *Child, NodeRole Role) {
1737be14a22bSIlya Biryukov if (!Child)
1738be14a22bSIlya Biryukov return;
17392325d6b4SEduardo Caldas Child = IgnoreImplicit(Child);
1740be14a22bSIlya Biryukov
1741a711a3a4SMarcel Hlopko syntax::Tree *ChildNode = Mapping.find(Child);
1742a711a3a4SMarcel Hlopko assert(ChildNode != nullptr);
1743a711a3a4SMarcel Hlopko setRole(ChildNode, Role);
174458fa50f4SIlya Biryukov }
174558fa50f4SIlya Biryukov
findToken(SourceLocation L) const17469b3f38f9SIlya Biryukov const syntax::Token *syntax::TreeBuilder::findToken(SourceLocation L) const {
174788bf9b3dSMarcel Hlopko if (L.isInvalid())
174888bf9b3dSMarcel Hlopko return nullptr;
174978194118SMikhail Maltsev auto It = LocationToToken.find(L);
1750c1bbefefSIlya Biryukov assert(It != LocationToToken.end());
1751c1bbefefSIlya Biryukov return It->second;
17529b3f38f9SIlya Biryukov }
17539b3f38f9SIlya Biryukov
buildSyntaxTree(Arena & A,TokenBufferTokenManager & TBTM,ASTContext & Context)1754142c6f82SKirill Bobyrev syntax::TranslationUnit *syntax::buildSyntaxTree(Arena &A,
1755263dcf45SHaojian Wu TokenBufferTokenManager& TBTM,
1756142c6f82SKirill Bobyrev ASTContext &Context) {
1757263dcf45SHaojian Wu TreeBuilder Builder(A, TBTM);
1758142c6f82SKirill Bobyrev BuildTreeVisitor(Context, Builder).TraverseAST(Context);
17599b3f38f9SIlya Biryukov return std::move(Builder).finalize();
17609b3f38f9SIlya Biryukov }
1761