13#include "clang/AST/ASTTypeTraits.h"
14#include "clang/AST/Expr.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/NestedNameSpecifier.h"
17#include "clang/AST/PrettyPrinter.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/TextNodeDumper.h"
20#include "clang/AST/Type.h"
21#include "clang/AST/TypeLoc.h"
22#include "clang/Basic/Specifiers.h"
23#include "clang/Tooling/Syntax/Tokens.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Support/raw_ostream.h"
32using llvm::raw_ostream;
33template <
typename Pr
int> std::string
toString(
const Print &
C) {
35 llvm::raw_string_ostream
OS(Result);
37 return std::move(
OS.str());
40bool isInjectedClassName(
Decl *D) {
41 if (
const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(D))
42 return CRD->isInjectedClassName();
49 const syntax::TokenBuffer &Tokens;
50 const ASTContext &Ctx;
55 std::vector<ASTNode *> Stack;
60 bool traverseNodePre(llvm::StringRef
Role,
const T &Node) {
62 assert(
Root.role.empty());
63 Stack.push_back(&Root);
65 Stack.back()->children.emplace_back();
66 Stack.push_back(&Stack.back()->children.back());
68 auto &N = *Stack.back();
70 N.kind = getKind(Node);
71 N.detail = getDetail(Node);
72 N.range = getRange(Node);
73 N.arcana = getArcana(Node);
76 bool traverseNodePost() {
77 assert(!Stack.empty());
81 template <
typename T,
typename Callable>
82 bool traverseNode(llvm::StringRef
Role,
const T &Node,
const Callable &Body) {
83 traverseNodePre(
Role, Node);
85 return traverseNodePost();
91 template <
typename T> std::optional<Range> getRange(
const T &Node) {
92 SourceRange SR = getSourceRange(Node);
93 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(SR));
97 Tokens.sourceManager(),
98 CharSourceRange::getCharRange(
Spelled->front().location(),
99 Spelled->back().endLocation()));
101 template <typename T, typename = decltype(std::declval<T>().getSourceRange())>
102 SourceRange getSourceRange(
const T &Node) {
103 return Node.getSourceRange();
105 template <
typename T,
106 typename =
decltype(std::declval<T *>()->getSourceRange())>
107 SourceRange getSourceRange(
const T *Node) {
108 return Node->getSourceRange();
111 SourceRange getSourceRange(
const TemplateName &Node) {
return SourceRange(); }
113 SourceRange getSourceRange(
const Attr *Node) {
return Node->getRange(); }
118 std::string getKind(
const Decl *D) {
return D->getDeclKindName(); }
119 std::string getKind(
const Stmt *S) {
120 std::string Result = S->getStmtClassName();
121 if (llvm::StringRef(Result).endswith(
"Stmt") ||
122 llvm::StringRef(Result).endswith(
"Expr"))
123 Result.resize(Result.size() - 4);
126 std::string getKind(
const TypeLoc &TL) {
128 if (TL.getTypeLocClass() == TypeLoc::Qualified)
130 return TL.getType()->getTypeClassName();
132 std::string getKind(
const TemplateArgumentLoc &TAL) {
133 switch (TAL.getArgument().getKind()) {
134#define TEMPLATE_ARGUMENT_KIND(X) \
135 case TemplateArgument::X: \
146#undef TEMPLATE_ARGUMENT_KIND
148 llvm_unreachable(
"Unhandled ArgKind enum");
150 std::string getKind(
const NestedNameSpecifierLoc &NNSL) {
151 assert(NNSL.getNestedNameSpecifier());
152 switch (NNSL.getNestedNameSpecifier()->getKind()) {
154 case NestedNameSpecifier::X: \
165 llvm_unreachable(
"Unhandled SpecifierKind enum");
167 std::string getKind(
const CXXCtorInitializer *CCI) {
168 if (CCI->isBaseInitializer())
169 return "BaseInitializer";
170 if (CCI->isDelegatingInitializer())
171 return "DelegatingInitializer";
172 if (CCI->isAnyMemberInitializer())
173 return "MemberInitializer";
174 llvm_unreachable(
"Unhandled CXXCtorInitializer type");
176 std::string getKind(
const TemplateName &TN) {
177 switch (TN.getKind()) {
178#define TEMPLATE_KIND(X) \
179 case TemplateName::X: \
191 llvm_unreachable(
"Unhandled NameKind enum");
193 std::string getKind(
const Attr *A) {
194 switch (
A->getKind()) {
198#include "clang/Basic/AttrList.inc"
201 llvm_unreachable(
"Unhandled attr::Kind enum");
203 std::string getKind(
const CXXBaseSpecifier &CBS) {
206 return getAccessSpelling(CBS.getAccessSpecifier()).str();
213 std::string getDetail(
const Decl *D) {
214 const auto *ND = dyn_cast<NamedDecl>(D);
215 if (!ND || llvm::isa_and_nonnull<CXXConstructorDecl>(ND->getAsFunction()) ||
216 isa<CXXDestructorDecl>(ND))
220 return "(anonymous)";
223 std::string getDetail(
const Stmt *S) {
224 if (
const auto *DRE = dyn_cast<DeclRefExpr>(S))
225 return DRE->getNameInfo().getAsString();
226 if (
const auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(S))
227 return DSDRE->getNameInfo().getAsString();
228 if (
const auto *ME = dyn_cast<MemberExpr>(S))
229 return ME->getMemberNameInfo().getAsString();
230 if (
const auto *
CE = dyn_cast<CastExpr>(S))
231 return CE->getCastKindName();
232 if (
const auto *BO = dyn_cast<BinaryOperator>(S))
233 return BO->getOpcodeStr().str();
234 if (
const auto *UO = dyn_cast<UnaryOperator>(S))
235 return UnaryOperator::getOpcodeStr(UO->getOpcode()).str();
236 if (
const auto *CCO = dyn_cast<CXXConstructExpr>(S))
237 return CCO->getConstructor()->getNameAsString();
238 if (
const auto *CTE = dyn_cast<CXXThisExpr>(S)) {
239 bool Const = CTE->getType()->getPointeeType().isLocalConstQualified();
240 if (CTE->isImplicit())
241 return Const ?
"const, implicit" :
"implicit";
246 if (isa<IntegerLiteral, FloatingLiteral, FixedPointLiteral,
247 CharacterLiteral, ImaginaryLiteral, CXXBoolLiteralExpr>(S))
249 S->printPretty(
OS,
nullptr, Ctx.getPrintingPolicy());
251 if (
const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(S))
252 return MTE->isBoundToLvalueReference() ?
"lvalue" :
"rvalue";
255 std::string getDetail(
const TypeLoc &TL) {
256 if (TL.getType().hasLocalQualifiers())
257 return TL.getType().getLocalQualifiers().getAsString(
258 Ctx.getPrintingPolicy());
259 if (
const auto *TT = dyn_cast<TagType>(TL.getTypePtr()))
260 return getDetail(TT->getDecl());
261 if (
const auto *DT = dyn_cast<DeducedType>(TL.getTypePtr()))
263 return DT->getDeducedType().getAsString(Ctx.getPrintingPolicy());
264 if (
const auto *BT = dyn_cast<BuiltinType>(TL.getTypePtr()))
265 return BT->getName(Ctx.getPrintingPolicy()).str();
266 if (
const auto *TTPT = dyn_cast<TemplateTypeParmType>(TL.getTypePtr()))
267 return getDetail(TTPT->getDecl());
268 if (
const auto *TT = dyn_cast<TypedefType>(TL.getTypePtr()))
269 return getDetail(TT->getDecl());
272 std::string getDetail(
const NestedNameSpecifierLoc &NNSL) {
273 const auto &NNS = *NNSL.getNestedNameSpecifier();
274 switch (NNS.getKind()) {
275 case NestedNameSpecifier::Identifier:
276 return NNS.getAsIdentifier()->getName().str() +
"::";
277 case NestedNameSpecifier::Namespace:
278 return NNS.getAsNamespace()->getNameAsString() +
"::";
279 case NestedNameSpecifier::NamespaceAlias:
280 return NNS.getAsNamespaceAlias()->getNameAsString() +
"::";
285 std::string getDetail(
const CXXCtorInitializer *CCI) {
286 if (FieldDecl *FD = CCI->getAnyMember())
287 return getDetail(FD);
288 if (TypeLoc TL = CCI->getBaseClassLoc())
289 return getDetail(TL);
292 std::string getDetail(
const TemplateArgumentLoc &TAL) {
293 if (TAL.getArgument().getKind() == TemplateArgument::Integral)
294 return toString(TAL.getArgument().getAsIntegral(), 10);
297 std::string getDetail(
const TemplateName &TN) {
299 TN.print(
OS, Ctx.getPrintingPolicy(), TemplateName::Qualified::None);
302 std::string getDetail(
const Attr *A) {
303 return A->getAttrName() ?
A->getNormalizedFullName() :
A->getSpelling();
305 std::string getDetail(
const CXXBaseSpecifier &CBS) {
306 return CBS.isVirtual() ?
"virtual" :
"";
311 template <
typename Dump> std::string dump(
const Dump &D) {
313 TextNodeDumper Dumper(
OS, Ctx,
false);
317 template <
typename T> std::string getArcana(
const T &N) {
318 return dump([&](TextNodeDumper &D) {
D.Visit(N); });
320 std::string getArcana(
const NestedNameSpecifierLoc &NNS) {
return ""; }
321 std::string getArcana(
const TemplateName &NNS) {
return ""; }
322 std::string getArcana(
const CXXBaseSpecifier &CBS) {
return ""; }
323 std::string getArcana(
const TemplateArgumentLoc &TAL) {
324 return dump([&](TextNodeDumper &D) {
325 D.Visit(TAL.getArgument(), TAL.getSourceRange());
328 std::string getArcana(
const TypeLoc &TL) {
329 return dump([&](TextNodeDumper &D) {
D.Visit(TL.getType()); });
334 DumpVisitor(
const syntax::TokenBuffer &Tokens,
const ASTContext &Ctx)
335 : Tokens(Tokens), Ctx(Ctx) {}
340 bool TraverseDecl(
Decl *D) {
341 return !
D || isInjectedClassName(D) ||
342 traverseNode(
"declaration", D, [&] { Base::TraverseDecl(D); });
344 bool TraverseTypeLoc(TypeLoc TL) {
345 return !TL || traverseNode(
"type", TL, [&] { Base::TraverseTypeLoc(TL); });
347 bool TraverseTemplateName(
const TemplateName &TN) {
348 return traverseNode(
"template name", TN,
349 [&] { Base::TraverseTemplateName(TN); });
351 bool TraverseTemplateArgumentLoc(
const TemplateArgumentLoc &TAL) {
352 return traverseNode(
"template argument", TAL,
353 [&] { Base::TraverseTemplateArgumentLoc(TAL); });
355 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
356 return !NNSL || traverseNode(
"specifier", NNSL, [&] {
357 Base::TraverseNestedNameSpecifierLoc(NNSL);
360 bool TraverseConstructorInitializer(CXXCtorInitializer *CCI) {
361 return !CCI || traverseNode(
"constructor initializer", CCI, [&] {
362 Base::TraverseConstructorInitializer(CCI);
365 bool TraverseAttr(Attr *A) {
366 return !
A || traverseNode(
"attribute", A, [&] { Base::TraverseAttr(A); });
368 bool TraverseCXXBaseSpecifier(
const CXXBaseSpecifier &CBS) {
369 return traverseNode(
"base", CBS,
370 [&] { Base::TraverseCXXBaseSpecifier(CBS); });
373 bool dataTraverseStmtPre(Stmt *S) {
374 return S && traverseNodePre(isa<Expr>(S) ?
"expression" :
"statement", S);
376 bool dataTraverseStmtPost(Stmt *
X) {
return traverseNodePost(); }
383 bool TraverseQualifiedTypeLoc(QualifiedTypeLoc QTL) {
384 return TraverseTypeLoc(QTL.getUnqualifiedLoc());
387 bool TraverseNestedNameSpecifier(NestedNameSpecifier *) {
return true; }
388 bool TraverseType(QualType) {
return true; }
391 bool TraverseOpaqueValueExpr(OpaqueValueExpr *
E) {
392 return TraverseStmt(
E->getSourceExpr());
395 bool TraversePseudoObjectExpr(PseudoObjectExpr *
E) {
396 return TraverseStmt(
E->getSyntacticForm());
403 const ASTContext &Ctx) {
404 DumpVisitor V(Tokens, Ctx);
406 if (
const auto *D = N.get<
Decl>())
407 V.TraverseDecl(
const_cast<Decl *
>(D));
408 else if (
const auto *S = N.get<Stmt>())
409 V.TraverseStmt(
const_cast<Stmt *
>(S));
410 else if (
const auto *NNSL = N.get<NestedNameSpecifierLoc>())
411 V.TraverseNestedNameSpecifierLoc(
412 *
const_cast<NestedNameSpecifierLoc *
>(NNSL));
413 else if (
const auto *NNS = N.get<NestedNameSpecifier>())
414 V.TraverseNestedNameSpecifier(
const_cast<NestedNameSpecifier *
>(NNS));
415 else if (
const auto *TL = N.get<TypeLoc>())
416 V.TraverseTypeLoc(*
const_cast<TypeLoc *
>(TL));
417 else if (
const auto *QT = N.get<QualType>())
418 V.TraverseType(*
const_cast<QualType *
>(QT));
419 else if (
const auto *CCI = N.get<CXXCtorInitializer>())
420 V.TraverseConstructorInitializer(
const_cast<CXXCtorInitializer *
>(CCI));
421 else if (
const auto *TAL = N.get<TemplateArgumentLoc>())
422 V.TraverseTemplateArgumentLoc(*
const_cast<TemplateArgumentLoc *
>(TAL));
423 else if (
const auto *CBS = N.get<CXXBaseSpecifier>())
424 V.TraverseCXXBaseSpecifier(*
const_cast<CXXBaseSpecifier *
>(CBS));
426 elog(
"dumpAST: unhandled DynTypedNode kind {0}",
427 N.getNodeKind().asStringRef());
428 return std::move(V.Root);
ArrayRef< const ParmVarDecl * > Pack
const FunctionDecl * Decl
#define TEMPLATE_ARGUMENT_KIND(X)
llvm::raw_string_ostream OS
index::SymbolRoleSet Role
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
ASTNode dumpAST(const DynTypedNode &N, const syntax::TokenBuffer &Tokens, const ASTContext &Ctx)
static const char * toString(OffsetEncoding OE)
@ Type
An inlay hint that for a type annotation.
void elog(const char *Fmt, Ts &&... Vals)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Simplified description of a clang AST node.