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 }
620 }
621
VisitUnresolvedUsingType(const UnresolvedUsingType * UUT)622 void JSONNodeDumper::VisitUnresolvedUsingType(const UnresolvedUsingType *UUT) {
623 JOS.attribute("decl", createBareDeclRef(UUT->getDecl()));
624 }
625
VisitUnaryTransformType(const UnaryTransformType * UTT)626 void JSONNodeDumper::VisitUnaryTransformType(const UnaryTransformType *UTT) {
627 switch (UTT->getUTTKind()) {
628 case UnaryTransformType::EnumUnderlyingType:
629 JOS.attribute("transformKind", "underlying_type");
630 break;
631 }
632 }
633
VisitTagType(const TagType * TT)634 void JSONNodeDumper::VisitTagType(const TagType *TT) {
635 JOS.attribute("decl", createBareDeclRef(TT->getDecl()));
636 }
637
VisitTemplateTypeParmType(const TemplateTypeParmType * TTPT)638 void JSONNodeDumper::VisitTemplateTypeParmType(
639 const TemplateTypeParmType *TTPT) {
640 JOS.attribute("depth", TTPT->getDepth());
641 JOS.attribute("index", TTPT->getIndex());
642 attributeOnlyIfTrue("isPack", TTPT->isParameterPack());
643 JOS.attribute("decl", createBareDeclRef(TTPT->getDecl()));
644 }
645
VisitAutoType(const AutoType * AT)646 void JSONNodeDumper::VisitAutoType(const AutoType *AT) {
647 JOS.attribute("undeduced", !AT->isDeduced());
648 switch (AT->getKeyword()) {
649 case AutoTypeKeyword::Auto:
650 JOS.attribute("typeKeyword", "auto");
651 break;
652 case AutoTypeKeyword::DecltypeAuto:
653 JOS.attribute("typeKeyword", "decltype(auto)");
654 break;
655 case AutoTypeKeyword::GNUAutoType:
656 JOS.attribute("typeKeyword", "__auto_type");
657 break;
658 }
659 }
660
VisitTemplateSpecializationType(const TemplateSpecializationType * TST)661 void JSONNodeDumper::VisitTemplateSpecializationType(
662 const TemplateSpecializationType *TST) {
663 attributeOnlyIfTrue("isAlias", TST->isTypeAlias());
664
665 std::string Str;
666 llvm::raw_string_ostream OS(Str);
667 TST->getTemplateName().print(OS, PrintPolicy);
668 JOS.attribute("templateName", OS.str());
669 }
670
VisitInjectedClassNameType(const InjectedClassNameType * ICNT)671 void JSONNodeDumper::VisitInjectedClassNameType(
672 const InjectedClassNameType *ICNT) {
673 JOS.attribute("decl", createBareDeclRef(ICNT->getDecl()));
674 }
675
VisitObjCInterfaceType(const ObjCInterfaceType * OIT)676 void JSONNodeDumper::VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
677 JOS.attribute("decl", createBareDeclRef(OIT->getDecl()));
678 }
679
VisitPackExpansionType(const PackExpansionType * PET)680 void JSONNodeDumper::VisitPackExpansionType(const PackExpansionType *PET) {
681 if (llvm::Optional<unsigned> N = PET->getNumExpansions())
682 JOS.attribute("numExpansions", *N);
683 }
684
VisitElaboratedType(const ElaboratedType * ET)685 void JSONNodeDumper::VisitElaboratedType(const ElaboratedType *ET) {
686 if (const NestedNameSpecifier *NNS = ET->getQualifier()) {
687 std::string Str;
688 llvm::raw_string_ostream OS(Str);
689 NNS->print(OS, PrintPolicy, /*ResolveTemplateArgs*/ true);
690 JOS.attribute("qualifier", OS.str());
691 }
692 if (const TagDecl *TD = ET->getOwnedTagDecl())
693 JOS.attribute("ownedTagDecl", createBareDeclRef(TD));
694 }
695
VisitMacroQualifiedType(const MacroQualifiedType * MQT)696 void JSONNodeDumper::VisitMacroQualifiedType(const MacroQualifiedType *MQT) {
697 JOS.attribute("macroName", MQT->getMacroIdentifier()->getName());
698 }
699
VisitMemberPointerType(const MemberPointerType * MPT)700 void JSONNodeDumper::VisitMemberPointerType(const MemberPointerType *MPT) {
701 attributeOnlyIfTrue("isData", MPT->isMemberDataPointer());
702 attributeOnlyIfTrue("isFunction", MPT->isMemberFunctionPointer());
703 }
704
VisitNamedDecl(const NamedDecl * ND)705 void JSONNodeDumper::VisitNamedDecl(const NamedDecl *ND) {
706 if (ND && ND->getDeclName()) {
707 JOS.attribute("name", ND->getNameAsString());
708 std::string MangledName = ASTNameGen.getName(ND);
709 if (!MangledName.empty())
710 JOS.attribute("mangledName", MangledName);
711 }
712 }
713
VisitTypedefDecl(const TypedefDecl * TD)714 void JSONNodeDumper::VisitTypedefDecl(const TypedefDecl *TD) {
715 VisitNamedDecl(TD);
716 JOS.attribute("type", createQualType(TD->getUnderlyingType()));
717 }
718
VisitTypeAliasDecl(const TypeAliasDecl * TAD)719 void JSONNodeDumper::VisitTypeAliasDecl(const TypeAliasDecl *TAD) {
720 VisitNamedDecl(TAD);
721 JOS.attribute("type", createQualType(TAD->getUnderlyingType()));
722 }
723
VisitNamespaceDecl(const NamespaceDecl * ND)724 void JSONNodeDumper::VisitNamespaceDecl(const NamespaceDecl *ND) {
725 VisitNamedDecl(ND);
726 attributeOnlyIfTrue("isInline", ND->isInline());
727 if (!ND->isOriginalNamespace())
728 JOS.attribute("originalNamespace",
729 createBareDeclRef(ND->getOriginalNamespace()));
730 }
731
VisitUsingDirectiveDecl(const UsingDirectiveDecl * UDD)732 void JSONNodeDumper::VisitUsingDirectiveDecl(const UsingDirectiveDecl *UDD) {
733 JOS.attribute("nominatedNamespace",
734 createBareDeclRef(UDD->getNominatedNamespace()));
735 }
736
VisitNamespaceAliasDecl(const NamespaceAliasDecl * NAD)737 void JSONNodeDumper::VisitNamespaceAliasDecl(const NamespaceAliasDecl *NAD) {
738 VisitNamedDecl(NAD);
739 JOS.attribute("aliasedNamespace",
740 createBareDeclRef(NAD->getAliasedNamespace()));
741 }
742
VisitUsingDecl(const UsingDecl * UD)743 void JSONNodeDumper::VisitUsingDecl(const UsingDecl *UD) {
744 std::string Name;
745 if (const NestedNameSpecifier *NNS = UD->getQualifier()) {
746 llvm::raw_string_ostream SOS(Name);
747 NNS->print(SOS, UD->getASTContext().getPrintingPolicy());
748 }
749 Name += UD->getNameAsString();
750 JOS.attribute("name", Name);
751 }
752
VisitUsingShadowDecl(const UsingShadowDecl * USD)753 void JSONNodeDumper::VisitUsingShadowDecl(const UsingShadowDecl *USD) {
754 JOS.attribute("target", createBareDeclRef(USD->getTargetDecl()));
755 }
756
VisitVarDecl(const VarDecl * VD)757 void JSONNodeDumper::VisitVarDecl(const VarDecl *VD) {
758 VisitNamedDecl(VD);
759 JOS.attribute("type", createQualType(VD->getType()));
760
761 StorageClass SC = VD->getStorageClass();
762 if (SC != SC_None)
763 JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
764 switch (VD->getTLSKind()) {
765 case VarDecl::TLS_Dynamic: JOS.attribute("tls", "dynamic"); break;
766 case VarDecl::TLS_Static: JOS.attribute("tls", "static"); break;
767 case VarDecl::TLS_None: break;
768 }
769 attributeOnlyIfTrue("nrvo", VD->isNRVOVariable());
770 attributeOnlyIfTrue("inline", VD->isInline());
771 attributeOnlyIfTrue("constexpr", VD->isConstexpr());
772 attributeOnlyIfTrue("modulePrivate", VD->isModulePrivate());
773 if (VD->hasInit()) {
774 switch (VD->getInitStyle()) {
775 case VarDecl::CInit: JOS.attribute("init", "c"); break;
776 case VarDecl::CallInit: JOS.attribute("init", "call"); break;
777 case VarDecl::ListInit: JOS.attribute("init", "list"); break;
778 }
779 }
780 attributeOnlyIfTrue("isParameterPack", VD->isParameterPack());
781 }
782
VisitFieldDecl(const FieldDecl * FD)783 void JSONNodeDumper::VisitFieldDecl(const FieldDecl *FD) {
784 VisitNamedDecl(FD);
785 JOS.attribute("type", createQualType(FD->getType()));
786 attributeOnlyIfTrue("mutable", FD->isMutable());
787 attributeOnlyIfTrue("modulePrivate", FD->isModulePrivate());
788 attributeOnlyIfTrue("isBitfield", FD->isBitField());
789 attributeOnlyIfTrue("hasInClassInitializer", FD->hasInClassInitializer());
790 }
791
VisitFunctionDecl(const FunctionDecl * FD)792 void JSONNodeDumper::VisitFunctionDecl(const FunctionDecl *FD) {
793 VisitNamedDecl(FD);
794 JOS.attribute("type", createQualType(FD->getType()));
795 StorageClass SC = FD->getStorageClass();
796 if (SC != SC_None)
797 JOS.attribute("storageClass", VarDecl::getStorageClassSpecifierString(SC));
798 attributeOnlyIfTrue("inline", FD->isInlineSpecified());
799 attributeOnlyIfTrue("virtual", FD->isVirtualAsWritten());
800 attributeOnlyIfTrue("pure", FD->isPure());
801 attributeOnlyIfTrue("explicitlyDeleted", FD->isDeletedAsWritten());
802 attributeOnlyIfTrue("constexpr", FD->isConstexpr());
803 attributeOnlyIfTrue("variadic", FD->isVariadic());
804
805 if (FD->isDefaulted())
806 JOS.attribute("explicitlyDefaulted",
807 FD->isDeleted() ? "deleted" : "default");
808 }
809
VisitEnumDecl(const EnumDecl * ED)810 void JSONNodeDumper::VisitEnumDecl(const EnumDecl *ED) {
811 VisitNamedDecl(ED);
812 if (ED->isFixed())
813 JOS.attribute("fixedUnderlyingType", createQualType(ED->getIntegerType()));
814 if (ED->isScoped())
815 JOS.attribute("scopedEnumTag",
816 ED->isScopedUsingClassTag() ? "class" : "struct");
817 }
VisitEnumConstantDecl(const EnumConstantDecl * ECD)818 void JSONNodeDumper::VisitEnumConstantDecl(const EnumConstantDecl *ECD) {
819 VisitNamedDecl(ECD);
820 JOS.attribute("type", createQualType(ECD->getType()));
821 }
822
VisitRecordDecl(const RecordDecl * RD)823 void JSONNodeDumper::VisitRecordDecl(const RecordDecl *RD) {
824 VisitNamedDecl(RD);
825 JOS.attribute("tagUsed", RD->getKindName());
826 attributeOnlyIfTrue("completeDefinition", RD->isCompleteDefinition());
827 }
VisitCXXRecordDecl(const CXXRecordDecl * RD)828 void JSONNodeDumper::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
829 VisitRecordDecl(RD);
830
831 // All other information requires a complete definition.
832 if (!RD->isCompleteDefinition())
833 return;
834
835 JOS.attribute("definitionData", createCXXRecordDefinitionData(RD));
836 if (RD->getNumBases()) {
837 JOS.attributeArray("bases", [this, RD] {
838 for (const auto &Spec : RD->bases())
839 JOS.value(createCXXBaseSpecifier(Spec));
840 });
841 }
842 }
843
VisitTemplateTypeParmDecl(const TemplateTypeParmDecl * D)844 void JSONNodeDumper::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
845 VisitNamedDecl(D);
846 JOS.attribute("tagUsed", D->wasDeclaredWithTypename() ? "typename" : "class");
847 JOS.attribute("depth", D->getDepth());
848 JOS.attribute("index", D->getIndex());
849 attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
850
851 if (D->hasDefaultArgument())
852 JOS.attributeObject("defaultArg", [=] {
853 Visit(D->getDefaultArgument(), SourceRange(),
854 D->getDefaultArgStorage().getInheritedFrom(),
855 D->defaultArgumentWasInherited() ? "inherited from" : "previous");
856 });
857 }
858
VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl * D)859 void JSONNodeDumper::VisitNonTypeTemplateParmDecl(
860 const NonTypeTemplateParmDecl *D) {
861 VisitNamedDecl(D);
862 JOS.attribute("type", createQualType(D->getType()));
863 JOS.attribute("depth", D->getDepth());
864 JOS.attribute("index", D->getIndex());
865 attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
866
867 if (D->hasDefaultArgument())
868 JOS.attributeObject("defaultArg", [=] {
869 Visit(D->getDefaultArgument(), SourceRange(),
870 D->getDefaultArgStorage().getInheritedFrom(),
871 D->defaultArgumentWasInherited() ? "inherited from" : "previous");
872 });
873 }
874
VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl * D)875 void JSONNodeDumper::VisitTemplateTemplateParmDecl(
876 const TemplateTemplateParmDecl *D) {
877 VisitNamedDecl(D);
878 JOS.attribute("depth", D->getDepth());
879 JOS.attribute("index", D->getIndex());
880 attributeOnlyIfTrue("isParameterPack", D->isParameterPack());
881
882 if (D->hasDefaultArgument())
883 JOS.attributeObject("defaultArg", [=] {
884 Visit(D->getDefaultArgument().getArgument(),
885 D->getDefaultArgStorage().getInheritedFrom()->getSourceRange(),
886 D->getDefaultArgStorage().getInheritedFrom(),
887 D->defaultArgumentWasInherited() ? "inherited from" : "previous");
888 });
889 }
890
VisitLinkageSpecDecl(const LinkageSpecDecl * LSD)891 void JSONNodeDumper::VisitLinkageSpecDecl(const LinkageSpecDecl *LSD) {
892 StringRef Lang;
893 switch (LSD->getLanguage()) {
894 case LinkageSpecDecl::lang_c: Lang = "C"; break;
895 case LinkageSpecDecl::lang_cxx: Lang = "C++"; break;
896 }
897 JOS.attribute("language", Lang);
898 attributeOnlyIfTrue("hasBraces", LSD->hasBraces());
899 }
900
VisitAccessSpecDecl(const AccessSpecDecl * ASD)901 void JSONNodeDumper::VisitAccessSpecDecl(const AccessSpecDecl *ASD) {
902 JOS.attribute("access", createAccessSpecifier(ASD->getAccess()));
903 }
904
VisitFriendDecl(const FriendDecl * FD)905 void JSONNodeDumper::VisitFriendDecl(const FriendDecl *FD) {
906 if (const TypeSourceInfo *T = FD->getFriendType())
907 JOS.attribute("type", createQualType(T->getType()));
908 }
909
VisitObjCIvarDecl(const ObjCIvarDecl * D)910 void JSONNodeDumper::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
911 VisitNamedDecl(D);
912 JOS.attribute("type", createQualType(D->getType()));
913 attributeOnlyIfTrue("synthesized", D->getSynthesize());
914 switch (D->getAccessControl()) {
915 case ObjCIvarDecl::None: JOS.attribute("access", "none"); break;
916 case ObjCIvarDecl::Private: JOS.attribute("access", "private"); break;
917 case ObjCIvarDecl::Protected: JOS.attribute("access", "protected"); break;
918 case ObjCIvarDecl::Public: JOS.attribute("access", "public"); break;
919 case ObjCIvarDecl::Package: JOS.attribute("access", "package"); break;
920 }
921 }
922
VisitObjCMethodDecl(const ObjCMethodDecl * D)923 void JSONNodeDumper::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
924 VisitNamedDecl(D);
925 JOS.attribute("returnType", createQualType(D->getReturnType()));
926 JOS.attribute("instance", D->isInstanceMethod());
927 attributeOnlyIfTrue("variadic", D->isVariadic());
928 }
929
VisitObjCTypeParamDecl(const ObjCTypeParamDecl * D)930 void JSONNodeDumper::VisitObjCTypeParamDecl(const ObjCTypeParamDecl *D) {
931 VisitNamedDecl(D);
932 JOS.attribute("type", createQualType(D->getUnderlyingType()));
933 attributeOnlyIfTrue("bounded", D->hasExplicitBound());
934 switch (D->getVariance()) {
935 case ObjCTypeParamVariance::Invariant:
936 break;
937 case ObjCTypeParamVariance::Covariant:
938 JOS.attribute("variance", "covariant");
939 break;
940 case ObjCTypeParamVariance::Contravariant:
941 JOS.attribute("variance", "contravariant");
942 break;
943 }
944 }
945
VisitObjCCategoryDecl(const ObjCCategoryDecl * D)946 void JSONNodeDumper::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
947 VisitNamedDecl(D);
948 JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
949 JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
950
951 llvm::json::Array Protocols;
952 for (const auto* P : D->protocols())
953 Protocols.push_back(createBareDeclRef(P));
954 if (!Protocols.empty())
955 JOS.attribute("protocols", std::move(Protocols));
956 }
957
VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl * D)958 void JSONNodeDumper::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
959 VisitNamedDecl(D);
960 JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
961 JOS.attribute("categoryDecl", createBareDeclRef(D->getCategoryDecl()));
962 }
963
VisitObjCProtocolDecl(const ObjCProtocolDecl * D)964 void JSONNodeDumper::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
965 VisitNamedDecl(D);
966
967 llvm::json::Array Protocols;
968 for (const auto *P : D->protocols())
969 Protocols.push_back(createBareDeclRef(P));
970 if (!Protocols.empty())
971 JOS.attribute("protocols", std::move(Protocols));
972 }
973
VisitObjCInterfaceDecl(const ObjCInterfaceDecl * D)974 void JSONNodeDumper::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
975 VisitNamedDecl(D);
976 JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
977 JOS.attribute("implementation", createBareDeclRef(D->getImplementation()));
978
979 llvm::json::Array Protocols;
980 for (const auto* P : D->protocols())
981 Protocols.push_back(createBareDeclRef(P));
982 if (!Protocols.empty())
983 JOS.attribute("protocols", std::move(Protocols));
984 }
985
VisitObjCImplementationDecl(const ObjCImplementationDecl * D)986 void JSONNodeDumper::VisitObjCImplementationDecl(
987 const ObjCImplementationDecl *D) {
988 VisitNamedDecl(D);
989 JOS.attribute("super", createBareDeclRef(D->getSuperClass()));
990 JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
991 }
992
VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl * D)993 void JSONNodeDumper::VisitObjCCompatibleAliasDecl(
994 const ObjCCompatibleAliasDecl *D) {
995 VisitNamedDecl(D);
996 JOS.attribute("interface", createBareDeclRef(D->getClassInterface()));
997 }
998
VisitObjCPropertyDecl(const ObjCPropertyDecl * D)999 void JSONNodeDumper::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
1000 VisitNamedDecl(D);
1001 JOS.attribute("type", createQualType(D->getType()));
1002
1003 switch (D->getPropertyImplementation()) {
1004 case ObjCPropertyDecl::None: break;
1005 case ObjCPropertyDecl::Required: JOS.attribute("control", "required"); break;
1006 case ObjCPropertyDecl::Optional: JOS.attribute("control", "optional"); break;
1007 }
1008
1009 ObjCPropertyAttribute::Kind Attrs = D->getPropertyAttributes();
1010 if (Attrs != ObjCPropertyAttribute::kind_noattr) {
1011 if (Attrs & ObjCPropertyAttribute::kind_getter)
1012 JOS.attribute("getter", createBareDeclRef(D->getGetterMethodDecl()));
1013 if (Attrs & ObjCPropertyAttribute::kind_setter)
1014 JOS.attribute("setter", createBareDeclRef(D->getSetterMethodDecl()));
1015 attributeOnlyIfTrue("readonly",
1016 Attrs & ObjCPropertyAttribute::kind_readonly);
1017 attributeOnlyIfTrue("assign", Attrs & ObjCPropertyAttribute::kind_assign);
1018 attributeOnlyIfTrue("readwrite",
1019 Attrs & ObjCPropertyAttribute::kind_readwrite);
1020 attributeOnlyIfTrue("retain", Attrs & ObjCPropertyAttribute::kind_retain);
1021 attributeOnlyIfTrue("copy", Attrs & ObjCPropertyAttribute::kind_copy);
1022 attributeOnlyIfTrue("nonatomic",
1023 Attrs & ObjCPropertyAttribute::kind_nonatomic);
1024 attributeOnlyIfTrue("atomic", Attrs & ObjCPropertyAttribute::kind_atomic);
1025 attributeOnlyIfTrue("weak", Attrs & ObjCPropertyAttribute::kind_weak);
1026 attributeOnlyIfTrue("strong", Attrs & ObjCPropertyAttribute::kind_strong);
1027 attributeOnlyIfTrue("unsafe_unretained",
1028 Attrs & ObjCPropertyAttribute::kind_unsafe_unretained);
1029 attributeOnlyIfTrue("class", Attrs & ObjCPropertyAttribute::kind_class);
1030 attributeOnlyIfTrue("direct", Attrs & ObjCPropertyAttribute::kind_direct);
1031 attributeOnlyIfTrue("nullability",
1032 Attrs & ObjCPropertyAttribute::kind_nullability);
1033 attributeOnlyIfTrue("null_resettable",
1034 Attrs & ObjCPropertyAttribute::kind_null_resettable);
1035 }
1036 }
1037
VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl * D)1038 void JSONNodeDumper::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
1039 VisitNamedDecl(D->getPropertyDecl());
1040 JOS.attribute("implKind", D->getPropertyImplementation() ==
1041 ObjCPropertyImplDecl::Synthesize
1042 ? "synthesize"
1043 : "dynamic");
1044 JOS.attribute("propertyDecl", createBareDeclRef(D->getPropertyDecl()));
1045 JOS.attribute("ivarDecl", createBareDeclRef(D->getPropertyIvarDecl()));
1046 }
1047
VisitBlockDecl(const BlockDecl * D)1048 void JSONNodeDumper::VisitBlockDecl(const BlockDecl *D) {
1049 attributeOnlyIfTrue("variadic", D->isVariadic());
1050 attributeOnlyIfTrue("capturesThis", D->capturesCXXThis());
1051 }
1052
VisitObjCEncodeExpr(const ObjCEncodeExpr * OEE)1053 void JSONNodeDumper::VisitObjCEncodeExpr(const ObjCEncodeExpr *OEE) {
1054 JOS.attribute("encodedType", createQualType(OEE->getEncodedType()));
1055 }
1056
VisitObjCMessageExpr(const ObjCMessageExpr * OME)1057 void JSONNodeDumper::VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
1058 std::string Str;
1059 llvm::raw_string_ostream OS(Str);
1060
1061 OME->getSelector().print(OS);
1062 JOS.attribute("selector", OS.str());
1063
1064 switch (OME->getReceiverKind()) {
1065 case ObjCMessageExpr::Instance:
1066 JOS.attribute("receiverKind", "instance");
1067 break;
1068 case ObjCMessageExpr::Class:
1069 JOS.attribute("receiverKind", "class");
1070 JOS.attribute("classType", createQualType(OME->getClassReceiver()));
1071 break;
1072 case ObjCMessageExpr::SuperInstance:
1073 JOS.attribute("receiverKind", "super (instance)");
1074 JOS.attribute("superType", createQualType(OME->getSuperType()));
1075 break;
1076 case ObjCMessageExpr::SuperClass:
1077 JOS.attribute("receiverKind", "super (class)");
1078 JOS.attribute("superType", createQualType(OME->getSuperType()));
1079 break;
1080 }
1081
1082 QualType CallReturnTy = OME->getCallReturnType(Ctx);
1083 if (OME->getType() != CallReturnTy)
1084 JOS.attribute("callReturnType", createQualType(CallReturnTy));
1085 }
1086
VisitObjCBoxedExpr(const ObjCBoxedExpr * OBE)1087 void JSONNodeDumper::VisitObjCBoxedExpr(const ObjCBoxedExpr *OBE) {
1088 if (const ObjCMethodDecl *MD = OBE->getBoxingMethod()) {
1089 std::string Str;
1090 llvm::raw_string_ostream OS(Str);
1091
1092 MD->getSelector().print(OS);
1093 JOS.attribute("selector", OS.str());
1094 }
1095 }
1096
VisitObjCSelectorExpr(const ObjCSelectorExpr * OSE)1097 void JSONNodeDumper::VisitObjCSelectorExpr(const ObjCSelectorExpr *OSE) {
1098 std::string Str;
1099 llvm::raw_string_ostream OS(Str);
1100
1101 OSE->getSelector().print(OS);
1102 JOS.attribute("selector", OS.str());
1103 }
1104
VisitObjCProtocolExpr(const ObjCProtocolExpr * OPE)1105 void JSONNodeDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
1106 JOS.attribute("protocol", createBareDeclRef(OPE->getProtocol()));
1107 }
1108
VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr * OPRE)1109 void JSONNodeDumper::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
1110 if (OPRE->isImplicitProperty()) {
1111 JOS.attribute("propertyKind", "implicit");
1112 if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertyGetter())
1113 JOS.attribute("getter", createBareDeclRef(MD));
1114 if (const ObjCMethodDecl *MD = OPRE->getImplicitPropertySetter())
1115 JOS.attribute("setter", createBareDeclRef(MD));
1116 } else {
1117 JOS.attribute("propertyKind", "explicit");
1118 JOS.attribute("property", createBareDeclRef(OPRE->getExplicitProperty()));
1119 }
1120
1121 attributeOnlyIfTrue("isSuperReceiver", OPRE->isSuperReceiver());
1122 attributeOnlyIfTrue("isMessagingGetter", OPRE->isMessagingGetter());
1123 attributeOnlyIfTrue("isMessagingSetter", OPRE->isMessagingSetter());
1124 }
1125
VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr * OSRE)1126 void JSONNodeDumper::VisitObjCSubscriptRefExpr(
1127 const ObjCSubscriptRefExpr *OSRE) {
1128 JOS.attribute("subscriptKind",
1129 OSRE->isArraySubscriptRefExpr() ? "array" : "dictionary");
1130
1131 if (const ObjCMethodDecl *MD = OSRE->getAtIndexMethodDecl())
1132 JOS.attribute("getter", createBareDeclRef(MD));
1133 if (const ObjCMethodDecl *MD = OSRE->setAtIndexMethodDecl())
1134 JOS.attribute("setter", createBareDeclRef(MD));
1135 }
1136
VisitObjCIvarRefExpr(const ObjCIvarRefExpr * OIRE)1137 void JSONNodeDumper::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
1138 JOS.attribute("decl", createBareDeclRef(OIRE->getDecl()));
1139 attributeOnlyIfTrue("isFreeIvar", OIRE->isFreeIvar());
1140 JOS.attribute("isArrow", OIRE->isArrow());
1141 }
1142
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * OBLE)1143 void JSONNodeDumper::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *OBLE) {
1144 JOS.attribute("value", OBLE->getValue() ? "__objc_yes" : "__objc_no");
1145 }
1146
VisitDeclRefExpr(const DeclRefExpr * DRE)1147 void JSONNodeDumper::VisitDeclRefExpr(const DeclRefExpr *DRE) {
1148 JOS.attribute("referencedDecl", createBareDeclRef(DRE->getDecl()));
1149 if (DRE->getDecl() != DRE->getFoundDecl())
1150 JOS.attribute("foundReferencedDecl",
1151 createBareDeclRef(DRE->getFoundDecl()));
1152 switch (DRE->isNonOdrUse()) {
1153 case NOUR_None: break;
1154 case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
1155 case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
1156 case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
1157 }
1158 }
1159
VisitPredefinedExpr(const PredefinedExpr * PE)1160 void JSONNodeDumper::VisitPredefinedExpr(const PredefinedExpr *PE) {
1161 JOS.attribute("name", PredefinedExpr::getIdentKindName(PE->getIdentKind()));
1162 }
1163
VisitUnaryOperator(const UnaryOperator * UO)1164 void JSONNodeDumper::VisitUnaryOperator(const UnaryOperator *UO) {
1165 JOS.attribute("isPostfix", UO->isPostfix());
1166 JOS.attribute("opcode", UnaryOperator::getOpcodeStr(UO->getOpcode()));
1167 if (!UO->canOverflow())
1168 JOS.attribute("canOverflow", false);
1169 }
1170
VisitBinaryOperator(const BinaryOperator * BO)1171 void JSONNodeDumper::VisitBinaryOperator(const BinaryOperator *BO) {
1172 JOS.attribute("opcode", BinaryOperator::getOpcodeStr(BO->getOpcode()));
1173 }
1174
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)1175 void JSONNodeDumper::VisitCompoundAssignOperator(
1176 const CompoundAssignOperator *CAO) {
1177 VisitBinaryOperator(CAO);
1178 JOS.attribute("computeLHSType", createQualType(CAO->getComputationLHSType()));
1179 JOS.attribute("computeResultType",
1180 createQualType(CAO->getComputationResultType()));
1181 }
1182
VisitMemberExpr(const MemberExpr * ME)1183 void JSONNodeDumper::VisitMemberExpr(const MemberExpr *ME) {
1184 // Note, we always write this Boolean field because the information it conveys
1185 // is critical to understanding the AST node.
1186 ValueDecl *VD = ME->getMemberDecl();
1187 JOS.attribute("name", VD && VD->getDeclName() ? VD->getNameAsString() : "");
1188 JOS.attribute("isArrow", ME->isArrow());
1189 JOS.attribute("referencedMemberDecl", createPointerRepresentation(VD));
1190 switch (ME->isNonOdrUse()) {
1191 case NOUR_None: break;
1192 case NOUR_Unevaluated: JOS.attribute("nonOdrUseReason", "unevaluated"); break;
1193 case NOUR_Constant: JOS.attribute("nonOdrUseReason", "constant"); break;
1194 case NOUR_Discarded: JOS.attribute("nonOdrUseReason", "discarded"); break;
1195 }
1196 }
1197
VisitCXXNewExpr(const CXXNewExpr * NE)1198 void JSONNodeDumper::VisitCXXNewExpr(const CXXNewExpr *NE) {
1199 attributeOnlyIfTrue("isGlobal", NE->isGlobalNew());
1200 attributeOnlyIfTrue("isArray", NE->isArray());
1201 attributeOnlyIfTrue("isPlacement", NE->getNumPlacementArgs() != 0);
1202 switch (NE->getInitializationStyle()) {
1203 case CXXNewExpr::NoInit: break;
1204 case CXXNewExpr::CallInit: JOS.attribute("initStyle", "call"); break;
1205 case CXXNewExpr::ListInit: JOS.attribute("initStyle", "list"); break;
1206 }
1207 if (const FunctionDecl *FD = NE->getOperatorNew())
1208 JOS.attribute("operatorNewDecl", createBareDeclRef(FD));
1209 if (const FunctionDecl *FD = NE->getOperatorDelete())
1210 JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
1211 }
VisitCXXDeleteExpr(const CXXDeleteExpr * DE)1212 void JSONNodeDumper::VisitCXXDeleteExpr(const CXXDeleteExpr *DE) {
1213 attributeOnlyIfTrue("isGlobal", DE->isGlobalDelete());
1214 attributeOnlyIfTrue("isArray", DE->isArrayForm());
1215 attributeOnlyIfTrue("isArrayAsWritten", DE->isArrayFormAsWritten());
1216 if (const FunctionDecl *FD = DE->getOperatorDelete())
1217 JOS.attribute("operatorDeleteDecl", createBareDeclRef(FD));
1218 }
1219
VisitCXXThisExpr(const CXXThisExpr * TE)1220 void JSONNodeDumper::VisitCXXThisExpr(const CXXThisExpr *TE) {
1221 attributeOnlyIfTrue("implicit", TE->isImplicit());
1222 }
1223
VisitCastExpr(const CastExpr * CE)1224 void JSONNodeDumper::VisitCastExpr(const CastExpr *CE) {
1225 JOS.attribute("castKind", CE->getCastKindName());
1226 llvm::json::Array Path = createCastPath(CE);
1227 if (!Path.empty())
1228 JOS.attribute("path", std::move(Path));
1229 // FIXME: This may not be useful information as it can be obtusely gleaned
1230 // from the inner[] array.
1231 if (const NamedDecl *ND = CE->getConversionFunction())
1232 JOS.attribute("conversionFunc", createBareDeclRef(ND));
1233 }
1234
VisitImplicitCastExpr(const ImplicitCastExpr * ICE)1235 void JSONNodeDumper::VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
1236 VisitCastExpr(ICE);
1237 attributeOnlyIfTrue("isPartOfExplicitCast", ICE->isPartOfExplicitCast());
1238 }
1239
VisitCallExpr(const CallExpr * CE)1240 void JSONNodeDumper::VisitCallExpr(const CallExpr *CE) {
1241 attributeOnlyIfTrue("adl", CE->usesADL());
1242 }
1243
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * TTE)1244 void JSONNodeDumper::VisitUnaryExprOrTypeTraitExpr(
1245 const UnaryExprOrTypeTraitExpr *TTE) {
1246 JOS.attribute("name", getTraitSpelling(TTE->getKind()));
1247 if (TTE->isArgumentType())
1248 JOS.attribute("argType", createQualType(TTE->getArgumentType()));
1249 }
1250
VisitSizeOfPackExpr(const SizeOfPackExpr * SOPE)1251 void JSONNodeDumper::VisitSizeOfPackExpr(const SizeOfPackExpr *SOPE) {
1252 VisitNamedDecl(SOPE->getPack());
1253 }
1254
VisitUnresolvedLookupExpr(const UnresolvedLookupExpr * ULE)1255 void JSONNodeDumper::VisitUnresolvedLookupExpr(
1256 const UnresolvedLookupExpr *ULE) {
1257 JOS.attribute("usesADL", ULE->requiresADL());
1258 JOS.attribute("name", ULE->getName().getAsString());
1259
1260 JOS.attributeArray("lookups", [this, ULE] {
1261 for (const NamedDecl *D : ULE->decls())
1262 JOS.value(createBareDeclRef(D));
1263 });
1264 }
1265
VisitAddrLabelExpr(const AddrLabelExpr * ALE)1266 void JSONNodeDumper::VisitAddrLabelExpr(const AddrLabelExpr *ALE) {
1267 JOS.attribute("name", ALE->getLabel()->getName());
1268 JOS.attribute("labelDeclId", createPointerRepresentation(ALE->getLabel()));
1269 }
1270
VisitCXXTypeidExpr(const CXXTypeidExpr * CTE)1271 void JSONNodeDumper::VisitCXXTypeidExpr(const CXXTypeidExpr *CTE) {
1272 if (CTE->isTypeOperand()) {
1273 QualType Adjusted = CTE->getTypeOperand(Ctx);
1274 QualType Unadjusted = CTE->getTypeOperandSourceInfo()->getType();
1275 JOS.attribute("typeArg", createQualType(Unadjusted));
1276 if (Adjusted != Unadjusted)
1277 JOS.attribute("adjustedTypeArg", createQualType(Adjusted));
1278 }
1279 }
1280
VisitConstantExpr(const ConstantExpr * CE)1281 void JSONNodeDumper::VisitConstantExpr(const ConstantExpr *CE) {
1282 if (CE->getResultAPValueKind() != APValue::None)
1283 Visit(CE->getAPValueResult(), CE->getType());
1284 }
1285
VisitInitListExpr(const InitListExpr * ILE)1286 void JSONNodeDumper::VisitInitListExpr(const InitListExpr *ILE) {
1287 if (const FieldDecl *FD = ILE->getInitializedFieldInUnion())
1288 JOS.attribute("field", createBareDeclRef(FD));
1289 }
1290
VisitGenericSelectionExpr(const GenericSelectionExpr * GSE)1291 void JSONNodeDumper::VisitGenericSelectionExpr(
1292 const GenericSelectionExpr *GSE) {
1293 attributeOnlyIfTrue("resultDependent", GSE->isResultDependent());
1294 }
1295
VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr * UCE)1296 void JSONNodeDumper::VisitCXXUnresolvedConstructExpr(
1297 const CXXUnresolvedConstructExpr *UCE) {
1298 if (UCE->getType() != UCE->getTypeAsWritten())
1299 JOS.attribute("typeAsWritten", createQualType(UCE->getTypeAsWritten()));
1300 attributeOnlyIfTrue("list", UCE->isListInitialization());
1301 }
1302
VisitCXXConstructExpr(const CXXConstructExpr * CE)1303 void JSONNodeDumper::VisitCXXConstructExpr(const CXXConstructExpr *CE) {
1304 CXXConstructorDecl *Ctor = CE->getConstructor();
1305 JOS.attribute("ctorType", createQualType(Ctor->getType()));
1306 attributeOnlyIfTrue("elidable", CE->isElidable());
1307 attributeOnlyIfTrue("list", CE->isListInitialization());
1308 attributeOnlyIfTrue("initializer_list", CE->isStdInitListInitialization());
1309 attributeOnlyIfTrue("zeroing", CE->requiresZeroInitialization());
1310 attributeOnlyIfTrue("hadMultipleCandidates", CE->hadMultipleCandidates());
1311
1312 switch (CE->getConstructionKind()) {
1313 case CXXConstructExpr::CK_Complete:
1314 JOS.attribute("constructionKind", "complete");
1315 break;
1316 case CXXConstructExpr::CK_Delegating:
1317 JOS.attribute("constructionKind", "delegating");
1318 break;
1319 case CXXConstructExpr::CK_NonVirtualBase:
1320 JOS.attribute("constructionKind", "non-virtual base");
1321 break;
1322 case CXXConstructExpr::CK_VirtualBase:
1323 JOS.attribute("constructionKind", "virtual base");
1324 break;
1325 }
1326 }
1327
VisitExprWithCleanups(const ExprWithCleanups * EWC)1328 void JSONNodeDumper::VisitExprWithCleanups(const ExprWithCleanups *EWC) {
1329 attributeOnlyIfTrue("cleanupsHaveSideEffects",
1330 EWC->cleanupsHaveSideEffects());
1331 if (EWC->getNumObjects()) {
1332 JOS.attributeArray("cleanups", [this, EWC] {
1333 for (const ExprWithCleanups::CleanupObject &CO : EWC->getObjects())
1334 if (auto *BD = CO.dyn_cast<BlockDecl *>()) {
1335 JOS.value(createBareDeclRef(BD));
1336 } else if (auto *CLE = CO.dyn_cast<CompoundLiteralExpr *>()) {
1337 llvm::json::Object Obj;
1338 Obj["id"] = createPointerRepresentation(CLE);
1339 Obj["kind"] = CLE->getStmtClassName();
1340 JOS.value(std::move(Obj));
1341 } else {
1342 llvm_unreachable("unexpected cleanup object type");
1343 }
1344 });
1345 }
1346 }
1347
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * BTE)1348 void JSONNodeDumper::VisitCXXBindTemporaryExpr(
1349 const CXXBindTemporaryExpr *BTE) {
1350 const CXXTemporary *Temp = BTE->getTemporary();
1351 JOS.attribute("temp", createPointerRepresentation(Temp));
1352 if (const CXXDestructorDecl *Dtor = Temp->getDestructor())
1353 JOS.attribute("dtor", createBareDeclRef(Dtor));
1354 }
1355
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * MTE)1356 void JSONNodeDumper::VisitMaterializeTemporaryExpr(
1357 const MaterializeTemporaryExpr *MTE) {
1358 if (const ValueDecl *VD = MTE->getExtendingDecl())
1359 JOS.attribute("extendingDecl", createBareDeclRef(VD));
1360
1361 switch (MTE->getStorageDuration()) {
1362 case SD_Automatic:
1363 JOS.attribute("storageDuration", "automatic");
1364 break;
1365 case SD_Dynamic:
1366 JOS.attribute("storageDuration", "dynamic");
1367 break;
1368 case SD_FullExpression:
1369 JOS.attribute("storageDuration", "full expression");
1370 break;
1371 case SD_Static:
1372 JOS.attribute("storageDuration", "static");
1373 break;
1374 case SD_Thread:
1375 JOS.attribute("storageDuration", "thread");
1376 break;
1377 }
1378
1379 attributeOnlyIfTrue("boundToLValueRef", MTE->isBoundToLvalueReference());
1380 }
1381
VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr * DSME)1382 void JSONNodeDumper::VisitCXXDependentScopeMemberExpr(
1383 const CXXDependentScopeMemberExpr *DSME) {
1384 JOS.attribute("isArrow", DSME->isArrow());
1385 JOS.attribute("member", DSME->getMember().getAsString());
1386 attributeOnlyIfTrue("hasTemplateKeyword", DSME->hasTemplateKeyword());
1387 attributeOnlyIfTrue("hasExplicitTemplateArgs",
1388 DSME->hasExplicitTemplateArgs());
1389
1390 if (DSME->getNumTemplateArgs()) {
1391 JOS.attributeArray("explicitTemplateArgs", [DSME, this] {
1392 for (const TemplateArgumentLoc &TAL : DSME->template_arguments())
1393 JOS.object(
1394 [&TAL, this] { Visit(TAL.getArgument(), TAL.getSourceRange()); });
1395 });
1396 }
1397 }
1398
VisitIntegerLiteral(const IntegerLiteral * IL)1399 void JSONNodeDumper::VisitIntegerLiteral(const IntegerLiteral *IL) {
1400 JOS.attribute("value",
1401 IL->getValue().toString(
1402 /*Radix=*/10, IL->getType()->isSignedIntegerType()));
1403 }
VisitCharacterLiteral(const CharacterLiteral * CL)1404 void JSONNodeDumper::VisitCharacterLiteral(const CharacterLiteral *CL) {
1405 // FIXME: This should probably print the character literal as a string,
1406 // rather than as a numerical value. It would be nice if the behavior matched
1407 // what we do to print a string literal; right now, it is impossible to tell
1408 // the difference between 'a' and L'a' in C from the JSON output.
1409 JOS.attribute("value", CL->getValue());
1410 }
VisitFixedPointLiteral(const FixedPointLiteral * FPL)1411 void JSONNodeDumper::VisitFixedPointLiteral(const FixedPointLiteral *FPL) {
1412 JOS.attribute("value", FPL->getValueAsString(/*Radix=*/10));
1413 }
VisitFloatingLiteral(const FloatingLiteral * FL)1414 void JSONNodeDumper::VisitFloatingLiteral(const FloatingLiteral *FL) {
1415 llvm::SmallVector<char, 16> Buffer;
1416 FL->getValue().toString(Buffer);
1417 JOS.attribute("value", Buffer);
1418 }
VisitStringLiteral(const StringLiteral * SL)1419 void JSONNodeDumper::VisitStringLiteral(const StringLiteral *SL) {
1420 std::string Buffer;
1421 llvm::raw_string_ostream SS(Buffer);
1422 SL->outputString(SS);
1423 JOS.attribute("value", SS.str());
1424 }
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * BLE)1425 void JSONNodeDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *BLE) {
1426 JOS.attribute("value", BLE->getValue());
1427 }
1428
VisitIfStmt(const IfStmt * IS)1429 void JSONNodeDumper::VisitIfStmt(const IfStmt *IS) {
1430 attributeOnlyIfTrue("hasInit", IS->hasInitStorage());
1431 attributeOnlyIfTrue("hasVar", IS->hasVarStorage());
1432 attributeOnlyIfTrue("hasElse", IS->hasElseStorage());
1433 attributeOnlyIfTrue("isConstexpr", IS->isConstexpr());
1434 }
1435
VisitSwitchStmt(const SwitchStmt * SS)1436 void JSONNodeDumper::VisitSwitchStmt(const SwitchStmt *SS) {
1437 attributeOnlyIfTrue("hasInit", SS->hasInitStorage());
1438 attributeOnlyIfTrue("hasVar", SS->hasVarStorage());
1439 }
VisitCaseStmt(const CaseStmt * CS)1440 void JSONNodeDumper::VisitCaseStmt(const CaseStmt *CS) {
1441 attributeOnlyIfTrue("isGNURange", CS->caseStmtIsGNURange());
1442 }
1443
VisitLabelStmt(const LabelStmt * LS)1444 void JSONNodeDumper::VisitLabelStmt(const LabelStmt *LS) {
1445 JOS.attribute("name", LS->getName());
1446 JOS.attribute("declId", createPointerRepresentation(LS->getDecl()));
1447 }
VisitGotoStmt(const GotoStmt * GS)1448 void JSONNodeDumper::VisitGotoStmt(const GotoStmt *GS) {
1449 JOS.attribute("targetLabelDeclId",
1450 createPointerRepresentation(GS->getLabel()));
1451 }
1452
VisitWhileStmt(const WhileStmt * WS)1453 void JSONNodeDumper::VisitWhileStmt(const WhileStmt *WS) {
1454 attributeOnlyIfTrue("hasVar", WS->hasVarStorage());
1455 }
1456
VisitObjCAtCatchStmt(const ObjCAtCatchStmt * OACS)1457 void JSONNodeDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt* OACS) {
1458 // FIXME: it would be nice for the ASTNodeTraverser would handle the catch
1459 // parameter the same way for C++ and ObjC rather. In this case, C++ gets a
1460 // null child node and ObjC gets no child node.
1461 attributeOnlyIfTrue("isCatchAll", OACS->getCatchParamDecl() == nullptr);
1462 }
1463
VisitNullTemplateArgument(const TemplateArgument & TA)1464 void JSONNodeDumper::VisitNullTemplateArgument(const TemplateArgument &TA) {
1465 JOS.attribute("isNull", true);
1466 }
VisitTypeTemplateArgument(const TemplateArgument & TA)1467 void JSONNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
1468 JOS.attribute("type", createQualType(TA.getAsType()));
1469 }
VisitDeclarationTemplateArgument(const TemplateArgument & TA)1470 void JSONNodeDumper::VisitDeclarationTemplateArgument(
1471 const TemplateArgument &TA) {
1472 JOS.attribute("decl", createBareDeclRef(TA.getAsDecl()));
1473 }
VisitNullPtrTemplateArgument(const TemplateArgument & TA)1474 void JSONNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
1475 JOS.attribute("isNullptr", true);
1476 }
VisitIntegralTemplateArgument(const TemplateArgument & TA)1477 void JSONNodeDumper::VisitIntegralTemplateArgument(const TemplateArgument &TA) {
1478 JOS.attribute("value", TA.getAsIntegral().getSExtValue());
1479 }
VisitTemplateTemplateArgument(const TemplateArgument & TA)1480 void JSONNodeDumper::VisitTemplateTemplateArgument(const TemplateArgument &TA) {
1481 // FIXME: cannot just call dump() on the argument, as that doesn't specify
1482 // the output format.
1483 }
VisitTemplateExpansionTemplateArgument(const TemplateArgument & TA)1484 void JSONNodeDumper::VisitTemplateExpansionTemplateArgument(
1485 const TemplateArgument &TA) {
1486 // FIXME: cannot just call dump() on the argument, as that doesn't specify
1487 // the output format.
1488 }
VisitExpressionTemplateArgument(const TemplateArgument & TA)1489 void JSONNodeDumper::VisitExpressionTemplateArgument(
1490 const TemplateArgument &TA) {
1491 JOS.attribute("isExpr", true);
1492 }
VisitPackTemplateArgument(const TemplateArgument & TA)1493 void JSONNodeDumper::VisitPackTemplateArgument(const TemplateArgument &TA) {
1494 JOS.attribute("isPack", true);
1495 }
1496
getCommentCommandName(unsigned CommandID) const1497 StringRef JSONNodeDumper::getCommentCommandName(unsigned CommandID) const {
1498 if (Traits)
1499 return Traits->getCommandInfo(CommandID)->Name;
1500 if (const comments::CommandInfo *Info =
1501 comments::CommandTraits::getBuiltinCommandInfo(CommandID))
1502 return Info->Name;
1503 return "<invalid>";
1504 }
1505
visitTextComment(const comments::TextComment * C,const comments::FullComment *)1506 void JSONNodeDumper::visitTextComment(const comments::TextComment *C,
1507 const comments::FullComment *) {
1508 JOS.attribute("text", C->getText());
1509 }
1510
visitInlineCommandComment(const comments::InlineCommandComment * C,const comments::FullComment *)1511 void JSONNodeDumper::visitInlineCommandComment(
1512 const comments::InlineCommandComment *C, const comments::FullComment *) {
1513 JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1514
1515 switch (C->getRenderKind()) {
1516 case comments::InlineCommandComment::RenderNormal:
1517 JOS.attribute("renderKind", "normal");
1518 break;
1519 case comments::InlineCommandComment::RenderBold:
1520 JOS.attribute("renderKind", "bold");
1521 break;
1522 case comments::InlineCommandComment::RenderEmphasized:
1523 JOS.attribute("renderKind", "emphasized");
1524 break;
1525 case comments::InlineCommandComment::RenderMonospaced:
1526 JOS.attribute("renderKind", "monospaced");
1527 break;
1528 case comments::InlineCommandComment::RenderAnchor:
1529 JOS.attribute("renderKind", "anchor");
1530 break;
1531 }
1532
1533 llvm::json::Array Args;
1534 for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1535 Args.push_back(C->getArgText(I));
1536
1537 if (!Args.empty())
1538 JOS.attribute("args", std::move(Args));
1539 }
1540
visitHTMLStartTagComment(const comments::HTMLStartTagComment * C,const comments::FullComment *)1541 void JSONNodeDumper::visitHTMLStartTagComment(
1542 const comments::HTMLStartTagComment *C, const comments::FullComment *) {
1543 JOS.attribute("name", C->getTagName());
1544 attributeOnlyIfTrue("selfClosing", C->isSelfClosing());
1545 attributeOnlyIfTrue("malformed", C->isMalformed());
1546
1547 llvm::json::Array Attrs;
1548 for (unsigned I = 0, E = C->getNumAttrs(); I < E; ++I)
1549 Attrs.push_back(
1550 {{"name", C->getAttr(I).Name}, {"value", C->getAttr(I).Value}});
1551
1552 if (!Attrs.empty())
1553 JOS.attribute("attrs", std::move(Attrs));
1554 }
1555
visitHTMLEndTagComment(const comments::HTMLEndTagComment * C,const comments::FullComment *)1556 void JSONNodeDumper::visitHTMLEndTagComment(
1557 const comments::HTMLEndTagComment *C, const comments::FullComment *) {
1558 JOS.attribute("name", C->getTagName());
1559 }
1560
visitBlockCommandComment(const comments::BlockCommandComment * C,const comments::FullComment *)1561 void JSONNodeDumper::visitBlockCommandComment(
1562 const comments::BlockCommandComment *C, const comments::FullComment *) {
1563 JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1564
1565 llvm::json::Array Args;
1566 for (unsigned I = 0, E = C->getNumArgs(); I < E; ++I)
1567 Args.push_back(C->getArgText(I));
1568
1569 if (!Args.empty())
1570 JOS.attribute("args", std::move(Args));
1571 }
1572
visitParamCommandComment(const comments::ParamCommandComment * C,const comments::FullComment * FC)1573 void JSONNodeDumper::visitParamCommandComment(
1574 const comments::ParamCommandComment *C, const comments::FullComment *FC) {
1575 switch (C->getDirection()) {
1576 case comments::ParamCommandComment::In:
1577 JOS.attribute("direction", "in");
1578 break;
1579 case comments::ParamCommandComment::Out:
1580 JOS.attribute("direction", "out");
1581 break;
1582 case comments::ParamCommandComment::InOut:
1583 JOS.attribute("direction", "in,out");
1584 break;
1585 }
1586 attributeOnlyIfTrue("explicit", C->isDirectionExplicit());
1587
1588 if (C->hasParamName())
1589 JOS.attribute("param", C->isParamIndexValid() ? C->getParamName(FC)
1590 : C->getParamNameAsWritten());
1591
1592 if (C->isParamIndexValid() && !C->isVarArgParam())
1593 JOS.attribute("paramIdx", C->getParamIndex());
1594 }
1595
visitTParamCommandComment(const comments::TParamCommandComment * C,const comments::FullComment * FC)1596 void JSONNodeDumper::visitTParamCommandComment(
1597 const comments::TParamCommandComment *C, const comments::FullComment *FC) {
1598 if (C->hasParamName())
1599 JOS.attribute("param", C->isPositionValid() ? C->getParamName(FC)
1600 : C->getParamNameAsWritten());
1601 if (C->isPositionValid()) {
1602 llvm::json::Array Positions;
1603 for (unsigned I = 0, E = C->getDepth(); I < E; ++I)
1604 Positions.push_back(C->getIndex(I));
1605
1606 if (!Positions.empty())
1607 JOS.attribute("positions", std::move(Positions));
1608 }
1609 }
1610
visitVerbatimBlockComment(const comments::VerbatimBlockComment * C,const comments::FullComment *)1611 void JSONNodeDumper::visitVerbatimBlockComment(
1612 const comments::VerbatimBlockComment *C, const comments::FullComment *) {
1613 JOS.attribute("name", getCommentCommandName(C->getCommandID()));
1614 JOS.attribute("closeName", C->getCloseName());
1615 }
1616
visitVerbatimBlockLineComment(const comments::VerbatimBlockLineComment * C,const comments::FullComment *)1617 void JSONNodeDumper::visitVerbatimBlockLineComment(
1618 const comments::VerbatimBlockLineComment *C,
1619 const comments::FullComment *) {
1620 JOS.attribute("text", C->getText());
1621 }
1622
visitVerbatimLineComment(const comments::VerbatimLineComment * C,const comments::FullComment *)1623 void JSONNodeDumper::visitVerbatimLineComment(
1624 const comments::VerbatimLineComment *C, const comments::FullComment *) {
1625 JOS.attribute("text", C->getText());
1626 }
1627