JSONNodeDumper.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. llvm::json::Object createFPOptions(FPOptionsOverride FPO);
  143. void writeBareDeclRef(const Decl *D);
  144. llvm::json::Object createCXXRecordDefinitionData(const CXXRecordDecl *RD);
  145. llvm::json::Object createCXXBaseSpecifier(const CXXBaseSpecifier &BS);
  146. std::string createAccessSpecifier(AccessSpecifier AS);
  147. llvm::json::Array createCastPath(const CastExpr *C);
  148. void writePreviousDeclImpl(...) {}
  149. template <typename T> void writePreviousDeclImpl(const Mergeable<T> *D) {
  150. const T *First = D->getFirstDecl();
  151. if (First != D)
  152. JOS.attribute("firstRedecl", createPointerRepresentation(First));
  153. }
  154. template <typename T> void writePreviousDeclImpl(const Redeclarable<T> *D) {
  155. const T *Prev = D->getPreviousDecl();
  156. if (Prev)
  157. JOS.attribute("previousDecl", createPointerRepresentation(Prev));
  158. }
  159. void addPreviousDeclaration(const Decl *D);
  160. StringRef getCommentCommandName(unsigned CommandID) const;
  161. public:
  162. JSONNodeDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  163. const PrintingPolicy &PrintPolicy,
  164. const comments::CommandTraits *Traits)
  165. : NodeStreamer(OS), SM(SrcMgr), Ctx(Ctx), ASTNameGen(Ctx),
  166. PrintPolicy(PrintPolicy), Traits(Traits), LastLocLine(0),
  167. LastLocPresumedLine(0) {}
  168. void Visit(const Attr *A);
  169. void Visit(const Stmt *Node);
  170. void Visit(const Type *T);
  171. void Visit(QualType T);
  172. void Visit(const Decl *D);
  173. void Visit(const comments::Comment *C, const comments::FullComment *FC);
  174. void Visit(const TemplateArgument &TA, SourceRange R = {},
  175. const Decl *From = nullptr, StringRef Label = {});
  176. void Visit(const CXXCtorInitializer *Init);
  177. void Visit(const OMPClause *C);
  178. void Visit(const BlockDecl::Capture &C);
  179. void Visit(const GenericSelectionExpr::ConstAssociation &A);
  180. void Visit(const concepts::Requirement *R);
  181. void Visit(const APValue &Value, QualType Ty);
  182. void VisitTypedefType(const TypedefType *TT);
  183. void VisitUsingType(const UsingType *TT);
  184. void VisitFunctionType(const FunctionType *T);
  185. void VisitFunctionProtoType(const FunctionProtoType *T);
  186. void VisitRValueReferenceType(const ReferenceType *RT);
  187. void VisitArrayType(const ArrayType *AT);
  188. void VisitConstantArrayType(const ConstantArrayType *CAT);
  189. void VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *VT);
  190. void VisitVectorType(const VectorType *VT);
  191. void VisitUnresolvedUsingType(const UnresolvedUsingType *UUT);
  192. void VisitUnaryTransformType(const UnaryTransformType *UTT);
  193. void VisitTagType(const TagType *TT);
  194. void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT);
  195. void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *STTPT);
  196. void
  197. VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T);
  198. void VisitAutoType(const AutoType *AT);
  199. void VisitTemplateSpecializationType(const TemplateSpecializationType *TST);
  200. void VisitInjectedClassNameType(const InjectedClassNameType *ICNT);
  201. void VisitObjCInterfaceType(const ObjCInterfaceType *OIT);
  202. void VisitPackExpansionType(const PackExpansionType *PET);
  203. void VisitElaboratedType(const ElaboratedType *ET);
  204. void VisitMacroQualifiedType(const MacroQualifiedType *MQT);
  205. void VisitMemberPointerType(const MemberPointerType *MPT);
  206. void VisitNamedDecl(const NamedDecl *ND);
  207. void VisitTypedefDecl(const TypedefDecl *TD);
  208. void VisitTypeAliasDecl(const TypeAliasDecl *TAD);
  209. void VisitNamespaceDecl(const NamespaceDecl *ND);
  210. void VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD);
  211. void VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD);
  212. void VisitUsingDecl(const UsingDecl *UD);
  213. void VisitUsingEnumDecl(const UsingEnumDecl *UED);
  214. void VisitUsingShadowDecl(const UsingShadowDecl *USD);
  215. void VisitVarDecl(const VarDecl *VD);
  216. void VisitFieldDecl(const FieldDecl *FD);
  217. void VisitFunctionDecl(const FunctionDecl *FD);
  218. void VisitEnumDecl(const EnumDecl *ED);
  219. void VisitEnumConstantDecl(const EnumConstantDecl *ECD);
  220. void VisitRecordDecl(const RecordDecl *RD);
  221. void VisitCXXRecordDecl(const CXXRecordDecl *RD);
  222. void VisitHLSLBufferDecl(const HLSLBufferDecl *D);
  223. void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
  224. void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
  225. void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
  226. void VisitLinkageSpecDecl(const LinkageSpecDecl *LSD);
  227. void VisitAccessSpecDecl(const AccessSpecDecl *ASD);
  228. void VisitFriendDecl(const FriendDecl *FD);
  229. void VisitObjCIvarDecl(const ObjCIvarDecl *D);
  230. void VisitObjCMethodDecl(const ObjCMethodDecl *D);
  231. void VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D);
  232. void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
  233. void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
  234. void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
  235. void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
  236. void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
  237. void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
  238. void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
  239. void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
  240. void VisitBlockDecl(const BlockDecl *D);
  241. void VisitDeclRefExpr(const DeclRefExpr *DRE);
  242. void VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E);
  243. void VisitPredefinedExpr(const PredefinedExpr *PE);
  244. void VisitUnaryOperator(const UnaryOperator *UO);
  245. void VisitBinaryOperator(const BinaryOperator *BO);
  246. void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
  247. void VisitMemberExpr(const MemberExpr *ME);
  248. void VisitCXXNewExpr(const CXXNewExpr *NE);
  249. void VisitCXXDeleteExpr(const CXXDeleteExpr *DE);
  250. void VisitCXXThisExpr(const CXXThisExpr *TE);
  251. void VisitCastExpr(const CastExpr *CE);
  252. void VisitImplicitCastExpr(const ImplicitCastExpr *ICE);
  253. void VisitCallExpr(const CallExpr *CE);
  254. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *TTE);
  255. void VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE);
  256. void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *ULE);
  257. void VisitAddrLabelExpr(const AddrLabelExpr *ALE);
  258. void VisitCXXTypeidExpr(const CXXTypeidExpr *CTE);
  259. void VisitConstantExpr(const ConstantExpr *CE);
  260. void VisitInitListExpr(const InitListExpr *ILE);
  261. void VisitGenericSelectionExpr(const GenericSelectionExpr *GSE);
  262. void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *UCE);
  263. void VisitCXXConstructExpr(const CXXConstructExpr *CE);
  264. void VisitExprWithCleanups(const ExprWithCleanups *EWC);
  265. void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE);
  266. void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE);
  267. void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *ME);
  268. void VisitRequiresExpr(const RequiresExpr *RE);
  269. void VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE);
  270. void VisitObjCMessageExpr(const ObjCMessageExpr *OME);
  271. void VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE);
  272. void VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE);
  273. void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE);
  274. void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE);
  275. void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *OSRE);
  276. void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE);
  277. void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE);
  278. void VisitIntegerLiteral(const IntegerLiteral *IL);
  279. void VisitCharacterLiteral(const CharacterLiteral *CL);
  280. void VisitFixedPointLiteral(const FixedPointLiteral *FPL);
  281. void VisitFloatingLiteral(const FloatingLiteral *FL);
  282. void VisitStringLiteral(const StringLiteral *SL);
  283. void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE);
  284. void VisitIfStmt(const IfStmt *IS);
  285. void VisitSwitchStmt(const SwitchStmt *SS);
  286. void VisitCaseStmt(const CaseStmt *CS);
  287. void VisitLabelStmt(const LabelStmt *LS);
  288. void VisitGotoStmt(const GotoStmt *GS);
  289. void VisitWhileStmt(const WhileStmt *WS);
  290. void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *OACS);
  291. void VisitCompoundStmt(const CompoundStmt *IS);
  292. void VisitNullTemplateArgument(const TemplateArgument &TA);
  293. void VisitTypeTemplateArgument(const TemplateArgument &TA);
  294. void VisitDeclarationTemplateArgument(const TemplateArgument &TA);
  295. void VisitNullPtrTemplateArgument(const TemplateArgument &TA);
  296. void VisitIntegralTemplateArgument(const TemplateArgument &TA);
  297. void VisitTemplateTemplateArgument(const TemplateArgument &TA);
  298. void VisitTemplateExpansionTemplateArgument(const TemplateArgument &TA);
  299. void VisitExpressionTemplateArgument(const TemplateArgument &TA);
  300. void VisitPackTemplateArgument(const TemplateArgument &TA);
  301. void visitTextComment(const comments::TextComment *C,
  302. const comments::FullComment *);
  303. void visitInlineCommandComment(const comments::InlineCommandComment *C,
  304. const comments::FullComment *);
  305. void visitHTMLStartTagComment(const comments::HTMLStartTagComment *C,
  306. const comments::FullComment *);
  307. void visitHTMLEndTagComment(const comments::HTMLEndTagComment *C,
  308. const comments::FullComment *);
  309. void visitBlockCommandComment(const comments::BlockCommandComment *C,
  310. const comments::FullComment *);
  311. void visitParamCommandComment(const comments::ParamCommandComment *C,
  312. const comments::FullComment *FC);
  313. void visitTParamCommandComment(const comments::TParamCommandComment *C,
  314. const comments::FullComment *FC);
  315. void visitVerbatimBlockComment(const comments::VerbatimBlockComment *C,
  316. const comments::FullComment *);
  317. void
  318. visitVerbatimBlockLineComment(const comments::VerbatimBlockLineComment *C,
  319. const comments::FullComment *);
  320. void visitVerbatimLineComment(const comments::VerbatimLineComment *C,
  321. const comments::FullComment *);
  322. };
  323. class JSONDumper : public ASTNodeTraverser<JSONDumper, JSONNodeDumper> {
  324. JSONNodeDumper NodeDumper;
  325. template <typename SpecializationDecl>
  326. void writeTemplateDeclSpecialization(const SpecializationDecl *SD,
  327. bool DumpExplicitInst,
  328. bool DumpRefOnly) {
  329. bool DumpedAny = false;
  330. for (const auto *RedeclWithBadType : SD->redecls()) {
  331. // FIXME: The redecls() range sometimes has elements of a less-specific
  332. // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives
  333. // us TagDecls, and should give CXXRecordDecls).
  334. const auto *Redecl = dyn_cast<SpecializationDecl>(RedeclWithBadType);
  335. if (!Redecl) {
  336. // Found the injected-class-name for a class template. This will be
  337. // dumped as part of its surrounding class so we don't need to dump it
  338. // here.
  339. assert(isa<CXXRecordDecl>(RedeclWithBadType) &&
  340. "expected an injected-class-name");
  341. continue;
  342. }
  343. switch (Redecl->getTemplateSpecializationKind()) {
  344. case TSK_ExplicitInstantiationDeclaration:
  345. case TSK_ExplicitInstantiationDefinition:
  346. if (!DumpExplicitInst)
  347. break;
  348. [[fallthrough]];
  349. case TSK_Undeclared:
  350. case TSK_ImplicitInstantiation:
  351. if (DumpRefOnly)
  352. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(Redecl); });
  353. else
  354. Visit(Redecl);
  355. DumpedAny = true;
  356. break;
  357. case TSK_ExplicitSpecialization:
  358. break;
  359. }
  360. }
  361. // Ensure we dump at least one decl for each specialization.
  362. if (!DumpedAny)
  363. NodeDumper.AddChild([=] { NodeDumper.writeBareDeclRef(SD); });
  364. }
  365. template <typename TemplateDecl>
  366. void writeTemplateDecl(const TemplateDecl *TD, bool DumpExplicitInst) {
  367. // FIXME: it would be nice to dump template parameters and specializations
  368. // to their own named arrays rather than shoving them into the "inner"
  369. // array. However, template declarations are currently being handled at the
  370. // wrong "level" of the traversal hierarchy and so it is difficult to
  371. // achieve without losing information elsewhere.
  372. dumpTemplateParameters(TD->getTemplateParameters());
  373. Visit(TD->getTemplatedDecl());
  374. for (const auto *Child : TD->specializations())
  375. writeTemplateDeclSpecialization(Child, DumpExplicitInst,
  376. !TD->isCanonicalDecl());
  377. }
  378. public:
  379. JSONDumper(raw_ostream &OS, const SourceManager &SrcMgr, ASTContext &Ctx,
  380. const PrintingPolicy &PrintPolicy,
  381. const comments::CommandTraits *Traits)
  382. : NodeDumper(OS, SrcMgr, Ctx, PrintPolicy, Traits) {}
  383. JSONNodeDumper &doGetNodeDelegate() { return NodeDumper; }
  384. void VisitFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
  385. writeTemplateDecl(FTD, true);
  386. }
  387. void VisitClassTemplateDecl(const ClassTemplateDecl *CTD) {
  388. writeTemplateDecl(CTD, false);
  389. }
  390. void VisitVarTemplateDecl(const VarTemplateDecl *VTD) {
  391. writeTemplateDecl(VTD, false);
  392. }
  393. };
  394. } // namespace clang
  395. #endif // LLVM_CLANG_AST_JSONNODEDUMPER_H
  396. #ifdef __GNUC__
  397. #pragma GCC diagnostic pop
  398. #endif