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