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