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