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