DeclPrinter.cpp revision 7b6248766dda6eb4c410d58db25a8dd2824f78cc
1//===--- DeclPrinter.cpp - Printing implementation for Decl 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 Decl::dump method, which pretty print the
11// AST back out to C/Objective-C/C++/Objective-C++ code.
12//
13//===----------------------------------------------------------------------===//
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclVisitor.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/Streams.h"
23#include "llvm/Support/Format.h"
24#include "llvm/Support/raw_ostream.h"
25using namespace clang;
26
27namespace {
28  class VISIBILITY_HIDDEN DeclPrinter : public DeclVisitor<DeclPrinter> {
29    llvm::raw_ostream &Out;
30    ASTContext &Context;
31    PrintingPolicy Policy;
32    unsigned Indentation;
33
34    llvm::raw_ostream& Indent();
35    void ProcessDeclGroup(llvm::SmallVectorImpl<Decl*>& Decls);
36
37  public:
38    DeclPrinter(llvm::raw_ostream &Out, ASTContext &Context,
39                const PrintingPolicy &Policy,
40                unsigned Indentation = 0)
41      : Out(Out), Context(Context), Policy(Policy), Indentation(Indentation) { }
42
43    void VisitDeclContext(DeclContext *DC, bool Indent = true);
44
45    void VisitTranslationUnitDecl(TranslationUnitDecl *D);
46    void VisitTypedefDecl(TypedefDecl *D);
47    void VisitEnumDecl(EnumDecl *D);
48    void VisitRecordDecl(RecordDecl *D);
49    void VisitEnumConstantDecl(EnumConstantDecl *D);
50    void VisitFunctionDecl(FunctionDecl *D);
51    void VisitFieldDecl(FieldDecl *D);
52    void VisitVarDecl(VarDecl *D);
53    void VisitParmVarDecl(ParmVarDecl *D);
54    void VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
55    void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
56    void VisitOverloadedFunctionDecl(OverloadedFunctionDecl *D);
57    void VisitNamespaceDecl(NamespaceDecl *D);
58    void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
59    void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
60    void VisitCXXRecordDecl(CXXRecordDecl *D);
61    void VisitLinkageSpecDecl(LinkageSpecDecl *D);
62    void VisitTemplateDecl(TemplateDecl *D);
63    void VisitObjCMethodDecl(ObjCMethodDecl *D);
64    void VisitObjCClassDecl(ObjCClassDecl *D);
65    void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
66    void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
67    void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
68    void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
69    void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
70    void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
71    void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
72    void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
73    void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
74  };
75}
76
77void Decl::print(llvm::raw_ostream &Out, unsigned Indentation) {
78  print(Out, getASTContext().PrintingPolicy, Indentation);
79}
80
81void Decl::print(llvm::raw_ostream &Out, const PrintingPolicy &Policy,
82                 unsigned Indentation) {
83  DeclPrinter Printer(Out, getASTContext(), Policy, Indentation);
84  Printer.Visit(this);
85}
86
87static QualType GetBaseType(QualType T) {
88  // FIXME: This should be on the Type class!
89  QualType BaseType = T;
90  while (!BaseType->isSpecifierType()) {
91    if (isa<TypedefType>(BaseType))
92      break;
93    else if (const PointerType* PTy = BaseType->getAsPointerType())
94      BaseType = PTy->getPointeeType();
95    else if (const ArrayType* ATy = dyn_cast<ArrayType>(BaseType))
96      BaseType = ATy->getElementType();
97    else if (const FunctionType* FTy = BaseType->getAsFunctionType())
98      BaseType = FTy->getResultType();
99    else if (const VectorType *VTy = BaseType->getAsVectorType())
100      BaseType = VTy->getElementType();
101    else
102      assert(0 && "Unknown declarator!");
103  }
104  return BaseType;
105}
106
107static QualType getDeclType(Decl* D) {
108  if (TypedefDecl* TDD = dyn_cast<TypedefDecl>(D))
109    return TDD->getUnderlyingType();
110  if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
111    return VD->getType();
112  return QualType();
113}
114
115void Decl::printGroup(Decl** Begin, unsigned NumDecls,
116                      llvm::raw_ostream &Out, const PrintingPolicy &Policy,
117                      unsigned Indentation) {
118  if (NumDecls == 1) {
119    (*Begin)->print(Out, Policy, Indentation);
120    return;
121  }
122
123  Decl** End = Begin + NumDecls;
124  TagDecl* TD = dyn_cast<TagDecl>(*Begin);
125  if (TD)
126    ++Begin;
127
128  PrintingPolicy SubPolicy(Policy);
129  if (TD && TD->isDefinition()) {
130    TD->print(Out, Policy, Indentation);
131    Out << " ";
132    SubPolicy.SuppressTag = true;
133  }
134
135  bool isFirst = true;
136  for ( ; Begin != End; ++Begin) {
137    if (isFirst) {
138      SubPolicy.SuppressSpecifiers = false;
139      isFirst = false;
140    } else {
141      if (!isFirst) Out << ", ";
142      SubPolicy.SuppressSpecifiers = true;
143    }
144
145    (*Begin)->print(Out, SubPolicy, Indentation);
146  }
147}
148
149void Decl::dump() {
150  print(llvm::errs());
151}
152
153llvm::raw_ostream& DeclPrinter::Indent() {
154  for (unsigned i = 0; i < Indentation; ++i)
155    Out << "  ";
156  return Out;
157}
158
159void DeclPrinter::ProcessDeclGroup(llvm::SmallVectorImpl<Decl*>& Decls) {
160  this->Indent();
161  Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
162  Out << ";\n";
163  Decls.clear();
164
165}
166
167//----------------------------------------------------------------------------
168// Common C declarations
169//----------------------------------------------------------------------------
170
171void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
172  if (Indent)
173    Indentation += Policy.Indentation;
174
175  llvm::SmallVector<Decl*, 2> Decls;
176  for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
177       D != DEnd; ++D) {
178    if (!Policy.Dump) {
179      // Skip over implicit declarations in pretty-printing mode.
180      if (D->isImplicit()) continue;
181      // FIXME: Ugly hack so we don't pretty-print the builtin declaration
182      // of __builtin_va_list.  There should be some other way to check that.
183      if (isa<NamedDecl>(*D) && cast<NamedDecl>(*D)->getNameAsString() ==
184          "__builtin_va_list")
185        continue;
186    }
187
188    // The next bits of code handles stuff like "struct {int x;} a,b"; we're
189    // forced to merge the declarations because there's no other way to
190    // refer to the struct in question.  This limited merging is safe without
191    // a bunch of other checks because it only merges declarations directly
192    // referring to the tag, not typedefs.
193    //
194    // Check whether the current declaration should be grouped with a previous
195    // unnamed struct.
196    QualType CurDeclType = getDeclType(*D);
197    if (!Decls.empty() && !CurDeclType.isNull()) {
198      QualType BaseType = GetBaseType(CurDeclType);
199      if (!BaseType.isNull() && isa<TagType>(BaseType) &&
200          cast<TagType>(BaseType)->getDecl() == Decls[0]) {
201        Decls.push_back(*D);
202        continue;
203      }
204    }
205
206    // If we have a merged group waiting to be handled, handle it now.
207    if (!Decls.empty())
208      ProcessDeclGroup(Decls);
209
210    // If the current declaration is an unnamed tag type, save it
211    // so we can merge it with the subsequent declaration(s) using it.
212    if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->getIdentifier()) {
213      Decls.push_back(*D);
214      continue;
215    }
216    this->Indent();
217    Visit(*D);
218
219    // FIXME: Need to be able to tell the DeclPrinter when
220    const char *Terminator = 0;
221    if (isa<FunctionDecl>(*D) &&
222        cast<FunctionDecl>(*D)->isThisDeclarationADefinition())
223      Terminator = 0;
224    else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->getBody())
225      Terminator = 0;
226    else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
227             isa<ObjCImplementationDecl>(*D) ||
228             isa<ObjCInterfaceDecl>(*D) ||
229             isa<ObjCProtocolDecl>(*D) ||
230             isa<ObjCCategoryImplDecl>(*D) ||
231             isa<ObjCCategoryDecl>(*D))
232      Terminator = 0;
233    else if (isa<EnumConstantDecl>(*D)) {
234      DeclContext::decl_iterator Next = D;
235      ++Next;
236      if (Next != DEnd)
237        Terminator = ",";
238    } else
239      Terminator = ";";
240
241    if (Terminator)
242      Out << Terminator;
243    Out << "\n";
244  }
245
246  if (!Decls.empty())
247    ProcessDeclGroup(Decls);
248
249  if (Indent)
250    Indentation -= Policy.Indentation;
251}
252
253void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
254  VisitDeclContext(D, false);
255}
256
257void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
258  std::string S = D->getNameAsString();
259  D->getUnderlyingType().getAsStringInternal(S, Policy);
260  if (!Policy.SuppressSpecifiers)
261    Out << "typedef ";
262  Out << S;
263}
264
265void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
266  Out << "enum " << D->getNameAsString() << " {\n";
267  VisitDeclContext(D);
268  Indent() << "}";
269}
270
271void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
272  Out << D->getKindName();
273  if (D->getIdentifier()) {
274    Out << " ";
275    Out << D->getNameAsString();
276  }
277
278  if (D->isDefinition()) {
279    Out << " {\n";
280    VisitDeclContext(D);
281    Indent() << "}";
282  }
283}
284
285void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
286  Out << D->getNameAsString();
287  if (Expr *Init = D->getInitExpr()) {
288    Out << " = ";
289    Init->printPretty(Out, Context, 0, Policy, Indentation);
290  }
291}
292
293void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
294  if (!Policy.SuppressSpecifiers) {
295    switch (D->getStorageClass()) {
296    case FunctionDecl::None: break;
297    case FunctionDecl::Extern: Out << "extern "; break;
298    case FunctionDecl::Static: Out << "static "; break;
299    case FunctionDecl::PrivateExtern: Out << "__private_extern__ "; break;
300    }
301
302    if (D->isInline())           Out << "inline ";
303    if (D->isVirtualAsWritten()) Out << "virtual ";
304  }
305
306  PrintingPolicy SubPolicy(Policy);
307  SubPolicy.SuppressSpecifiers = false;
308  std::string Proto = D->getNameAsString();
309  if (isa<FunctionType>(D->getType().getTypePtr())) {
310    const FunctionType *AFT = D->getType()->getAsFunctionType();
311
312    const FunctionProtoType *FT = 0;
313    if (D->hasWrittenPrototype())
314      FT = dyn_cast<FunctionProtoType>(AFT);
315
316    Proto += "(";
317    if (FT) {
318      llvm::raw_string_ostream POut(Proto);
319      DeclPrinter ParamPrinter(POut, Context, SubPolicy, Indentation);
320      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
321        if (i) POut << ", ";
322        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
323      }
324
325      if (FT->isVariadic()) {
326        if (D->getNumParams()) POut << ", ";
327        POut << "...";
328      }
329    } else if (D->isThisDeclarationADefinition() && !D->hasPrototype()) {
330      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
331        if (i)
332          Proto += ", ";
333        Proto += D->getParamDecl(i)->getNameAsString();
334      }
335    }
336
337    Proto += ")";
338    if (CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D)) {
339      if (CDecl->getNumBaseOrMemberInitializers() > 0) {
340        Proto += " : ";
341        Out << Proto;
342        Proto.clear();
343        for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(),
344             E = CDecl->init_end();
345             B != E; ++B) {
346          CXXBaseOrMemberInitializer * BMInitializer = (*B);
347          if (B != CDecl->init_begin())
348            Out << ", ";
349          bool hasArguments = (BMInitializer->begin() != BMInitializer->end());
350          if (BMInitializer->isMemberInitializer()) {
351            FieldDecl *FD = BMInitializer->getMember();
352            Out <<  FD->getNameAsString();
353          }
354          else // FIXME. skip dependent types for now.
355            if (const RecordType *RT =
356                BMInitializer->getBaseClass()->getAsRecordType()) {
357              const CXXRecordDecl *BaseDecl =
358                cast<CXXRecordDecl>(RT->getDecl());
359              Out << BaseDecl->getNameAsString();
360          }
361          if (hasArguments) {
362            Out << "(";
363            for (CXXBaseOrMemberInitializer::arg_const_iterator BE =
364                 BMInitializer->begin(), EE =  BMInitializer->end();
365                 BE != EE; BE++) {
366              if (BE != BMInitializer->begin())
367                Out<< ", ";
368              Expr *Exp = (*BE);
369              Exp->printPretty(Out, Context, 0, Policy, Indentation);
370            }
371            Out << ")";
372          } else
373            Out << "()";
374        }
375      }
376    }
377#if 0
378    else if (CXXDestructorDecl *DDecl = dyn_cast<CXXDestructorDecl>(D)) {
379      if (DDecl->getNumBaseOrMemberDestructions() > 0) {
380        // FIXME. This is strictly for visualization of destructor's AST for
381        // how base/members are destructed. It has no other validity.
382        assert (D->isThisDeclarationADefinition() && "Destructor with dtor-list");
383        Proto += " : ";
384        for (CXXDestructorDecl::destr_const_iterator B = DDecl->destr_begin(),
385             E = DDecl->destr_end();
386             B != E; ++B) {
387          CXXBaseOrMemberInitializer * BMInitializer = (*B);
388          if (B != DDecl->destr_begin())
389            Proto += ", ";
390
391          if (BMInitializer->isMemberInitializer()) {
392            FieldDecl *FD = BMInitializer->getMember();
393            Proto += "~";
394            Proto += FD->getNameAsString();
395          }
396          else // FIXME. skip dependent types for now.
397            if (const RecordType *RT =
398                BMInitializer->getBaseClass()->getAsRecordType()) {
399              const CXXRecordDecl *BaseDecl =
400                cast<CXXRecordDecl>(RT->getDecl());
401              Proto += "~";
402              Proto += BaseDecl->getNameAsString();
403            }
404          Proto += "()";
405        }
406      }
407    }
408#endif
409    else
410      AFT->getResultType().getAsStringInternal(Proto, Policy);
411  } else {
412    D->getType().getAsStringInternal(Proto, Policy);
413  }
414
415  Out << Proto;
416
417  if (D->isPure())
418    Out << " = 0";
419  else if (D->isDeleted())
420    Out << " = delete";
421  else if (D->isThisDeclarationADefinition()) {
422    if (!D->hasPrototype() && D->getNumParams()) {
423      // This is a K&R function definition, so we need to print the
424      // parameters.
425      Out << '\n';
426      DeclPrinter ParamPrinter(Out, Context, SubPolicy, Indentation);
427      Indentation += Policy.Indentation;
428      for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
429        Indent();
430        ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
431        Out << ";\n";
432      }
433      Indentation -= Policy.Indentation;
434    } else
435      Out << ' ';
436
437    D->getBody()->printPretty(Out, Context, 0, SubPolicy, Indentation);
438    Out << '\n';
439  }
440}
441
442void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
443  if (!Policy.SuppressSpecifiers && D->isMutable())
444    Out << "mutable ";
445
446  std::string Name = D->getNameAsString();
447  D->getType().getAsStringInternal(Name, Policy);
448  Out << Name;
449
450  if (D->isBitField()) {
451    Out << " : ";
452    D->getBitWidth()->printPretty(Out, Context, 0, Policy, Indentation);
453  }
454}
455
456void DeclPrinter::VisitVarDecl(VarDecl *D) {
457  if (!Policy.SuppressSpecifiers && D->getStorageClass() != VarDecl::None)
458    Out << VarDecl::getStorageClassSpecifierString(D->getStorageClass()) << " ";
459
460  if (!Policy.SuppressSpecifiers && D->isThreadSpecified())
461    Out << "__thread ";
462
463  std::string Name = D->getNameAsString();
464  QualType T = D->getType();
465  if (OriginalParmVarDecl *Parm = dyn_cast<OriginalParmVarDecl>(D))
466    T = Parm->getOriginalType();
467  T.getAsStringInternal(Name, Policy);
468  Out << Name;
469  if (D->getInit()) {
470    if (D->hasCXXDirectInitializer())
471      Out << "(";
472    else
473      Out << " = ";
474    D->getInit()->printPretty(Out, Context, 0, Policy, Indentation);
475    if (D->hasCXXDirectInitializer())
476      Out << ")";
477  }
478}
479
480void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
481  VisitVarDecl(D);
482}
483
484void DeclPrinter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
485  VisitVarDecl(D);
486}
487
488void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
489  Out << "__asm (";
490  D->getAsmString()->printPretty(Out, Context, 0, Policy, Indentation);
491  Out << ")";
492}
493
494//----------------------------------------------------------------------------
495// C++ declarations
496//----------------------------------------------------------------------------
497void DeclPrinter::VisitOverloadedFunctionDecl(OverloadedFunctionDecl *D) {
498  assert(false &&
499         "OverloadedFunctionDecls aren't really decls and are never printed");
500}
501
502void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
503  Out << "namespace " << D->getNameAsString() << " {\n";
504  VisitDeclContext(D);
505  Indent() << "}";
506}
507
508void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
509  Out << "using namespace ";
510  if (D->getQualifier())
511    D->getQualifier()->print(Out, Policy);
512  Out << D->getNominatedNamespace()->getNameAsString();
513}
514
515void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
516  Out << "namespace " << D->getNameAsString() << " = ";
517  if (D->getQualifier())
518    D->getQualifier()->print(Out, Policy);
519  Out << D->getAliasedNamespace()->getNameAsString();
520}
521
522void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
523  Out << D->getKindName();
524  if (D->getIdentifier()) {
525    Out << " ";
526    Out << D->getNameAsString();
527  }
528
529  if (D->isDefinition()) {
530    // Print the base classes
531    if (D->getNumBases()) {
532      Out << " : ";
533      for(CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
534                                          BaseEnd = D->bases_end();
535          Base != BaseEnd; ++Base) {
536        if (Base != D->bases_begin())
537          Out << ", ";
538
539        if (Base->isVirtual())
540          Out << "virtual ";
541
542        switch(Base->getAccessSpecifierAsWritten()) {
543        case AS_none:      break;
544        case AS_public:    Out << "public "; break;
545        case AS_protected: Out << "protected "; break;
546        case AS_private:   Out << " private "; break;
547        }
548
549        Out << Base->getType().getAsString(Policy);
550      }
551    }
552
553    // Print the class definition
554    // FIXME: Doesn't print access specifiers, e.g., "public:"
555    Out << " {\n";
556    VisitDeclContext(D);
557    Indent() << "}";
558  }
559}
560
561void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
562  const char *l;
563  if (D->getLanguage() == LinkageSpecDecl::lang_c)
564    l = "C";
565  else {
566    assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
567           "unknown language in linkage specification");
568    l = "C++";
569  }
570
571  Out << "extern \"" << l << "\" ";
572  if (D->hasBraces()) {
573    Out << "{\n";
574    VisitDeclContext(D);
575    Indent() << "}";
576  } else
577    Visit(*D->decls_begin());
578}
579
580void DeclPrinter::VisitTemplateDecl(TemplateDecl *D) {
581  Out << "template <";
582
583  TemplateParameterList *Params = D->getTemplateParameters();
584  for (unsigned i = 0, e = Params->size(); i != e; ++i) {
585    if (i != 0)
586      Out << ", ";
587
588    const Decl *Param = Params->getParam(i);
589    if (const TemplateTypeParmDecl *TTP =
590          dyn_cast<TemplateTypeParmDecl>(Param)) {
591
592      QualType ParamType =
593        Context.getTypeDeclType(const_cast<TemplateTypeParmDecl*>(TTP));
594
595      if (TTP->wasDeclaredWithTypename())
596        Out << "typename ";
597      else
598        Out << "class ";
599
600      if (TTP->isParameterPack())
601        Out << "... ";
602
603      Out << ParamType.getAsString(Policy);
604
605      if (TTP->hasDefaultArgument()) {
606        Out << " = ";
607        Out << TTP->getDefaultArgument().getAsString(Policy);
608      };
609    } else if (const NonTypeTemplateParmDecl *NTTP =
610                 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
611      Out << NTTP->getType().getAsString(Policy);
612
613      if (IdentifierInfo *Name = NTTP->getIdentifier()) {
614        Out << ' ';
615        Out << Name->getName();
616      }
617
618      if (NTTP->hasDefaultArgument()) {
619        Out << " = ";
620        NTTP->getDefaultArgument()->printPretty(Out, Context, 0, Policy,
621                                                Indentation);
622      }
623    }
624  }
625
626  Out << "> ";
627
628  Visit(D->getTemplatedDecl());
629}
630
631//----------------------------------------------------------------------------
632// Objective-C declarations
633//----------------------------------------------------------------------------
634
635void DeclPrinter::VisitObjCClassDecl(ObjCClassDecl *D) {
636  Out << "@class ";
637  for (ObjCClassDecl::iterator I = D->begin(), E = D->end();
638       I != E; ++I) {
639    if (I != D->begin()) Out << ", ";
640    Out << (*I)->getNameAsString();
641  }
642}
643
644void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
645  if (OMD->isInstanceMethod())
646    Out << "- ";
647  else
648    Out << "+ ";
649  if (!OMD->getResultType().isNull())
650    Out << '(' << OMD->getResultType().getAsString(Policy) << ")";
651
652  std::string name = OMD->getSelector().getAsString();
653  std::string::size_type pos, lastPos = 0;
654  for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
655       E = OMD->param_end(); PI != E; ++PI) {
656    // FIXME: selector is missing here!
657    pos = name.find_first_of(":", lastPos);
658    Out << " " << name.substr(lastPos, pos - lastPos);
659    Out << ":(" << (*PI)->getType().getAsString(Policy) << ")"
660        << (*PI)->getNameAsString();
661    lastPos = pos + 1;
662  }
663
664  if (OMD->param_begin() == OMD->param_end())
665    Out << " " << name;
666
667  if (OMD->isVariadic())
668      Out << ", ...";
669
670  if (OMD->getBody()) {
671    Out << ' ';
672    OMD->getBody()->printPretty(Out, Context, 0, Policy);
673    Out << '\n';
674  }
675}
676
677void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
678  std::string I = OID->getNameAsString();
679  ObjCInterfaceDecl *SID = OID->getSuperClass();
680
681  if (SID)
682    Out << "@implementation " << I << " : " << SID->getNameAsString();
683  else
684    Out << "@implementation " << I;
685  Out << "\n";
686  VisitDeclContext(OID, false);
687  Out << "@end";
688}
689
690void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
691  std::string I = OID->getNameAsString();
692  ObjCInterfaceDecl *SID = OID->getSuperClass();
693
694  if (SID)
695    Out << "@interface " << I << " : " << SID->getNameAsString();
696  else
697    Out << "@interface " << I;
698
699  // Protocols?
700  const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
701  if (!Protocols.empty()) {
702    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
703         E = Protocols.end(); I != E; ++I)
704      Out << (I == Protocols.begin() ? '<' : ',') << (*I)->getNameAsString();
705  }
706
707  if (!Protocols.empty())
708    Out << "> ";
709
710  if (OID->ivar_size() > 0) {
711    Out << "{\n";
712    Indentation += Policy.Indentation;
713    for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
714         E = OID->ivar_end(); I != E; ++I) {
715      Indent() << (*I)->getType().getAsString(Policy)
716          << ' '  << (*I)->getNameAsString() << ";\n";
717    }
718    Indentation -= Policy.Indentation;
719    Out << "}\n";
720  }
721
722  VisitDeclContext(OID, false);
723  Out << "@end";
724  // FIXME: implement the rest...
725}
726
727void DeclPrinter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
728  Out << "@protocol ";
729  for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
730         E = D->protocol_end();
731       I != E; ++I) {
732    if (I != D->protocol_begin()) Out << ", ";
733    Out << (*I)->getNameAsString();
734  }
735}
736
737void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
738  Out << "@protocol " << PID->getNameAsString() << '\n';
739  VisitDeclContext(PID, false);
740  Out << "@end";
741}
742
743void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
744  Out << "@implementation "
745      << PID->getClassInterface()->getNameAsString()
746      << '(' << PID->getNameAsString() << ")\n";
747
748  VisitDeclContext(PID, false);
749  Out << "@end";
750  // FIXME: implement the rest...
751}
752
753void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
754  Out << "@interface "
755      << PID->getClassInterface()->getNameAsString()
756      << '(' << PID->getNameAsString() << ")\n";
757  VisitDeclContext(PID, false);
758  Out << "@end";
759
760  // FIXME: implement the rest...
761}
762
763void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
764  Out << "@compatibility_alias " << AID->getNameAsString()
765      << ' ' << AID->getClassInterface()->getNameAsString() << ";\n";
766}
767
768/// PrintObjCPropertyDecl - print a property declaration.
769///
770void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
771  if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
772    Out << "@required\n";
773  else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
774    Out << "@optional\n";
775
776  Out << "@property";
777  if (PDecl->getPropertyAttributes() != ObjCPropertyDecl::OBJC_PR_noattr) {
778    bool first = true;
779    Out << " (";
780    if (PDecl->getPropertyAttributes() &
781        ObjCPropertyDecl::OBJC_PR_readonly) {
782      Out << (first ? ' ' : ',') << "readonly";
783      first = false;
784  }
785
786  if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
787    Out << (first ? ' ' : ',') << "getter = "
788        << PDecl->getGetterName().getAsString();
789    first = false;
790  }
791  if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
792    Out << (first ? ' ' : ',') << "setter = "
793        << PDecl->getSetterName().getAsString();
794    first = false;
795  }
796
797  if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_assign) {
798    Out << (first ? ' ' : ',') << "assign";
799    first = false;
800  }
801
802  if (PDecl->getPropertyAttributes() &
803      ObjCPropertyDecl::OBJC_PR_readwrite) {
804    Out << (first ? ' ' : ',') << "readwrite";
805    first = false;
806  }
807
808  if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) {
809    Out << (first ? ' ' : ',') << "retain";
810    first = false;
811  }
812
813  if (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) {
814    Out << (first ? ' ' : ',') << "copy";
815    first = false;
816  }
817
818  if (PDecl->getPropertyAttributes() &
819      ObjCPropertyDecl::OBJC_PR_nonatomic) {
820    Out << (first ? ' ' : ',') << "nonatomic";
821    first = false;
822  }
823  Out << " )";
824  }
825  Out << ' ' << PDecl->getType().getAsString(Policy)
826  << ' ' << PDecl->getNameAsString();
827}
828
829void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
830  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
831    Out << "@synthesize ";
832  else
833    Out << "@dynamic ";
834  Out << PID->getPropertyDecl()->getNameAsString();
835  if (PID->getPropertyIvarDecl())
836    Out << "=" << PID->getPropertyIvarDecl()->getNameAsString();
837}
838