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