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