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