1 //===--- ASTDumper.cpp - Dumping implementation for ASTs ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AST dump methods, which dump out the
11 // AST in a form that exposes type details and other fields.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CommentVisitor.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclLookups.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Module.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
28 using namespace clang::comments;
29 
30 //===----------------------------------------------------------------------===//
31 // ASTDumper Visitor
32 //===----------------------------------------------------------------------===//
33 
34 namespace  {
35   // Colors used for various parts of the AST dump
36   // Do not use bold yellow for any text.  It is hard to read on white screens.
37 
38   struct TerminalColor {
39     raw_ostream::Colors Color;
40     bool Bold;
41   };
42 
43   // Red           - CastColor
44   // Green         - TypeColor
45   // Bold Green    - DeclKindNameColor, UndeserializedColor
46   // Yellow        - AddressColor, LocationColor
47   // Blue          - CommentColor, NullColor, IndentColor
48   // Bold Blue     - AttrColor
49   // Bold Magenta  - StmtColor
50   // Cyan          - ValueKindColor, ObjectKindColor
51   // Bold Cyan     - ValueColor, DeclNameColor
52 
53   // Decl kind names (VarDecl, FunctionDecl, etc)
54   static const TerminalColor DeclKindNameColor = { raw_ostream::GREEN, true };
55   // Attr names (CleanupAttr, GuardedByAttr, etc)
56   static const TerminalColor AttrColor = { raw_ostream::BLUE, true };
57   // Statement names (DeclStmt, ImplicitCastExpr, etc)
58   static const TerminalColor StmtColor = { raw_ostream::MAGENTA, true };
59   // Comment names (FullComment, ParagraphComment, TextComment, etc)
60   static const TerminalColor CommentColor = { raw_ostream::BLUE, false };
61 
62   // Type names (int, float, etc, plus user defined types)
63   static const TerminalColor TypeColor = { raw_ostream::GREEN, false };
64 
65   // Pointer address
66   static const TerminalColor AddressColor = { raw_ostream::YELLOW, false };
67   // Source locations
68   static const TerminalColor LocationColor = { raw_ostream::YELLOW, false };
69 
70   // lvalue/xvalue
71   static const TerminalColor ValueKindColor = { raw_ostream::CYAN, false };
72   // bitfield/objcproperty/objcsubscript/vectorcomponent
73   static const TerminalColor ObjectKindColor = { raw_ostream::CYAN, false };
74 
75   // Null statements
76   static const TerminalColor NullColor = { raw_ostream::BLUE, false };
77 
78   // Undeserialized entities
79   static const TerminalColor UndeserializedColor = { raw_ostream::GREEN, true };
80 
81   // CastKind from CastExpr's
82   static const TerminalColor CastColor = { raw_ostream::RED, false };
83 
84   // Value of the statement
85   static const TerminalColor ValueColor = { raw_ostream::CYAN, true };
86   // Decl names
87   static const TerminalColor DeclNameColor = { raw_ostream::CYAN, true };
88 
89   // Indents ( `, -. | )
90   static const TerminalColor IndentColor = { raw_ostream::BLUE, false };
91 
92   class ASTDumper
93       : public ConstDeclVisitor<ASTDumper>, public ConstStmtVisitor<ASTDumper>,
94         public ConstCommentVisitor<ASTDumper>, public TypeVisitor<ASTDumper> {
95     raw_ostream &OS;
96     const CommandTraits *Traits;
97     const SourceManager *SM;
98 
99     /// Pending[i] is an action to dump an entity at level i.
100     llvm::SmallVector<std::function<void(bool isLastChild)>, 32> Pending;
101 
102     /// Indicates whether we're at the top level.
103     bool TopLevel;
104 
105     /// Indicates if we're handling the first child after entering a new depth.
106     bool FirstChild;
107 
108     /// Prefix for currently-being-dumped entity.
109     std::string Prefix;
110 
111     /// Keep track of the last location we print out so that we can
112     /// print out deltas from then on out.
113     const char *LastLocFilename;
114     unsigned LastLocLine;
115 
116     /// The \c FullComment parent of the comment being dumped.
117     const FullComment *FC;
118 
119     bool ShowColors;
120 
121     /// Dump a child of the current node.
122     template<typename Fn> void dumpChild(Fn doDumpChild) {
123       // If we're at the top level, there's nothing interesting to do; just
124       // run the dumper.
125       if (TopLevel) {
126         TopLevel = false;
127         doDumpChild();
128         while (!Pending.empty()) {
129           Pending.back()(true);
130           Pending.pop_back();
131         }
132         Prefix.clear();
133         OS << "\n";
134         TopLevel = true;
135         return;
136       }
137 
138       const FullComment *OrigFC = FC;
139       auto dumpWithIndent = [this, doDumpChild, OrigFC](bool isLastChild) {
140         // Print out the appropriate tree structure and work out the prefix for
141         // children of this node. For instance:
142         //
143         //   A        Prefix = ""
144         //   |-B      Prefix = "| "
145         //   | `-C    Prefix = "|   "
146         //   `-D      Prefix = "  "
147         //     |-E    Prefix = "  | "
148         //     `-F    Prefix = "    "
149         //   G        Prefix = ""
150         //
151         // Note that the first level gets no prefix.
152         {
153           OS << '\n';
154           ColorScope Color(*this, IndentColor);
155           OS << Prefix << (isLastChild ? '`' : '|') << '-';
156           this->Prefix.push_back(isLastChild ? ' ' : '|');
157           this->Prefix.push_back(' ');
158         }
159 
160         FirstChild = true;
161         unsigned Depth = Pending.size();
162 
163         FC = OrigFC;
164         doDumpChild();
165 
166         // If any children are left, they're the last at their nesting level.
167         // Dump those ones out now.
168         while (Depth < Pending.size()) {
169           Pending.back()(true);
170           this->Pending.pop_back();
171         }
172 
173         // Restore the old prefix.
174         this->Prefix.resize(Prefix.size() - 2);
175       };
176 
177       if (FirstChild) {
178         Pending.push_back(std::move(dumpWithIndent));
179       } else {
180         Pending.back()(false);
181         Pending.back() = std::move(dumpWithIndent);
182       }
183       FirstChild = false;
184     }
185 
186     class ColorScope {
187       ASTDumper &Dumper;
188     public:
189       ColorScope(ASTDumper &Dumper, TerminalColor Color)
190         : Dumper(Dumper) {
191         if (Dumper.ShowColors)
192           Dumper.OS.changeColor(Color.Color, Color.Bold);
193       }
194       ~ColorScope() {
195         if (Dumper.ShowColors)
196           Dumper.OS.resetColor();
197       }
198     };
199 
200   public:
201     ASTDumper(raw_ostream &OS, const CommandTraits *Traits,
202               const SourceManager *SM)
203       : OS(OS), Traits(Traits), SM(SM), TopLevel(true), FirstChild(true),
204         LastLocFilename(""), LastLocLine(~0U), FC(nullptr),
205         ShowColors(SM && SM->getDiagnostics().getShowColors()) { }
206 
207     ASTDumper(raw_ostream &OS, const CommandTraits *Traits,
208               const SourceManager *SM, bool ShowColors)
209       : OS(OS), Traits(Traits), SM(SM), TopLevel(true), FirstChild(true),
210         LastLocFilename(""), LastLocLine(~0U),
211         ShowColors(ShowColors) { }
212 
213     void dumpDecl(const Decl *D);
214     void dumpStmt(const Stmt *S);
215     void dumpFullComment(const FullComment *C);
216 
217     // Utilities
218     void dumpPointer(const void *Ptr);
219     void dumpSourceRange(SourceRange R);
220     void dumpLocation(SourceLocation Loc);
221     void dumpBareType(QualType T, bool Desugar = true);
222     void dumpType(QualType T);
223     void dumpTypeAsChild(QualType T);
224     void dumpTypeAsChild(const Type *T);
225     void dumpBareDeclRef(const Decl *Node);
226     void dumpDeclRef(const Decl *Node, const char *Label = nullptr);
227     void dumpName(const NamedDecl *D);
228     bool hasNodes(const DeclContext *DC);
229     void dumpDeclContext(const DeclContext *DC);
230     void dumpLookups(const DeclContext *DC, bool DumpDecls);
231     void dumpAttr(const Attr *A);
232 
233     // C++ Utilities
234     void dumpAccessSpecifier(AccessSpecifier AS);
235     void dumpCXXCtorInitializer(const CXXCtorInitializer *Init);
236     void dumpTemplateParameters(const TemplateParameterList *TPL);
237     void dumpTemplateArgumentListInfo(const TemplateArgumentListInfo &TALI);
238     void dumpTemplateArgumentLoc(const TemplateArgumentLoc &A);
239     void dumpTemplateArgumentList(const TemplateArgumentList &TAL);
240     void dumpTemplateArgument(const TemplateArgument &A,
241                               SourceRange R = SourceRange());
242 
243     // Types
244     void VisitComplexType(const ComplexType *T) {
245       dumpTypeAsChild(T->getElementType());
246     }
247     void VisitPointerType(const PointerType *T) {
248       dumpTypeAsChild(T->getPointeeType());
249     }
250     void VisitBlockPointerType(const BlockPointerType *T) {
251       dumpTypeAsChild(T->getPointeeType());
252     }
253     void VisitReferenceType(const ReferenceType *T) {
254       dumpTypeAsChild(T->getPointeeType());
255     }
256     void VisitRValueReferenceType(const ReferenceType *T) {
257       if (T->isSpelledAsLValue())
258         OS << " written as lvalue reference";
259       VisitReferenceType(T);
260     }
261     void VisitMemberPointerType(const MemberPointerType *T) {
262       dumpTypeAsChild(T->getClass());
263       dumpTypeAsChild(T->getPointeeType());
264     }
265     void VisitArrayType(const ArrayType *T) {
266       switch (T->getSizeModifier()) {
267         case ArrayType::Normal: break;
268         case ArrayType::Static: OS << " static"; break;
269         case ArrayType::Star: OS << " *"; break;
270       }
271       OS << " " << T->getIndexTypeQualifiers().getAsString();
272       dumpTypeAsChild(T->getElementType());
273     }
274     void VisitConstantArrayType(const ConstantArrayType *T) {
275       OS << " " << T->getSize();
276       VisitArrayType(T);
277     }
278     void VisitVariableArrayType(const VariableArrayType *T) {
279       OS << " ";
280       dumpSourceRange(T->getBracketsRange());
281       VisitArrayType(T);
282       dumpStmt(T->getSizeExpr());
283     }
284     void VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
285       VisitArrayType(T);
286       OS << " ";
287       dumpSourceRange(T->getBracketsRange());
288       dumpStmt(T->getSizeExpr());
289     }
290     void VisitDependentSizedExtVectorType(
291         const DependentSizedExtVectorType *T) {
292       OS << " ";
293       dumpLocation(T->getAttributeLoc());
294       dumpTypeAsChild(T->getElementType());
295       dumpStmt(T->getSizeExpr());
296     }
297     void VisitVectorType(const VectorType *T) {
298       switch (T->getVectorKind()) {
299         case VectorType::GenericVector: break;
300         case VectorType::AltiVecVector: OS << " altivec"; break;
301         case VectorType::AltiVecPixel: OS << " altivec pixel"; break;
302         case VectorType::AltiVecBool: OS << " altivec bool"; break;
303         case VectorType::NeonVector: OS << " neon"; break;
304         case VectorType::NeonPolyVector: OS << " neon poly"; break;
305       }
306       OS << " " << T->getNumElements();
307       dumpTypeAsChild(T->getElementType());
308     }
309     void VisitFunctionType(const FunctionType *T) {
310       auto EI = T->getExtInfo();
311       if (EI.getNoReturn()) OS << " noreturn";
312       if (EI.getProducesResult()) OS << " produces_result";
313       if (EI.getHasRegParm()) OS << " regparm " << EI.getRegParm();
314       OS << " " << FunctionType::getNameForCallConv(EI.getCC());
315       dumpTypeAsChild(T->getReturnType());
316     }
317     void VisitFunctionProtoType(const FunctionProtoType *T) {
318       auto EPI = T->getExtProtoInfo();
319       if (EPI.HasTrailingReturn) OS << " trailing_return";
320       if (T->isConst()) OS << " const";
321       if (T->isVolatile()) OS << " volatile";
322       if (T->isRestrict()) OS << " restrict";
323       switch (EPI.RefQualifier) {
324         case RQ_None: break;
325         case RQ_LValue: OS << " &"; break;
326         case RQ_RValue: OS << " &&"; break;
327       }
328       // FIXME: Exception specification.
329       // FIXME: Consumed parameters.
330       VisitFunctionType(T);
331       for (QualType PT : T->getParamTypes())
332         dumpTypeAsChild(PT);
333       if (EPI.Variadic)
334         dumpChild([=] { OS << "..."; });
335     }
336     void VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
337       dumpDeclRef(T->getDecl());
338     }
339     void VisitTypedefType(const TypedefType *T) {
340       dumpDeclRef(T->getDecl());
341     }
342     void VisitTypeOfExprType(const TypeOfExprType *T) {
343       dumpStmt(T->getUnderlyingExpr());
344     }
345     void VisitDecltypeType(const DecltypeType *T) {
346       dumpStmt(T->getUnderlyingExpr());
347     }
348     void VisitUnaryTransformType(const UnaryTransformType *T) {
349       switch (T->getUTTKind()) {
350       case UnaryTransformType::EnumUnderlyingType:
351         OS << " underlying_type";
352         break;
353       }
354       dumpTypeAsChild(T->getBaseType());
355     }
356     void VisitTagType(const TagType *T) {
357       dumpDeclRef(T->getDecl());
358     }
359     void VisitAttributedType(const AttributedType *T) {
360       // FIXME: AttrKind
361       dumpTypeAsChild(T->getModifiedType());
362     }
363     void VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
364       OS << " depth " << T->getDepth() << " index " << T->getIndex();
365       if (T->isParameterPack()) OS << " pack";
366       dumpDeclRef(T->getDecl());
367     }
368     void VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
369       dumpTypeAsChild(T->getReplacedParameter());
370     }
371     void VisitSubstTemplateTypeParmPackType(
372         const SubstTemplateTypeParmPackType *T) {
373       dumpTypeAsChild(T->getReplacedParameter());
374       dumpTemplateArgument(T->getArgumentPack());
375     }
376     void VisitAutoType(const AutoType *T) {
377       if (T->isDecltypeAuto()) OS << " decltype(auto)";
378       if (!T->isDeduced())
379         OS << " undeduced";
380     }
381     void VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
382       if (T->isTypeAlias()) OS << " alias";
383       OS << " "; T->getTemplateName().dump(OS);
384       for (auto &Arg : *T)
385         dumpTemplateArgument(Arg);
386       if (T->isTypeAlias())
387         dumpTypeAsChild(T->getAliasedType());
388     }
389     void VisitInjectedClassNameType(const InjectedClassNameType *T) {
390       dumpDeclRef(T->getDecl());
391     }
392     void VisitObjCInterfaceType(const ObjCInterfaceType *T) {
393       dumpDeclRef(T->getDecl());
394     }
395     void VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
396       dumpTypeAsChild(T->getPointeeType());
397     }
398     void VisitAtomicType(const AtomicType *T) {
399       dumpTypeAsChild(T->getValueType());
400     }
401     void VisitAdjustedType(const AdjustedType *T) {
402       dumpTypeAsChild(T->getOriginalType());
403     }
404     void VisitPackExpansionType(const PackExpansionType *T) {
405       if (auto N = T->getNumExpansions()) OS << " expansions " << *N;
406       if (!T->isSugared())
407         dumpTypeAsChild(T->getPattern());
408     }
409     // FIXME: ElaboratedType, DependentNameType,
410     // DependentTemplateSpecializationType, ObjCObjectType
411 
412     // Decls
413     void VisitLabelDecl(const LabelDecl *D);
414     void VisitTypedefDecl(const TypedefDecl *D);
415     void VisitEnumDecl(const EnumDecl *D);
416     void VisitRecordDecl(const RecordDecl *D);
417     void VisitEnumConstantDecl(const EnumConstantDecl *D);
418     void VisitIndirectFieldDecl(const IndirectFieldDecl *D);
419     void VisitFunctionDecl(const FunctionDecl *D);
420     void VisitFieldDecl(const FieldDecl *D);
421     void VisitVarDecl(const VarDecl *D);
422     void VisitFileScopeAsmDecl(const FileScopeAsmDecl *D);
423     void VisitImportDecl(const ImportDecl *D);
424 
425     // C++ Decls
426     void VisitNamespaceDecl(const NamespaceDecl *D);
427     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D);
428     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
429     void VisitTypeAliasDecl(const TypeAliasDecl *D);
430     void VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D);
431     void VisitCXXRecordDecl(const CXXRecordDecl *D);
432     void VisitStaticAssertDecl(const StaticAssertDecl *D);
433     template<typename SpecializationDecl>
434     void VisitTemplateDeclSpecialization(const SpecializationDecl *D,
435                                          bool DumpExplicitInst,
436                                          bool DumpRefOnly);
437     template<typename TemplateDecl>
438     void VisitTemplateDecl(const TemplateDecl *D, bool DumpExplicitInst);
439     void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
440     void VisitClassTemplateDecl(const ClassTemplateDecl *D);
441     void VisitClassTemplateSpecializationDecl(
442         const ClassTemplateSpecializationDecl *D);
443     void VisitClassTemplatePartialSpecializationDecl(
444         const ClassTemplatePartialSpecializationDecl *D);
445     void VisitClassScopeFunctionSpecializationDecl(
446         const ClassScopeFunctionSpecializationDecl *D);
447     void VisitVarTemplateDecl(const VarTemplateDecl *D);
448     void VisitVarTemplateSpecializationDecl(
449         const VarTemplateSpecializationDecl *D);
450     void VisitVarTemplatePartialSpecializationDecl(
451         const VarTemplatePartialSpecializationDecl *D);
452     void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
453     void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
454     void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
455     void VisitUsingDecl(const UsingDecl *D);
456     void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
457     void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
458     void VisitUsingShadowDecl(const UsingShadowDecl *D);
459     void VisitLinkageSpecDecl(const LinkageSpecDecl *D);
460     void VisitAccessSpecDecl(const AccessSpecDecl *D);
461     void VisitFriendDecl(const FriendDecl *D);
462 
463     // ObjC Decls
464     void VisitObjCIvarDecl(const ObjCIvarDecl *D);
465     void VisitObjCMethodDecl(const ObjCMethodDecl *D);
466     void VisitObjCCategoryDecl(const ObjCCategoryDecl *D);
467     void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D);
468     void VisitObjCProtocolDecl(const ObjCProtocolDecl *D);
469     void VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D);
470     void VisitObjCImplementationDecl(const ObjCImplementationDecl *D);
471     void VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D);
472     void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
473     void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
474     void VisitBlockDecl(const BlockDecl *D);
475 
476     // Stmts.
477     void VisitStmt(const Stmt *Node);
478     void VisitDeclStmt(const DeclStmt *Node);
479     void VisitAttributedStmt(const AttributedStmt *Node);
480     void VisitLabelStmt(const LabelStmt *Node);
481     void VisitGotoStmt(const GotoStmt *Node);
482     void VisitCXXCatchStmt(const CXXCatchStmt *Node);
483 
484     // Exprs
485     void VisitExpr(const Expr *Node);
486     void VisitCastExpr(const CastExpr *Node);
487     void VisitDeclRefExpr(const DeclRefExpr *Node);
488     void VisitPredefinedExpr(const PredefinedExpr *Node);
489     void VisitCharacterLiteral(const CharacterLiteral *Node);
490     void VisitIntegerLiteral(const IntegerLiteral *Node);
491     void VisitFloatingLiteral(const FloatingLiteral *Node);
492     void VisitStringLiteral(const StringLiteral *Str);
493     void VisitInitListExpr(const InitListExpr *ILE);
494     void VisitUnaryOperator(const UnaryOperator *Node);
495     void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Node);
496     void VisitMemberExpr(const MemberExpr *Node);
497     void VisitExtVectorElementExpr(const ExtVectorElementExpr *Node);
498     void VisitBinaryOperator(const BinaryOperator *Node);
499     void VisitCompoundAssignOperator(const CompoundAssignOperator *Node);
500     void VisitAddrLabelExpr(const AddrLabelExpr *Node);
501     void VisitBlockExpr(const BlockExpr *Node);
502     void VisitOpaqueValueExpr(const OpaqueValueExpr *Node);
503 
504     // C++
505     void VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node);
506     void VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node);
507     void VisitCXXThisExpr(const CXXThisExpr *Node);
508     void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node);
509     void VisitCXXConstructExpr(const CXXConstructExpr *Node);
510     void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node);
511     void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node);
512     void VisitExprWithCleanups(const ExprWithCleanups *Node);
513     void VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node);
514     void dumpCXXTemporary(const CXXTemporary *Temporary);
515     void VisitLambdaExpr(const LambdaExpr *Node) {
516       VisitExpr(Node);
517       dumpDecl(Node->getLambdaClass());
518     }
519 
520     // ObjC
521     void VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node);
522     void VisitObjCEncodeExpr(const ObjCEncodeExpr *Node);
523     void VisitObjCMessageExpr(const ObjCMessageExpr *Node);
524     void VisitObjCBoxedExpr(const ObjCBoxedExpr *Node);
525     void VisitObjCSelectorExpr(const ObjCSelectorExpr *Node);
526     void VisitObjCProtocolExpr(const ObjCProtocolExpr *Node);
527     void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node);
528     void VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node);
529     void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node);
530     void VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node);
531 
532     // Comments.
533     const char *getCommandName(unsigned CommandID);
534     void dumpComment(const Comment *C);
535 
536     // Inline comments.
537     void visitTextComment(const TextComment *C);
538     void visitInlineCommandComment(const InlineCommandComment *C);
539     void visitHTMLStartTagComment(const HTMLStartTagComment *C);
540     void visitHTMLEndTagComment(const HTMLEndTagComment *C);
541 
542     // Block comments.
543     void visitBlockCommandComment(const BlockCommandComment *C);
544     void visitParamCommandComment(const ParamCommandComment *C);
545     void visitTParamCommandComment(const TParamCommandComment *C);
546     void visitVerbatimBlockComment(const VerbatimBlockComment *C);
547     void visitVerbatimBlockLineComment(const VerbatimBlockLineComment *C);
548     void visitVerbatimLineComment(const VerbatimLineComment *C);
549   };
550 }
551 
552 //===----------------------------------------------------------------------===//
553 //  Utilities
554 //===----------------------------------------------------------------------===//
555 
556 void ASTDumper::dumpPointer(const void *Ptr) {
557   ColorScope Color(*this, AddressColor);
558   OS << ' ' << Ptr;
559 }
560 
561 void ASTDumper::dumpLocation(SourceLocation Loc) {
562   if (!SM)
563     return;
564 
565   ColorScope Color(*this, LocationColor);
566   SourceLocation SpellingLoc = SM->getSpellingLoc(Loc);
567 
568   // The general format we print out is filename:line:col, but we drop pieces
569   // that haven't changed since the last loc printed.
570   PresumedLoc PLoc = SM->getPresumedLoc(SpellingLoc);
571 
572   if (PLoc.isInvalid()) {
573     OS << "<invalid sloc>";
574     return;
575   }
576 
577   if (strcmp(PLoc.getFilename(), LastLocFilename) != 0) {
578     OS << PLoc.getFilename() << ':' << PLoc.getLine()
579        << ':' << PLoc.getColumn();
580     LastLocFilename = PLoc.getFilename();
581     LastLocLine = PLoc.getLine();
582   } else if (PLoc.getLine() != LastLocLine) {
583     OS << "line" << ':' << PLoc.getLine()
584        << ':' << PLoc.getColumn();
585     LastLocLine = PLoc.getLine();
586   } else {
587     OS << "col" << ':' << PLoc.getColumn();
588   }
589 }
590 
591 void ASTDumper::dumpSourceRange(SourceRange R) {
592   // Can't translate locations if a SourceManager isn't available.
593   if (!SM)
594     return;
595 
596   OS << " <";
597   dumpLocation(R.getBegin());
598   if (R.getBegin() != R.getEnd()) {
599     OS << ", ";
600     dumpLocation(R.getEnd());
601   }
602   OS << ">";
603 
604   // <t2.c:123:421[blah], t2.c:412:321>
605 
606 }
607 
608 void ASTDumper::dumpBareType(QualType T, bool Desugar) {
609   ColorScope Color(*this, TypeColor);
610 
611   SplitQualType T_split = T.split();
612   OS << "'" << QualType::getAsString(T_split) << "'";
613 
614   if (Desugar && !T.isNull()) {
615     // If the type is sugared, also dump a (shallow) desugared type.
616     SplitQualType D_split = T.getSplitDesugaredType();
617     if (T_split != D_split)
618       OS << ":'" << QualType::getAsString(D_split) << "'";
619   }
620 }
621 
622 void ASTDumper::dumpType(QualType T) {
623   OS << ' ';
624   dumpBareType(T);
625 }
626 
627 void ASTDumper::dumpTypeAsChild(QualType T) {
628   SplitQualType SQT = T.split();
629   if (!SQT.Quals.hasQualifiers())
630     return dumpTypeAsChild(SQT.Ty);
631 
632   dumpChild([=] {
633     OS << "QualType";
634     dumpPointer(T.getAsOpaquePtr());
635     OS << " ";
636     dumpBareType(T, false);
637     OS << " " << T.split().Quals.getAsString();
638     dumpTypeAsChild(T.split().Ty);
639   });
640 }
641 
642 void ASTDumper::dumpTypeAsChild(const Type *T) {
643   dumpChild([=] {
644     if (!T) {
645       ColorScope Color(*this, NullColor);
646       OS << "<<<NULL>>>";
647       return;
648     }
649 
650     {
651       ColorScope Color(*this, TypeColor);
652       OS << T->getTypeClassName() << "Type";
653     }
654     dumpPointer(T);
655     OS << " ";
656     dumpBareType(QualType(T, 0), false);
657 
658     QualType SingleStepDesugar =
659         T->getLocallyUnqualifiedSingleStepDesugaredType();
660     if (SingleStepDesugar != QualType(T, 0))
661       OS << " sugar";
662     if (T->isDependentType())
663       OS << " dependent";
664     else if (T->isInstantiationDependentType())
665       OS << " instantiation_dependent";
666     if (T->isVariablyModifiedType())
667       OS << " variably_modified";
668     if (T->containsUnexpandedParameterPack())
669       OS << " contains_unexpanded_pack";
670     if (T->isFromAST())
671       OS << " imported";
672 
673     TypeVisitor<ASTDumper>::Visit(T);
674 
675     if (SingleStepDesugar != QualType(T, 0))
676       dumpTypeAsChild(SingleStepDesugar);
677   });
678 }
679 
680 void ASTDumper::dumpBareDeclRef(const Decl *D) {
681   {
682     ColorScope Color(*this, DeclKindNameColor);
683     OS << D->getDeclKindName();
684   }
685   dumpPointer(D);
686 
687   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
688     ColorScope Color(*this, DeclNameColor);
689     OS << " '" << ND->getDeclName() << '\'';
690   }
691 
692   if (const ValueDecl *VD = dyn_cast<ValueDecl>(D))
693     dumpType(VD->getType());
694 }
695 
696 void ASTDumper::dumpDeclRef(const Decl *D, const char *Label) {
697   if (!D)
698     return;
699 
700   dumpChild([=]{
701     if (Label)
702       OS << Label << ' ';
703     dumpBareDeclRef(D);
704   });
705 }
706 
707 void ASTDumper::dumpName(const NamedDecl *ND) {
708   if (ND->getDeclName()) {
709     ColorScope Color(*this, DeclNameColor);
710     OS << ' ' << ND->getNameAsString();
711   }
712 }
713 
714 bool ASTDumper::hasNodes(const DeclContext *DC) {
715   if (!DC)
716     return false;
717 
718   return DC->hasExternalLexicalStorage() ||
719          DC->noload_decls_begin() != DC->noload_decls_end();
720 }
721 
722 void ASTDumper::dumpDeclContext(const DeclContext *DC) {
723   if (!DC)
724     return;
725 
726   for (auto *D : DC->noload_decls())
727     dumpDecl(D);
728 
729   if (DC->hasExternalLexicalStorage()) {
730     dumpChild([=]{
731       ColorScope Color(*this, UndeserializedColor);
732       OS << "<undeserialized declarations>";
733     });
734   }
735 }
736 
737 void ASTDumper::dumpLookups(const DeclContext *DC, bool DumpDecls) {
738   dumpChild([=] {
739     OS << "StoredDeclsMap ";
740     dumpBareDeclRef(cast<Decl>(DC));
741 
742     const DeclContext *Primary = DC->getPrimaryContext();
743     if (Primary != DC) {
744       OS << " primary";
745       dumpPointer(cast<Decl>(Primary));
746     }
747 
748     bool HasUndeserializedLookups = Primary->hasExternalVisibleStorage();
749 
750     DeclContext::all_lookups_iterator I = Primary->noload_lookups_begin(),
751                                       E = Primary->noload_lookups_end();
752     while (I != E) {
753       DeclarationName Name = I.getLookupName();
754       DeclContextLookupResult R = *I++;
755 
756       dumpChild([=] {
757         OS << "DeclarationName ";
758         {
759           ColorScope Color(*this, DeclNameColor);
760           OS << '\'' << Name << '\'';
761         }
762 
763         for (DeclContextLookupResult::iterator RI = R.begin(), RE = R.end();
764              RI != RE; ++RI) {
765           dumpChild([=] {
766             dumpBareDeclRef(*RI);
767 
768             if ((*RI)->isHidden())
769               OS << " hidden";
770 
771             // If requested, dump the redecl chain for this lookup.
772             if (DumpDecls) {
773               // Dump earliest decl first.
774               std::function<void(Decl *)> DumpWithPrev = [&](Decl *D) {
775                 if (Decl *Prev = D->getPreviousDecl())
776                   DumpWithPrev(Prev);
777                 dumpDecl(D);
778               };
779               DumpWithPrev(*RI);
780             }
781           });
782         }
783       });
784     }
785 
786     if (HasUndeserializedLookups) {
787       dumpChild([=] {
788         ColorScope Color(*this, UndeserializedColor);
789         OS << "<undeserialized lookups>";
790       });
791     }
792   });
793 }
794 
795 void ASTDumper::dumpAttr(const Attr *A) {
796   dumpChild([=] {
797     {
798       ColorScope Color(*this, AttrColor);
799 
800       switch (A->getKind()) {
801 #define ATTR(X) case attr::X: OS << #X; break;
802 #include "clang/Basic/AttrList.inc"
803       default:
804         llvm_unreachable("unexpected attribute kind");
805       }
806       OS << "Attr";
807     }
808     dumpPointer(A);
809     dumpSourceRange(A->getRange());
810     if (A->isInherited())
811       OS << " Inherited";
812     if (A->isImplicit())
813       OS << " Implicit";
814 #include "clang/AST/AttrDump.inc"
815   });
816 }
817 
818 static void dumpPreviousDeclImpl(raw_ostream &OS, ...) {}
819 
820 template<typename T>
821 static void dumpPreviousDeclImpl(raw_ostream &OS, const Mergeable<T> *D) {
822   const T *First = D->getFirstDecl();
823   if (First != D)
824     OS << " first " << First;
825 }
826 
827 template<typename T>
828 static void dumpPreviousDeclImpl(raw_ostream &OS, const Redeclarable<T> *D) {
829   const T *Prev = D->getPreviousDecl();
830   if (Prev)
831     OS << " prev " << Prev;
832 }
833 
834 /// Dump the previous declaration in the redeclaration chain for a declaration,
835 /// if any.
836 static void dumpPreviousDecl(raw_ostream &OS, const Decl *D) {
837   switch (D->getKind()) {
838 #define DECL(DERIVED, BASE) \
839   case Decl::DERIVED: \
840     return dumpPreviousDeclImpl(OS, cast<DERIVED##Decl>(D));
841 #define ABSTRACT_DECL(DECL)
842 #include "clang/AST/DeclNodes.inc"
843   }
844   llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
845 }
846 
847 //===----------------------------------------------------------------------===//
848 //  C++ Utilities
849 //===----------------------------------------------------------------------===//
850 
851 void ASTDumper::dumpAccessSpecifier(AccessSpecifier AS) {
852   switch (AS) {
853   case AS_none:
854     break;
855   case AS_public:
856     OS << "public";
857     break;
858   case AS_protected:
859     OS << "protected";
860     break;
861   case AS_private:
862     OS << "private";
863     break;
864   }
865 }
866 
867 void ASTDumper::dumpCXXCtorInitializer(const CXXCtorInitializer *Init) {
868   dumpChild([=] {
869     OS << "CXXCtorInitializer";
870     if (Init->isAnyMemberInitializer()) {
871       OS << ' ';
872       dumpBareDeclRef(Init->getAnyMember());
873     } else if (Init->isBaseInitializer()) {
874       dumpType(QualType(Init->getBaseClass(), 0));
875     } else if (Init->isDelegatingInitializer()) {
876       dumpType(Init->getTypeSourceInfo()->getType());
877     } else {
878       llvm_unreachable("Unknown initializer type");
879     }
880     dumpStmt(Init->getInit());
881   });
882 }
883 
884 void ASTDumper::dumpTemplateParameters(const TemplateParameterList *TPL) {
885   if (!TPL)
886     return;
887 
888   for (TemplateParameterList::const_iterator I = TPL->begin(), E = TPL->end();
889        I != E; ++I)
890     dumpDecl(*I);
891 }
892 
893 void ASTDumper::dumpTemplateArgumentListInfo(
894     const TemplateArgumentListInfo &TALI) {
895   for (unsigned i = 0, e = TALI.size(); i < e; ++i)
896     dumpTemplateArgumentLoc(TALI[i]);
897 }
898 
899 void ASTDumper::dumpTemplateArgumentLoc(const TemplateArgumentLoc &A) {
900   dumpTemplateArgument(A.getArgument(), A.getSourceRange());
901 }
902 
903 void ASTDumper::dumpTemplateArgumentList(const TemplateArgumentList &TAL) {
904   for (unsigned i = 0, e = TAL.size(); i < e; ++i)
905     dumpTemplateArgument(TAL[i]);
906 }
907 
908 void ASTDumper::dumpTemplateArgument(const TemplateArgument &A, SourceRange R) {
909   dumpChild([=] {
910     OS << "TemplateArgument";
911     if (R.isValid())
912       dumpSourceRange(R);
913 
914     switch (A.getKind()) {
915     case TemplateArgument::Null:
916       OS << " null";
917       break;
918     case TemplateArgument::Type:
919       OS << " type";
920       dumpType(A.getAsType());
921       break;
922     case TemplateArgument::Declaration:
923       OS << " decl";
924       dumpDeclRef(A.getAsDecl());
925       break;
926     case TemplateArgument::NullPtr:
927       OS << " nullptr";
928       break;
929     case TemplateArgument::Integral:
930       OS << " integral " << A.getAsIntegral();
931       break;
932     case TemplateArgument::Template:
933       OS << " template ";
934       A.getAsTemplate().dump(OS);
935       break;
936     case TemplateArgument::TemplateExpansion:
937       OS << " template expansion";
938       A.getAsTemplateOrTemplatePattern().dump(OS);
939       break;
940     case TemplateArgument::Expression:
941       OS << " expr";
942       dumpStmt(A.getAsExpr());
943       break;
944     case TemplateArgument::Pack:
945       OS << " pack";
946       for (TemplateArgument::pack_iterator I = A.pack_begin(), E = A.pack_end();
947            I != E; ++I)
948         dumpTemplateArgument(*I);
949       break;
950     }
951   });
952 }
953 
954 //===----------------------------------------------------------------------===//
955 //  Decl dumping methods.
956 //===----------------------------------------------------------------------===//
957 
958 void ASTDumper::dumpDecl(const Decl *D) {
959   dumpChild([=] {
960     if (!D) {
961       ColorScope Color(*this, NullColor);
962       OS << "<<<NULL>>>";
963       return;
964     }
965 
966     {
967       ColorScope Color(*this, DeclKindNameColor);
968       OS << D->getDeclKindName() << "Decl";
969     }
970     dumpPointer(D);
971     if (D->getLexicalDeclContext() != D->getDeclContext())
972       OS << " parent " << cast<Decl>(D->getDeclContext());
973     dumpPreviousDecl(OS, D);
974     dumpSourceRange(D->getSourceRange());
975     OS << ' ';
976     dumpLocation(D->getLocation());
977     if (Module *M = D->getOwningModule())
978       OS << " in " << M->getFullModuleName();
979     if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
980       if (ND->isHidden())
981         OS << " hidden";
982     if (D->isImplicit())
983       OS << " implicit";
984     if (D->isUsed())
985       OS << " used";
986     else if (D->isThisDeclarationReferenced())
987       OS << " referenced";
988     if (D->isInvalidDecl())
989       OS << " invalid";
990 
991     ConstDeclVisitor<ASTDumper>::Visit(D);
992 
993     for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); I != E;
994          ++I)
995       dumpAttr(*I);
996 
997     if (const FullComment *Comment =
998             D->getASTContext().getLocalCommentForDeclUncached(D))
999       dumpFullComment(Comment);
1000 
1001     // Decls within functions are visited by the body.
1002     if (!isa<FunctionDecl>(*D) && !isa<ObjCMethodDecl>(*D) &&
1003         hasNodes(dyn_cast<DeclContext>(D)))
1004       dumpDeclContext(cast<DeclContext>(D));
1005   });
1006 }
1007 
1008 void ASTDumper::VisitLabelDecl(const LabelDecl *D) {
1009   dumpName(D);
1010 }
1011 
1012 void ASTDumper::VisitTypedefDecl(const TypedefDecl *D) {
1013   dumpName(D);
1014   dumpType(D->getUnderlyingType());
1015   if (D->isModulePrivate())
1016     OS << " __module_private__";
1017 }
1018 
1019 void ASTDumper::VisitEnumDecl(const EnumDecl *D) {
1020   if (D->isScoped()) {
1021     if (D->isScopedUsingClassTag())
1022       OS << " class";
1023     else
1024       OS << " struct";
1025   }
1026   dumpName(D);
1027   if (D->isModulePrivate())
1028     OS << " __module_private__";
1029   if (D->isFixed())
1030     dumpType(D->getIntegerType());
1031 }
1032 
1033 void ASTDumper::VisitRecordDecl(const RecordDecl *D) {
1034   OS << ' ' << D->getKindName();
1035   dumpName(D);
1036   if (D->isModulePrivate())
1037     OS << " __module_private__";
1038   if (D->isCompleteDefinition())
1039     OS << " definition";
1040 }
1041 
1042 void ASTDumper::VisitEnumConstantDecl(const EnumConstantDecl *D) {
1043   dumpName(D);
1044   dumpType(D->getType());
1045   if (const Expr *Init = D->getInitExpr())
1046     dumpStmt(Init);
1047 }
1048 
1049 void ASTDumper::VisitIndirectFieldDecl(const IndirectFieldDecl *D) {
1050   dumpName(D);
1051   dumpType(D->getType());
1052 
1053   for (auto *Child : D->chain())
1054     dumpDeclRef(Child);
1055 }
1056 
1057 void ASTDumper::VisitFunctionDecl(const FunctionDecl *D) {
1058   dumpName(D);
1059   dumpType(D->getType());
1060 
1061   StorageClass SC = D->getStorageClass();
1062   if (SC != SC_None)
1063     OS << ' ' << VarDecl::getStorageClassSpecifierString(SC);
1064   if (D->isInlineSpecified())
1065     OS << " inline";
1066   if (D->isVirtualAsWritten())
1067     OS << " virtual";
1068   if (D->isModulePrivate())
1069     OS << " __module_private__";
1070 
1071   if (D->isPure())
1072     OS << " pure";
1073   else if (D->isDeletedAsWritten())
1074     OS << " delete";
1075 
1076   if (const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>()) {
1077     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1078     switch (EPI.ExceptionSpec.Type) {
1079     default: break;
1080     case EST_Unevaluated:
1081       OS << " noexcept-unevaluated " << EPI.ExceptionSpec.SourceDecl;
1082       break;
1083     case EST_Uninstantiated:
1084       OS << " noexcept-uninstantiated " << EPI.ExceptionSpec.SourceTemplate;
1085       break;
1086     }
1087   }
1088 
1089   if (const FunctionTemplateSpecializationInfo *FTSI =
1090           D->getTemplateSpecializationInfo())
1091     dumpTemplateArgumentList(*FTSI->TemplateArguments);
1092 
1093   for (ArrayRef<NamedDecl *>::iterator
1094        I = D->getDeclsInPrototypeScope().begin(),
1095        E = D->getDeclsInPrototypeScope().end(); I != E; ++I)
1096     dumpDecl(*I);
1097 
1098   for (FunctionDecl::param_const_iterator I = D->param_begin(),
1099                                           E = D->param_end();
1100        I != E; ++I)
1101     dumpDecl(*I);
1102 
1103   if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(D))
1104     for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
1105                                                  E = C->init_end();
1106          I != E; ++I)
1107       dumpCXXCtorInitializer(*I);
1108 
1109   if (D->doesThisDeclarationHaveABody())
1110     dumpStmt(D->getBody());
1111 }
1112 
1113 void ASTDumper::VisitFieldDecl(const FieldDecl *D) {
1114   dumpName(D);
1115   dumpType(D->getType());
1116   if (D->isMutable())
1117     OS << " mutable";
1118   if (D->isModulePrivate())
1119     OS << " __module_private__";
1120 
1121   if (D->isBitField())
1122     dumpStmt(D->getBitWidth());
1123   if (Expr *Init = D->getInClassInitializer())
1124     dumpStmt(Init);
1125 }
1126 
1127 void ASTDumper::VisitVarDecl(const VarDecl *D) {
1128   dumpName(D);
1129   dumpType(D->getType());
1130   StorageClass SC = D->getStorageClass();
1131   if (SC != SC_None)
1132     OS << ' ' << VarDecl::getStorageClassSpecifierString(SC);
1133   switch (D->getTLSKind()) {
1134   case VarDecl::TLS_None: break;
1135   case VarDecl::TLS_Static: OS << " tls"; break;
1136   case VarDecl::TLS_Dynamic: OS << " tls_dynamic"; break;
1137   }
1138   if (D->isModulePrivate())
1139     OS << " __module_private__";
1140   if (D->isNRVOVariable())
1141     OS << " nrvo";
1142   if (D->hasInit()) {
1143     switch (D->getInitStyle()) {
1144     case VarDecl::CInit: OS << " cinit"; break;
1145     case VarDecl::CallInit: OS << " callinit"; break;
1146     case VarDecl::ListInit: OS << " listinit"; break;
1147     }
1148     dumpStmt(D->getInit());
1149   }
1150 }
1151 
1152 void ASTDumper::VisitFileScopeAsmDecl(const FileScopeAsmDecl *D) {
1153   dumpStmt(D->getAsmString());
1154 }
1155 
1156 void ASTDumper::VisitImportDecl(const ImportDecl *D) {
1157   OS << ' ' << D->getImportedModule()->getFullModuleName();
1158 }
1159 
1160 //===----------------------------------------------------------------------===//
1161 // C++ Declarations
1162 //===----------------------------------------------------------------------===//
1163 
1164 void ASTDumper::VisitNamespaceDecl(const NamespaceDecl *D) {
1165   dumpName(D);
1166   if (D->isInline())
1167     OS << " inline";
1168   if (!D->isOriginalNamespace())
1169     dumpDeclRef(D->getOriginalNamespace(), "original");
1170 }
1171 
1172 void ASTDumper::VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
1173   OS << ' ';
1174   dumpBareDeclRef(D->getNominatedNamespace());
1175 }
1176 
1177 void ASTDumper::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
1178   dumpName(D);
1179   dumpDeclRef(D->getAliasedNamespace());
1180 }
1181 
1182 void ASTDumper::VisitTypeAliasDecl(const TypeAliasDecl *D) {
1183   dumpName(D);
1184   dumpType(D->getUnderlyingType());
1185 }
1186 
1187 void ASTDumper::VisitTypeAliasTemplateDecl(const TypeAliasTemplateDecl *D) {
1188   dumpName(D);
1189   dumpTemplateParameters(D->getTemplateParameters());
1190   dumpDecl(D->getTemplatedDecl());
1191 }
1192 
1193 void ASTDumper::VisitCXXRecordDecl(const CXXRecordDecl *D) {
1194   VisitRecordDecl(D);
1195   if (!D->isCompleteDefinition())
1196     return;
1197 
1198   for (const auto &I : D->bases()) {
1199     dumpChild([=] {
1200       if (I.isVirtual())
1201         OS << "virtual ";
1202       dumpAccessSpecifier(I.getAccessSpecifier());
1203       dumpType(I.getType());
1204       if (I.isPackExpansion())
1205         OS << "...";
1206     });
1207   }
1208 }
1209 
1210 void ASTDumper::VisitStaticAssertDecl(const StaticAssertDecl *D) {
1211   dumpStmt(D->getAssertExpr());
1212   dumpStmt(D->getMessage());
1213 }
1214 
1215 template<typename SpecializationDecl>
1216 void ASTDumper::VisitTemplateDeclSpecialization(const SpecializationDecl *D,
1217                                                 bool DumpExplicitInst,
1218                                                 bool DumpRefOnly) {
1219   bool DumpedAny = false;
1220   for (auto *RedeclWithBadType : D->redecls()) {
1221     // FIXME: The redecls() range sometimes has elements of a less-specific
1222     // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives
1223     // us TagDecls, and should give CXXRecordDecls).
1224     auto *Redecl = dyn_cast<SpecializationDecl>(RedeclWithBadType);
1225     if (!Redecl) {
1226       // Found the injected-class-name for a class template. This will be dumped
1227       // as part of its surrounding class so we don't need to dump it here.
1228       assert(isa<CXXRecordDecl>(RedeclWithBadType) &&
1229              "expected an injected-class-name");
1230       continue;
1231     }
1232 
1233     switch (Redecl->getTemplateSpecializationKind()) {
1234     case TSK_ExplicitInstantiationDeclaration:
1235     case TSK_ExplicitInstantiationDefinition:
1236       if (!DumpExplicitInst)
1237         break;
1238       // Fall through.
1239     case TSK_Undeclared:
1240     case TSK_ImplicitInstantiation:
1241       if (DumpRefOnly)
1242         dumpDeclRef(Redecl);
1243       else
1244         dumpDecl(Redecl);
1245       DumpedAny = true;
1246       break;
1247     case TSK_ExplicitSpecialization:
1248       break;
1249     }
1250   }
1251 
1252   // Ensure we dump at least one decl for each specialization.
1253   if (!DumpedAny)
1254     dumpDeclRef(D);
1255 }
1256 
1257 template<typename TemplateDecl>
1258 void ASTDumper::VisitTemplateDecl(const TemplateDecl *D,
1259                                   bool DumpExplicitInst) {
1260   dumpName(D);
1261   dumpTemplateParameters(D->getTemplateParameters());
1262 
1263   dumpDecl(D->getTemplatedDecl());
1264 
1265   for (auto *Child : D->specializations())
1266     VisitTemplateDeclSpecialization(Child, DumpExplicitInst,
1267                                     !D->isCanonicalDecl());
1268 }
1269 
1270 void ASTDumper::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
1271   // FIXME: We don't add a declaration of a function template specialization
1272   // to its context when it's explicitly instantiated, so dump explicit
1273   // instantiations when we dump the template itself.
1274   VisitTemplateDecl(D, true);
1275 }
1276 
1277 void ASTDumper::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
1278   VisitTemplateDecl(D, false);
1279 }
1280 
1281 void ASTDumper::VisitClassTemplateSpecializationDecl(
1282     const ClassTemplateSpecializationDecl *D) {
1283   VisitCXXRecordDecl(D);
1284   dumpTemplateArgumentList(D->getTemplateArgs());
1285 }
1286 
1287 void ASTDumper::VisitClassTemplatePartialSpecializationDecl(
1288     const ClassTemplatePartialSpecializationDecl *D) {
1289   VisitClassTemplateSpecializationDecl(D);
1290   dumpTemplateParameters(D->getTemplateParameters());
1291 }
1292 
1293 void ASTDumper::VisitClassScopeFunctionSpecializationDecl(
1294     const ClassScopeFunctionSpecializationDecl *D) {
1295   dumpDeclRef(D->getSpecialization());
1296   if (D->hasExplicitTemplateArgs())
1297     dumpTemplateArgumentListInfo(D->templateArgs());
1298 }
1299 
1300 void ASTDumper::VisitVarTemplateDecl(const VarTemplateDecl *D) {
1301   VisitTemplateDecl(D, false);
1302 }
1303 
1304 void ASTDumper::VisitVarTemplateSpecializationDecl(
1305     const VarTemplateSpecializationDecl *D) {
1306   dumpTemplateArgumentList(D->getTemplateArgs());
1307   VisitVarDecl(D);
1308 }
1309 
1310 void ASTDumper::VisitVarTemplatePartialSpecializationDecl(
1311     const VarTemplatePartialSpecializationDecl *D) {
1312   dumpTemplateParameters(D->getTemplateParameters());
1313   VisitVarTemplateSpecializationDecl(D);
1314 }
1315 
1316 void ASTDumper::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
1317   if (D->wasDeclaredWithTypename())
1318     OS << " typename";
1319   else
1320     OS << " class";
1321   if (D->isParameterPack())
1322     OS << " ...";
1323   dumpName(D);
1324   if (D->hasDefaultArgument())
1325     dumpTemplateArgument(D->getDefaultArgument());
1326 }
1327 
1328 void ASTDumper::VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1329   dumpType(D->getType());
1330   if (D->isParameterPack())
1331     OS << " ...";
1332   dumpName(D);
1333   if (D->hasDefaultArgument())
1334     dumpTemplateArgument(D->getDefaultArgument());
1335 }
1336 
1337 void ASTDumper::VisitTemplateTemplateParmDecl(
1338     const TemplateTemplateParmDecl *D) {
1339   if (D->isParameterPack())
1340     OS << " ...";
1341   dumpName(D);
1342   dumpTemplateParameters(D->getTemplateParameters());
1343   if (D->hasDefaultArgument())
1344     dumpTemplateArgumentLoc(D->getDefaultArgument());
1345 }
1346 
1347 void ASTDumper::VisitUsingDecl(const UsingDecl *D) {
1348   OS << ' ';
1349   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1350   OS << D->getNameAsString();
1351 }
1352 
1353 void ASTDumper::VisitUnresolvedUsingTypenameDecl(
1354     const UnresolvedUsingTypenameDecl *D) {
1355   OS << ' ';
1356   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1357   OS << D->getNameAsString();
1358 }
1359 
1360 void ASTDumper::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
1361   OS << ' ';
1362   D->getQualifier()->print(OS, D->getASTContext().getPrintingPolicy());
1363   OS << D->getNameAsString();
1364   dumpType(D->getType());
1365 }
1366 
1367 void ASTDumper::VisitUsingShadowDecl(const UsingShadowDecl *D) {
1368   OS << ' ';
1369   dumpBareDeclRef(D->getTargetDecl());
1370 }
1371 
1372 void ASTDumper::VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
1373   switch (D->getLanguage()) {
1374   case LinkageSpecDecl::lang_c: OS << " C"; break;
1375   case LinkageSpecDecl::lang_cxx: OS << " C++"; break;
1376   }
1377 }
1378 
1379 void ASTDumper::VisitAccessSpecDecl(const AccessSpecDecl *D) {
1380   OS << ' ';
1381   dumpAccessSpecifier(D->getAccess());
1382 }
1383 
1384 void ASTDumper::VisitFriendDecl(const FriendDecl *D) {
1385   if (TypeSourceInfo *T = D->getFriendType())
1386     dumpType(T->getType());
1387   else
1388     dumpDecl(D->getFriendDecl());
1389 }
1390 
1391 //===----------------------------------------------------------------------===//
1392 // Obj-C Declarations
1393 //===----------------------------------------------------------------------===//
1394 
1395 void ASTDumper::VisitObjCIvarDecl(const ObjCIvarDecl *D) {
1396   dumpName(D);
1397   dumpType(D->getType());
1398   if (D->getSynthesize())
1399     OS << " synthesize";
1400 
1401   switch (D->getAccessControl()) {
1402   case ObjCIvarDecl::None:
1403     OS << " none";
1404     break;
1405   case ObjCIvarDecl::Private:
1406     OS << " private";
1407     break;
1408   case ObjCIvarDecl::Protected:
1409     OS << " protected";
1410     break;
1411   case ObjCIvarDecl::Public:
1412     OS << " public";
1413     break;
1414   case ObjCIvarDecl::Package:
1415     OS << " package";
1416     break;
1417   }
1418 }
1419 
1420 void ASTDumper::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
1421   if (D->isInstanceMethod())
1422     OS << " -";
1423   else
1424     OS << " +";
1425   dumpName(D);
1426   dumpType(D->getReturnType());
1427 
1428   if (D->isThisDeclarationADefinition()) {
1429     dumpDeclContext(D);
1430   } else {
1431     for (ObjCMethodDecl::param_const_iterator I = D->param_begin(),
1432                                               E = D->param_end();
1433          I != E; ++I)
1434       dumpDecl(*I);
1435   }
1436 
1437   if (D->isVariadic())
1438     dumpChild([=] { OS << "..."; });
1439 
1440   if (D->hasBody())
1441     dumpStmt(D->getBody());
1442 }
1443 
1444 void ASTDumper::VisitObjCCategoryDecl(const ObjCCategoryDecl *D) {
1445   dumpName(D);
1446   dumpDeclRef(D->getClassInterface());
1447   dumpDeclRef(D->getImplementation());
1448   for (ObjCCategoryDecl::protocol_iterator I = D->protocol_begin(),
1449                                            E = D->protocol_end();
1450        I != E; ++I)
1451     dumpDeclRef(*I);
1452 }
1453 
1454 void ASTDumper::VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *D) {
1455   dumpName(D);
1456   dumpDeclRef(D->getClassInterface());
1457   dumpDeclRef(D->getCategoryDecl());
1458 }
1459 
1460 void ASTDumper::VisitObjCProtocolDecl(const ObjCProtocolDecl *D) {
1461   dumpName(D);
1462 
1463   for (auto *Child : D->protocols())
1464     dumpDeclRef(Child);
1465 }
1466 
1467 void ASTDumper::VisitObjCInterfaceDecl(const ObjCInterfaceDecl *D) {
1468   dumpName(D);
1469   dumpDeclRef(D->getSuperClass(), "super");
1470 
1471   dumpDeclRef(D->getImplementation());
1472   for (auto *Child : D->protocols())
1473     dumpDeclRef(Child);
1474 }
1475 
1476 void ASTDumper::VisitObjCImplementationDecl(const ObjCImplementationDecl *D) {
1477   dumpName(D);
1478   dumpDeclRef(D->getSuperClass(), "super");
1479   dumpDeclRef(D->getClassInterface());
1480   for (ObjCImplementationDecl::init_const_iterator I = D->init_begin(),
1481                                                    E = D->init_end();
1482        I != E; ++I)
1483     dumpCXXCtorInitializer(*I);
1484 }
1485 
1486 void ASTDumper::VisitObjCCompatibleAliasDecl(const ObjCCompatibleAliasDecl *D) {
1487   dumpName(D);
1488   dumpDeclRef(D->getClassInterface());
1489 }
1490 
1491 void ASTDumper::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
1492   dumpName(D);
1493   dumpType(D->getType());
1494 
1495   if (D->getPropertyImplementation() == ObjCPropertyDecl::Required)
1496     OS << " required";
1497   else if (D->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1498     OS << " optional";
1499 
1500   ObjCPropertyDecl::PropertyAttributeKind Attrs = D->getPropertyAttributes();
1501   if (Attrs != ObjCPropertyDecl::OBJC_PR_noattr) {
1502     if (Attrs & ObjCPropertyDecl::OBJC_PR_readonly)
1503       OS << " readonly";
1504     if (Attrs & ObjCPropertyDecl::OBJC_PR_assign)
1505       OS << " assign";
1506     if (Attrs & ObjCPropertyDecl::OBJC_PR_readwrite)
1507       OS << " readwrite";
1508     if (Attrs & ObjCPropertyDecl::OBJC_PR_retain)
1509       OS << " retain";
1510     if (Attrs & ObjCPropertyDecl::OBJC_PR_copy)
1511       OS << " copy";
1512     if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic)
1513       OS << " nonatomic";
1514     if (Attrs & ObjCPropertyDecl::OBJC_PR_atomic)
1515       OS << " atomic";
1516     if (Attrs & ObjCPropertyDecl::OBJC_PR_weak)
1517       OS << " weak";
1518     if (Attrs & ObjCPropertyDecl::OBJC_PR_strong)
1519       OS << " strong";
1520     if (Attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained)
1521       OS << " unsafe_unretained";
1522     if (Attrs & ObjCPropertyDecl::OBJC_PR_getter)
1523       dumpDeclRef(D->getGetterMethodDecl(), "getter");
1524     if (Attrs & ObjCPropertyDecl::OBJC_PR_setter)
1525       dumpDeclRef(D->getSetterMethodDecl(), "setter");
1526   }
1527 }
1528 
1529 void ASTDumper::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
1530   dumpName(D->getPropertyDecl());
1531   if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1532     OS << " synthesize";
1533   else
1534     OS << " dynamic";
1535   dumpDeclRef(D->getPropertyDecl());
1536   dumpDeclRef(D->getPropertyIvarDecl());
1537 }
1538 
1539 void ASTDumper::VisitBlockDecl(const BlockDecl *D) {
1540   for (auto I : D->params())
1541     dumpDecl(I);
1542 
1543   if (D->isVariadic())
1544     dumpChild([=]{ OS << "..."; });
1545 
1546   if (D->capturesCXXThis())
1547     dumpChild([=]{ OS << "capture this"; });
1548 
1549   for (const auto &I : D->captures()) {
1550     dumpChild([=] {
1551       OS << "capture";
1552       if (I.isByRef())
1553         OS << " byref";
1554       if (I.isNested())
1555         OS << " nested";
1556       if (I.getVariable()) {
1557         OS << ' ';
1558         dumpBareDeclRef(I.getVariable());
1559       }
1560       if (I.hasCopyExpr())
1561         dumpStmt(I.getCopyExpr());
1562     });
1563   }
1564   dumpStmt(D->getBody());
1565 }
1566 
1567 //===----------------------------------------------------------------------===//
1568 //  Stmt dumping methods.
1569 //===----------------------------------------------------------------------===//
1570 
1571 void ASTDumper::dumpStmt(const Stmt *S) {
1572   dumpChild([=] {
1573     if (!S) {
1574       ColorScope Color(*this, NullColor);
1575       OS << "<<<NULL>>>";
1576       return;
1577     }
1578 
1579     if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1580       VisitDeclStmt(DS);
1581       return;
1582     }
1583 
1584     ConstStmtVisitor<ASTDumper>::Visit(S);
1585 
1586     for (Stmt::const_child_range CI = S->children(); CI; ++CI)
1587       dumpStmt(*CI);
1588   });
1589 }
1590 
1591 void ASTDumper::VisitStmt(const Stmt *Node) {
1592   {
1593     ColorScope Color(*this, StmtColor);
1594     OS << Node->getStmtClassName();
1595   }
1596   dumpPointer(Node);
1597   dumpSourceRange(Node->getSourceRange());
1598 }
1599 
1600 void ASTDumper::VisitDeclStmt(const DeclStmt *Node) {
1601   VisitStmt(Node);
1602   for (DeclStmt::const_decl_iterator I = Node->decl_begin(),
1603                                      E = Node->decl_end();
1604        I != E; ++I)
1605     dumpDecl(*I);
1606 }
1607 
1608 void ASTDumper::VisitAttributedStmt(const AttributedStmt *Node) {
1609   VisitStmt(Node);
1610   for (ArrayRef<const Attr *>::iterator I = Node->getAttrs().begin(),
1611                                         E = Node->getAttrs().end();
1612        I != E; ++I)
1613     dumpAttr(*I);
1614 }
1615 
1616 void ASTDumper::VisitLabelStmt(const LabelStmt *Node) {
1617   VisitStmt(Node);
1618   OS << " '" << Node->getName() << "'";
1619 }
1620 
1621 void ASTDumper::VisitGotoStmt(const GotoStmt *Node) {
1622   VisitStmt(Node);
1623   OS << " '" << Node->getLabel()->getName() << "'";
1624   dumpPointer(Node->getLabel());
1625 }
1626 
1627 void ASTDumper::VisitCXXCatchStmt(const CXXCatchStmt *Node) {
1628   VisitStmt(Node);
1629   dumpDecl(Node->getExceptionDecl());
1630 }
1631 
1632 //===----------------------------------------------------------------------===//
1633 //  Expr dumping methods.
1634 //===----------------------------------------------------------------------===//
1635 
1636 void ASTDumper::VisitExpr(const Expr *Node) {
1637   VisitStmt(Node);
1638   dumpType(Node->getType());
1639 
1640   {
1641     ColorScope Color(*this, ValueKindColor);
1642     switch (Node->getValueKind()) {
1643     case VK_RValue:
1644       break;
1645     case VK_LValue:
1646       OS << " lvalue";
1647       break;
1648     case VK_XValue:
1649       OS << " xvalue";
1650       break;
1651     }
1652   }
1653 
1654   {
1655     ColorScope Color(*this, ObjectKindColor);
1656     switch (Node->getObjectKind()) {
1657     case OK_Ordinary:
1658       break;
1659     case OK_BitField:
1660       OS << " bitfield";
1661       break;
1662     case OK_ObjCProperty:
1663       OS << " objcproperty";
1664       break;
1665     case OK_ObjCSubscript:
1666       OS << " objcsubscript";
1667       break;
1668     case OK_VectorComponent:
1669       OS << " vectorcomponent";
1670       break;
1671     }
1672   }
1673 }
1674 
1675 static void dumpBasePath(raw_ostream &OS, const CastExpr *Node) {
1676   if (Node->path_empty())
1677     return;
1678 
1679   OS << " (";
1680   bool First = true;
1681   for (CastExpr::path_const_iterator I = Node->path_begin(),
1682                                      E = Node->path_end();
1683        I != E; ++I) {
1684     const CXXBaseSpecifier *Base = *I;
1685     if (!First)
1686       OS << " -> ";
1687 
1688     const CXXRecordDecl *RD =
1689     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1690 
1691     if (Base->isVirtual())
1692       OS << "virtual ";
1693     OS << RD->getName();
1694     First = false;
1695   }
1696 
1697   OS << ')';
1698 }
1699 
1700 void ASTDumper::VisitCastExpr(const CastExpr *Node) {
1701   VisitExpr(Node);
1702   OS << " <";
1703   {
1704     ColorScope Color(*this, CastColor);
1705     OS << Node->getCastKindName();
1706   }
1707   dumpBasePath(OS, Node);
1708   OS << ">";
1709 }
1710 
1711 void ASTDumper::VisitDeclRefExpr(const DeclRefExpr *Node) {
1712   VisitExpr(Node);
1713 
1714   OS << " ";
1715   dumpBareDeclRef(Node->getDecl());
1716   if (Node->getDecl() != Node->getFoundDecl()) {
1717     OS << " (";
1718     dumpBareDeclRef(Node->getFoundDecl());
1719     OS << ")";
1720   }
1721 }
1722 
1723 void ASTDumper::VisitUnresolvedLookupExpr(const UnresolvedLookupExpr *Node) {
1724   VisitExpr(Node);
1725   OS << " (";
1726   if (!Node->requiresADL())
1727     OS << "no ";
1728   OS << "ADL) = '" << Node->getName() << '\'';
1729 
1730   UnresolvedLookupExpr::decls_iterator
1731     I = Node->decls_begin(), E = Node->decls_end();
1732   if (I == E)
1733     OS << " empty";
1734   for (; I != E; ++I)
1735     dumpPointer(*I);
1736 }
1737 
1738 void ASTDumper::VisitObjCIvarRefExpr(const ObjCIvarRefExpr *Node) {
1739   VisitExpr(Node);
1740 
1741   {
1742     ColorScope Color(*this, DeclKindNameColor);
1743     OS << " " << Node->getDecl()->getDeclKindName() << "Decl";
1744   }
1745   OS << "='" << *Node->getDecl() << "'";
1746   dumpPointer(Node->getDecl());
1747   if (Node->isFreeIvar())
1748     OS << " isFreeIvar";
1749 }
1750 
1751 void ASTDumper::VisitPredefinedExpr(const PredefinedExpr *Node) {
1752   VisitExpr(Node);
1753   OS << " " << PredefinedExpr::getIdentTypeName(Node->getIdentType());
1754 }
1755 
1756 void ASTDumper::VisitCharacterLiteral(const CharacterLiteral *Node) {
1757   VisitExpr(Node);
1758   ColorScope Color(*this, ValueColor);
1759   OS << " " << Node->getValue();
1760 }
1761 
1762 void ASTDumper::VisitIntegerLiteral(const IntegerLiteral *Node) {
1763   VisitExpr(Node);
1764 
1765   bool isSigned = Node->getType()->isSignedIntegerType();
1766   ColorScope Color(*this, ValueColor);
1767   OS << " " << Node->getValue().toString(10, isSigned);
1768 }
1769 
1770 void ASTDumper::VisitFloatingLiteral(const FloatingLiteral *Node) {
1771   VisitExpr(Node);
1772   ColorScope Color(*this, ValueColor);
1773   OS << " " << Node->getValueAsApproximateDouble();
1774 }
1775 
1776 void ASTDumper::VisitStringLiteral(const StringLiteral *Str) {
1777   VisitExpr(Str);
1778   ColorScope Color(*this, ValueColor);
1779   OS << " ";
1780   Str->outputString(OS);
1781 }
1782 
1783 void ASTDumper::VisitInitListExpr(const InitListExpr *ILE) {
1784   VisitExpr(ILE);
1785   if (auto *Filler = ILE->getArrayFiller()) {
1786     dumpChild([=] {
1787       OS << "array filler";
1788       dumpStmt(Filler);
1789     });
1790   }
1791   if (auto *Field = ILE->getInitializedFieldInUnion()) {
1792     OS << " field ";
1793     dumpBareDeclRef(Field);
1794   }
1795 }
1796 
1797 void ASTDumper::VisitUnaryOperator(const UnaryOperator *Node) {
1798   VisitExpr(Node);
1799   OS << " " << (Node->isPostfix() ? "postfix" : "prefix")
1800      << " '" << UnaryOperator::getOpcodeStr(Node->getOpcode()) << "'";
1801 }
1802 
1803 void ASTDumper::VisitUnaryExprOrTypeTraitExpr(
1804     const UnaryExprOrTypeTraitExpr *Node) {
1805   VisitExpr(Node);
1806   switch(Node->getKind()) {
1807   case UETT_SizeOf:
1808     OS << " sizeof";
1809     break;
1810   case UETT_AlignOf:
1811     OS << " alignof";
1812     break;
1813   case UETT_VecStep:
1814     OS << " vec_step";
1815     break;
1816   }
1817   if (Node->isArgumentType())
1818     dumpType(Node->getArgumentType());
1819 }
1820 
1821 void ASTDumper::VisitMemberExpr(const MemberExpr *Node) {
1822   VisitExpr(Node);
1823   OS << " " << (Node->isArrow() ? "->" : ".") << *Node->getMemberDecl();
1824   dumpPointer(Node->getMemberDecl());
1825 }
1826 
1827 void ASTDumper::VisitExtVectorElementExpr(const ExtVectorElementExpr *Node) {
1828   VisitExpr(Node);
1829   OS << " " << Node->getAccessor().getNameStart();
1830 }
1831 
1832 void ASTDumper::VisitBinaryOperator(const BinaryOperator *Node) {
1833   VisitExpr(Node);
1834   OS << " '" << BinaryOperator::getOpcodeStr(Node->getOpcode()) << "'";
1835 }
1836 
1837 void ASTDumper::VisitCompoundAssignOperator(
1838     const CompoundAssignOperator *Node) {
1839   VisitExpr(Node);
1840   OS << " '" << BinaryOperator::getOpcodeStr(Node->getOpcode())
1841      << "' ComputeLHSTy=";
1842   dumpBareType(Node->getComputationLHSType());
1843   OS << " ComputeResultTy=";
1844   dumpBareType(Node->getComputationResultType());
1845 }
1846 
1847 void ASTDumper::VisitBlockExpr(const BlockExpr *Node) {
1848   VisitExpr(Node);
1849   dumpDecl(Node->getBlockDecl());
1850 }
1851 
1852 void ASTDumper::VisitOpaqueValueExpr(const OpaqueValueExpr *Node) {
1853   VisitExpr(Node);
1854 
1855   if (Expr *Source = Node->getSourceExpr())
1856     dumpStmt(Source);
1857 }
1858 
1859 // GNU extensions.
1860 
1861 void ASTDumper::VisitAddrLabelExpr(const AddrLabelExpr *Node) {
1862   VisitExpr(Node);
1863   OS << " " << Node->getLabel()->getName();
1864   dumpPointer(Node->getLabel());
1865 }
1866 
1867 //===----------------------------------------------------------------------===//
1868 // C++ Expressions
1869 //===----------------------------------------------------------------------===//
1870 
1871 void ASTDumper::VisitCXXNamedCastExpr(const CXXNamedCastExpr *Node) {
1872   VisitExpr(Node);
1873   OS << " " << Node->getCastName()
1874      << "<" << Node->getTypeAsWritten().getAsString() << ">"
1875      << " <" << Node->getCastKindName();
1876   dumpBasePath(OS, Node);
1877   OS << ">";
1878 }
1879 
1880 void ASTDumper::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *Node) {
1881   VisitExpr(Node);
1882   OS << " " << (Node->getValue() ? "true" : "false");
1883 }
1884 
1885 void ASTDumper::VisitCXXThisExpr(const CXXThisExpr *Node) {
1886   VisitExpr(Node);
1887   OS << " this";
1888 }
1889 
1890 void ASTDumper::VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *Node) {
1891   VisitExpr(Node);
1892   OS << " functional cast to " << Node->getTypeAsWritten().getAsString()
1893      << " <" << Node->getCastKindName() << ">";
1894 }
1895 
1896 void ASTDumper::VisitCXXConstructExpr(const CXXConstructExpr *Node) {
1897   VisitExpr(Node);
1898   CXXConstructorDecl *Ctor = Node->getConstructor();
1899   dumpType(Ctor->getType());
1900   if (Node->isElidable())
1901     OS << " elidable";
1902   if (Node->requiresZeroInitialization())
1903     OS << " zeroing";
1904 }
1905 
1906 void ASTDumper::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Node) {
1907   VisitExpr(Node);
1908   OS << " ";
1909   dumpCXXTemporary(Node->getTemporary());
1910 }
1911 
1912 void
1913 ASTDumper::VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Node) {
1914   VisitExpr(Node);
1915   if (const ValueDecl *VD = Node->getExtendingDecl()) {
1916     OS << " extended by ";
1917     dumpBareDeclRef(VD);
1918   }
1919 }
1920 
1921 void ASTDumper::VisitExprWithCleanups(const ExprWithCleanups *Node) {
1922   VisitExpr(Node);
1923   for (unsigned i = 0, e = Node->getNumObjects(); i != e; ++i)
1924     dumpDeclRef(Node->getObject(i), "cleanup");
1925 }
1926 
1927 void ASTDumper::dumpCXXTemporary(const CXXTemporary *Temporary) {
1928   OS << "(CXXTemporary";
1929   dumpPointer(Temporary);
1930   OS << ")";
1931 }
1932 
1933 //===----------------------------------------------------------------------===//
1934 // Obj-C Expressions
1935 //===----------------------------------------------------------------------===//
1936 
1937 void ASTDumper::VisitObjCMessageExpr(const ObjCMessageExpr *Node) {
1938   VisitExpr(Node);
1939   OS << " selector=";
1940   Node->getSelector().print(OS);
1941   switch (Node->getReceiverKind()) {
1942   case ObjCMessageExpr::Instance:
1943     break;
1944 
1945   case ObjCMessageExpr::Class:
1946     OS << " class=";
1947     dumpBareType(Node->getClassReceiver());
1948     break;
1949 
1950   case ObjCMessageExpr::SuperInstance:
1951     OS << " super (instance)";
1952     break;
1953 
1954   case ObjCMessageExpr::SuperClass:
1955     OS << " super (class)";
1956     break;
1957   }
1958 }
1959 
1960 void ASTDumper::VisitObjCBoxedExpr(const ObjCBoxedExpr *Node) {
1961   VisitExpr(Node);
1962   OS << " selector=";
1963   Node->getBoxingMethod()->getSelector().print(OS);
1964 }
1965 
1966 void ASTDumper::VisitObjCAtCatchStmt(const ObjCAtCatchStmt *Node) {
1967   VisitStmt(Node);
1968   if (const VarDecl *CatchParam = Node->getCatchParamDecl())
1969     dumpDecl(CatchParam);
1970   else
1971     OS << " catch all";
1972 }
1973 
1974 void ASTDumper::VisitObjCEncodeExpr(const ObjCEncodeExpr *Node) {
1975   VisitExpr(Node);
1976   dumpType(Node->getEncodedType());
1977 }
1978 
1979 void ASTDumper::VisitObjCSelectorExpr(const ObjCSelectorExpr *Node) {
1980   VisitExpr(Node);
1981 
1982   OS << " ";
1983   Node->getSelector().print(OS);
1984 }
1985 
1986 void ASTDumper::VisitObjCProtocolExpr(const ObjCProtocolExpr *Node) {
1987   VisitExpr(Node);
1988 
1989   OS << ' ' << *Node->getProtocol();
1990 }
1991 
1992 void ASTDumper::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Node) {
1993   VisitExpr(Node);
1994   if (Node->isImplicitProperty()) {
1995     OS << " Kind=MethodRef Getter=\"";
1996     if (Node->getImplicitPropertyGetter())
1997       Node->getImplicitPropertyGetter()->getSelector().print(OS);
1998     else
1999       OS << "(null)";
2000 
2001     OS << "\" Setter=\"";
2002     if (ObjCMethodDecl *Setter = Node->getImplicitPropertySetter())
2003       Setter->getSelector().print(OS);
2004     else
2005       OS << "(null)";
2006     OS << "\"";
2007   } else {
2008     OS << " Kind=PropertyRef Property=\"" << *Node->getExplicitProperty() <<'"';
2009   }
2010 
2011   if (Node->isSuperReceiver())
2012     OS << " super";
2013 
2014   OS << " Messaging=";
2015   if (Node->isMessagingGetter() && Node->isMessagingSetter())
2016     OS << "Getter&Setter";
2017   else if (Node->isMessagingGetter())
2018     OS << "Getter";
2019   else if (Node->isMessagingSetter())
2020     OS << "Setter";
2021 }
2022 
2023 void ASTDumper::VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *Node) {
2024   VisitExpr(Node);
2025   if (Node->isArraySubscriptRefExpr())
2026     OS << " Kind=ArraySubscript GetterForArray=\"";
2027   else
2028     OS << " Kind=DictionarySubscript GetterForDictionary=\"";
2029   if (Node->getAtIndexMethodDecl())
2030     Node->getAtIndexMethodDecl()->getSelector().print(OS);
2031   else
2032     OS << "(null)";
2033 
2034   if (Node->isArraySubscriptRefExpr())
2035     OS << "\" SetterForArray=\"";
2036   else
2037     OS << "\" SetterForDictionary=\"";
2038   if (Node->setAtIndexMethodDecl())
2039     Node->setAtIndexMethodDecl()->getSelector().print(OS);
2040   else
2041     OS << "(null)";
2042 }
2043 
2044 void ASTDumper::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *Node) {
2045   VisitExpr(Node);
2046   OS << " " << (Node->getValue() ? "__objc_yes" : "__objc_no");
2047 }
2048 
2049 //===----------------------------------------------------------------------===//
2050 // Comments
2051 //===----------------------------------------------------------------------===//
2052 
2053 const char *ASTDumper::getCommandName(unsigned CommandID) {
2054   if (Traits)
2055     return Traits->getCommandInfo(CommandID)->Name;
2056   const CommandInfo *Info = CommandTraits::getBuiltinCommandInfo(CommandID);
2057   if (Info)
2058     return Info->Name;
2059   return "<not a builtin command>";
2060 }
2061 
2062 void ASTDumper::dumpFullComment(const FullComment *C) {
2063   if (!C)
2064     return;
2065 
2066   FC = C;
2067   dumpComment(C);
2068   FC = nullptr;
2069 }
2070 
2071 void ASTDumper::dumpComment(const Comment *C) {
2072   dumpChild([=] {
2073     if (!C) {
2074       ColorScope Color(*this, NullColor);
2075       OS << "<<<NULL>>>";
2076       return;
2077     }
2078 
2079     {
2080       ColorScope Color(*this, CommentColor);
2081       OS << C->getCommentKindName();
2082     }
2083     dumpPointer(C);
2084     dumpSourceRange(C->getSourceRange());
2085     ConstCommentVisitor<ASTDumper>::visit(C);
2086     for (Comment::child_iterator I = C->child_begin(), E = C->child_end();
2087          I != E; ++I)
2088       dumpComment(*I);
2089   });
2090 }
2091 
2092 void ASTDumper::visitTextComment(const TextComment *C) {
2093   OS << " Text=\"" << C->getText() << "\"";
2094 }
2095 
2096 void ASTDumper::visitInlineCommandComment(const InlineCommandComment *C) {
2097   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
2098   switch (C->getRenderKind()) {
2099   case InlineCommandComment::RenderNormal:
2100     OS << " RenderNormal";
2101     break;
2102   case InlineCommandComment::RenderBold:
2103     OS << " RenderBold";
2104     break;
2105   case InlineCommandComment::RenderMonospaced:
2106     OS << " RenderMonospaced";
2107     break;
2108   case InlineCommandComment::RenderEmphasized:
2109     OS << " RenderEmphasized";
2110     break;
2111   }
2112 
2113   for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
2114     OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
2115 }
2116 
2117 void ASTDumper::visitHTMLStartTagComment(const HTMLStartTagComment *C) {
2118   OS << " Name=\"" << C->getTagName() << "\"";
2119   if (C->getNumAttrs() != 0) {
2120     OS << " Attrs: ";
2121     for (unsigned i = 0, e = C->getNumAttrs(); i != e; ++i) {
2122       const HTMLStartTagComment::Attribute &Attr = C->getAttr(i);
2123       OS << " \"" << Attr.Name << "=\"" << Attr.Value << "\"";
2124     }
2125   }
2126   if (C->isSelfClosing())
2127     OS << " SelfClosing";
2128 }
2129 
2130 void ASTDumper::visitHTMLEndTagComment(const HTMLEndTagComment *C) {
2131   OS << " Name=\"" << C->getTagName() << "\"";
2132 }
2133 
2134 void ASTDumper::visitBlockCommandComment(const BlockCommandComment *C) {
2135   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\"";
2136   for (unsigned i = 0, e = C->getNumArgs(); i != e; ++i)
2137     OS << " Arg[" << i << "]=\"" << C->getArgText(i) << "\"";
2138 }
2139 
2140 void ASTDumper::visitParamCommandComment(const ParamCommandComment *C) {
2141   OS << " " << ParamCommandComment::getDirectionAsString(C->getDirection());
2142 
2143   if (C->isDirectionExplicit())
2144     OS << " explicitly";
2145   else
2146     OS << " implicitly";
2147 
2148   if (C->hasParamName()) {
2149     if (C->isParamIndexValid())
2150       OS << " Param=\"" << C->getParamName(FC) << "\"";
2151     else
2152       OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
2153   }
2154 
2155   if (C->isParamIndexValid() && !C->isVarArgParam())
2156     OS << " ParamIndex=" << C->getParamIndex();
2157 }
2158 
2159 void ASTDumper::visitTParamCommandComment(const TParamCommandComment *C) {
2160   if (C->hasParamName()) {
2161     if (C->isPositionValid())
2162       OS << " Param=\"" << C->getParamName(FC) << "\"";
2163     else
2164       OS << " Param=\"" << C->getParamNameAsWritten() << "\"";
2165   }
2166 
2167   if (C->isPositionValid()) {
2168     OS << " Position=<";
2169     for (unsigned i = 0, e = C->getDepth(); i != e; ++i) {
2170       OS << C->getIndex(i);
2171       if (i != e - 1)
2172         OS << ", ";
2173     }
2174     OS << ">";
2175   }
2176 }
2177 
2178 void ASTDumper::visitVerbatimBlockComment(const VerbatimBlockComment *C) {
2179   OS << " Name=\"" << getCommandName(C->getCommandID()) << "\""
2180         " CloseName=\"" << C->getCloseName() << "\"";
2181 }
2182 
2183 void ASTDumper::visitVerbatimBlockLineComment(
2184     const VerbatimBlockLineComment *C) {
2185   OS << " Text=\"" << C->getText() << "\"";
2186 }
2187 
2188 void ASTDumper::visitVerbatimLineComment(const VerbatimLineComment *C) {
2189   OS << " Text=\"" << C->getText() << "\"";
2190 }
2191 
2192 //===----------------------------------------------------------------------===//
2193 // Type method implementations
2194 //===----------------------------------------------------------------------===//
2195 
2196 void QualType::dump(const char *msg) const {
2197   if (msg)
2198     llvm::errs() << msg << ": ";
2199   dump();
2200 }
2201 
2202 LLVM_DUMP_METHOD void QualType::dump() const {
2203   ASTDumper Dumper(llvm::errs(), nullptr, nullptr);
2204   Dumper.dumpTypeAsChild(*this);
2205 }
2206 
2207 LLVM_DUMP_METHOD void Type::dump() const { QualType(this, 0).dump(); }
2208 
2209 //===----------------------------------------------------------------------===//
2210 // Decl method implementations
2211 //===----------------------------------------------------------------------===//
2212 
2213 LLVM_DUMP_METHOD void Decl::dump() const { dump(llvm::errs()); }
2214 
2215 LLVM_DUMP_METHOD void Decl::dump(raw_ostream &OS) const {
2216   ASTDumper P(OS, &getASTContext().getCommentCommandTraits(),
2217               &getASTContext().getSourceManager());
2218   P.dumpDecl(this);
2219 }
2220 
2221 LLVM_DUMP_METHOD void Decl::dumpColor() const {
2222   ASTDumper P(llvm::errs(), &getASTContext().getCommentCommandTraits(),
2223               &getASTContext().getSourceManager(), /*ShowColors*/true);
2224   P.dumpDecl(this);
2225 }
2226 
2227 LLVM_DUMP_METHOD void DeclContext::dumpLookups() const {
2228   dumpLookups(llvm::errs());
2229 }
2230 
2231 LLVM_DUMP_METHOD void DeclContext::dumpLookups(raw_ostream &OS,
2232                                                bool DumpDecls) const {
2233   const DeclContext *DC = this;
2234   while (!DC->isTranslationUnit())
2235     DC = DC->getParent();
2236   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
2237   ASTDumper P(OS, &Ctx.getCommentCommandTraits(), &Ctx.getSourceManager());
2238   P.dumpLookups(this, DumpDecls);
2239 }
2240 
2241 //===----------------------------------------------------------------------===//
2242 // Stmt method implementations
2243 //===----------------------------------------------------------------------===//
2244 
2245 LLVM_DUMP_METHOD void Stmt::dump(SourceManager &SM) const {
2246   dump(llvm::errs(), SM);
2247 }
2248 
2249 LLVM_DUMP_METHOD void Stmt::dump(raw_ostream &OS, SourceManager &SM) const {
2250   ASTDumper P(OS, nullptr, &SM);
2251   P.dumpStmt(this);
2252 }
2253 
2254 LLVM_DUMP_METHOD void Stmt::dump() const {
2255   ASTDumper P(llvm::errs(), nullptr, nullptr);
2256   P.dumpStmt(this);
2257 }
2258 
2259 LLVM_DUMP_METHOD void Stmt::dumpColor() const {
2260   ASTDumper P(llvm::errs(), nullptr, nullptr, /*ShowColors*/true);
2261   P.dumpStmt(this);
2262 }
2263 
2264 //===----------------------------------------------------------------------===//
2265 // Comment method implementations
2266 //===----------------------------------------------------------------------===//
2267 
2268 LLVM_DUMP_METHOD void Comment::dump() const {
2269   dump(llvm::errs(), nullptr, nullptr);
2270 }
2271 
2272 LLVM_DUMP_METHOD void Comment::dump(const ASTContext &Context) const {
2273   dump(llvm::errs(), &Context.getCommentCommandTraits(),
2274        &Context.getSourceManager());
2275 }
2276 
2277 void Comment::dump(raw_ostream &OS, const CommandTraits *Traits,
2278                    const SourceManager *SM) const {
2279   const FullComment *FC = dyn_cast<FullComment>(this);
2280   ASTDumper D(OS, Traits, SM);
2281   D.dumpFullComment(FC);
2282 }
2283 
2284 LLVM_DUMP_METHOD void Comment::dumpColor() const {
2285   const FullComment *FC = dyn_cast<FullComment>(this);
2286   ASTDumper D(llvm::errs(), nullptr, nullptr, /*ShowColors*/true);
2287   D.dumpFullComment(FC);
2288 }
2289