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::VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE) {
838   JOS.attribute("encodedType", createQualType(OEE->getEncodedType()));
839 }
840 
841 void JSONNodeDumper::VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
842   std::string Str;
843   llvm::raw_string_ostream OS(Str);
844 
845   OME->getSelector().print(OS);
846   JOS.attribute("selector", OS.str());
847 
848   switch (OME->getReceiverKind()) {
849   case ObjCMessageExpr::Instance:
850     JOS.attribute("receiverKind", "instance");
851     break;
852   case ObjCMessageExpr::Class:
853     JOS.attribute("receiverKind", "class");
854     JOS.attribute("classType", createQualType(OME->getClassReceiver()));
855     break;
856   case ObjCMessageExpr::SuperInstance:
857     JOS.attribute("receiverKind", "super (instance)");
858     JOS.attribute("superType", createQualType(OME->getSuperType()));
859     break;
860   case ObjCMessageExpr::SuperClass:
861     JOS.attribute("receiverKind", "super (class)");
862     JOS.attribute("superType", createQualType(OME->getSuperType()));
863     break;
864   }
865 
866   QualType CallReturnTy = OME->getCallReturnType(Ctx);
867   if (OME->getType() != CallReturnTy)
868     JOS.attribute("callReturnType", createQualType(CallReturnTy));
869 }
870 
871 void JSONNodeDumper::VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE) {
872   if (const ObjCMethodDecl *MD = OBE->getBoxingMethod()) {
873     std::string Str;
874     llvm::raw_string_ostream OS(Str);
875 
876     MD->getSelector().print(OS);
877     JOS.attribute("selector", OS.str());
878   }
879 }
880 
881 void JSONNodeDumper::VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE) {
882   std::string Str;
883   llvm::raw_string_ostream OS(Str);
884 
885   OSE->getSelector().print(OS);
886   JOS.attribute("selector", OS.str());
887 }
888 
889 void JSONNodeDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
890   JOS.attribute("protocol", createBareDeclRef(OPE->getProtocol()));
891 }
892 
893 void JSONNodeDumper::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
894   if (OPRE->isImplicitProperty()) {
895     JOS.attribute("propertyKind", "implicit");
896     if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertyGetter())
897       JOS.attribute("getter", createBareDeclRef(MD));
898     if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertySetter())
899       JOS.attribute("setter", createBareDeclRef(MD));
900   } else {
901     JOS.attribute("propertyKind", "explicit");
902     JOS.attribute("property", createBareDeclRef(OPRE->getExplicitProperty()));
903   }
904 
905   attributeOnlyIfTrue("isSuperReceiver", OPRE->isSuperReceiver());
906   attributeOnlyIfTrue("isMessagingGetter", OPRE->isMessagingGetter());
907   attributeOnlyIfTrue("isMessagingSetter", OPRE->isMessagingSetter());
908 }
909 
910 void JSONNodeDumper::VisitObjCSubscriptRefExpr(
911     const ObjCSubscriptRefExpr *OSRE) {
912   JOS.attribute("subscriptKind",
913                 OSRE->isArraySubscriptRefExpr() ? "array" : "dictionary");
914 
915   if (const ObjCMethodDecl *MD = OSRE->getAtIndexMethodDecl())
916     JOS.attribute("getter", createBareDeclRef(MD));
917   if (const ObjCMethodDecl *MD = OSRE->setAtIndexMethodDecl())
918     JOS.attribute("setter", createBareDeclRef(MD));
919 }
920 
921 void JSONNodeDumper::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
922   JOS.attribute("decl", createBareDeclRef(OIRE->getDecl()));
923   attributeOnlyIfTrue("isFreeIvar", OIRE->isFreeIvar());
924   JOS.attribute("isArrow", OIRE->isArrow());
925 }
926 
927 void JSONNodeDumper::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE) {
928   JOS.attribute("value", OBLE->getValue() ? "__objc_yes" : "__objc_no");
929 }
930 
931 void JSONNodeDumper::VisitDeclRefExpr(const DeclRefExpr *DRE) {
932   JOS.attribute("referencedDecl", createBareDeclRef(DRE->getDecl()));
933   if (DRE->getDecl() != DRE->getFoundDecl())
934     JOS.attribute("foundReferencedDecl",
935                   createBareDeclRef(DRE->getFoundDecl()));
936   switch (DRE->isNonOdrUse()) {
937   case NOUR_None: break;
938   case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
939   case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
940   case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
941   }
942 }
943 
944 void JSONNodeDumper::VisitPredefinedExpr(const PredefinedExpr *PE) {
945   JOS.attribute("name", PredefinedExpr::getIdentKindName(PE->getIdentKind()));
946 }
947 
948 void JSONNodeDumper::VisitUnaryOperator(const UnaryOperator *UO) {
949   JOS.attribute("isPostfix", UO->isPostfix());
950   JOS.attribute("opcode", UnaryOperator::getOpcodeStr(UO->getOpcode()));
951   if (!UO->canOverflow())
952     JOS.attribute("canOverflow", false);
953 }
954 
955 void JSONNodeDumper::VisitBinaryOperator(const BinaryOperator *BO) {
956   JOS.attribute("opcode", BinaryOperator::getOpcodeStr(BO->getOpcode()));
957 }
958 
959 void JSONNodeDumper::VisitCompoundAssignOperator(
960     const CompoundAssignOperator *CAO) {
961   VisitBinaryOperator(CAO);
962   JOS.attribute("computeLHSType", createQualType(CAO->getComputationLHSType()));
963   JOS.attribute("computeResultType",
964                 createQualType(CAO->getComputationResultType()));
965 }
966 
967 void JSONNodeDumper::VisitMemberExpr(const MemberExpr *ME) {
968   // Note, we always write this Boolean field because the information it conveys
969   // is critical to understanding the AST node.
970   ValueDecl *VD = ME->getMemberDecl();
971   JOS.attribute("name", VD && VD->getDeclName() ? VD->getNameAsString() : "");
972   JOS.attribute("isArrow", ME->isArrow());
973   JOS.attribute("referencedMemberDecl", createPointerRepresentation(VD));
974   switch (ME->isNonOdrUse()) {
975   case NOUR_None: break;
976   case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
977   case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
978   case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
979   }
980 }
981 
982 void JSONNodeDumper::VisitCXXNewExpr(const CXXNewExpr *NE) {
983   attributeOnlyIfTrue("isGlobal", NE->isGlobalNew());
984   attributeOnlyIfTrue("isArray", NE->isArray());
985   attributeOnlyIfTrue("isPlacement", NE->getNumPlacementArgs() != 0);
986   switch (NE->getInitializationStyle()) {
987   case CXXNewExpr::NoInit: break;
988   case CXXNewExpr::CallInit: JOS.attribute("initStyle", "call"); break;
989   case CXXNewExpr::ListInit: JOS.attribute("initStyle", "list"); break;
990   }
991   if (const FunctionDecl *FD = NE->getOperatorNew())
992     JOS.attribute("operatorNewDecl", createBareDeclRef(FD));
993   if (const FunctionDecl *FD = NE->getOperatorDelete())
994     JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
995 }
996 void JSONNodeDumper::VisitCXXDeleteExpr(const CXXDeleteExpr *DE) {
997   attributeOnlyIfTrue("isGlobal", DE->isGlobalDelete());
998   attributeOnlyIfTrue("isArray", DE->isArrayForm());
999   attributeOnlyIfTrue("isArrayAsWritten", DE->isArrayFormAsWritten());
1000   if (const FunctionDecl *FD = DE->getOperatorDelete())
1001     JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
1002 }
1003 
1004 void JSONNodeDumper::VisitCXXThisExpr(const CXXThisExpr *TE) {
1005   attributeOnlyIfTrue("implicit", TE->isImplicit());
1006 }
1007 
1008 void JSONNodeDumper::VisitCastExpr(const CastExpr *CE) {
1009   JOS.attribute("castKind", CE->getCastKindName());
1010   llvm::json::Array Path = createCastPath(CE);
1011   if (!Path.empty())
1012     JOS.attribute("path", std::move(Path));
1013   // FIXME: This may not be useful information as it can be obtusely gleaned
1014   // from the inner[] array.
1015   if (const NamedDecl *ND = CE->getConversionFunction())
1016     JOS.attribute("conversionFunc", createBareDeclRef(ND));
1017 }
1018 
1019 void JSONNodeDumper::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
1020   VisitCastExpr(ICE);
1021   attributeOnlyIfTrue("isPartOfExplicitCast", ICE->isPartOfExplicitCast());
1022 }
1023 
1024 void JSONNodeDumper::VisitCallExpr(const CallExpr *CE) {
1025   attributeOnlyIfTrue("adl", CE->usesADL());
1026 }
1027 
1028 void JSONNodeDumper::VisitUnaryExprOrTypeTraitExpr(
1029     const UnaryExprOrTypeTraitExpr *TTE) {
1030   switch (TTE->getKind()) {
1031   case UETT_SizeOf: JOS.attribute("name", "sizeof"); break;
1032   case UETT_AlignOf: JOS.attribute("name", "alignof"); break;
1033   case UETT_VecStep:  JOS.attribute("name", "vec_step"); break;
1034   case UETT_PreferredAlignOf:  JOS.attribute("name", "__alignof"); break;
1035   case UETT_OpenMPRequiredSimdAlign:
1036     JOS.attribute("name", "__builtin_omp_required_simd_align"); break;
1037   }
1038   if (TTE->isArgumentType())
1039     JOS.attribute("argType", createQualType(TTE->getArgumentType()));
1040 }
1041 
1042 void JSONNodeDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE) {
1043   VisitNamedDecl(SOPE->getPack());
1044 }
1045 
1046 void JSONNodeDumper::VisitUnresolvedLookupExpr(
1047     const UnresolvedLookupExpr *ULE) {
1048   JOS.attribute("usesADL", ULE->requiresADL());
1049   JOS.attribute("name", ULE->getName().getAsString());
1050 
1051   JOS.attributeArray("lookups", [this, ULE] {
1052     for (const NamedDecl *D : ULE->decls())
1053       JOS.value(createBareDeclRef(D));
1054   });
1055 }
1056 
1057 void JSONNodeDumper::VisitAddrLabelExpr(const AddrLabelExpr *ALE) {
1058   JOS.attribute("name", ALE->getLabel()->getName());
1059   JOS.attribute("labelDeclId", createPointerRepresentation(ALE->getLabel()));
1060 }
1061 
1062 void JSONNodeDumper::VisitCXXTypeidExpr(const CXXTypeidExpr *CTE) {
1063   if (CTE->isTypeOperand()) {
1064     QualType Adjusted = CTE->getTypeOperand(Ctx);
1065     QualType Unadjusted = CTE->getTypeOperandSourceInfo()->getType();
1066     JOS.attribute("typeArg", createQualType(Unadjusted));
1067     if (Adjusted != Unadjusted)
1068       JOS.attribute("adjustedTypeArg", createQualType(Adjusted));
1069   }
1070 }
1071 
1072 void JSONNodeDumper::VisitConstantExpr(const ConstantExpr *CE) {
1073   if (CE->getResultAPValueKind() != APValue::None) {
1074     std::string Str;
1075     llvm::raw_string_ostream OS(Str);
1076     CE->getAPValueResult().printPretty(OS, Ctx, CE->getType());
1077     JOS.attribute("value", OS.str());
1078   }
1079 }
1080 
1081 void JSONNodeDumper::VisitInitListExpr(const InitListExpr *ILE) {
1082   if (const FieldDecl *FD = ILE->getInitializedFieldInUnion())
1083     JOS.attribute("field", createBareDeclRef(FD));
1084 }
1085 
1086 void JSONNodeDumper::VisitGenericSelectionExpr(
1087     const GenericSelectionExpr *GSE) {
1088   attributeOnlyIfTrue("resultDependent", GSE->isResultDependent());
1089 }
1090 
1091 void JSONNodeDumper::VisitCXXUnresolvedConstructExpr(
1092     const CXXUnresolvedConstructExpr *UCE) {
1093   if (UCE->getType() != UCE->getTypeAsWritten())
1094     JOS.attribute("typeAsWritten", createQualType(UCE->getTypeAsWritten()));
1095   attributeOnlyIfTrue("list", UCE->isListInitialization());
1096 }
1097 
1098 void JSONNodeDumper::VisitCXXConstructExpr(const CXXConstructExpr *CE) {
1099   CXXConstructorDecl *Ctor = CE->getConstructor();
1100   JOS.attribute("ctorType", createQualType(Ctor->getType()));
1101   attributeOnlyIfTrue("elidable", CE->isElidable());
1102   attributeOnlyIfTrue("list", CE->isListInitialization());
1103   attributeOnlyIfTrue("initializer_list", CE->isStdInitListInitialization());
1104   attributeOnlyIfTrue("zeroing", CE->requiresZeroInitialization());
1105   attributeOnlyIfTrue("hadMultipleCandidates", CE->hadMultipleCandidates());
1106 
1107   switch (CE->getConstructionKind()) {
1108   case CXXConstructExpr::CK_Complete:
1109     JOS.attribute("constructionKind", "complete");
1110     break;
1111   case CXXConstructExpr::CK_Delegating:
1112     JOS.attribute("constructionKind", "delegating");
1113     break;
1114   case CXXConstructExpr::CK_NonVirtualBase:
1115     JOS.attribute("constructionKind", "non-virtual base");
1116     break;
1117   case CXXConstructExpr::CK_VirtualBase:
1118     JOS.attribute("constructionKind", "virtual base");
1119     break;
1120   }
1121 }
1122 
1123 void JSONNodeDumper::VisitExprWithCleanups(const ExprWithCleanups *EWC) {
1124   attributeOnlyIfTrue("cleanupsHaveSideEffects",
1125                       EWC->cleanupsHaveSideEffects());
1126   if (EWC->getNumObjects()) {
1127     JOS.attributeArray("cleanups", [this, EWC] {
1128       for (const ExprWithCleanups::CleanupObject &CO : EWC->getObjects())
1129         JOS.value(createBareDeclRef(CO));
1130     });
1131   }
1132 }
1133 
1134 void JSONNodeDumper::VisitCXXBindTemporaryExpr(
1135     const CXXBindTemporaryExpr *BTE) {
1136   const CXXTemporary *Temp = BTE->getTemporary();
1137   JOS.attribute("temp", createPointerRepresentation(Temp));
1138   if (const CXXDestructorDecl *Dtor = Temp->getDestructor())
1139     JOS.attribute("dtor", createBareDeclRef(Dtor));
1140 }
1141 
1142 void JSONNodeDumper::VisitMaterializeTemporaryExpr(
1143     const MaterializeTemporaryExpr *MTE) {
1144   if (const ValueDecl *VD = MTE->getExtendingDecl())
1145     JOS.attribute("extendingDecl", createBareDeclRef(VD));
1146 
1147   switch (MTE->getStorageDuration()) {
1148   case SD_Automatic:
1149     JOS.attribute("storageDuration", "automatic");
1150     break;
1151   case SD_Dynamic:
1152     JOS.attribute("storageDuration", "dynamic");
1153     break;
1154   case SD_FullExpression:
1155     JOS.attribute("storageDuration", "full expression");
1156     break;
1157   case SD_Static:
1158     JOS.attribute("storageDuration", "static");
1159     break;
1160   case SD_Thread:
1161     JOS.attribute("storageDuration", "thread");
1162     break;
1163   }
1164 
1165   attributeOnlyIfTrue("boundToLValueRef", MTE->isBoundToLvalueReference());
1166 }
1167 
1168 void JSONNodeDumper::VisitCXXDependentScopeMemberExpr(
1169     const CXXDependentScopeMemberExpr *DSME) {
1170   JOS.attribute("isArrow", DSME->isArrow());
1171   JOS.attribute("member", DSME->getMember().getAsString());
1172   attributeOnlyIfTrue("hasTemplateKeyword", DSME->hasTemplateKeyword());
1173   attributeOnlyIfTrue("hasExplicitTemplateArgs",
1174                       DSME->hasExplicitTemplateArgs());
1175 
1176   if (DSME->getNumTemplateArgs()) {
1177     JOS.attributeArray("explicitTemplateArgs", [DSME, this] {
1178       for (const TemplateArgumentLoc &TAL : DSME->template_arguments())
1179         JOS.object(
1180             [&TAL, this] { Visit(TAL.getArgument(), TAL.getSourceRange()); });
1181     });
1182   }
1183 }
1184 
1185 void JSONNodeDumper::VisitIntegerLiteral(const IntegerLiteral *IL) {
1186   JOS.attribute("value",
1187                 IL->getValue().toString(
1188                     /*Radix=*/10, IL->getType()->isSignedIntegerType()));
1189 }
1190 void JSONNodeDumper::VisitCharacterLiteral(const CharacterLiteral *CL) {
1191   // FIXME: This should probably print the character literal as a string,
1192   // rather than as a numerical value. It would be nice if the behavior matched
1193   // what we do to print a string literal; right now, it is impossible to tell
1194   // the difference between 'a' and L'a' in C from the JSON output.
1195   JOS.attribute("value", CL->getValue());
1196 }
1197 void JSONNodeDumper::VisitFixedPointLiteral(const FixedPointLiteral *FPL) {
1198   JOS.attribute("value", FPL->getValueAsString(/*Radix=*/10));
1199 }
1200 void JSONNodeDumper::VisitFloatingLiteral(const FloatingLiteral *FL) {
1201   JOS.attribute("value", FL->getValueAsApproximateDouble());
1202 }
1203 void JSONNodeDumper::VisitStringLiteral(const StringLiteral *SL) {
1204   std::string Buffer;
1205   llvm::raw_string_ostream SS(Buffer);
1206   SL->outputString(SS);
1207   JOS.attribute("value", SS.str());
1208 }
1209 void JSONNodeDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE) {
1210   JOS.attribute("value", BLE->getValue());
1211 }
1212 
1213 void JSONNodeDumper::VisitIfStmt(const IfStmt *IS) {
1214   attributeOnlyIfTrue("hasInit", IS->hasInitStorage());
1215   attributeOnlyIfTrue("hasVar", IS->hasVarStorage());
1216   attributeOnlyIfTrue("hasElse", IS->hasElseStorage());
1217   attributeOnlyIfTrue("isConstexpr", IS->isConstexpr());
1218 }
1219 
1220 void JSONNodeDumper::VisitSwitchStmt(const SwitchStmt *SS) {
1221   attributeOnlyIfTrue("hasInit", SS->hasInitStorage());
1222   attributeOnlyIfTrue("hasVar", SS->hasVarStorage());
1223 }
1224 void JSONNodeDumper::VisitCaseStmt(const CaseStmt *CS) {
1225   attributeOnlyIfTrue("isGNURange", CS->caseStmtIsGNURange());
1226 }
1227 
1228 void JSONNodeDumper::VisitLabelStmt(const LabelStmt *LS) {
1229   JOS.attribute("name", LS->getName());
1230   JOS.attribute("declId", createPointerRepresentation(LS->getDecl()));
1231 }
1232 void JSONNodeDumper::VisitGotoStmt(const GotoStmt *GS) {
1233   JOS.attribute("targetLabelDeclId",
1234                 createPointerRepresentation(GS->getLabel()));
1235 }
1236 
1237 void JSONNodeDumper::VisitWhileStmt(const WhileStmt *WS) {
1238   attributeOnlyIfTrue("hasVar", WS->hasVarStorage());
1239 }
1240 
1241 void JSONNodeDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt* OACS) {
1242   // FIXME: it would be nice for the ASTNodeTraverser would handle the catch
1243   // parameter the same way for C++ and ObjC rather. In this case, C++ gets a
1244   // null child node and ObjC gets no child node.
1245   attributeOnlyIfTrue("isCatchAll", OACS->getCatchParamDecl() == nullptr);
1246 }
1247 
1248 void JSONNodeDumper::VisitNullTemplateArgument(const TemplateArgument &TA) {
1249   JOS.attribute("isNull", true);
1250 }
1251 void JSONNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
1252   JOS.attribute("type", createQualType(TA.getAsType()));
1253 }
1254 void JSONNodeDumper::VisitDeclarationTemplateArgument(
1255     const TemplateArgument &TA) {
1256   JOS.attribute("decl", createBareDeclRef(TA.getAsDecl()));
1257 }
1258 void JSONNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
1259   JOS.attribute("isNullptr", true);
1260 }
1261 void JSONNodeDumper::VisitIntegralTemplateArgument(const TemplateArgument &TA) {
1262   JOS.attribute("value", TA.getAsIntegral().getSExtValue());
1263 }
1264 void JSONNodeDumper::VisitTemplateTemplateArgument(const TemplateArgument &TA) {
1265   // FIXME: cannot just call dump() on the argument, as that doesn't specify
1266   // the output format.
1267 }
1268 void JSONNodeDumper::VisitTemplateExpansionTemplateArgument(
1269     const TemplateArgument &TA) {
1270   // FIXME: cannot just call dump() on the argument, as that doesn't specify
1271   // the output format.
1272 }
1273 void JSONNodeDumper::VisitExpressionTemplateArgument(
1274     const TemplateArgument &TA) {
1275   JOS.attribute("isExpr", true);
1276 }
1277 void JSONNodeDumper::VisitPackTemplateArgument(const TemplateArgument &TA) {
1278   JOS.attribute("isPack", true);
1279 }
1280 
1281 StringRef JSONNodeDumper::getCommentCommandName(unsigned CommandID) const {
1282   if (Traits)
1283     return Traits->getCommandInfo(CommandID)->Name;
1284   if (const comments::CommandInfo *Info =
1285           comments::CommandTraits::getBuiltinCommandInfo(CommandID))
1286     return Info->Name;
1287   return "<invalid>";
1288 }
1289 
1290 void JSONNodeDumper::visitTextComment(const comments::TextComment *C,
1291                                       const comments::FullComment *) {
1292   JOS.attribute("text", C->getText());
1293 }
1294 
1295 void JSONNodeDumper::visitInlineCommandComment(
1296     const comments::InlineCommandComment *C, const comments::FullComment *) {
1297   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1298 
1299   switch (C->getRenderKind()) {
1300   case comments::InlineCommandComment::RenderNormal:
1301     JOS.attribute("renderKind", "normal");
1302     break;
1303   case comments::InlineCommandComment::RenderBold:
1304     JOS.attribute("renderKind", "bold");
1305     break;
1306   case comments::InlineCommandComment::RenderEmphasized:
1307     JOS.attribute("renderKind", "emphasized");
1308     break;
1309   case comments::InlineCommandComment::RenderMonospaced:
1310     JOS.attribute("renderKind", "monospaced");
1311     break;
1312   }
1313 
1314   llvm::json::Array Args;
1315   for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1316     Args.push_back(C->getArgText(I));
1317 
1318   if (!Args.empty())
1319     JOS.attribute("args", std::move(Args));
1320 }
1321 
1322 void JSONNodeDumper::visitHTMLStartTagComment(
1323     const comments::HTMLStartTagComment *C, const comments::FullComment *) {
1324   JOS.attribute("name", C->getTagName());
1325   attributeOnlyIfTrue("selfClosing", C->isSelfClosing());
1326   attributeOnlyIfTrue("malformed", C->isMalformed());
1327 
1328   llvm::json::Array Attrs;
1329   for (unsigned I = 0, E = C->getNumAttrs(); I < E; ++I)
1330     Attrs.push_back(
1331         {{"name", C->getAttr(I).Name}, {"value", C->getAttr(I).Value}});
1332 
1333   if (!Attrs.empty())
1334     JOS.attribute("attrs", std::move(Attrs));
1335 }
1336 
1337 void JSONNodeDumper::visitHTMLEndTagComment(
1338     const comments::HTMLEndTagComment *C, const comments::FullComment *) {
1339   JOS.attribute("name", C->getTagName());
1340 }
1341 
1342 void JSONNodeDumper::visitBlockCommandComment(
1343     const comments::BlockCommandComment *C, const comments::FullComment *) {
1344   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1345 
1346   llvm::json::Array Args;
1347   for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1348     Args.push_back(C->getArgText(I));
1349 
1350   if (!Args.empty())
1351     JOS.attribute("args", std::move(Args));
1352 }
1353 
1354 void JSONNodeDumper::visitParamCommandComment(
1355     const comments::ParamCommandComment *C, const comments::FullComment *FC) {
1356   switch (C->getDirection()) {
1357   case comments::ParamCommandComment::In:
1358     JOS.attribute("direction", "in");
1359     break;
1360   case comments::ParamCommandComment::Out:
1361     JOS.attribute("direction", "out");
1362     break;
1363   case comments::ParamCommandComment::InOut:
1364     JOS.attribute("direction", "in,out");
1365     break;
1366   }
1367   attributeOnlyIfTrue("explicit", C->isDirectionExplicit());
1368 
1369   if (C->hasParamName())
1370     JOS.attribute("param", C->isParamIndexValid() ? C->getParamName(FC)
1371                                                   : C->getParamNameAsWritten());
1372 
1373   if (C->isParamIndexValid() && !C->isVarArgParam())
1374     JOS.attribute("paramIdx", C->getParamIndex());
1375 }
1376 
1377 void JSONNodeDumper::visitTParamCommandComment(
1378     const comments::TParamCommandComment *C, const comments::FullComment *FC) {
1379   if (C->hasParamName())
1380     JOS.attribute("param", C->isPositionValid() ? C->getParamName(FC)
1381                                                 : C->getParamNameAsWritten());
1382   if (C->isPositionValid()) {
1383     llvm::json::Array Positions;
1384     for (unsigned I = 0, E = C->getDepth(); I < E; ++I)
1385       Positions.push_back(C->getIndex(I));
1386 
1387     if (!Positions.empty())
1388       JOS.attribute("positions", std::move(Positions));
1389   }
1390 }
1391 
1392 void JSONNodeDumper::visitVerbatimBlockComment(
1393     const comments::VerbatimBlockComment *C, const comments::FullComment *) {
1394   JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1395   JOS.attribute("closeName", C->getCloseName());
1396 }
1397 
1398 void JSONNodeDumper::visitVerbatimBlockLineComment(
1399     const comments::VerbatimBlockLineComment *C,
1400     const comments::FullComment *) {
1401   JOS.attribute("text", C->getText());
1402 }
1403 
1404 void JSONNodeDumper::visitVerbatimLineComment(
1405     const comments::VerbatimLineComment *C, const comments::FullComment *) {
1406   JOS.attribute("text", C->getText());
1407 }
1408