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