JSONNodeDumper.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- JSONNodeDumper.h - Printing of AST nodes to JSON -----------------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file implements AST dumping of components of individual AST nodes to
  15. // a JSON.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_AST_JSONNODEDUMPER_H
  19. #define LLVM_CLANG_AST_JSONNODEDUMPER_H
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/ASTDumperUtils.h"
  22. #include "clang/AST/ASTNodeTraverser.h"
  23. #include "clang/AST/AttrVisitor.h"
  24. #include "clang/AST/CommentCommandTraits.h"
  25. #include "clang/AST/CommentVisitor.h"
  26. #include "clang/AST/ExprConcepts.h"
  27. #include "clang/AST/ExprCXX.h"
  28. #include "clang/AST/Mangle.h"
  29. #include "clang/AST/Type.h"
  30. #include "llvm/Support/JSON.h"
  31. namespace clang {
  32. class APValue;
  33. class NodeStreamer {
  34. bool FirstChild = true;
  35. bool TopLevel = true;
  36. llvm::SmallVector<std::function<void(bool IsLastChild)>, 32> Pending;
  37. protected:
  38. llvm::json::OStream JOS;
  39. public:
  40. /// Add a child of the current node. Calls DoAddChild without arguments
  41. template <typename Fn> void AddChild(Fn DoAddChild) {
  42. return AddChild("", DoAddChild);
  43. }
  44. /// Add a child of the current node with an optional label.
  45. /// Calls DoAddChild without arguments.
  46. template <typename Fn> void AddChild(StringRef Label, Fn DoAddChild) {
  47. // If we're at the top level, there's nothing interesting to do; just
  48. // run the dumper.
  49. if (TopLevel) {
  50. TopLevel = false;
  51. JOS.objectBegin();
  52. DoAddChild();
  53. while (!Pending.empty()) {
  54. Pending.back()(true);
  55. Pending.pop_back();
  56. }
  57. JOS.objectEnd();
  58. TopLevel = true;
  59. return;
  60. }
  61. // We need to capture an owning-string in the lambda because the lambda
  62. // is invoked in a deferred manner.
  63. std::string LabelStr(!Label.empty() ? Label : "inner");
  64. bool WasFirstChild = FirstChild;
  65. auto DumpWithIndent = [=](bool IsLastChild) {
  66. if (WasFirstChild) {
  67. JOS.attributeBegin(LabelStr);
  68. JOS.arrayBegin();
  69. }
  70. FirstChild = true;
  71. unsigned Depth = Pending.size();
  72. JOS.objectBegin();
  73. DoAddChild();
  74. // If any children are left, they're the last at their nesting level.
  75. // Dump those ones out now.
  76. while (Depth < Pending.size()) {
  77. Pending.back()(true);
  78. this->Pending.pop_back();
  79. }
  80. JOS.objectEnd();
  81. if (IsLastChild) {
  82. JOS.arrayEnd();
  83. JOS.attributeEnd();
  84. }
  85. };
  86. if (FirstChild) {
  87. Pending.push_back(std::move(DumpWithIndent));
  88. } else {
  89. Pending.back()(false);
  90. Pending.back() = std::move(DumpWithIndent);
  91. }
  92. FirstChild = false;
  93. }
  94. NodeStreamer(raw_ostream &OS) : JOS(OS, 2) {}
  95. };
  96. // Dumps AST nodes in JSON format. There is no implied stability for the
  97. // content or format of the dump between major releases of Clang, other than it
  98. // being valid JSON output. Further, there is no requirement that the
  99. // information dumped is a complete representation of the AST, only that the
  100. // information presented is correct.
  101. class JSONNodeDumper
  102. : public ConstAttrVisitor<JSONNodeDumper>,
  103. public comments::ConstCommentVisitor<JSONNodeDumper, void,
  104. const comments::FullComment *>,
  105. public ConstTemplateArgumentVisitor<JSONNodeDumper>,
  106. public ConstStmtVisitor<JSONNodeDumper>,
  107. public TypeVisitor<JSONNodeDumper>,
  108. public ConstDeclVisitor<JSONNodeDumper>,
  109. public NodeStreamer {
  110. friend class JSONDumper;
  111. const SourceManager &SM;
  112. ASTContext& Ctx;
  113. ASTNameGenerator ASTNameGen;
  114. PrintingPolicy PrintPolicy;
  115. const comments::CommandTraits *Traits;
  116. StringRef LastLocFilename, LastLocPresumedFilename;
  117. unsigned LastLocLine, LastLocPresumedLine;
  118. using InnerAttrVisitor = ConstAttrVisitor<JSONNodeDumper>;
  119. using InnerCommentVisitor =
  120. comments::ConstCommentVisitor<JSONNodeDumper, void,
  121. const comments::FullComment *>;
  122. using InnerTemplateArgVisitor = ConstTemplateArgumentVisitor<JSONNodeDumper>;
  123. using InnerStmtVisitor = ConstStmtVisitor<JSONNodeDumper>;
  124. using InnerTypeVisitor = TypeVisitor<JSONNodeDumper>;
  125. using InnerDeclVisitor = ConstDeclVisitor<JSONNodeDumper>;
  126. void attributeOnlyIfTrue(StringRef Key, bool Value) {
  127. if (Value)
  128. JOS.attribute(Key, Value);
  129. }
  130. void writeIncludeStack(PresumedLoc Loc, bool JustFirst = false);
  131. // Writes the attributes of a SourceLocation object without.
  132. void writeBareSourceLocation(SourceLocation Loc, bool IsSpelling);
  133. // Writes the attributes of a SourceLocation to JSON based on its presumed
  134. // spelling location. If the given location represents a macro invocation,
  135. // this outputs two sub-objects: one for the spelling and one for the
  136. // expansion location.
  137. void writeSourceLocation(SourceLocation Loc);
  138. void writeSourceRange(SourceRange R);
  139. std::string createPointerRepresentation(const void *Ptr);
  140. llvm::json::Object createQualType(QualType QT, bool Desugar = true);
  141. llvm::json::Object createBareDeclRef(const Decl *D);
  142. void writeBareDeclRef(const Decl *D);
  143. llvm::json::Object createCXXRecordDefinitionData(const CXXRecordDecl *RD);
  144. llvm::json::Object createCXXBaseSpecifier(const CXXBaseSpecifier &BS);
  145. std::string createAccessSpecifier(AccessSpecifier AS);
  146. llvm::json::Array createCastPath(const CastExpr *C);
  147. void writePreviousDeclImpl(...) {}
  148. template <typename T> void writePreviousDeclImpl(const Mergeable<T> *D) {
  149. const T *First = D->getFirstDecl();
  150. if (First != D)
  151. JOS.attribute("firstRedecl", createPointerRepresentation(First));
  152. }
  153. template <typename T> void writePreviousDeclImpl(const Redeclarable<T> *D) {
  154. const T *Prev = D->getPreviousDecl();
  155. if (Prev)
  156. JOS.attribute("previousDecl", createPointerRepresentation(Prev));
  157. }
  158. void addPreviousDeclaration(const Decl *D);
  159. StringRef getCommentCommandName(unsigned CommandID) const;
  160. public:
  161. JSONNodeDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  162. const PrintingPolicy &PrintPolicy,
  163. const comments::CommandTraits *Traits)
  164. : NodeStreamer(OS), SM(SrcMgr), Ctx(Ctx), ASTNameGen(Ctx),
  165. PrintPolicy(PrintPolicy), Traits(Traits), LastLocLine(0),
  166. LastLocPresumedLine(0) {}
  167. void Visit(const Attr *A);
  168. void Visit(const Stmt *Node);
  169. void Visit(const Type *T);
  170. void Visit(QualType T);
  171. void Visit(const Decl *D);
  172. void Visit(const comments::Comment *C, const comments::FullComment *FC);
  173. void Visit(const TemplateArgument &TA, SourceRange R = {},
  174. const Decl *From = nullptr, StringRef Label = {});
  175. void Visit(const CXXCtorInitializer *Init);
  176. void Visit(const OMPClause *C);
  177. void Visit(const BlockDecl::Capture &C);
  178. void Visit(const GenericSelectionExpr::ConstAssociation &A);
  179. void Visit(const concepts::Requirement *R);
  180. void Visit(const APValue &Value, QualType Ty);
  181. void VisitTypedefType(const TypedefType *TT);
  182. void VisitFunctionType(const FunctionType *T);
  183. void VisitFunctionProtoType(const FunctionProtoType *T);
  184. void VisitRValueReferenceType(const ReferenceType *RT);
  185. void VisitArrayType(const ArrayType *AT);
  186. void VisitConstantArrayType(const ConstantArrayType *CAT);
  187. void VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *VT);
  188. void VisitVectorType(const VectorType *VT);
  189. void VisitUnresolvedUsingType(const UnresolvedUsingType *UUT);
  190. void VisitUnaryTransformType(const UnaryTransformType *UTT);
  191. void VisitTagType(const TagType *TT);
  192. void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT);
  193. void VisitAutoType(const AutoType *AT);
  194. void VisitTemplateSpecializationType(const TemplateSpecializationType *TST);
  195. void VisitInjectedClassNameType(const InjectedClassNameType *ICNT);
  196. void VisitObjCInterfaceType(const ObjCInterfaceType *OIT);
  197. void VisitPackExpansionType(const PackExpansionType *PET);
  198. void VisitElaboratedType(const ElaboratedType *ET);
  199. void VisitMacroQualifiedType(const MacroQualifiedType *MQT);
  200. void VisitMemberPointerType(const MemberPointerType *MPT);
  201. void VisitNamedDecl(const NamedDecl *ND);
  202. void VisitTypedefDecl(const TypedefDecl *TD);
  203. void VisitTypeAliasDecl(const TypeAliasDecl *TAD);
  204. void VisitNamespaceDecl(const NamespaceDecl *ND);
  205. void VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD);
  206. void VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD);
  207. void VisitUsingDecl(const UsingDecl *UD);
  208. void VisitUsingEnumDecl(const UsingEnumDecl *UED);
  209. void VisitUsingShadowDecl(const UsingShadowDecl *USD);
  210. void VisitVarDecl(const VarDecl *VD);
  211. void VisitFieldDecl(const FieldDecl *FD);
  212. void VisitFunctionDecl(const FunctionDecl *FD);
  213. void VisitEnumDecl(const EnumDecl *ED);
  214. void VisitEnumConstantDecl(const EnumConstantDecl *ECD);
  215. void VisitRecordDecl(const RecordDecl *RD);
  216. void VisitCXXRecordDecl(const CXXRecordDecl *RD);
  217. void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
  218. void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
  219. void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
  220. void VisitLinkageSpecDecl(const LinkageSpecDecl *LSD);
  221. void VisitAccessSpecDecl(const AccessSpecDecl *ASD);
  222. void VisitFriendDecl(const FriendDecl *FD);
  223. void VisitObjCIvarDecl(const ObjCIvarDecl *D);
  224. void VisitObjCMethodDecl(const ObjCMethodDecl *D);
  225. void VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D);
  226. void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
  227. void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
  228. void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
  229. void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
  230. void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
  231. void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
  232. void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
  233. void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
  234. void VisitBlockDecl(const BlockDecl *D);
  235. void VisitDeclRefExpr(const DeclRefExpr *DRE);
  236. void VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E);
  237. void VisitPredefinedExpr(const PredefinedExpr *PE);
  238. void VisitUnaryOperator(const UnaryOperator *UO);
  239. void VisitBinaryOperator(const BinaryOperator *BO);
  240. void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  241. void VisitMemberExpr(const MemberExpr *ME);
  242. void VisitCXXNewExpr(const CXXNewExpr *NE);
  243. void VisitCXXDeleteExpr(const CXXDeleteExpr *DE);
  244. void VisitCXXThisExpr(const CXXThisExpr *TE);
  245. void VisitCastExpr(const CastExpr *CE);
  246. void VisitImplicitCastExpr(const ImplicitCastExpr *ICE);
  247. void VisitCallExpr(const CallExpr *CE);
  248. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *TTE);
  249. void VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE);
  250. void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *ULE);
  251. void VisitAddrLabelExpr(const AddrLabelExpr *ALE);
  252. void VisitCXXTypeidExpr(const CXXTypeidExpr *CTE);
  253. void VisitConstantExpr(const ConstantExpr *CE);
  254. void VisitInitListExpr(const InitListExpr *ILE);
  255. void VisitGenericSelectionExpr(const GenericSelectionExpr *GSE);
  256. void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *UCE);
  257. void VisitCXXConstructExpr(const CXXConstructExpr *CE);
  258. void VisitExprWithCleanups(const ExprWithCleanups *EWC);
  259. void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE);
  260. void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE);
  261. void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *ME);
  262. void VisitRequiresExpr(const RequiresExpr *RE);
  263. void VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE);
  264. void VisitObjCMessageExpr(const ObjCMessageExpr *OME);
  265. void VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE);
  266. void VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE);
  267. void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE);
  268. void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE);
  269. void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *OSRE);
  270. void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE);
  271. void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE);
  272. void VisitIntegerLiteral(const IntegerLiteral *IL);
  273. void VisitCharacterLiteral(const CharacterLiteral *CL);
  274. void VisitFixedPointLiteral(const FixedPointLiteral *FPL);
  275. void VisitFloatingLiteral(const FloatingLiteral *FL);
  276. void VisitStringLiteral(const StringLiteral *SL);
  277. void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE);
  278. void VisitIfStmt(const IfStmt *IS);
  279. void VisitSwitchStmt(const SwitchStmt *SS);
  280. void VisitCaseStmt(const CaseStmt *CS);
  281. void VisitLabelStmt(const LabelStmt *LS);
  282. void VisitGotoStmt(const GotoStmt *GS);
  283. void VisitWhileStmt(const WhileStmt *WS);
  284. void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *OACS);
  285. void VisitNullTemplateArgument(const TemplateArgument &TA);
  286. void VisitTypeTemplateArgument(const TemplateArgument &TA);
  287. void VisitDeclarationTemplateArgument(const TemplateArgument &TA);
  288. void VisitNullPtrTemplateArgument(const TemplateArgument &TA);
  289. void VisitIntegralTemplateArgument(const TemplateArgument &TA);
  290. void VisitTemplateTemplateArgument(const TemplateArgument &TA);
  291. void VisitTemplateExpansionTemplateArgument(const TemplateArgument &TA);
  292. void VisitExpressionTemplateArgument(const TemplateArgument &TA);
  293. void VisitPackTemplateArgument(const TemplateArgument &TA);
  294. void visitTextComment(const comments::TextComment *C,
  295. const comments::FullComment *);
  296. void visitInlineCommandComment(const comments::InlineCommandComment *C,
  297. const comments::FullComment *);
  298. void visitHTMLStartTagComment(const comments::HTMLStartTagComment *C,
  299. const comments::FullComment *);
  300. void visitHTMLEndTagComment(const comments::HTMLEndTagComment *C,
  301. const comments::FullComment *);
  302. void visitBlockCommandComment(const comments::BlockCommandComment *C,
  303. const comments::FullComment *);
  304. void visitParamCommandComment(const comments::ParamCommandComment *C,
  305. const comments::FullComment *FC);
  306. void visitTParamCommandComment(const comments::TParamCommandComment *C,
  307. const comments::FullComment *FC);
  308. void visitVerbatimBlockComment(const comments::VerbatimBlockComment *C,
  309. const comments::FullComment *);
  310. void
  311. visitVerbatimBlockLineComment(const comments::VerbatimBlockLineComment *C,
  312. const comments::FullComment *);
  313. void visitVerbatimLineComment(const comments::VerbatimLineComment *C,
  314. const comments::FullComment *);
  315. };
  316. class JSONDumper : public ASTNodeTraverser<JSONDumper, JSONNodeDumper> {
  317. JSONNodeDumper NodeDumper;
  318. template <typename SpecializationDecl>
  319. void writeTemplateDeclSpecialization(const SpecializationDecl *SD,
  320. bool DumpExplicitInst,
  321. bool DumpRefOnly) {
  322. bool DumpedAny = false;
  323. for (const auto *RedeclWithBadType : SD->redecls()) {
  324. // FIXME: The redecls() range sometimes has elements of a less-specific
  325. // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives
  326. // us TagDecls, and should give CXXRecordDecls).
  327. const auto *Redecl = dyn_cast<SpecializationDecl>(RedeclWithBadType);
  328. if (!Redecl) {
  329. // Found the injected-class-name for a class template. This will be
  330. // dumped as part of its surrounding class so we don't need to dump it
  331. // here.
  332. assert(isa<CXXRecordDecl>(RedeclWithBadType) &&
  333. "expected an injected-class-name");
  334. continue;
  335. }
  336. switch (Redecl->getTemplateSpecializationKind()) {
  337. case TSK_ExplicitInstantiationDeclaration:
  338. case TSK_ExplicitInstantiationDefinition:
  339. if (!DumpExplicitInst)
  340. break;
  341. LLVM_FALLTHROUGH;
  342. case TSK_Undeclared:
  343. case TSK_ImplicitInstantiation:
  344. if (DumpRefOnly)
  345. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(Redecl); });
  346. else
  347. Visit(Redecl);
  348. DumpedAny = true;
  349. break;
  350. case TSK_ExplicitSpecialization:
  351. break;
  352. }
  353. }
  354. // Ensure we dump at least one decl for each specialization.
  355. if (!DumpedAny)
  356. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(SD); });
  357. }
  358. template <typename TemplateDecl>
  359. void writeTemplateDecl(const TemplateDecl *TD, bool DumpExplicitInst) {
  360. // FIXME: it would be nice to dump template parameters and specializations
  361. // to their own named arrays rather than shoving them into the "inner"
  362. // array. However, template declarations are currently being handled at the
  363. // wrong "level" of the traversal hierarchy and so it is difficult to
  364. // achieve without losing information elsewhere.
  365. dumpTemplateParameters(TD->getTemplateParameters());
  366. Visit(TD->getTemplatedDecl());
  367. for (const auto *Child : TD->specializations())
  368. writeTemplateDeclSpecialization(Child, DumpExplicitInst,
  369. !TD->isCanonicalDecl());
  370. }
  371. public:
  372. JSONDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  373. const PrintingPolicy &PrintPolicy,
  374. const comments::CommandTraits *Traits)
  375. : NodeDumper(OS, SrcMgr, Ctx, PrintPolicy, Traits) {}
  376. JSONNodeDumper &doGetNodeDelegate() { return NodeDumper; }
  377. void VisitFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
  378. writeTemplateDecl(FTD, true);
  379. }
  380. void VisitClassTemplateDecl(const ClassTemplateDecl *CTD) {
  381. writeTemplateDecl(CTD, false);
  382. }
  383. void VisitVarTemplateDecl(const VarTemplateDecl *VTD) {
  384. writeTemplateDecl(VTD, false);
  385. }
  386. };
  387. } // namespace clang
  388. #endif // LLVM_CLANG_AST_JSONNODEDUMPER_H
  389. #ifdef __GNUC__
  390. #pragma GCC diagnostic pop
  391. #endif