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