JSONNodeDumper.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. #include "clang/AST/JSONNodeDumper.h"
  2. #include "clang/AST/Type.h"
  3. #include "clang/Basic/SourceManager.h"
  4. #include "clang/Basic/Specifiers.h"
  5. #include "clang/Lex/Lexer.h"
  6. #include <optional>
  7. using namespace clang;
  8. void JSONNodeDumper::addPreviousDeclaration(const Decl *D) {
  9. switch (D->getKind()) {
  10. #define DECL(DERIVED, BASE) \
  11. case Decl::DERIVED: \
  12. return writePreviousDeclImpl(cast<DERIVED##Decl>(D));
  13. #define ABSTRACT_DECL(DECL)
  14. #include "clang/AST/DeclNodes.inc"
  15. #undef ABSTRACT_DECL
  16. #undef DECL
  17. }
  18. llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
  19. }
  20. void JSONNodeDumper::Visit(const Attr *A) {
  21. const char *AttrName = nullptr;
  22. switch (A->getKind()) {
  23. #define ATTR(X) \
  24. case attr::X: \
  25. AttrName = #X"Attr"; \
  26. break;
  27. #include "clang/Basic/AttrList.inc"
  28. #undef ATTR
  29. }
  30. JOS.attribute("id", createPointerRepresentation(A));
  31. JOS.attribute("kind", AttrName);
  32. JOS.attributeObject("range", [A, this] { writeSourceRange(A->getRange()); });
  33. attributeOnlyIfTrue("inherited", A->isInherited());
  34. attributeOnlyIfTrue("implicit", A->isImplicit());
  35. // FIXME: it would be useful for us to output the spelling kind as well as
  36. // the actual spelling. This would allow us to distinguish between the
  37. // various attribute syntaxes, but we don't currently track that information
  38. // within the AST.
  39. //JOS.attribute("spelling", A->getSpelling());
  40. InnerAttrVisitor::Visit(A);
  41. }
  42. void JSONNodeDumper::Visit(const Stmt *S) {
  43. if (!S)
  44. return;
  45. JOS.attribute("id", createPointerRepresentation(S));
  46. JOS.attribute("kind", S->getStmtClassName());
  47. JOS.attributeObject("range",
  48. [S, this] { writeSourceRange(S->getSourceRange()); });
  49. if (const auto *E = dyn_cast<Expr>(S)) {
  50. JOS.attribute("type", createQualType(E->getType()));
  51. const char *Category = nullptr;
  52. switch (E->getValueKind()) {
  53. case VK_LValue: Category = "lvalue"; break;
  54. case VK_XValue: Category = "xvalue"; break;
  55. case VK_PRValue:
  56. Category = "prvalue";
  57. break;
  58. }
  59. JOS.attribute("valueCategory", Category);
  60. }
  61. InnerStmtVisitor::Visit(S);
  62. }
  63. void JSONNodeDumper::Visit(const Type *T) {
  64. JOS.attribute("id", createPointerRepresentation(T));
  65. if (!T)
  66. return;
  67. JOS.attribute("kind", (llvm::Twine(T->getTypeClassName()) + "Type").str());
  68. JOS.attribute("type", createQualType(QualType(T, 0), /*Desugar*/ false));
  69. attributeOnlyIfTrue("containsErrors", T->containsErrors());
  70. attributeOnlyIfTrue("isDependent", T->isDependentType());
  71. attributeOnlyIfTrue("isInstantiationDependent",
  72. T->isInstantiationDependentType());
  73. attributeOnlyIfTrue("isVariablyModified", T->isVariablyModifiedType());
  74. attributeOnlyIfTrue("containsUnexpandedPack",
  75. T->containsUnexpandedParameterPack());
  76. attributeOnlyIfTrue("isImported", T->isFromAST());
  77. InnerTypeVisitor::Visit(T);
  78. }
  79. void JSONNodeDumper::Visit(QualType T) {
  80. JOS.attribute("id", createPointerRepresentation(T.getAsOpaquePtr()));
  81. JOS.attribute("kind", "QualType");
  82. JOS.attribute("type", createQualType(T));
  83. JOS.attribute("qualifiers", T.split().Quals.getAsString());
  84. }
  85. void JSONNodeDumper::Visit(const Decl *D) {
  86. JOS.attribute("id", createPointerRepresentation(D));
  87. if (!D)
  88. return;
  89. JOS.attribute("kind", (llvm::Twine(D->getDeclKindName()) + "Decl").str());
  90. JOS.attributeObject("loc",
  91. [D, this] { writeSourceLocation(D->getLocation()); });
  92. JOS.attributeObject("range",
  93. [D, this] { writeSourceRange(D->getSourceRange()); });
  94. attributeOnlyIfTrue("isImplicit", D->isImplicit());
  95. attributeOnlyIfTrue("isInvalid", D->isInvalidDecl());
  96. if (D->isUsed())
  97. JOS.attribute("isUsed", true);
  98. else if (D->isThisDeclarationReferenced())
  99. JOS.attribute("isReferenced", true);
  100. if (const auto *ND = dyn_cast<NamedDecl>(D))
  101. attributeOnlyIfTrue("isHidden", !ND->isUnconditionallyVisible());
  102. if (D->getLexicalDeclContext() != D->getDeclContext()) {
  103. // Because of multiple inheritance, a DeclContext pointer does not produce
  104. // the same pointer representation as a Decl pointer that references the
  105. // same AST Node.
  106. const auto *ParentDeclContextDecl = dyn_cast<Decl>(D->getDeclContext());
  107. JOS.attribute("parentDeclContextId",
  108. createPointerRepresentation(ParentDeclContextDecl));
  109. }
  110. addPreviousDeclaration(D);
  111. InnerDeclVisitor::Visit(D);
  112. }
  113. void JSONNodeDumper::Visit(const comments::Comment *C,
  114. const comments::FullComment *FC) {
  115. if (!C)
  116. return;
  117. JOS.attribute("id", createPointerRepresentation(C));
  118. JOS.attribute("kind", C->getCommentKindName());
  119. JOS.attributeObject("loc",
  120. [C, this] { writeSourceLocation(C->getLocation()); });
  121. JOS.attributeObject("range",
  122. [C, this] { writeSourceRange(C->getSourceRange()); });
  123. InnerCommentVisitor::visit(C, FC);
  124. }
  125. void JSONNodeDumper::Visit(const TemplateArgument &TA, SourceRange R,
  126. const Decl *From, StringRef Label) {
  127. JOS.attribute("kind", "TemplateArgument");
  128. if (R.isValid())
  129. JOS.attributeObject("range", [R, this] { writeSourceRange(R); });
  130. if (From)
  131. JOS.attribute(Label.empty() ? "fromDecl" : Label, createBareDeclRef(From));
  132. InnerTemplateArgVisitor::Visit(TA);
  133. }
  134. void JSONNodeDumper::Visit(const CXXCtorInitializer *Init) {
  135. JOS.attribute("kind", "CXXCtorInitializer");
  136. if (Init->isAnyMemberInitializer())
  137. JOS.attribute("anyInit", createBareDeclRef(Init->getAnyMember()));
  138. else if (Init->isBaseInitializer())
  139. JOS.attribute("baseInit",
  140. createQualType(QualType(Init->getBaseClass(), 0)));
  141. else if (Init->isDelegatingInitializer())
  142. JOS.attribute("delegatingInit",
  143. createQualType(Init->getTypeSourceInfo()->getType()));
  144. else
  145. llvm_unreachable("Unknown initializer type");
  146. }
  147. void JSONNodeDumper::Visit(const OMPClause *C) {}
  148. void JSONNodeDumper::Visit(const BlockDecl::Capture &C) {
  149. JOS.attribute("kind", "Capture");
  150. attributeOnlyIfTrue("byref", C.isByRef());
  151. attributeOnlyIfTrue("nested", C.isNested());
  152. if (C.getVariable())
  153. JOS.attribute("var", createBareDeclRef(C.getVariable()));
  154. }
  155. void JSONNodeDumper::Visit(const GenericSelectionExpr::ConstAssociation &A) {
  156. JOS.attribute("associationKind", A.getTypeSourceInfo() ? "case" : "default");
  157. attributeOnlyIfTrue("selected", A.isSelected());
  158. }
  159. void JSONNodeDumper::Visit(const concepts::Requirement *R) {
  160. if (!R)
  161. return;
  162. switch (R->getKind()) {
  163. case concepts::Requirement::RK_Type:
  164. JOS.attribute("kind", "TypeRequirement");
  165. break;
  166. case concepts::Requirement::RK_Simple:
  167. JOS.attribute("kind", "SimpleRequirement");
  168. break;
  169. case concepts::Requirement::RK_Compound:
  170. JOS.attribute("kind", "CompoundRequirement");
  171. break;
  172. case concepts::Requirement::RK_Nested:
  173. JOS.attribute("kind", "NestedRequirement");
  174. break;
  175. }
  176. if (auto *ER = dyn_cast<concepts::ExprRequirement>(R))
  177. attributeOnlyIfTrue("noexcept", ER->hasNoexceptRequirement());
  178. attributeOnlyIfTrue("isDependent", R->isDependent());
  179. if (!R->isDependent())
  180. JOS.attribute("satisfied", R->isSatisfied());
  181. attributeOnlyIfTrue("containsUnexpandedPack",
  182. R->containsUnexpandedParameterPack());
  183. }
  184. void JSONNodeDumper::Visit(const APValue &Value, QualType Ty) {
  185. std::string Str;
  186. llvm::raw_string_ostream OS(Str);
  187. Value.printPretty(OS, Ctx, Ty);
  188. JOS.attribute("value", OS.str());
  189. }
  190. void JSONNodeDumper::writeIncludeStack(PresumedLoc Loc, bool JustFirst) {
  191. if (Loc.isInvalid())
  192. return;
  193. JOS.attributeBegin("includedFrom");
  194. JOS.objectBegin();
  195. if (!JustFirst) {
  196. // Walk the stack recursively, then print out the presumed location.
  197. writeIncludeStack(SM.getPresumedLoc(Loc.getIncludeLoc()));
  198. }
  199. JOS.attribute("file", Loc.getFilename());
  200. JOS.objectEnd();
  201. JOS.attributeEnd();
  202. }
  203. void JSONNodeDumper::writeBareSourceLocation(SourceLocation Loc,
  204. bool IsSpelling) {
  205. PresumedLoc Presumed = SM.getPresumedLoc(Loc);
  206. unsigned ActualLine = IsSpelling ? SM.getSpellingLineNumber(Loc)
  207. : SM.getExpansionLineNumber(Loc);
  208. StringRef ActualFile = SM.getBufferName(Loc);
  209. if (Presumed.isValid()) {
  210. JOS.attribute("offset", SM.getDecomposedLoc(Loc).second);
  211. if (LastLocFilename != ActualFile) {
  212. JOS.attribute("file", ActualFile);
  213. JOS.attribute("line", ActualLine);
  214. } else if (LastLocLine != ActualLine)
  215. JOS.attribute("line", ActualLine);
  216. StringRef PresumedFile = Presumed.getFilename();
  217. if (PresumedFile != ActualFile && LastLocPresumedFilename != PresumedFile)
  218. JOS.attribute("presumedFile", PresumedFile);
  219. unsigned PresumedLine = Presumed.getLine();
  220. if (ActualLine != PresumedLine && LastLocPresumedLine != PresumedLine)
  221. JOS.attribute("presumedLine", PresumedLine);
  222. JOS.attribute("col", Presumed.getColumn());
  223. JOS.attribute("tokLen",
  224. Lexer::MeasureTokenLength(Loc, SM, Ctx.getLangOpts()));
  225. LastLocFilename = ActualFile;
  226. LastLocPresumedFilename = PresumedFile;
  227. LastLocPresumedLine = PresumedLine;
  228. LastLocLine = ActualLine;
  229. // Orthogonal to the file, line, and column de-duplication is whether the
  230. // given location was a result of an include. If so, print where the
  231. // include location came from.
  232. writeIncludeStack(SM.getPresumedLoc(Presumed.getIncludeLoc()),
  233. /*JustFirst*/ true);
  234. }
  235. }
  236. void JSONNodeDumper::writeSourceLocation(SourceLocation Loc) {
  237. SourceLocation Spelling = SM.getSpellingLoc(Loc);
  238. SourceLocation Expansion = SM.getExpansionLoc(Loc);
  239. if (Expansion != Spelling) {
  240. // If the expansion and the spelling are different, output subobjects
  241. // describing both locations.
  242. JOS.attributeObject("spellingLoc", [Spelling, this] {
  243. writeBareSourceLocation(Spelling, /*IsSpelling*/ true);
  244. });
  245. JOS.attributeObject("expansionLoc", [Expansion, Loc, this] {
  246. writeBareSourceLocation(Expansion, /*IsSpelling*/ false);
  247. // If there is a macro expansion, add extra information if the interesting
  248. // bit is the macro arg expansion.
  249. if (SM.isMacroArgExpansion(Loc))
  250. JOS.attribute("isMacroArgExpansion", true);
  251. });
  252. } else
  253. writeBareSourceLocation(Spelling, /*IsSpelling*/ true);
  254. }
  255. void JSONNodeDumper::writeSourceRange(SourceRange R) {
  256. JOS.attributeObject("begin",
  257. [R, this] { writeSourceLocation(R.getBegin()); });
  258. JOS.attributeObject("end", [R, this] { writeSourceLocation(R.getEnd()); });
  259. }
  260. std::string JSONNodeDumper::createPointerRepresentation(const void *Ptr) {
  261. // Because JSON stores integer values as signed 64-bit integers, trying to
  262. // represent them as such makes for very ugly pointer values in the resulting
  263. // output. Instead, we convert the value to hex and treat it as a string.
  264. return "0x" + llvm::utohexstr(reinterpret_cast<uint64_t>(Ptr), true);
  265. }
  266. llvm::json::Object JSONNodeDumper::createQualType(QualType QT, bool Desugar) {
  267. SplitQualType SQT = QT.split();
  268. llvm::json::Object Ret{{"qualType", QualType::getAsString(SQT, PrintPolicy)}};
  269. if (Desugar && !QT.isNull()) {
  270. SplitQualType DSQT = QT.getSplitDesugaredType();
  271. if (DSQT != SQT)
  272. Ret["desugaredQualType"] = QualType::getAsString(DSQT, PrintPolicy);
  273. if (const auto *TT = QT->getAs<TypedefType>())
  274. Ret["typeAliasDeclId"] = createPointerRepresentation(TT->getDecl());
  275. }
  276. return Ret;
  277. }
  278. void JSONNodeDumper::writeBareDeclRef(const Decl *D) {
  279. JOS.attribute("id", createPointerRepresentation(D));
  280. if (!D)
  281. return;
  282. JOS.attribute("kind", (llvm::Twine(D->getDeclKindName()) + "Decl").str());
  283. if (const auto *ND = dyn_cast<NamedDecl>(D))
  284. JOS.attribute("name", ND->getDeclName().getAsString());
  285. if (const auto *VD = dyn_cast<ValueDecl>(D))
  286. JOS.attribute("type", createQualType(VD->getType()));
  287. }
  288. llvm::json::Object JSONNodeDumper::createBareDeclRef(const Decl *D) {
  289. llvm::json::Object Ret{{"id", createPointerRepresentation(D)}};
  290. if (!D)
  291. return Ret;
  292. Ret["kind"] = (llvm::Twine(D->getDeclKindName()) + "Decl").str();
  293. if (const auto *ND = dyn_cast<NamedDecl>(D))
  294. Ret["name"] = ND->getDeclName().getAsString();
  295. if (const auto *VD = dyn_cast<ValueDecl>(D))
  296. Ret["type"] = createQualType(VD->getType());
  297. return Ret;
  298. }
  299. llvm::json::Array JSONNodeDumper::createCastPath(const CastExpr *C) {
  300. llvm::json::Array Ret;
  301. if (C->path_empty())
  302. return Ret;
  303. for (auto I = C->path_begin(), E = C->path_end(); I != E; ++I) {
  304. const CXXBaseSpecifier *Base = *I;
  305. const auto *RD =
  306. cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
  307. llvm::json::Object Val{{"name", RD->getName()}};
  308. if (Base->isVirtual())
  309. Val["isVirtual"] = true;
  310. Ret.push_back(std::move(Val));
  311. }
  312. return Ret;
  313. }
  314. #define FIELD2(Name, Flag) if (RD->Flag()) Ret[Name] = true
  315. #define FIELD1(Flag) FIELD2(#Flag, Flag)
  316. static llvm::json::Object
  317. createDefaultConstructorDefinitionData(const CXXRecordDecl *RD) {
  318. llvm::json::Object Ret;
  319. FIELD2("exists", hasDefaultConstructor);
  320. FIELD2("trivial", hasTrivialDefaultConstructor);
  321. FIELD2("nonTrivial", hasNonTrivialDefaultConstructor);
  322. FIELD2("userProvided", hasUserProvidedDefaultConstructor);
  323. FIELD2("isConstexpr", hasConstexprDefaultConstructor);
  324. FIELD2("needsImplicit", needsImplicitDefaultConstructor);
  325. FIELD2("defaultedIsConstexpr", defaultedDefaultConstructorIsConstexpr);
  326. return Ret;
  327. }
  328. static llvm::json::Object
  329. createCopyConstructorDefinitionData(const CXXRecordDecl *RD) {
  330. llvm::json::Object Ret;
  331. FIELD2("simple", hasSimpleCopyConstructor);
  332. FIELD2("trivial", hasTrivialCopyConstructor);
  333. FIELD2("nonTrivial", hasNonTrivialCopyConstructor);
  334. FIELD2("userDeclared", hasUserDeclaredCopyConstructor);
  335. FIELD2("hasConstParam", hasCopyConstructorWithConstParam);
  336. FIELD2("implicitHasConstParam", implicitCopyConstructorHasConstParam);
  337. FIELD2("needsImplicit", needsImplicitCopyConstructor);
  338. FIELD2("needsOverloadResolution", needsOverloadResolutionForCopyConstructor);
  339. if (!RD->needsOverloadResolutionForCopyConstructor())
  340. FIELD2("defaultedIsDeleted", defaultedCopyConstructorIsDeleted);
  341. return Ret;
  342. }
  343. static llvm::json::Object
  344. createMoveConstructorDefinitionData(const CXXRecordDecl *RD) {
  345. llvm::json::Object Ret;
  346. FIELD2("exists", hasMoveConstructor);
  347. FIELD2("simple", hasSimpleMoveConstructor);
  348. FIELD2("trivial", hasTrivialMoveConstructor);
  349. FIELD2("nonTrivial", hasNonTrivialMoveConstructor);
  350. FIELD2("userDeclared", hasUserDeclaredMoveConstructor);
  351. FIELD2("needsImplicit", needsImplicitMoveConstructor);
  352. FIELD2("needsOverloadResolution", needsOverloadResolutionForMoveConstructor);
  353. if (!RD->needsOverloadResolutionForMoveConstructor())
  354. FIELD2("defaultedIsDeleted", defaultedMoveConstructorIsDeleted);
  355. return Ret;
  356. }
  357. static llvm::json::Object
  358. createCopyAssignmentDefinitionData(const CXXRecordDecl *RD) {
  359. llvm::json::Object Ret;
  360. FIELD2("simple", hasSimpleCopyAssignment);
  361. FIELD2("trivial", hasTrivialCopyAssignment);
  362. FIELD2("nonTrivial", hasNonTrivialCopyAssignment);
  363. FIELD2("hasConstParam", hasCopyAssignmentWithConstParam);
  364. FIELD2("implicitHasConstParam", implicitCopyAssignmentHasConstParam);
  365. FIELD2("userDeclared", hasUserDeclaredCopyAssignment);
  366. FIELD2("needsImplicit", needsImplicitCopyAssignment);
  367. FIELD2("needsOverloadResolution", needsOverloadResolutionForCopyAssignment);
  368. return Ret;
  369. }
  370. static llvm::json::Object
  371. createMoveAssignmentDefinitionData(const CXXRecordDecl *RD) {
  372. llvm::json::Object Ret;
  373. FIELD2("exists", hasMoveAssignment);
  374. FIELD2("simple", hasSimpleMoveAssignment);
  375. FIELD2("trivial", hasTrivialMoveAssignment);
  376. FIELD2("nonTrivial", hasNonTrivialMoveAssignment);
  377. FIELD2("userDeclared", hasUserDeclaredMoveAssignment);
  378. FIELD2("needsImplicit", needsImplicitMoveAssignment);
  379. FIELD2("needsOverloadResolution", needsOverloadResolutionForMoveAssignment);
  380. return Ret;
  381. }
  382. static llvm::json::Object
  383. createDestructorDefinitionData(const CXXRecordDecl *RD) {
  384. llvm::json::Object Ret;
  385. FIELD2("simple", hasSimpleDestructor);
  386. FIELD2("irrelevant", hasIrrelevantDestructor);
  387. FIELD2("trivial", hasTrivialDestructor);
  388. FIELD2("nonTrivial", hasNonTrivialDestructor);
  389. FIELD2("userDeclared", hasUserDeclaredDestructor);
  390. FIELD2("needsImplicit", needsImplicitDestructor);
  391. FIELD2("needsOverloadResolution", needsOverloadResolutionForDestructor);
  392. if (!RD->needsOverloadResolutionForDestructor())
  393. FIELD2("defaultedIsDeleted", defaultedDestructorIsDeleted);
  394. return Ret;
  395. }
  396. llvm::json::Object
  397. JSONNodeDumper::createCXXRecordDefinitionData(const CXXRecordDecl *RD) {
  398. llvm::json::Object Ret;
  399. // This data is common to all C++ classes.
  400. FIELD1(isGenericLambda);
  401. FIELD1(isLambda);
  402. FIELD1(isEmpty);
  403. FIELD1(isAggregate);
  404. FIELD1(isStandardLayout);
  405. FIELD1(isTriviallyCopyable);
  406. FIELD1(isPOD);
  407. FIELD1(isTrivial);
  408. FIELD1(isPolymorphic);
  409. FIELD1(isAbstract);
  410. FIELD1(isLiteral);
  411. FIELD1(canPassInRegisters);
  412. FIELD1(hasUserDeclaredConstructor);
  413. FIELD1(hasConstexprNonCopyMoveConstructor);
  414. FIELD1(hasMutableFields);
  415. FIELD1(hasVariantMembers);
  416. FIELD2("canConstDefaultInit", allowConstDefaultInit);
  417. Ret["defaultCtor"] = createDefaultConstructorDefinitionData(RD);
  418. Ret["copyCtor"] = createCopyConstructorDefinitionData(RD);
  419. Ret["moveCtor"] = createMoveConstructorDefinitionData(RD);
  420. Ret["copyAssign"] = createCopyAssignmentDefinitionData(RD);
  421. Ret["moveAssign"] = createMoveAssignmentDefinitionData(RD);
  422. Ret["dtor"] = createDestructorDefinitionData(RD);
  423. return Ret;
  424. }
  425. #undef FIELD1
  426. #undef FIELD2
  427. std::string JSONNodeDumper::createAccessSpecifier(AccessSpecifier AS) {
  428. const auto AccessSpelling = getAccessSpelling(AS);
  429. if (AccessSpelling.empty())
  430. return "none";
  431. return AccessSpelling.str();
  432. }
  433. llvm::json::Object
  434. JSONNodeDumper::createCXXBaseSpecifier(const CXXBaseSpecifier &BS) {
  435. llvm::json::Object Ret;
  436. Ret["type"] = createQualType(BS.getType());
  437. Ret["access"] = createAccessSpecifier(BS.getAccessSpecifier());
  438. Ret["writtenAccess"] =
  439. createAccessSpecifier(BS.getAccessSpecifierAsWritten());
  440. if (BS.isVirtual())
  441. Ret["isVirtual"] = true;
  442. if (BS.isPackExpansion())
  443. Ret["isPackExpansion"] = true;
  444. return Ret;
  445. }
  446. void JSONNodeDumper::VisitTypedefType(const TypedefType *TT) {
  447. JOS.attribute("decl", createBareDeclRef(TT->getDecl()));
  448. if (!TT->typeMatchesDecl())
  449. JOS.attribute("type", createQualType(TT->desugar()));
  450. }
  451. void JSONNodeDumper::VisitUsingType(const UsingType *TT) {
  452. JOS.attribute("decl", createBareDeclRef(TT->getFoundDecl()));
  453. if (!TT->typeMatchesDecl())
  454. JOS.attribute("type", createQualType(TT->desugar()));
  455. }
  456. void JSONNodeDumper::VisitFunctionType(const FunctionType *T) {
  457. FunctionType::ExtInfo E = T->getExtInfo();
  458. attributeOnlyIfTrue("noreturn", E.getNoReturn());
  459. attributeOnlyIfTrue("producesResult", E.getProducesResult());
  460. if (E.getHasRegParm())
  461. JOS.attribute("regParm", E.getRegParm());
  462. JOS.attribute("cc", FunctionType::getNameForCallConv(E.getCC()));
  463. }
  464. void JSONNodeDumper::VisitFunctionProtoType(const FunctionProtoType *T) {
  465. FunctionProtoType::ExtProtoInfo E = T->getExtProtoInfo();
  466. attributeOnlyIfTrue("trailingReturn", E.HasTrailingReturn);
  467. attributeOnlyIfTrue("const", T->isConst());
  468. attributeOnlyIfTrue("volatile", T->isVolatile());
  469. attributeOnlyIfTrue("restrict", T->isRestrict());
  470. attributeOnlyIfTrue("variadic", E.Variadic);
  471. switch (E.RefQualifier) {
  472. case RQ_LValue: JOS.attribute("refQualifier", "&"); break;
  473. case RQ_RValue: JOS.attribute("refQualifier", "&&"); break;
  474. case RQ_None: break;
  475. }
  476. switch (E.ExceptionSpec.Type) {
  477. case EST_DynamicNone:
  478. case EST_Dynamic: {
  479. JOS.attribute("exceptionSpec", "throw");
  480. llvm::json::Array Types;
  481. for (QualType QT : E.ExceptionSpec.Exceptions)
  482. Types.push_back(createQualType(QT));
  483. JOS.attribute("exceptionTypes", std::move(Types));
  484. } break;
  485. case EST_MSAny:
  486. JOS.attribute("exceptionSpec", "throw");
  487. JOS.attribute("throwsAny", true);
  488. break;
  489. case EST_BasicNoexcept:
  490. JOS.attribute("exceptionSpec", "noexcept");
  491. break;
  492. case EST_NoexceptTrue:
  493. case EST_NoexceptFalse:
  494. JOS.attribute("exceptionSpec", "noexcept");
  495. JOS.attribute("conditionEvaluatesTo",
  496. E.ExceptionSpec.Type == EST_NoexceptTrue);
  497. //JOS.attributeWithCall("exceptionSpecExpr",
  498. // [this, E]() { Visit(E.ExceptionSpec.NoexceptExpr); });
  499. break;
  500. case EST_NoThrow:
  501. JOS.attribute("exceptionSpec", "nothrow");
  502. break;
  503. // FIXME: I cannot find a way to trigger these cases while dumping the AST. I
  504. // suspect you can only run into them when executing an AST dump from within
  505. // the debugger, which is not a use case we worry about for the JSON dumping
  506. // feature.
  507. case EST_DependentNoexcept:
  508. case EST_Unevaluated:
  509. case EST_Uninstantiated:
  510. case EST_Unparsed:
  511. case EST_None: break;
  512. }
  513. VisitFunctionType(T);
  514. }
  515. void JSONNodeDumper::VisitRValueReferenceType(const ReferenceType *RT) {
  516. attributeOnlyIfTrue("spelledAsLValue", RT->isSpelledAsLValue());
  517. }
  518. void JSONNodeDumper::VisitArrayType(const ArrayType *AT) {
  519. switch (AT->getSizeModifier()) {
  520. case ArrayType::Star:
  521. JOS.attribute("sizeModifier", "*");
  522. break;
  523. case ArrayType::Static:
  524. JOS.attribute("sizeModifier", "static");
  525. break;
  526. case ArrayType::Normal:
  527. break;
  528. }
  529. std::string Str = AT->getIndexTypeQualifiers().getAsString();
  530. if (!Str.empty())
  531. JOS.attribute("indexTypeQualifiers", Str);
  532. }
  533. void JSONNodeDumper::VisitConstantArrayType(const ConstantArrayType *CAT) {
  534. // FIXME: this should use ZExt instead of SExt, but JSON doesn't allow a
  535. // narrowing conversion to int64_t so it cannot be expressed.
  536. JOS.attribute("size", CAT->getSize().getSExtValue());
  537. VisitArrayType(CAT);
  538. }
  539. void JSONNodeDumper::VisitDependentSizedExtVectorType(
  540. const DependentSizedExtVectorType *VT) {
  541. JOS.attributeObject(
  542. "attrLoc", [VT, this] { writeSourceLocation(VT->getAttributeLoc()); });
  543. }
  544. void JSONNodeDumper::VisitVectorType(const VectorType *VT) {
  545. JOS.attribute("numElements", VT->getNumElements());
  546. switch (VT->getVectorKind()) {
  547. case VectorType::GenericVector:
  548. break;
  549. case VectorType::AltiVecVector:
  550. JOS.attribute("vectorKind", "altivec");
  551. break;
  552. case VectorType::AltiVecPixel:
  553. JOS.attribute("vectorKind", "altivec pixel");
  554. break;
  555. case VectorType::AltiVecBool:
  556. JOS.attribute("vectorKind", "altivec bool");
  557. break;
  558. case VectorType::NeonVector:
  559. JOS.attribute("vectorKind", "neon");
  560. break;
  561. case VectorType::NeonPolyVector:
  562. JOS.attribute("vectorKind", "neon poly");
  563. break;
  564. case VectorType::SveFixedLengthDataVector:
  565. JOS.attribute("vectorKind", "fixed-length sve data vector");
  566. break;
  567. case VectorType::SveFixedLengthPredicateVector:
  568. JOS.attribute("vectorKind", "fixed-length sve predicate vector");
  569. break;
  570. }
  571. }
  572. void JSONNodeDumper::VisitUnresolvedUsingType(const UnresolvedUsingType *UUT) {
  573. JOS.attribute("decl", createBareDeclRef(UUT->getDecl()));
  574. }
  575. void JSONNodeDumper::VisitUnaryTransformType(const UnaryTransformType *UTT) {
  576. switch (UTT->getUTTKind()) {
  577. #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
  578. case UnaryTransformType::Enum: \
  579. JOS.attribute("transformKind", #Trait); \
  580. break;
  581. #include "clang/Basic/TransformTypeTraits.def"
  582. }
  583. }
  584. void JSONNodeDumper::VisitTagType(const TagType *TT) {
  585. JOS.attribute("decl", createBareDeclRef(TT->getDecl()));
  586. }
  587. void JSONNodeDumper::VisitTemplateTypeParmType(
  588. const TemplateTypeParmType *TTPT) {
  589. JOS.attribute("depth", TTPT->getDepth());
  590. JOS.attribute("index", TTPT->getIndex());
  591. attributeOnlyIfTrue("isPack", TTPT->isParameterPack());
  592. JOS.attribute("decl", createBareDeclRef(TTPT->getDecl()));
  593. }
  594. void JSONNodeDumper::VisitSubstTemplateTypeParmType(
  595. const SubstTemplateTypeParmType *STTPT) {
  596. JOS.attribute("index", STTPT->getIndex());
  597. if (auto PackIndex = STTPT->getPackIndex())
  598. JOS.attribute("pack_index", *PackIndex);
  599. }
  600. void JSONNodeDumper::VisitSubstTemplateTypeParmPackType(
  601. const SubstTemplateTypeParmPackType *T) {
  602. JOS.attribute("index", T->getIndex());
  603. }
  604. void JSONNodeDumper::VisitAutoType(const AutoType *AT) {
  605. JOS.attribute("undeduced", !AT->isDeduced());
  606. switch (AT->getKeyword()) {
  607. case AutoTypeKeyword::Auto:
  608. JOS.attribute("typeKeyword", "auto");
  609. break;
  610. case AutoTypeKeyword::DecltypeAuto:
  611. JOS.attribute("typeKeyword", "decltype(auto)");
  612. break;
  613. case AutoTypeKeyword::GNUAutoType:
  614. JOS.attribute("typeKeyword", "__auto_type");
  615. break;
  616. }
  617. }
  618. void JSONNodeDumper::VisitTemplateSpecializationType(
  619. const TemplateSpecializationType *TST) {
  620. attributeOnlyIfTrue("isAlias", TST->isTypeAlias());
  621. std::string Str;
  622. llvm::raw_string_ostream OS(Str);
  623. TST->getTemplateName().print(OS, PrintPolicy);
  624. JOS.attribute("templateName", OS.str());
  625. }
  626. void JSONNodeDumper::VisitInjectedClassNameType(
  627. const InjectedClassNameType *ICNT) {
  628. JOS.attribute("decl", createBareDeclRef(ICNT->getDecl()));
  629. }
  630. void JSONNodeDumper::VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
  631. JOS.attribute("decl", createBareDeclRef(OIT->getDecl()));
  632. }
  633. void JSONNodeDumper::VisitPackExpansionType(const PackExpansionType *PET) {
  634. if (std::optional<unsigned> N = PET->getNumExpansions())
  635. JOS.attribute("numExpansions", *N);
  636. }
  637. void JSONNodeDumper::VisitElaboratedType(const ElaboratedType *ET) {
  638. if (const NestedNameSpecifier *NNS = ET->getQualifier()) {
  639. std::string Str;
  640. llvm::raw_string_ostream OS(Str);
  641. NNS->print(OS, PrintPolicy, /*ResolveTemplateArgs*/ true);
  642. JOS.attribute("qualifier", OS.str());
  643. }
  644. if (const TagDecl *TD = ET->getOwnedTagDecl())
  645. JOS.attribute("ownedTagDecl", createBareDeclRef(TD));
  646. }
  647. void JSONNodeDumper::VisitMacroQualifiedType(const MacroQualifiedType *MQT) {
  648. JOS.attribute("macroName", MQT->getMacroIdentifier()->getName());
  649. }
  650. void JSONNodeDumper::VisitMemberPointerType(const MemberPointerType *MPT) {
  651. attributeOnlyIfTrue("isData", MPT->isMemberDataPointer());
  652. attributeOnlyIfTrue("isFunction", MPT->isMemberFunctionPointer());
  653. }
  654. void JSONNodeDumper::VisitNamedDecl(const NamedDecl *ND) {
  655. if (ND && ND->getDeclName()) {
  656. JOS.attribute("name", ND->getNameAsString());
  657. // FIXME: There are likely other contexts in which it makes no sense to ask
  658. // for a mangled name.
  659. if (isa<RequiresExprBodyDecl>(ND->getDeclContext()))
  660. return;
  661. // Mangled names are not meaningful for locals, and may not be well-defined
  662. // in the case of VLAs.
  663. auto *VD = dyn_cast<VarDecl>(ND);
  664. if (VD && VD->hasLocalStorage())
  665. return;
  666. std::string MangledName = ASTNameGen.getName(ND);
  667. if (!MangledName.empty())
  668. JOS.attribute("mangledName", MangledName);
  669. }
  670. }
  671. void JSONNodeDumper::VisitTypedefDecl(const TypedefDecl *TD) {
  672. VisitNamedDecl(TD);
  673. JOS.attribute("type", createQualType(TD->getUnderlyingType()));
  674. }
  675. void JSONNodeDumper::VisitTypeAliasDecl(const TypeAliasDecl *TAD) {
  676. VisitNamedDecl(TAD);
  677. JOS.attribute("type", createQualType(TAD->getUnderlyingType()));
  678. }
  679. void JSONNodeDumper::VisitNamespaceDecl(const NamespaceDecl *ND) {
  680. VisitNamedDecl(ND);
  681. attributeOnlyIfTrue("isInline", ND->isInline());
  682. attributeOnlyIfTrue("isNested", ND->isNested());
  683. if (!ND->isOriginalNamespace())
  684. JOS.attribute("originalNamespace",
  685. createBareDeclRef(ND->getOriginalNamespace()));
  686. }
  687. void JSONNodeDumper::VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD) {
  688. JOS.attribute("nominatedNamespace",
  689. createBareDeclRef(UDD->getNominatedNamespace()));
  690. }
  691. void JSONNodeDumper::VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD) {
  692. VisitNamedDecl(NAD);
  693. JOS.attribute("aliasedNamespace",
  694. createBareDeclRef(NAD->getAliasedNamespace()));
  695. }
  696. void JSONNodeDumper::VisitUsingDecl(const UsingDecl *UD) {
  697. std::string Name;
  698. if (const NestedNameSpecifier *NNS = UD->getQualifier()) {
  699. llvm::raw_string_ostream SOS(Name);
  700. NNS->print(SOS, UD->getASTContext().getPrintingPolicy());
  701. }
  702. Name += UD->getNameAsString();
  703. JOS.attribute("name", Name);
  704. }
  705. void JSONNodeDumper::VisitUsingEnumDecl(const UsingEnumDecl *UED) {
  706. JOS.attribute("target", createBareDeclRef(UED->getEnumDecl()));
  707. }
  708. void JSONNodeDumper::VisitUsingShadowDecl(const UsingShadowDecl *USD) {
  709. JOS.attribute("target", createBareDeclRef(USD->getTargetDecl()));
  710. }
  711. void JSONNodeDumper::VisitVarDecl(const VarDecl *VD) {
  712. VisitNamedDecl(VD);
  713. JOS.attribute("type", createQualType(VD->getType()));
  714. StorageClass SC = VD->getStorageClass();
  715. if (SC != SC_None)
  716. JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
  717. switch (VD->getTLSKind()) {
  718. case VarDecl::TLS_Dynamic: JOS.attribute("tls", "dynamic"); break;
  719. case VarDecl::TLS_Static: JOS.attribute("tls", "static"); break;
  720. case VarDecl::TLS_None: break;
  721. }
  722. attributeOnlyIfTrue("nrvo", VD->isNRVOVariable());
  723. attributeOnlyIfTrue("inline", VD->isInline());
  724. attributeOnlyIfTrue("constexpr", VD->isConstexpr());
  725. attributeOnlyIfTrue("modulePrivate", VD->isModulePrivate());
  726. if (VD->hasInit()) {
  727. switch (VD->getInitStyle()) {
  728. case VarDecl::CInit: JOS.attribute("init", "c"); break;
  729. case VarDecl::CallInit: JOS.attribute("init", "call"); break;
  730. case VarDecl::ListInit: JOS.attribute("init", "list"); break;
  731. case VarDecl::ParenListInit:
  732. JOS.attribute("init", "paren-list");
  733. break;
  734. }
  735. }
  736. attributeOnlyIfTrue("isParameterPack", VD->isParameterPack());
  737. }
  738. void JSONNodeDumper::VisitFieldDecl(const FieldDecl *FD) {
  739. VisitNamedDecl(FD);
  740. JOS.attribute("type", createQualType(FD->getType()));
  741. attributeOnlyIfTrue("mutable", FD->isMutable());
  742. attributeOnlyIfTrue("modulePrivate", FD->isModulePrivate());
  743. attributeOnlyIfTrue("isBitfield", FD->isBitField());
  744. attributeOnlyIfTrue("hasInClassInitializer", FD->hasInClassInitializer());
  745. }
  746. void JSONNodeDumper::VisitFunctionDecl(const FunctionDecl *FD) {
  747. VisitNamedDecl(FD);
  748. JOS.attribute("type", createQualType(FD->getType()));
  749. StorageClass SC = FD->getStorageClass();
  750. if (SC != SC_None)
  751. JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
  752. attributeOnlyIfTrue("inline", FD->isInlineSpecified());
  753. attributeOnlyIfTrue("virtual", FD->isVirtualAsWritten());
  754. attributeOnlyIfTrue("pure", FD->isPure());
  755. attributeOnlyIfTrue("explicitlyDeleted", FD->isDeletedAsWritten());
  756. attributeOnlyIfTrue("constexpr", FD->isConstexpr());
  757. attributeOnlyIfTrue("variadic", FD->isVariadic());
  758. if (FD->isDefaulted())
  759. JOS.attribute("explicitlyDefaulted",
  760. FD->isDeleted() ? "deleted" : "default");
  761. }
  762. void JSONNodeDumper::VisitEnumDecl(const EnumDecl *ED) {
  763. VisitNamedDecl(ED);
  764. if (ED->isFixed())
  765. JOS.attribute("fixedUnderlyingType", createQualType(ED->getIntegerType()));
  766. if (ED->isScoped())
  767. JOS.attribute("scopedEnumTag",
  768. ED->isScopedUsingClassTag() ? "class" : "struct");
  769. }
  770. void JSONNodeDumper::VisitEnumConstantDecl(const EnumConstantDecl *ECD) {
  771. VisitNamedDecl(ECD);
  772. JOS.attribute("type", createQualType(ECD->getType()));
  773. }
  774. void JSONNodeDumper::VisitRecordDecl(const RecordDecl *RD) {
  775. VisitNamedDecl(RD);
  776. JOS.attribute("tagUsed", RD->getKindName());
  777. attributeOnlyIfTrue("completeDefinition", RD->isCompleteDefinition());
  778. }
  779. void JSONNodeDumper::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
  780. VisitRecordDecl(RD);
  781. // All other information requires a complete definition.
  782. if (!RD->isCompleteDefinition())
  783. return;
  784. JOS.attribute("definitionData", createCXXRecordDefinitionData(RD));
  785. if (RD->getNumBases()) {
  786. JOS.attributeArray("bases", [this, RD] {
  787. for (const auto &Spec : RD->bases())
  788. JOS.value(createCXXBaseSpecifier(Spec));
  789. });
  790. }
  791. }
  792. void JSONNodeDumper::VisitHLSLBufferDecl(const HLSLBufferDecl *D) {
  793. VisitNamedDecl(D);
  794. JOS.attribute("bufferKind", D->isCBuffer() ? "cbuffer" : "tbuffer");
  795. }
  796. void JSONNodeDumper::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
  797. VisitNamedDecl(D);
  798. JOS.attribute("tagUsed", D->wasDeclaredWithTypename() ? "typename" : "class");
  799. JOS.attribute("depth", D->getDepth());
  800. JOS.attribute("index", D->getIndex());
  801. attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
  802. if (D->hasDefaultArgument())
  803. JOS.attributeObject("defaultArg", [=] {
  804. Visit(D->getDefaultArgument(), SourceRange(),
  805. D->getDefaultArgStorage().getInheritedFrom(),
  806. D->defaultArgumentWasInherited() ? "inherited from" : "previous");
  807. });
  808. }
  809. void JSONNodeDumper::VisitNonTypeTemplateParmDecl(
  810. const NonTypeTemplateParmDecl *D) {
  811. VisitNamedDecl(D);
  812. JOS.attribute("type", createQualType(D->getType()));
  813. JOS.attribute("depth", D->getDepth());
  814. JOS.attribute("index", D->getIndex());
  815. attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
  816. if (D->hasDefaultArgument())
  817. JOS.attributeObject("defaultArg", [=] {
  818. Visit(D->getDefaultArgument(), SourceRange(),
  819. D->getDefaultArgStorage().getInheritedFrom(),
  820. D->defaultArgumentWasInherited() ? "inherited from" : "previous");
  821. });
  822. }
  823. void JSONNodeDumper::VisitTemplateTemplateParmDecl(
  824. const TemplateTemplateParmDecl *D) {
  825. VisitNamedDecl(D);
  826. JOS.attribute("depth", D->getDepth());
  827. JOS.attribute("index", D->getIndex());
  828. attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
  829. if (D->hasDefaultArgument())
  830. JOS.attributeObject("defaultArg", [=] {
  831. const auto *InheritedFrom = D->getDefaultArgStorage().getInheritedFrom();
  832. Visit(D->getDefaultArgument().getArgument(),
  833. InheritedFrom ? InheritedFrom->getSourceRange() : SourceLocation{},
  834. InheritedFrom,
  835. D->defaultArgumentWasInherited() ? "inherited from" : "previous");
  836. });
  837. }
  838. void JSONNodeDumper::VisitLinkageSpecDecl(const LinkageSpecDecl *LSD) {
  839. StringRef Lang;
  840. switch (LSD->getLanguage()) {
  841. case LinkageSpecDecl::lang_c: Lang = "C"; break;
  842. case LinkageSpecDecl::lang_cxx: Lang = "C++"; break;
  843. }
  844. JOS.attribute("language", Lang);
  845. attributeOnlyIfTrue("hasBraces", LSD->hasBraces());
  846. }
  847. void JSONNodeDumper::VisitAccessSpecDecl(const AccessSpecDecl *ASD) {
  848. JOS.attribute("access", createAccessSpecifier(ASD->getAccess()));
  849. }
  850. void JSONNodeDumper::VisitFriendDecl(const FriendDecl *FD) {
  851. if (const TypeSourceInfo *T = FD->getFriendType())
  852. JOS.attribute("type", createQualType(T->getType()));
  853. }
  854. void JSONNodeDumper::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
  855. VisitNamedDecl(D);
  856. JOS.attribute("type", createQualType(D->getType()));
  857. attributeOnlyIfTrue("synthesized", D->getSynthesize());
  858. switch (D->getAccessControl()) {
  859. case ObjCIvarDecl::None: JOS.attribute("access", "none"); break;
  860. case ObjCIvarDecl::Private: JOS.attribute("access", "private"); break;
  861. case ObjCIvarDecl::Protected: JOS.attribute("access", "protected"); break;
  862. case ObjCIvarDecl::Public: JOS.attribute("access", "public"); break;
  863. case ObjCIvarDecl::Package: JOS.attribute("access", "package"); break;
  864. }
  865. }
  866. void JSONNodeDumper::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
  867. VisitNamedDecl(D);
  868. JOS.attribute("returnType", createQualType(D->getReturnType()));
  869. JOS.attribute("instance", D->isInstanceMethod());
  870. attributeOnlyIfTrue("variadic", D->isVariadic());
  871. }
  872. void JSONNodeDumper::VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D) {
  873. VisitNamedDecl(D);
  874. JOS.attribute("type", createQualType(D->getUnderlyingType()));
  875. attributeOnlyIfTrue("bounded", D->hasExplicitBound());
  876. switch (D->getVariance()) {
  877. case ObjCTypeParamVariance::Invariant:
  878. break;
  879. case ObjCTypeParamVariance::Covariant:
  880. JOS.attribute("variance", "covariant");
  881. break;
  882. case ObjCTypeParamVariance::Contravariant:
  883. JOS.attribute("variance", "contravariant");
  884. break;
  885. }
  886. }
  887. void JSONNodeDumper::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
  888. VisitNamedDecl(D);
  889. JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
  890. JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
  891. llvm::json::Array Protocols;
  892. for (const auto* P : D->protocols())
  893. Protocols.push_back(createBareDeclRef(P));
  894. if (!Protocols.empty())
  895. JOS.attribute("protocols", std::move(Protocols));
  896. }
  897. void JSONNodeDumper::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
  898. VisitNamedDecl(D);
  899. JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
  900. JOS.attribute("categoryDecl", createBareDeclRef(D->getCategoryDecl()));
  901. }
  902. void JSONNodeDumper::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
  903. VisitNamedDecl(D);
  904. llvm::json::Array Protocols;
  905. for (const auto *P : D->protocols())
  906. Protocols.push_back(createBareDeclRef(P));
  907. if (!Protocols.empty())
  908. JOS.attribute("protocols", std::move(Protocols));
  909. }
  910. void JSONNodeDumper::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
  911. VisitNamedDecl(D);
  912. JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
  913. JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
  914. llvm::json::Array Protocols;
  915. for (const auto* P : D->protocols())
  916. Protocols.push_back(createBareDeclRef(P));
  917. if (!Protocols.empty())
  918. JOS.attribute("protocols", std::move(Protocols));
  919. }
  920. void JSONNodeDumper::VisitObjCImplementationDecl(
  921. const ObjCImplementationDecl *D) {
  922. VisitNamedDecl(D);
  923. JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
  924. JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
  925. }
  926. void JSONNodeDumper::VisitObjCCompatibleAliasDecl(
  927. const ObjCCompatibleAliasDecl *D) {
  928. VisitNamedDecl(D);
  929. JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
  930. }
  931. void JSONNodeDumper::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
  932. VisitNamedDecl(D);
  933. JOS.attribute("type", createQualType(D->getType()));
  934. switch (D->getPropertyImplementation()) {
  935. case ObjCPropertyDecl::None: break;
  936. case ObjCPropertyDecl::Required: JOS.attribute("control", "required"); break;
  937. case ObjCPropertyDecl::Optional: JOS.attribute("control", "optional"); break;
  938. }
  939. ObjCPropertyAttribute::Kind Attrs = D->getPropertyAttributes();
  940. if (Attrs != ObjCPropertyAttribute::kind_noattr) {
  941. if (Attrs & ObjCPropertyAttribute::kind_getter)
  942. JOS.attribute("getter", createBareDeclRef(D->getGetterMethodDecl()));
  943. if (Attrs & ObjCPropertyAttribute::kind_setter)
  944. JOS.attribute("setter", createBareDeclRef(D->getSetterMethodDecl()));
  945. attributeOnlyIfTrue("readonly",
  946. Attrs & ObjCPropertyAttribute::kind_readonly);
  947. attributeOnlyIfTrue("assign", Attrs & ObjCPropertyAttribute::kind_assign);
  948. attributeOnlyIfTrue("readwrite",
  949. Attrs & ObjCPropertyAttribute::kind_readwrite);
  950. attributeOnlyIfTrue("retain", Attrs & ObjCPropertyAttribute::kind_retain);
  951. attributeOnlyIfTrue("copy", Attrs & ObjCPropertyAttribute::kind_copy);
  952. attributeOnlyIfTrue("nonatomic",
  953. Attrs & ObjCPropertyAttribute::kind_nonatomic);
  954. attributeOnlyIfTrue("atomic", Attrs & ObjCPropertyAttribute::kind_atomic);
  955. attributeOnlyIfTrue("weak", Attrs & ObjCPropertyAttribute::kind_weak);
  956. attributeOnlyIfTrue("strong", Attrs & ObjCPropertyAttribute::kind_strong);
  957. attributeOnlyIfTrue("unsafe_unretained",
  958. Attrs & ObjCPropertyAttribute::kind_unsafe_unretained);
  959. attributeOnlyIfTrue("class", Attrs & ObjCPropertyAttribute::kind_class);
  960. attributeOnlyIfTrue("direct", Attrs & ObjCPropertyAttribute::kind_direct);
  961. attributeOnlyIfTrue("nullability",
  962. Attrs & ObjCPropertyAttribute::kind_nullability);
  963. attributeOnlyIfTrue("null_resettable",
  964. Attrs & ObjCPropertyAttribute::kind_null_resettable);
  965. }
  966. }
  967. void JSONNodeDumper::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
  968. VisitNamedDecl(D->getPropertyDecl());
  969. JOS.attribute("implKind", D->getPropertyImplementation() ==
  970. ObjCPropertyImplDecl::Synthesize
  971. ? "synthesize"
  972. : "dynamic");
  973. JOS.attribute("propertyDecl", createBareDeclRef(D->getPropertyDecl()));
  974. JOS.attribute("ivarDecl", createBareDeclRef(D->getPropertyIvarDecl()));
  975. }
  976. void JSONNodeDumper::VisitBlockDecl(const BlockDecl *D) {
  977. attributeOnlyIfTrue("variadic", D->isVariadic());
  978. attributeOnlyIfTrue("capturesThis", D->capturesCXXThis());
  979. }
  980. void JSONNodeDumper::VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE) {
  981. JOS.attribute("encodedType", createQualType(OEE->getEncodedType()));
  982. }
  983. void JSONNodeDumper::VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
  984. std::string Str;
  985. llvm::raw_string_ostream OS(Str);
  986. OME->getSelector().print(OS);
  987. JOS.attribute("selector", OS.str());
  988. switch (OME->getReceiverKind()) {
  989. case ObjCMessageExpr::Instance:
  990. JOS.attribute("receiverKind", "instance");
  991. break;
  992. case ObjCMessageExpr::Class:
  993. JOS.attribute("receiverKind", "class");
  994. JOS.attribute("classType", createQualType(OME->getClassReceiver()));
  995. break;
  996. case ObjCMessageExpr::SuperInstance:
  997. JOS.attribute("receiverKind", "super (instance)");
  998. JOS.attribute("superType", createQualType(OME->getSuperType()));
  999. break;
  1000. case ObjCMessageExpr::SuperClass:
  1001. JOS.attribute("receiverKind", "super (class)");
  1002. JOS.attribute("superType", createQualType(OME->getSuperType()));
  1003. break;
  1004. }
  1005. QualType CallReturnTy = OME->getCallReturnType(Ctx);
  1006. if (OME->getType() != CallReturnTy)
  1007. JOS.attribute("callReturnType", createQualType(CallReturnTy));
  1008. }
  1009. void JSONNodeDumper::VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE) {
  1010. if (const ObjCMethodDecl *MD = OBE->getBoxingMethod()) {
  1011. std::string Str;
  1012. llvm::raw_string_ostream OS(Str);
  1013. MD->getSelector().print(OS);
  1014. JOS.attribute("selector", OS.str());
  1015. }
  1016. }
  1017. void JSONNodeDumper::VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE) {
  1018. std::string Str;
  1019. llvm::raw_string_ostream OS(Str);
  1020. OSE->getSelector().print(OS);
  1021. JOS.attribute("selector", OS.str());
  1022. }
  1023. void JSONNodeDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
  1024. JOS.attribute("protocol", createBareDeclRef(OPE->getProtocol()));
  1025. }
  1026. void JSONNodeDumper::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
  1027. if (OPRE->isImplicitProperty()) {
  1028. JOS.attribute("propertyKind", "implicit");
  1029. if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertyGetter())
  1030. JOS.attribute("getter", createBareDeclRef(MD));
  1031. if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertySetter())
  1032. JOS.attribute("setter", createBareDeclRef(MD));
  1033. } else {
  1034. JOS.attribute("propertyKind", "explicit");
  1035. JOS.attribute("property", createBareDeclRef(OPRE->getExplicitProperty()));
  1036. }
  1037. attributeOnlyIfTrue("isSuperReceiver", OPRE->isSuperReceiver());
  1038. attributeOnlyIfTrue("isMessagingGetter", OPRE->isMessagingGetter());
  1039. attributeOnlyIfTrue("isMessagingSetter", OPRE->isMessagingSetter());
  1040. }
  1041. void JSONNodeDumper::VisitObjCSubscriptRefExpr(
  1042. const ObjCSubscriptRefExpr *OSRE) {
  1043. JOS.attribute("subscriptKind",
  1044. OSRE->isArraySubscriptRefExpr() ? "array" : "dictionary");
  1045. if (const ObjCMethodDecl *MD = OSRE->getAtIndexMethodDecl())
  1046. JOS.attribute("getter", createBareDeclRef(MD));
  1047. if (const ObjCMethodDecl *MD = OSRE->setAtIndexMethodDecl())
  1048. JOS.attribute("setter", createBareDeclRef(MD));
  1049. }
  1050. void JSONNodeDumper::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
  1051. JOS.attribute("decl", createBareDeclRef(OIRE->getDecl()));
  1052. attributeOnlyIfTrue("isFreeIvar", OIRE->isFreeIvar());
  1053. JOS.attribute("isArrow", OIRE->isArrow());
  1054. }
  1055. void JSONNodeDumper::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE) {
  1056. JOS.attribute("value", OBLE->getValue() ? "__objc_yes" : "__objc_no");
  1057. }
  1058. void JSONNodeDumper::VisitDeclRefExpr(const DeclRefExpr *DRE) {
  1059. JOS.attribute("referencedDecl", createBareDeclRef(DRE->getDecl()));
  1060. if (DRE->getDecl() != DRE->getFoundDecl())
  1061. JOS.attribute("foundReferencedDecl",
  1062. createBareDeclRef(DRE->getFoundDecl()));
  1063. switch (DRE->isNonOdrUse()) {
  1064. case NOUR_None: break;
  1065. case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
  1066. case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
  1067. case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
  1068. }
  1069. }
  1070. void JSONNodeDumper::VisitSYCLUniqueStableNameExpr(
  1071. const SYCLUniqueStableNameExpr *E) {
  1072. JOS.attribute("typeSourceInfo",
  1073. createQualType(E->getTypeSourceInfo()->getType()));
  1074. }
  1075. void JSONNodeDumper::VisitPredefinedExpr(const PredefinedExpr *PE) {
  1076. JOS.attribute("name", PredefinedExpr::getIdentKindName(PE->getIdentKind()));
  1077. }
  1078. void JSONNodeDumper::VisitUnaryOperator(const UnaryOperator *UO) {
  1079. JOS.attribute("isPostfix", UO->isPostfix());
  1080. JOS.attribute("opcode", UnaryOperator::getOpcodeStr(UO->getOpcode()));
  1081. if (!UO->canOverflow())
  1082. JOS.attribute("canOverflow", false);
  1083. }
  1084. void JSONNodeDumper::VisitBinaryOperator(const BinaryOperator *BO) {
  1085. JOS.attribute("opcode", BinaryOperator::getOpcodeStr(BO->getOpcode()));
  1086. }
  1087. void JSONNodeDumper::VisitCompoundAssignOperator(
  1088. const CompoundAssignOperator *CAO) {
  1089. VisitBinaryOperator(CAO);
  1090. JOS.attribute("computeLHSType", createQualType(CAO->getComputationLHSType()));
  1091. JOS.attribute("computeResultType",
  1092. createQualType(CAO->getComputationResultType()));
  1093. }
  1094. void JSONNodeDumper::VisitMemberExpr(const MemberExpr *ME) {
  1095. // Note, we always write this Boolean field because the information it conveys
  1096. // is critical to understanding the AST node.
  1097. ValueDecl *VD = ME->getMemberDecl();
  1098. JOS.attribute("name", VD && VD->getDeclName() ? VD->getNameAsString() : "");
  1099. JOS.attribute("isArrow", ME->isArrow());
  1100. JOS.attribute("referencedMemberDecl", createPointerRepresentation(VD));
  1101. switch (ME->isNonOdrUse()) {
  1102. case NOUR_None: break;
  1103. case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
  1104. case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
  1105. case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
  1106. }
  1107. }
  1108. void JSONNodeDumper::VisitCXXNewExpr(const CXXNewExpr *NE) {
  1109. attributeOnlyIfTrue("isGlobal", NE->isGlobalNew());
  1110. attributeOnlyIfTrue("isArray", NE->isArray());
  1111. attributeOnlyIfTrue("isPlacement", NE->getNumPlacementArgs() != 0);
  1112. switch (NE->getInitializationStyle()) {
  1113. case CXXNewExpr::NoInit: break;
  1114. case CXXNewExpr::CallInit: JOS.attribute("initStyle", "call"); break;
  1115. case CXXNewExpr::ListInit: JOS.attribute("initStyle", "list"); break;
  1116. }
  1117. if (const FunctionDecl *FD = NE->getOperatorNew())
  1118. JOS.attribute("operatorNewDecl", createBareDeclRef(FD));
  1119. if (const FunctionDecl *FD = NE->getOperatorDelete())
  1120. JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
  1121. }
  1122. void JSONNodeDumper::VisitCXXDeleteExpr(const CXXDeleteExpr *DE) {
  1123. attributeOnlyIfTrue("isGlobal", DE->isGlobalDelete());
  1124. attributeOnlyIfTrue("isArray", DE->isArrayForm());
  1125. attributeOnlyIfTrue("isArrayAsWritten", DE->isArrayFormAsWritten());
  1126. if (const FunctionDecl *FD = DE->getOperatorDelete())
  1127. JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
  1128. }
  1129. void JSONNodeDumper::VisitCXXThisExpr(const CXXThisExpr *TE) {
  1130. attributeOnlyIfTrue("implicit", TE->isImplicit());
  1131. }
  1132. void JSONNodeDumper::VisitCastExpr(const CastExpr *CE) {
  1133. JOS.attribute("castKind", CE->getCastKindName());
  1134. llvm::json::Array Path = createCastPath(CE);
  1135. if (!Path.empty())
  1136. JOS.attribute("path", std::move(Path));
  1137. // FIXME: This may not be useful information as it can be obtusely gleaned
  1138. // from the inner[] array.
  1139. if (const NamedDecl *ND = CE->getConversionFunction())
  1140. JOS.attribute("conversionFunc", createBareDeclRef(ND));
  1141. }
  1142. void JSONNodeDumper::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
  1143. VisitCastExpr(ICE);
  1144. attributeOnlyIfTrue("isPartOfExplicitCast", ICE->isPartOfExplicitCast());
  1145. }
  1146. void JSONNodeDumper::VisitCallExpr(const CallExpr *CE) {
  1147. attributeOnlyIfTrue("adl", CE->usesADL());
  1148. }
  1149. void JSONNodeDumper::VisitUnaryExprOrTypeTraitExpr(
  1150. const UnaryExprOrTypeTraitExpr *TTE) {
  1151. JOS.attribute("name", getTraitSpelling(TTE->getKind()));
  1152. if (TTE->isArgumentType())
  1153. JOS.attribute("argType", createQualType(TTE->getArgumentType()));
  1154. }
  1155. void JSONNodeDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE) {
  1156. VisitNamedDecl(SOPE->getPack());
  1157. }
  1158. void JSONNodeDumper::VisitUnresolvedLookupExpr(
  1159. const UnresolvedLookupExpr *ULE) {
  1160. JOS.attribute("usesADL", ULE->requiresADL());
  1161. JOS.attribute("name", ULE->getName().getAsString());
  1162. JOS.attributeArray("lookups", [this, ULE] {
  1163. for (const NamedDecl *D : ULE->decls())
  1164. JOS.value(createBareDeclRef(D));
  1165. });
  1166. }
  1167. void JSONNodeDumper::VisitAddrLabelExpr(const AddrLabelExpr *ALE) {
  1168. JOS.attribute("name", ALE->getLabel()->getName());
  1169. JOS.attribute("labelDeclId", createPointerRepresentation(ALE->getLabel()));
  1170. }
  1171. void JSONNodeDumper::VisitCXXTypeidExpr(const CXXTypeidExpr *CTE) {
  1172. if (CTE->isTypeOperand()) {
  1173. QualType Adjusted = CTE->getTypeOperand(Ctx);
  1174. QualType Unadjusted = CTE->getTypeOperandSourceInfo()->getType();
  1175. JOS.attribute("typeArg", createQualType(Unadjusted));
  1176. if (Adjusted != Unadjusted)
  1177. JOS.attribute("adjustedTypeArg", createQualType(Adjusted));
  1178. }
  1179. }
  1180. void JSONNodeDumper::VisitConstantExpr(const ConstantExpr *CE) {
  1181. if (CE->getResultAPValueKind() != APValue::None)
  1182. Visit(CE->getAPValueResult(), CE->getType());
  1183. }
  1184. void JSONNodeDumper::VisitInitListExpr(const InitListExpr *ILE) {
  1185. if (const FieldDecl *FD = ILE->getInitializedFieldInUnion())
  1186. JOS.attribute("field", createBareDeclRef(FD));
  1187. }
  1188. void JSONNodeDumper::VisitGenericSelectionExpr(
  1189. const GenericSelectionExpr *GSE) {
  1190. attributeOnlyIfTrue("resultDependent", GSE->isResultDependent());
  1191. }
  1192. void JSONNodeDumper::VisitCXXUnresolvedConstructExpr(
  1193. const CXXUnresolvedConstructExpr *UCE) {
  1194. if (UCE->getType() != UCE->getTypeAsWritten())
  1195. JOS.attribute("typeAsWritten", createQualType(UCE->getTypeAsWritten()));
  1196. attributeOnlyIfTrue("list", UCE->isListInitialization());
  1197. }
  1198. void JSONNodeDumper::VisitCXXConstructExpr(const CXXConstructExpr *CE) {
  1199. CXXConstructorDecl *Ctor = CE->getConstructor();
  1200. JOS.attribute("ctorType", createQualType(Ctor->getType()));
  1201. attributeOnlyIfTrue("elidable", CE->isElidable());
  1202. attributeOnlyIfTrue("list", CE->isListInitialization());
  1203. attributeOnlyIfTrue("initializer_list", CE->isStdInitListInitialization());
  1204. attributeOnlyIfTrue("zeroing", CE->requiresZeroInitialization());
  1205. attributeOnlyIfTrue("hadMultipleCandidates", CE->hadMultipleCandidates());
  1206. switch (CE->getConstructionKind()) {
  1207. case CXXConstructExpr::CK_Complete:
  1208. JOS.attribute("constructionKind", "complete");
  1209. break;
  1210. case CXXConstructExpr::CK_Delegating:
  1211. JOS.attribute("constructionKind", "delegating");
  1212. break;
  1213. case CXXConstructExpr::CK_NonVirtualBase:
  1214. JOS.attribute("constructionKind", "non-virtual base");
  1215. break;
  1216. case CXXConstructExpr::CK_VirtualBase:
  1217. JOS.attribute("constructionKind", "virtual base");
  1218. break;
  1219. }
  1220. }
  1221. void JSONNodeDumper::VisitExprWithCleanups(const ExprWithCleanups *EWC) {
  1222. attributeOnlyIfTrue("cleanupsHaveSideEffects",
  1223. EWC->cleanupsHaveSideEffects());
  1224. if (EWC->getNumObjects()) {
  1225. JOS.attributeArray("cleanups", [this, EWC] {
  1226. for (const ExprWithCleanups::CleanupObject &CO : EWC->getObjects())
  1227. if (auto *BD = CO.dyn_cast<BlockDecl *>()) {
  1228. JOS.value(createBareDeclRef(BD));
  1229. } else if (auto *CLE = CO.dyn_cast<CompoundLiteralExpr *>()) {
  1230. llvm::json::Object Obj;
  1231. Obj["id"] = createPointerRepresentation(CLE);
  1232. Obj["kind"] = CLE->getStmtClassName();
  1233. JOS.value(std::move(Obj));
  1234. } else {
  1235. llvm_unreachable("unexpected cleanup object type");
  1236. }
  1237. });
  1238. }
  1239. }
  1240. void JSONNodeDumper::VisitCXXBindTemporaryExpr(
  1241. const CXXBindTemporaryExpr *BTE) {
  1242. const CXXTemporary *Temp = BTE->getTemporary();
  1243. JOS.attribute("temp", createPointerRepresentation(Temp));
  1244. if (const CXXDestructorDecl *Dtor = Temp->getDestructor())
  1245. JOS.attribute("dtor", createBareDeclRef(Dtor));
  1246. }
  1247. void JSONNodeDumper::VisitMaterializeTemporaryExpr(
  1248. const MaterializeTemporaryExpr *MTE) {
  1249. if (const ValueDecl *VD = MTE->getExtendingDecl())
  1250. JOS.attribute("extendingDecl", createBareDeclRef(VD));
  1251. switch (MTE->getStorageDuration()) {
  1252. case SD_Automatic:
  1253. JOS.attribute("storageDuration", "automatic");
  1254. break;
  1255. case SD_Dynamic:
  1256. JOS.attribute("storageDuration", "dynamic");
  1257. break;
  1258. case SD_FullExpression:
  1259. JOS.attribute("storageDuration", "full expression");
  1260. break;
  1261. case SD_Static:
  1262. JOS.attribute("storageDuration", "static");
  1263. break;
  1264. case SD_Thread:
  1265. JOS.attribute("storageDuration", "thread");
  1266. break;
  1267. }
  1268. attributeOnlyIfTrue("boundToLValueRef", MTE->isBoundToLvalueReference());
  1269. }
  1270. void JSONNodeDumper::VisitCXXDependentScopeMemberExpr(
  1271. const CXXDependentScopeMemberExpr *DSME) {
  1272. JOS.attribute("isArrow", DSME->isArrow());
  1273. JOS.attribute("member", DSME->getMember().getAsString());
  1274. attributeOnlyIfTrue("hasTemplateKeyword", DSME->hasTemplateKeyword());
  1275. attributeOnlyIfTrue("hasExplicitTemplateArgs",
  1276. DSME->hasExplicitTemplateArgs());
  1277. if (DSME->getNumTemplateArgs()) {
  1278. JOS.attributeArray("explicitTemplateArgs", [DSME, this] {
  1279. for (const TemplateArgumentLoc &TAL : DSME->template_arguments())
  1280. JOS.object(
  1281. [&TAL, this] { Visit(TAL.getArgument(), TAL.getSourceRange()); });
  1282. });
  1283. }
  1284. }
  1285. void JSONNodeDumper::VisitRequiresExpr(const RequiresExpr *RE) {
  1286. if (!RE->isValueDependent())
  1287. JOS.attribute("satisfied", RE->isSatisfied());
  1288. }
  1289. void JSONNodeDumper::VisitIntegerLiteral(const IntegerLiteral *IL) {
  1290. llvm::SmallString<16> Buffer;
  1291. IL->getValue().toString(Buffer,
  1292. /*Radix=*/10, IL->getType()->isSignedIntegerType());
  1293. JOS.attribute("value", Buffer);
  1294. }
  1295. void JSONNodeDumper::VisitCharacterLiteral(const CharacterLiteral *CL) {
  1296. // FIXME: This should probably print the character literal as a string,
  1297. // rather than as a numerical value. It would be nice if the behavior matched
  1298. // what we do to print a string literal; right now, it is impossible to tell
  1299. // the difference between 'a' and L'a' in C from the JSON output.
  1300. JOS.attribute("value", CL->getValue());
  1301. }
  1302. void JSONNodeDumper::VisitFixedPointLiteral(const FixedPointLiteral *FPL) {
  1303. JOS.attribute("value", FPL->getValueAsString(/*Radix=*/10));
  1304. }
  1305. void JSONNodeDumper::VisitFloatingLiteral(const FloatingLiteral *FL) {
  1306. llvm::SmallString<16> Buffer;
  1307. FL->getValue().toString(Buffer);
  1308. JOS.attribute("value", Buffer);
  1309. }
  1310. void JSONNodeDumper::VisitStringLiteral(const StringLiteral *SL) {
  1311. std::string Buffer;
  1312. llvm::raw_string_ostream SS(Buffer);
  1313. SL->outputString(SS);
  1314. JOS.attribute("value", SS.str());
  1315. }
  1316. void JSONNodeDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE) {
  1317. JOS.attribute("value", BLE->getValue());
  1318. }
  1319. void JSONNodeDumper::VisitIfStmt(const IfStmt *IS) {
  1320. attributeOnlyIfTrue("hasInit", IS->hasInitStorage());
  1321. attributeOnlyIfTrue("hasVar", IS->hasVarStorage());
  1322. attributeOnlyIfTrue("hasElse", IS->hasElseStorage());
  1323. attributeOnlyIfTrue("isConstexpr", IS->isConstexpr());
  1324. attributeOnlyIfTrue("isConsteval", IS->isConsteval());
  1325. attributeOnlyIfTrue("constevalIsNegated", IS->isNegatedConsteval());
  1326. }
  1327. void JSONNodeDumper::VisitSwitchStmt(const SwitchStmt *SS) {
  1328. attributeOnlyIfTrue("hasInit", SS->hasInitStorage());
  1329. attributeOnlyIfTrue("hasVar", SS->hasVarStorage());
  1330. }
  1331. void JSONNodeDumper::VisitCaseStmt(const CaseStmt *CS) {
  1332. attributeOnlyIfTrue("isGNURange", CS->caseStmtIsGNURange());
  1333. }
  1334. void JSONNodeDumper::VisitLabelStmt(const LabelStmt *LS) {
  1335. JOS.attribute("name", LS->getName());
  1336. JOS.attribute("declId", createPointerRepresentation(LS->getDecl()));
  1337. attributeOnlyIfTrue("sideEntry", LS->isSideEntry());
  1338. }
  1339. void JSONNodeDumper::VisitGotoStmt(const GotoStmt *GS) {
  1340. JOS.attribute("targetLabelDeclId",
  1341. createPointerRepresentation(GS->getLabel()));
  1342. }
  1343. void JSONNodeDumper::VisitWhileStmt(const WhileStmt *WS) {
  1344. attributeOnlyIfTrue("hasVar", WS->hasVarStorage());
  1345. }
  1346. void JSONNodeDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt* OACS) {
  1347. // FIXME: it would be nice for the ASTNodeTraverser would handle the catch
  1348. // parameter the same way for C++ and ObjC rather. In this case, C++ gets a
  1349. // null child node and ObjC gets no child node.
  1350. attributeOnlyIfTrue("isCatchAll", OACS->getCatchParamDecl() == nullptr);
  1351. }
  1352. void JSONNodeDumper::VisitNullTemplateArgument(const TemplateArgument &TA) {
  1353. JOS.attribute("isNull", true);
  1354. }
  1355. void JSONNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
  1356. JOS.attribute("type", createQualType(TA.getAsType()));
  1357. }
  1358. void JSONNodeDumper::VisitDeclarationTemplateArgument(
  1359. const TemplateArgument &TA) {
  1360. JOS.attribute("decl", createBareDeclRef(TA.getAsDecl()));
  1361. }
  1362. void JSONNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
  1363. JOS.attribute("isNullptr", true);
  1364. }
  1365. void JSONNodeDumper::VisitIntegralTemplateArgument(const TemplateArgument &TA) {
  1366. JOS.attribute("value", TA.getAsIntegral().getSExtValue());
  1367. }
  1368. void JSONNodeDumper::VisitTemplateTemplateArgument(const TemplateArgument &TA) {
  1369. // FIXME: cannot just call dump() on the argument, as that doesn't specify
  1370. // the output format.
  1371. }
  1372. void JSONNodeDumper::VisitTemplateExpansionTemplateArgument(
  1373. const TemplateArgument &TA) {
  1374. // FIXME: cannot just call dump() on the argument, as that doesn't specify
  1375. // the output format.
  1376. }
  1377. void JSONNodeDumper::VisitExpressionTemplateArgument(
  1378. const TemplateArgument &TA) {
  1379. JOS.attribute("isExpr", true);
  1380. }
  1381. void JSONNodeDumper::VisitPackTemplateArgument(const TemplateArgument &TA) {
  1382. JOS.attribute("isPack", true);
  1383. }
  1384. StringRef JSONNodeDumper::getCommentCommandName(unsigned CommandID) const {
  1385. if (Traits)
  1386. return Traits->getCommandInfo(CommandID)->Name;
  1387. if (const comments::CommandInfo *Info =
  1388. comments::CommandTraits::getBuiltinCommandInfo(CommandID))
  1389. return Info->Name;
  1390. return "<invalid>";
  1391. }
  1392. void JSONNodeDumper::visitTextComment(const comments::TextComment *C,
  1393. const comments::FullComment *) {
  1394. JOS.attribute("text", C->getText());
  1395. }
  1396. void JSONNodeDumper::visitInlineCommandComment(
  1397. const comments::InlineCommandComment *C, const comments::FullComment *) {
  1398. JOS.attribute("name", getCommentCommandName(C->getCommandID()));
  1399. switch (C->getRenderKind()) {
  1400. case comments::InlineCommandComment::RenderNormal:
  1401. JOS.attribute("renderKind", "normal");
  1402. break;
  1403. case comments::InlineCommandComment::RenderBold:
  1404. JOS.attribute("renderKind", "bold");
  1405. break;
  1406. case comments::InlineCommandComment::RenderEmphasized:
  1407. JOS.attribute("renderKind", "emphasized");
  1408. break;
  1409. case comments::InlineCommandComment::RenderMonospaced:
  1410. JOS.attribute("renderKind", "monospaced");
  1411. break;
  1412. case comments::InlineCommandComment::RenderAnchor:
  1413. JOS.attribute("renderKind", "anchor");
  1414. break;
  1415. }
  1416. llvm::json::Array Args;
  1417. for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
  1418. Args.push_back(C->getArgText(I));
  1419. if (!Args.empty())
  1420. JOS.attribute("args", std::move(Args));
  1421. }
  1422. void JSONNodeDumper::visitHTMLStartTagComment(
  1423. const comments::HTMLStartTagComment *C, const comments::FullComment *) {
  1424. JOS.attribute("name", C->getTagName());
  1425. attributeOnlyIfTrue("selfClosing", C->isSelfClosing());
  1426. attributeOnlyIfTrue("malformed", C->isMalformed());
  1427. llvm::json::Array Attrs;
  1428. for (unsigned I = 0, E = C->getNumAttrs(); I < E; ++I)
  1429. Attrs.push_back(
  1430. {{"name", C->getAttr(I).Name}, {"value", C->getAttr(I).Value}});
  1431. if (!Attrs.empty())
  1432. JOS.attribute("attrs", std::move(Attrs));
  1433. }
  1434. void JSONNodeDumper::visitHTMLEndTagComment(
  1435. const comments::HTMLEndTagComment *C, const comments::FullComment *) {
  1436. JOS.attribute("name", C->getTagName());
  1437. }
  1438. void JSONNodeDumper::visitBlockCommandComment(
  1439. const comments::BlockCommandComment *C, const comments::FullComment *) {
  1440. JOS.attribute("name", getCommentCommandName(C->getCommandID()));
  1441. llvm::json::Array Args;
  1442. for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
  1443. Args.push_back(C->getArgText(I));
  1444. if (!Args.empty())
  1445. JOS.attribute("args", std::move(Args));
  1446. }
  1447. void JSONNodeDumper::visitParamCommandComment(
  1448. const comments::ParamCommandComment *C, const comments::FullComment *FC) {
  1449. switch (C->getDirection()) {
  1450. case comments::ParamCommandComment::In:
  1451. JOS.attribute("direction", "in");
  1452. break;
  1453. case comments::ParamCommandComment::Out:
  1454. JOS.attribute("direction", "out");
  1455. break;
  1456. case comments::ParamCommandComment::InOut:
  1457. JOS.attribute("direction", "in,out");
  1458. break;
  1459. }
  1460. attributeOnlyIfTrue("explicit", C->isDirectionExplicit());
  1461. if (C->hasParamName())
  1462. JOS.attribute("param", C->isParamIndexValid() ? C->getParamName(FC)
  1463. : C->getParamNameAsWritten());
  1464. if (C->isParamIndexValid() && !C->isVarArgParam())
  1465. JOS.attribute("paramIdx", C->getParamIndex());
  1466. }
  1467. void JSONNodeDumper::visitTParamCommandComment(
  1468. const comments::TParamCommandComment *C, const comments::FullComment *FC) {
  1469. if (C->hasParamName())
  1470. JOS.attribute("param", C->isPositionValid() ? C->getParamName(FC)
  1471. : C->getParamNameAsWritten());
  1472. if (C->isPositionValid()) {
  1473. llvm::json::Array Positions;
  1474. for (unsigned I = 0, E = C->getDepth(); I < E; ++I)
  1475. Positions.push_back(C->getIndex(I));
  1476. if (!Positions.empty())
  1477. JOS.attribute("positions", std::move(Positions));
  1478. }
  1479. }
  1480. void JSONNodeDumper::visitVerbatimBlockComment(
  1481. const comments::VerbatimBlockComment *C, const comments::FullComment *) {
  1482. JOS.attribute("name", getCommentCommandName(C->getCommandID()));
  1483. JOS.attribute("closeName", C->getCloseName());
  1484. }
  1485. void JSONNodeDumper::visitVerbatimBlockLineComment(
  1486. const comments::VerbatimBlockLineComment *C,
  1487. const comments::FullComment *) {
  1488. JOS.attribute("text", C->getText());
  1489. }
  1490. void JSONNodeDumper::visitVerbatimLineComment(
  1491. const comments::VerbatimLineComment *C, const comments::FullComment *) {
  1492. JOS.attribute("text", C->getText());
  1493. }
  1494. llvm::json::Object JSONNodeDumper::createFPOptions(FPOptionsOverride FPO) {
  1495. llvm::json::Object Ret;
  1496. #define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
  1497. if (FPO.has##NAME##Override()) \
  1498. Ret.try_emplace(#NAME, static_cast<unsigned>(FPO.get##NAME##Override()));
  1499. #include "clang/Basic/FPOptions.def"
  1500. return Ret;
  1501. }
  1502. void JSONNodeDumper::VisitCompoundStmt(const CompoundStmt *S) {
  1503. VisitStmt(S);
  1504. if (S->hasStoredFPFeatures())
  1505. JOS.attribute("fpoptions", createFPOptions(S->getStoredFPFeatures()));
  1506. }