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