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