1 //===--- ASTConsumers.cpp - ASTConsumer implementations -------------------===//
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 // AST Consumer Implementations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Frontend/ASTConsumers.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/AST/AST.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "llvm/Module.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/Timer.h"
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 /// ASTPrinter - Pretty-printer and dumper of ASTs
32 
33 namespace {
34   class ASTPrinter : public ASTConsumer,
35                      public RecursiveASTVisitor<ASTPrinter> {
36     typedef RecursiveASTVisitor<ASTPrinter> base;
37 
38   public:
39     ASTPrinter(raw_ostream *Out = NULL, bool Dump = false,
40                StringRef FilterString = "")
41         : Out(Out ? *Out : llvm::outs()), Dump(Dump),
42           FilterString(FilterString) {}
43 
44     virtual void HandleTranslationUnit(ASTContext &Context) {
45       TranslationUnitDecl *D = Context.getTranslationUnitDecl();
46 
47       if (FilterString.empty()) {
48         if (Dump)
49           D->dump(Out);
50         else
51           D->print(Out, /*Indentation=*/0, /*PrintInstantiation=*/true);
52         return;
53       }
54 
55       TraverseDecl(D);
56     }
57 
58     bool shouldWalkTypesOfTypeLocs() const { return false; }
59 
60     bool TraverseDecl(Decl *D) {
61       if (filterMatches(D)) {
62         Out.changeColor(llvm::raw_ostream::BLUE) <<
63             (Dump ? "Dumping " : "Printing ") << getName(D) << ":\n";
64         Out.resetColor();
65         if (Dump)
66           D->dump(Out);
67         else
68           D->print(Out, /*Indentation=*/0, /*PrintInstantiation=*/true);
69         // Don't traverse child nodes to avoid output duplication.
70         return true;
71       }
72       return base::TraverseDecl(D);
73     }
74 
75   private:
76     std::string getName(Decl *D) {
77       if (isa<NamedDecl>(D))
78         return cast<NamedDecl>(D)->getQualifiedNameAsString();
79       return "";
80     }
81     bool filterMatches(Decl *D) {
82       return getName(D).find(FilterString) != std::string::npos;
83     }
84 
85     raw_ostream &Out;
86     bool Dump;
87     std::string FilterString;
88   };
89 } // end anonymous namespace
90 
91 ASTConsumer *clang::CreateASTPrinter(raw_ostream *Out,
92                                      StringRef FilterString) {
93   return new ASTPrinter(Out, /*Dump=*/ false, FilterString);
94 }
95 
96 ASTConsumer *clang::CreateASTDumper(StringRef FilterString) {
97   return new ASTPrinter(0, /*Dump=*/ true, FilterString);
98 }
99 
100 //===----------------------------------------------------------------------===//
101 /// ASTViewer - AST Visualization
102 
103 namespace {
104   class ASTViewer : public ASTConsumer {
105     ASTContext *Context;
106   public:
107     void Initialize(ASTContext &Context) {
108       this->Context = &Context;
109     }
110 
111     virtual bool HandleTopLevelDecl(DeclGroupRef D) {
112       for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
113         HandleTopLevelSingleDecl(*I);
114       return true;
115     }
116 
117     void HandleTopLevelSingleDecl(Decl *D);
118   };
119 }
120 
121 void ASTViewer::HandleTopLevelSingleDecl(Decl *D) {
122   if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
123     D->print(llvm::errs());
124 
125     if (Stmt *Body = D->getBody()) {
126       llvm::errs() << '\n';
127       Body->viewAST();
128       llvm::errs() << '\n';
129     }
130   }
131 }
132 
133 
134 ASTConsumer *clang::CreateASTViewer() { return new ASTViewer(); }
135 
136 //===----------------------------------------------------------------------===//
137 /// DeclContextPrinter - Decl and DeclContext Visualization
138 
139 namespace {
140 
141 class DeclContextPrinter : public ASTConsumer {
142   raw_ostream& Out;
143 public:
144   DeclContextPrinter() : Out(llvm::errs()) {}
145 
146   void HandleTranslationUnit(ASTContext &C) {
147     PrintDeclContext(C.getTranslationUnitDecl(), 4);
148   }
149 
150   void PrintDeclContext(const DeclContext* DC, unsigned Indentation);
151 };
152 }  // end anonymous namespace
153 
154 void DeclContextPrinter::PrintDeclContext(const DeclContext* DC,
155                                           unsigned Indentation) {
156   // Print DeclContext name.
157   switch (DC->getDeclKind()) {
158   case Decl::TranslationUnit:
159     Out << "[translation unit] " << DC;
160     break;
161   case Decl::Namespace: {
162     Out << "[namespace] ";
163     const NamespaceDecl* ND = cast<NamespaceDecl>(DC);
164     Out << *ND;
165     break;
166   }
167   case Decl::Enum: {
168     const EnumDecl* ED = cast<EnumDecl>(DC);
169     if (ED->isCompleteDefinition())
170       Out << "[enum] ";
171     else
172       Out << "<enum> ";
173     Out << *ED;
174     break;
175   }
176   case Decl::Record: {
177     const RecordDecl* RD = cast<RecordDecl>(DC);
178     if (RD->isCompleteDefinition())
179       Out << "[struct] ";
180     else
181       Out << "<struct> ";
182     Out << *RD;
183     break;
184   }
185   case Decl::CXXRecord: {
186     const CXXRecordDecl* RD = cast<CXXRecordDecl>(DC);
187     if (RD->isCompleteDefinition())
188       Out << "[class] ";
189     else
190       Out << "<class> ";
191     Out << *RD << ' ' << DC;
192     break;
193   }
194   case Decl::ObjCMethod:
195     Out << "[objc method]";
196     break;
197   case Decl::ObjCInterface:
198     Out << "[objc interface]";
199     break;
200   case Decl::ObjCCategory:
201     Out << "[objc category]";
202     break;
203   case Decl::ObjCProtocol:
204     Out << "[objc protocol]";
205     break;
206   case Decl::ObjCImplementation:
207     Out << "[objc implementation]";
208     break;
209   case Decl::ObjCCategoryImpl:
210     Out << "[objc categoryimpl]";
211     break;
212   case Decl::LinkageSpec:
213     Out << "[linkage spec]";
214     break;
215   case Decl::Block:
216     Out << "[block]";
217     break;
218   case Decl::Function: {
219     const FunctionDecl* FD = cast<FunctionDecl>(DC);
220     if (FD->doesThisDeclarationHaveABody())
221       Out << "[function] ";
222     else
223       Out << "<function> ";
224     Out << *FD;
225     // Print the parameters.
226     Out << "(";
227     bool PrintComma = false;
228     for (FunctionDecl::param_const_iterator I = FD->param_begin(),
229            E = FD->param_end(); I != E; ++I) {
230       if (PrintComma)
231         Out << ", ";
232       else
233         PrintComma = true;
234       Out << **I;
235     }
236     Out << ")";
237     break;
238   }
239   case Decl::CXXMethod: {
240     const CXXMethodDecl* D = cast<CXXMethodDecl>(DC);
241     if (D->isOutOfLine())
242       Out << "[c++ method] ";
243     else if (D->isImplicit())
244       Out << "(c++ method) ";
245     else
246       Out << "<c++ method> ";
247     Out << *D;
248     // Print the parameters.
249     Out << "(";
250     bool PrintComma = false;
251     for (FunctionDecl::param_const_iterator I = D->param_begin(),
252            E = D->param_end(); I != E; ++I) {
253       if (PrintComma)
254         Out << ", ";
255       else
256         PrintComma = true;
257       Out << **I;
258     }
259     Out << ")";
260 
261     // Check the semantic DeclContext.
262     const DeclContext* SemaDC = D->getDeclContext();
263     const DeclContext* LexicalDC = D->getLexicalDeclContext();
264     if (SemaDC != LexicalDC)
265       Out << " [[" << SemaDC << "]]";
266 
267     break;
268   }
269   case Decl::CXXConstructor: {
270     const CXXConstructorDecl* D = cast<CXXConstructorDecl>(DC);
271     if (D->isOutOfLine())
272       Out << "[c++ ctor] ";
273     else if (D->isImplicit())
274       Out << "(c++ ctor) ";
275     else
276       Out << "<c++ ctor> ";
277     Out << *D;
278     // Print the parameters.
279     Out << "(";
280     bool PrintComma = false;
281     for (FunctionDecl::param_const_iterator I = D->param_begin(),
282            E = D->param_end(); I != E; ++I) {
283       if (PrintComma)
284         Out << ", ";
285       else
286         PrintComma = true;
287       Out << **I;
288     }
289     Out << ")";
290 
291     // Check the semantic DC.
292     const DeclContext* SemaDC = D->getDeclContext();
293     const DeclContext* LexicalDC = D->getLexicalDeclContext();
294     if (SemaDC != LexicalDC)
295       Out << " [[" << SemaDC << "]]";
296     break;
297   }
298   case Decl::CXXDestructor: {
299     const CXXDestructorDecl* D = cast<CXXDestructorDecl>(DC);
300     if (D->isOutOfLine())
301       Out << "[c++ dtor] ";
302     else if (D->isImplicit())
303       Out << "(c++ dtor) ";
304     else
305       Out << "<c++ dtor> ";
306     Out << *D;
307     // Check the semantic DC.
308     const DeclContext* SemaDC = D->getDeclContext();
309     const DeclContext* LexicalDC = D->getLexicalDeclContext();
310     if (SemaDC != LexicalDC)
311       Out << " [[" << SemaDC << "]]";
312     break;
313   }
314   case Decl::CXXConversion: {
315     const CXXConversionDecl* D = cast<CXXConversionDecl>(DC);
316     if (D->isOutOfLine())
317       Out << "[c++ conversion] ";
318     else if (D->isImplicit())
319       Out << "(c++ conversion) ";
320     else
321       Out << "<c++ conversion> ";
322     Out << *D;
323     // Check the semantic DC.
324     const DeclContext* SemaDC = D->getDeclContext();
325     const DeclContext* LexicalDC = D->getLexicalDeclContext();
326     if (SemaDC != LexicalDC)
327       Out << " [[" << SemaDC << "]]";
328     break;
329   }
330 
331   default:
332     llvm_unreachable("a decl that inherits DeclContext isn't handled");
333   }
334 
335   Out << "\n";
336 
337   // Print decls in the DeclContext.
338   for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
339        I != E; ++I) {
340     for (unsigned i = 0; i < Indentation; ++i)
341       Out << "  ";
342 
343     Decl::Kind DK = I->getKind();
344     switch (DK) {
345     case Decl::Namespace:
346     case Decl::Enum:
347     case Decl::Record:
348     case Decl::CXXRecord:
349     case Decl::ObjCMethod:
350     case Decl::ObjCInterface:
351     case Decl::ObjCCategory:
352     case Decl::ObjCProtocol:
353     case Decl::ObjCImplementation:
354     case Decl::ObjCCategoryImpl:
355     case Decl::LinkageSpec:
356     case Decl::Block:
357     case Decl::Function:
358     case Decl::CXXMethod:
359     case Decl::CXXConstructor:
360     case Decl::CXXDestructor:
361     case Decl::CXXConversion:
362     {
363       DeclContext* DC = cast<DeclContext>(*I);
364       PrintDeclContext(DC, Indentation+2);
365       break;
366     }
367     case Decl::IndirectField: {
368       IndirectFieldDecl* IFD = cast<IndirectFieldDecl>(*I);
369       Out << "<IndirectField> " << *IFD << '\n';
370       break;
371     }
372     case Decl::Label: {
373       LabelDecl *LD = cast<LabelDecl>(*I);
374       Out << "<Label> " << *LD << '\n';
375       break;
376     }
377     case Decl::Field: {
378       FieldDecl *FD = cast<FieldDecl>(*I);
379       Out << "<field> " << *FD << '\n';
380       break;
381     }
382     case Decl::Typedef:
383     case Decl::TypeAlias: {
384       TypedefNameDecl* TD = cast<TypedefNameDecl>(*I);
385       Out << "<typedef> " << *TD << '\n';
386       break;
387     }
388     case Decl::EnumConstant: {
389       EnumConstantDecl* ECD = cast<EnumConstantDecl>(*I);
390       Out << "<enum constant> " << *ECD << '\n';
391       break;
392     }
393     case Decl::Var: {
394       VarDecl* VD = cast<VarDecl>(*I);
395       Out << "<var> " << *VD << '\n';
396       break;
397     }
398     case Decl::ImplicitParam: {
399       ImplicitParamDecl* IPD = cast<ImplicitParamDecl>(*I);
400       Out << "<implicit parameter> " << *IPD << '\n';
401       break;
402     }
403     case Decl::ParmVar: {
404       ParmVarDecl* PVD = cast<ParmVarDecl>(*I);
405       Out << "<parameter> " << *PVD << '\n';
406       break;
407     }
408     case Decl::ObjCProperty: {
409       ObjCPropertyDecl* OPD = cast<ObjCPropertyDecl>(*I);
410       Out << "<objc property> " << *OPD << '\n';
411       break;
412     }
413     case Decl::FunctionTemplate: {
414       FunctionTemplateDecl* FTD = cast<FunctionTemplateDecl>(*I);
415       Out << "<function template> " << *FTD << '\n';
416       break;
417     }
418     case Decl::FileScopeAsm: {
419       Out << "<file-scope asm>\n";
420       break;
421     }
422     case Decl::UsingDirective: {
423       Out << "<using directive>\n";
424       break;
425     }
426     case Decl::NamespaceAlias: {
427       NamespaceAliasDecl* NAD = cast<NamespaceAliasDecl>(*I);
428       Out << "<namespace alias> " << *NAD << '\n';
429       break;
430     }
431     case Decl::ClassTemplate: {
432       ClassTemplateDecl *CTD = cast<ClassTemplateDecl>(*I);
433       Out << "<class template> " << *CTD << '\n';
434       break;
435     }
436     default:
437       Out << "DeclKind: " << DK << '"' << *I << "\"\n";
438       llvm_unreachable("decl unhandled");
439     }
440   }
441 }
442 ASTConsumer *clang::CreateDeclContextPrinter() {
443   return new DeclContextPrinter();
444 }
445 
446 //===----------------------------------------------------------------------===//
447 /// ASTDumperXML - In-depth XML dumping.
448 
449 namespace {
450 class ASTDumpXML : public ASTConsumer {
451   raw_ostream &OS;
452 
453 public:
454   ASTDumpXML(raw_ostream &OS) : OS(OS) {}
455 
456   void HandleTranslationUnit(ASTContext &C) {
457     C.getTranslationUnitDecl()->dumpXML(OS);
458   }
459 };
460 }
461 
462 ASTConsumer *clang::CreateASTDumperXML(raw_ostream &OS) {
463   return new ASTDumpXML(OS);
464 }
465