1 #include "clang/AST/JSONNodeDumper.h"
2 #include "llvm/ADT/StringSwitch.h"
3 
4 using namespace clang;
5 
6 void JSONNodeDumper::addPreviousDeclaration(const Decl *D) {
7   switch (D->getKind()) {
8 #define DECL(DERIVED, BASE)                                                    \
9   case Decl::DERIVED:                                                          \
10     return writePreviousDeclImpl(cast<DERIVED##Decl>(D));
11 #define ABSTRACT_DECL(DECL)
12 #include "clang/AST/DeclNodes.inc"
13 #undef ABSTRACT_DECL
14 #undef DECL
15   }
16   llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
17 }
18 
19 void JSONNodeDumper::Visit(const Attr *A) {
20   const char *AttrName = nullptr;
21   switch (A->getKind()) {
22 #define ATTR(X)                                                                \
23   case attr::X:                                                                \
24     AttrName = #X"Attr";                                                       \
25     break;
26 #include "clang/Basic/AttrList.inc"
27 #undef ATTR
28   }
29   JOS.attribute("id", createPointerRepresentation(A));
30   JOS.attribute("kind", AttrName);
31   JOS.attribute("range", createSourceRange(A->getRange()));
32   attributeOnlyIfTrue("inherited", A->isInherited());
33   attributeOnlyIfTrue("implicit", A->isImplicit());
34 
35   // FIXME: it would be useful for us to output the spelling kind as well as
36   // the actual spelling. This would allow us to distinguish between the
37   // various attribute syntaxes, but we don't currently track that information
38   // within the AST.
39   //JOS.attribute("spelling", A->getSpelling());
40 
41   InnerAttrVisitor::Visit(A);
42 }
43 
44 void JSONNodeDumper::Visit(const Stmt *S) {
45   if (!S)
46     return;
47 
48   JOS.attribute("id", createPointerRepresentation(S));
49   JOS.attribute("kind", S->getStmtClassName());
50   JOS.attribute("range", createSourceRange(S->getSourceRange()));
51 
52   if (const auto *E = dyn_cast<Expr>(S)) {
53     JOS.attribute("type", createQualType(E->getType()));
54     const char *Category = nullptr;
55     switch (E->getValueKind()) {
56     case VK_LValue: Category = "lvalue"; break;
57     case VK_XValue: Category = "xvalue"; break;
58     case VK_RValue: Category = "rvalue"; break;
59     }
60     JOS.attribute("valueCategory", Category);
61   }
62   InnerStmtVisitor::Visit(S);
63 }
64 
65 void JSONNodeDumper::Visit(const Type *T) {
66   JOS.attribute("id", createPointerRepresentation(T));
67   JOS.attribute("kind", (llvm::Twine(T->getTypeClassName()) + "Type").str());
68   JOS.attribute("type", createQualType(QualType(T, 0), /*Desugar*/ false));
69   attributeOnlyIfTrue("isDependent", T->isDependentType());
70   attributeOnlyIfTrue("isInstantiationDependent",
71                       T->isInstantiationDependentType());
72   attributeOnlyIfTrue("isVariablyModified", T->isVariablyModifiedType());
73   attributeOnlyIfTrue("containsUnexpandedPack",
74                       T->containsUnexpandedParameterPack());
75   attributeOnlyIfTrue("isImported", T->isFromAST());
76   InnerTypeVisitor::Visit(T);
77 }
78 
79 void JSONNodeDumper::Visit(QualType T) {
80   JOS.attribute("id", createPointerRepresentation(T.getAsOpaquePtr()));
81   JOS.attribute("type", createQualType(T));
82   JOS.attribute("qualifiers", T.split().Quals.getAsString());
83 }
84 
85 void JSONNodeDumper::Visit(const Decl *D) {
86   JOS.attribute("id", createPointerRepresentation(D));
87 
88   if (!D)
89     return;
90 
91   JOS.attribute("kind", (llvm::Twine(D->getDeclKindName()) + "Decl").str());
92   JOS.attribute("loc", createSourceLocation(D->getLocation()));
93   JOS.attribute("range", createSourceRange(D->getSourceRange()));
94   attributeOnlyIfTrue("isImplicit", D->isImplicit());
95   attributeOnlyIfTrue("isInvalid", D->isInvalidDecl());
96 
97   if (D->isUsed())
98     JOS.attribute("isUsed", true);
99   else if (D->isThisDeclarationReferenced())
100     JOS.attribute("isReferenced", true);
101 
102   if (const auto *ND = dyn_cast<NamedDecl>(D))
103     attributeOnlyIfTrue("isHidden", ND->isHidden());
104 
105   if (D->getLexicalDeclContext() != D->getDeclContext())
106     JOS.attribute("parentDeclContext",
107                   createPointerRepresentation(D->getDeclContext()));
108 
109   addPreviousDeclaration(D);
110   InnerDeclVisitor::Visit(D);
111 }
112 
113 void JSONNodeDumper::Visit(const comments::Comment *C,
114                            const comments::FullComment *FC) {
115   if (!C)
116     return;
117 
118   JOS.attribute("id", createPointerRepresentation(C));
119   JOS.attribute("kind", C->getCommentKindName());
120   JOS.attribute("loc", createSourceLocation(C->getLocation()));
121   JOS.attribute("range", createSourceRange(C->getSourceRange()));
122 
123   InnerCommentVisitor::visit(C, FC);
124 }
125 
126 void JSONNodeDumper::Visit(const TemplateArgument &TA, SourceRange R,
127                            const Decl *From, StringRef Label) {
128   JOS.attribute("kind", "TemplateArgument");
129   if (R.isValid())
130     JOS.attribute("range", createSourceRange(R));
131 
132   if (From)
133     JOS.attribute(Label.empty() ? "fromDecl" : Label, createBareDeclRef(From));
134 
135   InnerTemplateArgVisitor::Visit(TA);
136 }
137 
138 void JSONNodeDumper::Visit(const CXXCtorInitializer *Init) {
139   JOS.attribute("kind", "CXXCtorInitializer");
140   if (Init->isAnyMemberInitializer())
141     JOS.attribute("anyInit", createBareDeclRef(Init->getAnyMember()));
142   else if (Init->isBaseInitializer())
143     JOS.attribute("baseInit",
144                   createQualType(QualType(Init->getBaseClass(), 0)));
145   else if (Init->isDelegatingInitializer())
146     JOS.attribute("delegatingInit",
147                   createQualType(Init->getTypeSourceInfo()->getType()));
148   else
149     llvm_unreachable("Unknown initializer type");
150 }
151 
152 void JSONNodeDumper::Visit(const OMPClause *C) {}
153 
154 void JSONNodeDumper::Visit(const BlockDecl::Capture &C) {
155   JOS.attribute("kind", "Capture");
156   attributeOnlyIfTrue("byref", C.isByRef());
157   attributeOnlyIfTrue("nested", C.isNested());
158   if (C.getVariable())
159     JOS.attribute("var", createBareDeclRef(C.getVariable()));
160 }
161 
162 void JSONNodeDumper::Visit(const GenericSelectionExpr::ConstAssociation &A) {
163   JOS.attribute("associationKind", A.getTypeSourceInfo() ? "case" : "default");
164   attributeOnlyIfTrue("selected", A.isSelected());
165 }
166 
167 llvm::json::Object
168 JSONNodeDumper::createBareSourceLocation(SourceLocation Loc) {
169   PresumedLoc Presumed = SM.getPresumedLoc(Loc);
170 
171   if (Presumed.isInvalid())
172     return llvm::json::Object{};
173 
174   return llvm::json::Object{{"file", Presumed.getFilename()},
175                             {"line", Presumed.getLine()},
176                             {"col", Presumed.getColumn()}};
177 }
178 
179 llvm::json::Object JSONNodeDumper::createSourceLocation(SourceLocation Loc) {
180   SourceLocation Spelling = SM.getSpellingLoc(Loc);
181   SourceLocation Expansion = SM.getExpansionLoc(Loc);
182 
183   llvm::json::Object SLoc = createBareSourceLocation(Spelling);
184   if (Expansion != Spelling) {
185     // If the expansion and the spelling are different, output subobjects
186     // describing both locations.
187     llvm::json::Object ELoc = createBareSourceLocation(Expansion);
188 
189     // If there is a macro expansion, add extra information if the interesting
190     // bit is the macro arg expansion.
191     if (SM.isMacroArgExpansion(Loc))
192       ELoc["isMacroArgExpansion"] = true;
193 
194     return llvm::json::Object{{"spellingLoc", std::move(SLoc)},
195                               {"expansionLoc", std::move(ELoc)}};
196   }
197 
198   return SLoc;
199 }
200 
201 llvm::json::Object JSONNodeDumper::createSourceRange(SourceRange R) {
202   return llvm::json::Object{{"begin", createSourceLocation(R.getBegin())},
203                             {"end", createSourceLocation(R.getEnd())}};
204 }
205 
206 std::string JSONNodeDumper::createPointerRepresentation(const void *Ptr) {
207   // Because JSON stores integer values as signed 64-bit integers, trying to
208   // represent them as such makes for very ugly pointer values in the resulting
209   // output. Instead, we convert the value to hex and treat it as a string.
210   return "0x" + llvm::utohexstr(reinterpret_cast<uint64_t>(Ptr), true);
211 }
212 
213 llvm::json::Object JSONNodeDumper::createQualType(QualType QT, bool Desugar) {
214   SplitQualType SQT = QT.split();
215   llvm::json::Object Ret{{"qualType", QualType::getAsString(SQT, PrintPolicy)}};
216 
217   if (Desugar && !QT.isNull()) {
218     SplitQualType DSQT = QT.getSplitDesugaredType();
219     if (DSQT != SQT)
220       Ret["desugaredQualType"] = QualType::getAsString(DSQT, PrintPolicy);
221   }
222   return Ret;
223 }
224 
225 llvm::json::Object JSONNodeDumper::createBareDeclRef(const Decl *D) {
226   llvm::json::Object Ret{{"id", createPointerRepresentation(D)}};
227   if (!D)
228     return Ret;
229 
230   Ret["kind"] = (llvm::Twine(D->getDeclKindName()) + "Decl").str();
231   if (const auto *ND = dyn_cast<NamedDecl>(D))
232     Ret["name"] = ND->getDeclName().getAsString();
233   if (const auto *VD = dyn_cast<ValueDecl>(D))
234     Ret["type"] = createQualType(VD->getType());
235   return Ret;
236 }
237 
238 llvm::json::Array JSONNodeDumper::createCastPath(const CastExpr *C) {
239   llvm::json::Array Ret;
240   if (C->path_empty())
241     return Ret;
242 
243   for (auto I = C->path_begin(), E = C->path_end(); I != E; ++I) {
244     const CXXBaseSpecifier *Base = *I;
245     const auto *RD =
246         cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
247 
248     llvm::json::Object Val{{"name", RD->getName()}};
249     if (Base->isVirtual())
250       Val["isVirtual"] = true;
251     Ret.push_back(std::move(Val));
252   }
253   return Ret;
254 }
255 
256 #define FIELD2(Name, Flag)  if (RD->Flag()) Ret[Name] = true
257 #define FIELD1(Flag)        FIELD2(#Flag, Flag)
258 
259 static llvm::json::Object
260 createDefaultConstructorDefinitionData(const CXXRecordDecl *RD) {
261   llvm::json::Object Ret;
262 
263   FIELD2("exists", hasDefaultConstructor);
264   FIELD2("trivial", hasTrivialDefaultConstructor);
265   FIELD2("nonTrivial", hasNonTrivialDefaultConstructor);
266   FIELD2("userProvided", hasUserProvidedDefaultConstructor);
267   FIELD2("isConstexpr", hasConstexprDefaultConstructor);
268   FIELD2("needsImplicit", needsImplicitDefaultConstructor);
269   FIELD2("defaultedIsConstexpr", defaultedDefaultConstructorIsConstexpr);
270 
271   return Ret;
272 }
273 
274 static llvm::json::Object
275 createCopyConstructorDefinitionData(const CXXRecordDecl *RD) {
276   llvm::json::Object Ret;
277 
278   FIELD2("simple", hasSimpleCopyConstructor);
279   FIELD2("trivial", hasTrivialCopyConstructor);
280   FIELD2("nonTrivial", hasNonTrivialCopyConstructor);
281   FIELD2("userDeclared", hasUserDeclaredCopyConstructor);
282   FIELD2("hasConstParam", hasCopyConstructorWithConstParam);
283   FIELD2("implicitHasConstParam", implicitCopyConstructorHasConstParam);
284   FIELD2("needsImplicit", needsImplicitCopyConstructor);
285   FIELD2("needsOverloadResolution", needsOverloadResolutionForCopyConstructor);
286   if (!RD->needsOverloadResolutionForCopyConstructor())
287     FIELD2("defaultedIsDeleted", defaultedCopyConstructorIsDeleted);
288 
289   return Ret;
290 }
291 
292 static llvm::json::Object
293 createMoveConstructorDefinitionData(const CXXRecordDecl *RD) {
294   llvm::json::Object Ret;
295 
296   FIELD2("exists", hasMoveConstructor);
297   FIELD2("simple", hasSimpleMoveConstructor);
298   FIELD2("trivial", hasTrivialMoveConstructor);
299   FIELD2("nonTrivial", hasNonTrivialMoveConstructor);
300   FIELD2("userDeclared", hasUserDeclaredMoveConstructor);
301   FIELD2("needsImplicit", needsImplicitMoveConstructor);
302   FIELD2("needsOverloadResolution", needsOverloadResolutionForMoveConstructor);
303   if (!RD->needsOverloadResolutionForMoveConstructor())
304     FIELD2("defaultedIsDeleted", defaultedMoveConstructorIsDeleted);
305 
306   return Ret;
307 }
308 
309 static llvm::json::Object
310 createCopyAssignmentDefinitionData(const CXXRecordDecl *RD) {
311   llvm::json::Object Ret;
312 
313   FIELD2("trivial", hasTrivialCopyAssignment);
314   FIELD2("nonTrivial", hasNonTrivialCopyAssignment);
315   FIELD2("hasConstParam", hasCopyAssignmentWithConstParam);
316   FIELD2("implicitHasConstParam", implicitCopyAssignmentHasConstParam);
317   FIELD2("userDeclared", hasUserDeclaredCopyAssignment);
318   FIELD2("needsImplicit", needsImplicitCopyAssignment);
319   FIELD2("needsOverloadResolution", needsOverloadResolutionForCopyAssignment);
320 
321   return Ret;
322 }
323 
324 static llvm::json::Object
325 createMoveAssignmentDefinitionData(const CXXRecordDecl *RD) {
326   llvm::json::Object Ret;
327 
328   FIELD2("exists", hasMoveAssignment);
329   FIELD2("simple", hasSimpleMoveAssignment);
330   FIELD2("trivial", hasTrivialMoveAssignment);
331   FIELD2("nonTrivial", hasNonTrivialMoveAssignment);
332   FIELD2("userDeclared", hasUserDeclaredMoveAssignment);
333   FIELD2("needsImplicit", needsImplicitMoveAssignment);
334   FIELD2("needsOverloadResolution", needsOverloadResolutionForMoveAssignment);
335 
336   return Ret;
337 }
338 
339 static llvm::json::Object
340 createDestructorDefinitionData(const CXXRecordDecl *RD) {
341   llvm::json::Object Ret;
342 
343   FIELD2("simple", hasSimpleDestructor);
344   FIELD2("irrelevant", hasIrrelevantDestructor);
345   FIELD2("trivial", hasTrivialDestructor);
346   FIELD2("nonTrivial", hasNonTrivialDestructor);
347   FIELD2("userDeclared", hasUserDeclaredDestructor);
348   FIELD2("needsImplicit", needsImplicitDestructor);
349   FIELD2("needsOverloadResolution", needsOverloadResolutionForDestructor);
350   if (!RD->needsOverloadResolutionForDestructor())
351     FIELD2("defaultedIsDeleted", defaultedDestructorIsDeleted);
352 
353   return Ret;
354 }
355 
356 llvm::json::Object
357 JSONNodeDumper::createCXXRecordDefinitionData(const CXXRecordDecl *RD) {
358   llvm::json::Object Ret;
359 
360   // This data is common to all C++ classes.
361   FIELD1(isGenericLambda);
362   FIELD1(isLambda);
363   FIELD1(isEmpty);
364   FIELD1(isAggregate);
365   FIELD1(isStandardLayout);
366   FIELD1(isTriviallyCopyable);
367   FIELD1(isPOD);
368   FIELD1(isTrivial);
369   FIELD1(isPolymorphic);
370   FIELD1(isAbstract);
371   FIELD1(isLiteral);
372   FIELD1(canPassInRegisters);
373   FIELD1(hasUserDeclaredConstructor);
374   FIELD1(hasConstexprNonCopyMoveConstructor);
375   FIELD1(hasMutableFields);
376   FIELD1(hasVariantMembers);
377   FIELD2("canConstDefaultInit", allowConstDefaultInit);
378 
379   Ret["defaultCtor"] = createDefaultConstructorDefinitionData(RD);
380   Ret["copyCtor"] = createCopyConstructorDefinitionData(RD);
381   Ret["moveCtor"] = createMoveConstructorDefinitionData(RD);
382   Ret["copyAssign"] = createCopyAssignmentDefinitionData(RD);
383   Ret["moveAssign"] = createMoveAssignmentDefinitionData(RD);
384   Ret["dtor"] = createDestructorDefinitionData(RD);
385 
386   return Ret;
387 }
388 
389 #undef FIELD1
390 #undef FIELD2
391 
392 std::string JSONNodeDumper::createAccessSpecifier(AccessSpecifier AS) {
393   switch (AS) {
394   case AS_none: return "none";
395   case AS_private: return "private";
396   case AS_protected: return "protected";
397   case AS_public: return "public";
398   }
399   llvm_unreachable("Unknown access specifier");
400 }
401 
402 llvm::json::Object
403 JSONNodeDumper::createCXXBaseSpecifier(const CXXBaseSpecifier &BS) {
404   llvm::json::Object Ret;
405 
406   Ret["type"] = createQualType(BS.getType());
407   Ret["access"] = createAccessSpecifier(BS.getAccessSpecifier());
408   Ret["writtenAccess"] =
409       createAccessSpecifier(BS.getAccessSpecifierAsWritten());
410   if (BS.isVirtual())
411     Ret["isVirtual"] = true;
412   if (BS.isPackExpansion())
413     Ret["isPackExpansion"] = true;
414 
415   return Ret;
416 }
417 
418 void JSONNodeDumper::VisitTypedefType(const TypedefType *TT) {
419   JOS.attribute("decl", createBareDeclRef(TT->getDecl()));
420 }
421 
422 void JSONNodeDumper::VisitFunctionType(const FunctionType *T) {
423   FunctionType::ExtInfo E = T->getExtInfo();
424   attributeOnlyIfTrue("noreturn", E.getNoReturn());
425   attributeOnlyIfTrue("producesResult", E.getProducesResult());
426   if (E.getHasRegParm())
427     JOS.attribute("regParm", E.getRegParm());
428   JOS.attribute("cc", FunctionType::getNameForCallConv(E.getCC()));
429 }
430 
431 void JSONNodeDumper::VisitFunctionProtoType(const FunctionProtoType *T) {
432   FunctionProtoType::ExtProtoInfo E = T->getExtProtoInfo();
433   attributeOnlyIfTrue("trailingReturn", E.HasTrailingReturn);
434   attributeOnlyIfTrue("const", T->isConst());
435   attributeOnlyIfTrue("volatile", T->isVolatile());
436   attributeOnlyIfTrue("restrict", T->isRestrict());
437   attributeOnlyIfTrue("variadic", E.Variadic);
438   switch (E.RefQualifier) {
439   case RQ_LValue: JOS.attribute("refQualifier", "&"); break;
440   case RQ_RValue: JOS.attribute("refQualifier", "&&"); break;
441   case RQ_None: break;
442   }
443   switch (E.ExceptionSpec.Type) {
444   case EST_DynamicNone:
445   case EST_Dynamic: {
446     JOS.attribute("exceptionSpec", "throw");
447     llvm::json::Array Types;
448     for (QualType QT : E.ExceptionSpec.Exceptions)
449       Types.push_back(createQualType(QT));
450     JOS.attribute("exceptionTypes", std::move(Types));
451   } break;
452   case EST_MSAny:
453     JOS.attribute("exceptionSpec", "throw");
454     JOS.attribute("throwsAny", true);
455     break;
456   case EST_BasicNoexcept:
457     JOS.attribute("exceptionSpec", "noexcept");
458     break;
459   case EST_NoexceptTrue:
460   case EST_NoexceptFalse:
461     JOS.attribute("exceptionSpec", "noexcept");
462     JOS.attribute("conditionEvaluatesTo",
463                 E.ExceptionSpec.Type == EST_NoexceptTrue);
464     //JOS.attributeWithCall("exceptionSpecExpr",
465     //                    [this, E]() { Visit(E.ExceptionSpec.NoexceptExpr); });
466     break;
467   case EST_NoThrow:
468     JOS.attribute("exceptionSpec", "nothrow");
469     break;
470   // FIXME: I cannot find a way to trigger these cases while dumping the AST. I
471   // suspect you can only run into them when executing an AST dump from within
472   // the debugger, which is not a use case we worry about for the JSON dumping
473   // feature.
474   case EST_DependentNoexcept:
475   case EST_Unevaluated:
476   case EST_Uninstantiated:
477   case EST_Unparsed:
478   case EST_None: break;
479   }
480   VisitFunctionType(T);
481 }
482 
483 void JSONNodeDumper::VisitNamedDecl(const NamedDecl *ND) {
484   if (ND && ND->getDeclName())
485     JOS.attribute("name", ND->getNameAsString());
486 }
487 
488 void JSONNodeDumper::VisitTypedefDecl(const TypedefDecl *TD) {
489   VisitNamedDecl(TD);
490   JOS.attribute("type", createQualType(TD->getUnderlyingType()));
491 }
492 
493 void JSONNodeDumper::VisitTypeAliasDecl(const TypeAliasDecl *TAD) {
494   VisitNamedDecl(TAD);
495   JOS.attribute("type", createQualType(TAD->getUnderlyingType()));
496 }
497 
498 void JSONNodeDumper::VisitNamespaceDecl(const NamespaceDecl *ND) {
499   VisitNamedDecl(ND);
500   attributeOnlyIfTrue("isInline", ND->isInline());
501   if (!ND->isOriginalNamespace())
502     JOS.attribute("originalNamespace",
503                   createBareDeclRef(ND->getOriginalNamespace()));
504 }
505 
506 void JSONNodeDumper::VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD) {
507   JOS.attribute("nominatedNamespace",
508                 createBareDeclRef(UDD->getNominatedNamespace()));
509 }
510 
511 void JSONNodeDumper::VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD) {
512   VisitNamedDecl(NAD);
513   JOS.attribute("aliasedNamespace",
514                 createBareDeclRef(NAD->getAliasedNamespace()));
515 }
516 
517 void JSONNodeDumper::VisitUsingDecl(const UsingDecl *UD) {
518   std::string Name;
519   if (const NestedNameSpecifier *NNS = UD->getQualifier()) {
520     llvm::raw_string_ostream SOS(Name);
521     NNS->print(SOS, UD->getASTContext().getPrintingPolicy());
522   }
523   Name += UD->getNameAsString();
524   JOS.attribute("name", Name);
525 }
526 
527 void JSONNodeDumper::VisitUsingShadowDecl(const UsingShadowDecl *USD) {
528   JOS.attribute("target", createBareDeclRef(USD->getTargetDecl()));
529 }
530 
531 void JSONNodeDumper::VisitVarDecl(const VarDecl *VD) {
532   VisitNamedDecl(VD);
533   JOS.attribute("type", createQualType(VD->getType()));
534 
535   StorageClass SC = VD->getStorageClass();
536   if (SC != SC_None)
537     JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
538   switch (VD->getTLSKind()) {
539   case VarDecl::TLS_Dynamic: JOS.attribute("tls", "dynamic"); break;
540   case VarDecl::TLS_Static: JOS.attribute("tls", "static"); break;
541   case VarDecl::TLS_None: break;
542   }
543   attributeOnlyIfTrue("nrvo", VD->isNRVOVariable());
544   attributeOnlyIfTrue("inline", VD->isInline());
545   attributeOnlyIfTrue("constexpr", VD->isConstexpr());
546   attributeOnlyIfTrue("modulePrivate", VD->isModulePrivate());
547   if (VD->hasInit()) {
548     switch (VD->getInitStyle()) {
549     case VarDecl::CInit: JOS.attribute("init", "c");  break;
550     case VarDecl::CallInit: JOS.attribute("init", "call"); break;
551     case VarDecl::ListInit: JOS.attribute("init", "list"); break;
552     }
553   }
554   attributeOnlyIfTrue("isParameterPack", VD->isParameterPack());
555 }
556 
557 void JSONNodeDumper::VisitFieldDecl(const FieldDecl *FD) {
558   VisitNamedDecl(FD);
559   JOS.attribute("type", createQualType(FD->getType()));
560   attributeOnlyIfTrue("mutable", FD->isMutable());
561   attributeOnlyIfTrue("modulePrivate", FD->isModulePrivate());
562   attributeOnlyIfTrue("isBitfield", FD->isBitField());
563   attributeOnlyIfTrue("hasInClassInitializer", FD->hasInClassInitializer());
564 }
565 
566 void JSONNodeDumper::VisitFunctionDecl(const FunctionDecl *FD) {
567   VisitNamedDecl(FD);
568   JOS.attribute("type", createQualType(FD->getType()));
569   StorageClass SC = FD->getStorageClass();
570   if (SC != SC_None)
571     JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
572   attributeOnlyIfTrue("inline", FD->isInlineSpecified());
573   attributeOnlyIfTrue("virtual", FD->isVirtualAsWritten());
574   attributeOnlyIfTrue("pure", FD->isPure());
575   attributeOnlyIfTrue("explicitlyDeleted", FD->isDeletedAsWritten());
576   attributeOnlyIfTrue("constexpr", FD->isConstexpr());
577   attributeOnlyIfTrue("variadic", FD->isVariadic());
578 
579   if (FD->isDefaulted())
580     JOS.attribute("explicitlyDefaulted",
581                   FD->isDeleted() ? "deleted" : "default");
582 }
583 
584 void JSONNodeDumper::VisitEnumDecl(const EnumDecl *ED) {
585   VisitNamedDecl(ED);
586   if (ED->isFixed())
587     JOS.attribute("fixedUnderlyingType", createQualType(ED->getIntegerType()));
588   if (ED->isScoped())
589     JOS.attribute("scopedEnumTag",
590                   ED->isScopedUsingClassTag() ? "class" : "struct");
591 }
592 void JSONNodeDumper::VisitEnumConstantDecl(const EnumConstantDecl *ECD) {
593   VisitNamedDecl(ECD);
594   JOS.attribute("type", createQualType(ECD->getType()));
595 }
596 
597 void JSONNodeDumper::VisitRecordDecl(const RecordDecl *RD) {
598   VisitNamedDecl(RD);
599   JOS.attribute("tagUsed", RD->getKindName());
600   attributeOnlyIfTrue("completeDefinition", RD->isCompleteDefinition());
601 }
602 void JSONNodeDumper::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
603   VisitRecordDecl(RD);
604 
605   // All other information requires a complete definition.
606   if (!RD->isCompleteDefinition())
607     return;
608 
609   JOS.attribute("definitionData", createCXXRecordDefinitionData(RD));
610   if (RD->getNumBases()) {
611     JOS.attributeArray("bases", [this, RD] {
612       for (const auto &Spec : RD->bases())
613         JOS.value(createCXXBaseSpecifier(Spec));
614     });
615   }
616 }
617 
618 void JSONNodeDumper::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
619   VisitNamedDecl(D);
620   JOS.attribute("tagUsed", D->wasDeclaredWithTypename() ? "typename" : "class");
621   JOS.attribute("depth", D->getDepth());
622   JOS.attribute("index", D->getIndex());
623   attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
624 }
625 
626 void JSONNodeDumper::VisitNonTypeTemplateParmDecl(
627     const NonTypeTemplateParmDecl *D) {
628   VisitNamedDecl(D);
629   JOS.attribute("type", createQualType(D->getType()));
630   JOS.attribute("depth", D->getDepth());
631   JOS.attribute("index", D->getIndex());
632   attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
633 }
634 
635 void JSONNodeDumper::VisitTemplateTemplateParmDecl(
636     const TemplateTemplateParmDecl *D) {
637   VisitNamedDecl(D);
638   JOS.attribute("depth", D->getDepth());
639   JOS.attribute("index", D->getIndex());
640   attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
641 }
642 
643 void JSONNodeDumper::VisitLinkageSpecDecl(const LinkageSpecDecl *LSD) {
644   StringRef Lang;
645   switch (LSD->getLanguage()) {
646   case LinkageSpecDecl::lang_c: Lang = "C"; break;
647   case LinkageSpecDecl::lang_cxx: Lang = "C++"; break;
648   }
649   JOS.attribute("language", Lang);
650   attributeOnlyIfTrue("hasBraces", LSD->hasBraces());
651 }
652 
653 void JSONNodeDumper::VisitAccessSpecDecl(const AccessSpecDecl *ASD) {
654   JOS.attribute("access", createAccessSpecifier(ASD->getAccess()));
655 }
656 
657 void JSONNodeDumper::VisitFriendDecl(const FriendDecl *FD) {
658   if (const TypeSourceInfo *T = FD->getFriendType())
659     JOS.attribute("type", createQualType(T->getType()));
660 }
661 
662 void JSONNodeDumper::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
663   VisitNamedDecl(D);
664   JOS.attribute("type", createQualType(D->getType()));
665   attributeOnlyIfTrue("synthesized", D->getSynthesize());
666   switch (D->getAccessControl()) {
667   case ObjCIvarDecl::None: JOS.attribute("access", "none"); break;
668   case ObjCIvarDecl::Private: JOS.attribute("access", "private"); break;
669   case ObjCIvarDecl::Protected: JOS.attribute("access", "protected"); break;
670   case ObjCIvarDecl::Public: JOS.attribute("access", "public"); break;
671   case ObjCIvarDecl::Package: JOS.attribute("access", "package"); break;
672   }
673 }
674 
675 void JSONNodeDumper::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
676   VisitNamedDecl(D);
677   JOS.attribute("returnType", createQualType(D->getReturnType()));
678   JOS.attribute("instance", D->isInstanceMethod());
679   attributeOnlyIfTrue("variadic", D->isVariadic());
680 }
681 
682 void JSONNodeDumper::VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D) {
683   VisitNamedDecl(D);
684   JOS.attribute("type", createQualType(D->getUnderlyingType()));
685   attributeOnlyIfTrue("bounded", D->hasExplicitBound());
686   switch (D->getVariance()) {
687   case ObjCTypeParamVariance::Invariant:
688     break;
689   case ObjCTypeParamVariance::Covariant:
690     JOS.attribute("variance", "covariant");
691     break;
692   case ObjCTypeParamVariance::Contravariant:
693     JOS.attribute("variance", "contravariant");
694     break;
695   }
696 }
697 
698 void JSONNodeDumper::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
699   VisitNamedDecl(D);
700   JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
701   JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
702 
703   llvm::json::Array Protocols;
704   for (const auto* P : D->protocols())
705     Protocols.push_back(createBareDeclRef(P));
706   if (!Protocols.empty())
707     JOS.attribute("protocols", std::move(Protocols));
708 }
709 
710 void JSONNodeDumper::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
711   VisitNamedDecl(D);
712   JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
713   JOS.attribute("categoryDecl", createBareDeclRef(D->getCategoryDecl()));
714 }
715 
716 void JSONNodeDumper::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
717   VisitNamedDecl(D);
718 
719   llvm::json::Array Protocols;
720   for (const auto *P : D->protocols())
721     Protocols.push_back(createBareDeclRef(P));
722   if (!Protocols.empty())
723     JOS.attribute("protocols", std::move(Protocols));
724 }
725 
726 void JSONNodeDumper::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
727   VisitNamedDecl(D);
728   JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
729   JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
730 
731   llvm::json::Array Protocols;
732   for (const auto* P : D->protocols())
733     Protocols.push_back(createBareDeclRef(P));
734   if (!Protocols.empty())
735     JOS.attribute("protocols", std::move(Protocols));
736 }
737 
738 void JSONNodeDumper::VisitObjCImplementationDecl(
739     const ObjCImplementationDecl *D) {
740   VisitNamedDecl(D);
741   JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
742   JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
743 }
744 
745 void JSONNodeDumper::VisitObjCCompatibleAliasDecl(
746     const ObjCCompatibleAliasDecl *D) {
747   VisitNamedDecl(D);
748   JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
749 }
750 
751 void JSONNodeDumper::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
752   VisitNamedDecl(D);
753   JOS.attribute("type", createQualType(D->getType()));
754 
755   switch (D->getPropertyImplementation()) {
756   case ObjCPropertyDecl::None: break;
757   case ObjCPropertyDecl::Required: JOS.attribute("control", "required"); break;
758   case ObjCPropertyDecl::Optional: JOS.attribute("control", "optional"); break;
759   }
760 
761   ObjCPropertyDecl::PropertyAttributeKind Attrs = D->getPropertyAttributes();
762   if (Attrs != ObjCPropertyDecl::OBJC_PR_noattr) {
763     if (Attrs & ObjCPropertyDecl::OBJC_PR_getter)
764       JOS.attribute("getter", createBareDeclRef(D->getGetterMethodDecl()));
765     if (Attrs & ObjCPropertyDecl::OBJC_PR_setter)
766       JOS.attribute("setter", createBareDeclRef(D->getSetterMethodDecl()));
767     attributeOnlyIfTrue("readonly", Attrs & ObjCPropertyDecl::OBJC_PR_readonly);
768     attributeOnlyIfTrue("assign", Attrs & ObjCPropertyDecl::OBJC_PR_assign);
769     attributeOnlyIfTrue("readwrite",
770                         Attrs & ObjCPropertyDecl::OBJC_PR_readwrite);
771     attributeOnlyIfTrue("retain", Attrs & ObjCPropertyDecl::OBJC_PR_retain);
772     attributeOnlyIfTrue("copy", Attrs & ObjCPropertyDecl::OBJC_PR_copy);
773     attributeOnlyIfTrue("nonatomic",
774                         Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic);
775     attributeOnlyIfTrue("atomic", Attrs & ObjCPropertyDecl::OBJC_PR_atomic);
776     attributeOnlyIfTrue("weak", Attrs & ObjCPropertyDecl::OBJC_PR_weak);
777     attributeOnlyIfTrue("strong", Attrs & ObjCPropertyDecl::OBJC_PR_strong);
778     attributeOnlyIfTrue("unsafe_unretained",
779                         Attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
780     attributeOnlyIfTrue("class", Attrs & ObjCPropertyDecl::OBJC_PR_class);
781     attributeOnlyIfTrue("nullability",
782                         Attrs & ObjCPropertyDecl::OBJC_PR_nullability);
783     attributeOnlyIfTrue("null_resettable",
784                         Attrs & ObjCPropertyDecl::OBJC_PR_null_resettable);
785   }
786 }
787 
788 void JSONNodeDumper::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
789   VisitNamedDecl(D->getPropertyDecl());
790   JOS.attribute("implKind", D->getPropertyImplementation() ==
791                                     ObjCPropertyImplDecl::Synthesize
792                                 ? "synthesize"
793                                 : "dynamic");
794   JOS.attribute("propertyDecl", createBareDeclRef(D->getPropertyDecl()));
795   JOS.attribute("ivarDecl", createBareDeclRef(D->getPropertyIvarDecl()));
796 }
797 
798 void JSONNodeDumper::VisitBlockDecl(const BlockDecl *D) {
799   attributeOnlyIfTrue("variadic", D->isVariadic());
800   attributeOnlyIfTrue("capturesThis", D->capturesCXXThis());
801 }
802 
803 void JSONNodeDumper::VisitDeclRefExpr(const DeclRefExpr *DRE) {
804   JOS.attribute("referencedDecl", createBareDeclRef(DRE->getDecl()));
805   if (DRE->getDecl() != DRE->getFoundDecl())
806     JOS.attribute("foundReferencedDecl",
807                   createBareDeclRef(DRE->getFoundDecl()));
808   switch (DRE->isNonOdrUse()) {
809   case NOUR_None: break;
810   case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
811   case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
812   case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
813   }
814 }
815 
816 void JSONNodeDumper::VisitPredefinedExpr(const PredefinedExpr *PE) {
817   JOS.attribute("name", PredefinedExpr::getIdentKindName(PE->getIdentKind()));
818 }
819 
820 void JSONNodeDumper::VisitUnaryOperator(const UnaryOperator *UO) {
821   JOS.attribute("isPostfix", UO->isPostfix());
822   JOS.attribute("opcode", UnaryOperator::getOpcodeStr(UO->getOpcode()));
823   if (!UO->canOverflow())
824     JOS.attribute("canOverflow", false);
825 }
826 
827 void JSONNodeDumper::VisitBinaryOperator(const BinaryOperator *BO) {
828   JOS.attribute("opcode", BinaryOperator::getOpcodeStr(BO->getOpcode()));
829 }
830 
831 void JSONNodeDumper::VisitCompoundAssignOperator(
832     const CompoundAssignOperator *CAO) {
833   VisitBinaryOperator(CAO);
834   JOS.attribute("computeLHSType", createQualType(CAO->getComputationLHSType()));
835   JOS.attribute("computeResultType",
836                 createQualType(CAO->getComputationResultType()));
837 }
838 
839 void JSONNodeDumper::VisitMemberExpr(const MemberExpr *ME) {
840   // Note, we always write this Boolean field because the information it conveys
841   // is critical to understanding the AST node.
842   ValueDecl *VD = ME->getMemberDecl();
843   JOS.attribute("name", VD && VD->getDeclName() ? VD->getNameAsString() : "");
844   JOS.attribute("isArrow", ME->isArrow());
845   JOS.attribute("referencedMemberDecl", createPointerRepresentation(VD));
846   switch (ME->isNonOdrUse()) {
847   case NOUR_None: break;
848   case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
849   case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
850   case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
851   }
852 }
853 
854 void JSONNodeDumper::VisitCXXNewExpr(const CXXNewExpr *NE) {
855   attributeOnlyIfTrue("isGlobal", NE->isGlobalNew());
856   attributeOnlyIfTrue("isArray", NE->isArray());
857   attributeOnlyIfTrue("isPlacement", NE->getNumPlacementArgs() != 0);
858   switch (NE->getInitializationStyle()) {
859   case CXXNewExpr::NoInit: break;
860   case CXXNewExpr::CallInit: JOS.attribute("initStyle", "call"); break;
861   case CXXNewExpr::ListInit: JOS.attribute("initStyle", "list"); break;
862   }
863   if (const FunctionDecl *FD = NE->getOperatorNew())
864     JOS.attribute("operatorNewDecl", createBareDeclRef(FD));
865   if (const FunctionDecl *FD = NE->getOperatorDelete())
866     JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
867 }
868 void JSONNodeDumper::VisitCXXDeleteExpr(const CXXDeleteExpr *DE) {
869   attributeOnlyIfTrue("isGlobal", DE->isGlobalDelete());
870   attributeOnlyIfTrue("isArray", DE->isArrayForm());
871   attributeOnlyIfTrue("isArrayAsWritten", DE->isArrayFormAsWritten());
872   if (const FunctionDecl *FD = DE->getOperatorDelete())
873     JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
874 }
875 
876 void JSONNodeDumper::VisitCXXThisExpr(const CXXThisExpr *TE) {
877   attributeOnlyIfTrue("implicit", TE->isImplicit());
878 }
879 
880 void JSONNodeDumper::VisitCastExpr(const CastExpr *CE) {
881   JOS.attribute("castKind", CE->getCastKindName());
882   llvm::json::Array Path = createCastPath(CE);
883   if (!Path.empty())
884     JOS.attribute("path", std::move(Path));
885   // FIXME: This may not be useful information as it can be obtusely gleaned
886   // from the inner[] array.
887   if (const NamedDecl *ND = CE->getConversionFunction())
888     JOS.attribute("conversionFunc", createBareDeclRef(ND));
889 }
890 
891 void JSONNodeDumper::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
892   VisitCastExpr(ICE);
893   attributeOnlyIfTrue("isPartOfExplicitCast", ICE->isPartOfExplicitCast());
894 }
895 
896 void JSONNodeDumper::VisitCallExpr(const CallExpr *CE) {
897   attributeOnlyIfTrue("adl", CE->usesADL());
898 }
899 
900 void JSONNodeDumper::VisitUnaryExprOrTypeTraitExpr(
901     const UnaryExprOrTypeTraitExpr *TTE) {
902   switch (TTE->getKind()) {
903   case UETT_SizeOf: JOS.attribute("name", "sizeof"); break;
904   case UETT_AlignOf: JOS.attribute("name", "alignof"); break;
905   case UETT_VecStep:  JOS.attribute("name", "vec_step"); break;
906   case UETT_PreferredAlignOf:  JOS.attribute("name", "__alignof"); break;
907   case UETT_OpenMPRequiredSimdAlign:
908     JOS.attribute("name", "__builtin_omp_required_simd_align"); break;
909   }
910   if (TTE->isArgumentType())
911     JOS.attribute("argType", createQualType(TTE->getArgumentType()));
912 }
913 
914 void JSONNodeDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE) {
915   VisitNamedDecl(SOPE->getPack());
916 }
917 
918 void JSONNodeDumper::VisitUnresolvedLookupExpr(
919     const UnresolvedLookupExpr *ULE) {
920   JOS.attribute("usesADL", ULE->requiresADL());
921   JOS.attribute("name", ULE->getName().getAsString());
922 
923   JOS.attributeArray("lookups", [this, ULE] {
924     for (const NamedDecl *D : ULE->decls())
925       JOS.value(createBareDeclRef(D));
926   });
927 }
928 
929 void JSONNodeDumper::VisitAddrLabelExpr(const AddrLabelExpr *ALE) {
930   JOS.attribute("name", ALE->getLabel()->getName());
931   JOS.attribute("labelDeclId", createPointerRepresentation(ALE->getLabel()));
932 }
933 
934 void JSONNodeDumper::VisitCXXTypeidExpr(const CXXTypeidExpr *CTE) {
935   if (CTE->isTypeOperand()) {
936     QualType Adjusted = CTE->getTypeOperand(Ctx);
937     QualType Unadjusted = CTE->getTypeOperandSourceInfo()->getType();
938     JOS.attribute("typeArg", createQualType(Unadjusted));
939     if (Adjusted != Unadjusted)
940       JOS.attribute("adjustedTypeArg", createQualType(Adjusted));
941   }
942 }
943 
944 void JSONNodeDumper::VisitIntegerLiteral(const IntegerLiteral *IL) {
945   JOS.attribute("value",
946                 IL->getValue().toString(
947                     /*Radix=*/10, IL->getType()->isSignedIntegerType()));
948 }
949 void JSONNodeDumper::VisitCharacterLiteral(const CharacterLiteral *CL) {
950   // FIXME: This should probably print the character literal as a string,
951   // rather than as a numerical value. It would be nice if the behavior matched
952   // what we do to print a string literal; right now, it is impossible to tell
953   // the difference between 'a' and L'a' in C from the JSON output.
954   JOS.attribute("value", CL->getValue());
955 }
956 void JSONNodeDumper::VisitFixedPointLiteral(const FixedPointLiteral *FPL) {
957   JOS.attribute("value", FPL->getValueAsString(/*Radix=*/10));
958 }
959 void JSONNodeDumper::VisitFloatingLiteral(const FloatingLiteral *FL) {
960   JOS.attribute("value", FL->getValueAsApproximateDouble());
961 }
962 void JSONNodeDumper::VisitStringLiteral(const StringLiteral *SL) {
963   std::string Buffer;
964   llvm::raw_string_ostream SS(Buffer);
965   SL->outputString(SS);
966   JOS.attribute("value", SS.str());
967 }
968 void JSONNodeDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE) {
969   JOS.attribute("value", BLE->getValue());
970 }
971 
972 void JSONNodeDumper::VisitIfStmt(const IfStmt *IS) {
973   attributeOnlyIfTrue("hasInit", IS->hasInitStorage());
974   attributeOnlyIfTrue("hasVar", IS->hasVarStorage());
975   attributeOnlyIfTrue("hasElse", IS->hasElseStorage());
976   attributeOnlyIfTrue("isConstexpr", IS->isConstexpr());
977 }
978 
979 void JSONNodeDumper::VisitSwitchStmt(const SwitchStmt *SS) {
980   attributeOnlyIfTrue("hasInit", SS->hasInitStorage());
981   attributeOnlyIfTrue("hasVar", SS->hasVarStorage());
982 }
983 void JSONNodeDumper::VisitCaseStmt(const CaseStmt *CS) {
984   attributeOnlyIfTrue("isGNURange", CS->caseStmtIsGNURange());
985 }
986 
987 void JSONNodeDumper::VisitLabelStmt(const LabelStmt *LS) {
988   JOS.attribute("name", LS->getName());
989   JOS.attribute("declId", createPointerRepresentation(LS->getDecl()));
990 }
991 void JSONNodeDumper::VisitGotoStmt(const GotoStmt *GS) {
992   JOS.attribute("targetLabelDeclId",
993                 createPointerRepresentation(GS->getLabel()));
994 }
995 
996 void JSONNodeDumper::VisitWhileStmt(const WhileStmt *WS) {
997   attributeOnlyIfTrue("hasVar", WS->hasVarStorage());
998 }
999 
1000 void JSONNodeDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt* OACS) {
1001   // FIXME: it would be nice for the ASTNodeTraverser would handle the catch
1002   // parameter the same way for C++ and ObjC rather. In this case, C++ gets a
1003   // null child node and ObjC gets no child node.
1004   attributeOnlyIfTrue("isCatchAll", OACS->getCatchParamDecl() == nullptr);
1005 }
1006 
1007 StringRef JSONNodeDumper::getCommentCommandName(unsigned CommandID) const {
1008   if (Traits)
1009     return Traits->getCommandInfo(CommandID)->Name;
1010   if (const comments::CommandInfo *Info =
1011           comments::CommandTraits::getBuiltinCommandInfo(CommandID))
1012     return Info->Name;
1013   return "<invalid>";
1014 }
1015 
1016 void JSONNodeDumper::visitTextComment(const comments::TextComment *C,
1017                                       const comments::FullComment *) {
1018   JOS.attribute("text", C->getText());
1019 }
1020 
1021 void JSONNodeDumper::visitInlineCommandComment(
1022     const comments::InlineCommandComment *C, const comments::FullComment *) {
1023   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1024 
1025   switch (C->getRenderKind()) {
1026   case comments::InlineCommandComment::RenderNormal:
1027     JOS.attribute("renderKind", "normal");
1028     break;
1029   case comments::InlineCommandComment::RenderBold:
1030     JOS.attribute("renderKind", "bold");
1031     break;
1032   case comments::InlineCommandComment::RenderEmphasized:
1033     JOS.attribute("renderKind", "emphasized");
1034     break;
1035   case comments::InlineCommandComment::RenderMonospaced:
1036     JOS.attribute("renderKind", "monospaced");
1037     break;
1038   }
1039 
1040   llvm::json::Array Args;
1041   for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1042     Args.push_back(C->getArgText(I));
1043 
1044   if (!Args.empty())
1045     JOS.attribute("args", std::move(Args));
1046 }
1047 
1048 void JSONNodeDumper::visitHTMLStartTagComment(
1049     const comments::HTMLStartTagComment *C, const comments::FullComment *) {
1050   JOS.attribute("name", C->getTagName());
1051   attributeOnlyIfTrue("selfClosing", C->isSelfClosing());
1052   attributeOnlyIfTrue("malformed", C->isMalformed());
1053 
1054   llvm::json::Array Attrs;
1055   for (unsigned I = 0, E = C->getNumAttrs(); I < E; ++I)
1056     Attrs.push_back(
1057         {{"name", C->getAttr(I).Name}, {"value", C->getAttr(I).Value}});
1058 
1059   if (!Attrs.empty())
1060     JOS.attribute("attrs", std::move(Attrs));
1061 }
1062 
1063 void JSONNodeDumper::visitHTMLEndTagComment(
1064     const comments::HTMLEndTagComment *C, const comments::FullComment *) {
1065   JOS.attribute("name", C->getTagName());
1066 }
1067 
1068 void JSONNodeDumper::visitBlockCommandComment(
1069     const comments::BlockCommandComment *C, const comments::FullComment *) {
1070   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1071 
1072   llvm::json::Array Args;
1073   for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1074     Args.push_back(C->getArgText(I));
1075 
1076   if (!Args.empty())
1077     JOS.attribute("args", std::move(Args));
1078 }
1079 
1080 void JSONNodeDumper::visitParamCommandComment(
1081     const comments::ParamCommandComment *C, const comments::FullComment *FC) {
1082   switch (C->getDirection()) {
1083   case comments::ParamCommandComment::In:
1084     JOS.attribute("direction", "in");
1085     break;
1086   case comments::ParamCommandComment::Out:
1087     JOS.attribute("direction", "out");
1088     break;
1089   case comments::ParamCommandComment::InOut:
1090     JOS.attribute("direction", "in,out");
1091     break;
1092   }
1093   attributeOnlyIfTrue("explicit", C->isDirectionExplicit());
1094 
1095   if (C->hasParamName())
1096     JOS.attribute("param", C->isParamIndexValid() ? C->getParamName(FC)
1097                                                   : C->getParamNameAsWritten());
1098 
1099   if (C->isParamIndexValid() && !C->isVarArgParam())
1100     JOS.attribute("paramIdx", C->getParamIndex());
1101 }
1102 
1103 void JSONNodeDumper::visitTParamCommandComment(
1104     const comments::TParamCommandComment *C, const comments::FullComment *FC) {
1105   if (C->hasParamName())
1106     JOS.attribute("param", C->isPositionValid() ? C->getParamName(FC)
1107                                                 : C->getParamNameAsWritten());
1108   if (C->isPositionValid()) {
1109     llvm::json::Array Positions;
1110     for (unsigned I = 0, E = C->getDepth(); I < E; ++I)
1111       Positions.push_back(C->getIndex(I));
1112 
1113     if (!Positions.empty())
1114       JOS.attribute("positions", std::move(Positions));
1115   }
1116 }
1117 
1118 void JSONNodeDumper::visitVerbatimBlockComment(
1119     const comments::VerbatimBlockComment *C, const comments::FullComment *) {
1120   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1121   JOS.attribute("closeName", C->getCloseName());
1122 }
1123 
1124 void JSONNodeDumper::visitVerbatimBlockLineComment(
1125     const comments::VerbatimBlockLineComment *C,
1126     const comments::FullComment *) {
1127   JOS.attribute("text", C->getText());
1128 }
1129 
1130 void JSONNodeDumper::visitVerbatimLineComment(
1131     const comments::VerbatimLineComment *C, const comments::FullComment *) {
1132   JOS.attribute("text", C->getText());
1133 }
1134