StmtPrinter.cpp revision 17330019f05966762bc952840ef1926b9becb145
1//===--- StmtPrinter.cpp - Printing implementation for Stmt 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 Stmt::dumpPretty/Stmt::printPretty methods, which
11// pretty print the AST back out to C code.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/StmtVisitor.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/PrettyPrinter.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/Streams.h"
21#include "llvm/Support/Format.h"
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// StmtPrinter Visitor
26//===----------------------------------------------------------------------===//
27
28namespace  {
29  class VISIBILITY_HIDDEN StmtPrinter : public StmtVisitor<StmtPrinter> {
30    llvm::raw_ostream &OS;
31    unsigned IndentLevel;
32    clang::PrinterHelper* Helper;
33  public:
34    StmtPrinter(llvm::raw_ostream &os, PrinterHelper* helper) :
35      OS(os), IndentLevel(0), Helper(helper) {}
36
37    void PrintStmt(Stmt *S, int SubIndent = 1) {
38      IndentLevel += SubIndent;
39      if (S && isa<Expr>(S)) {
40        // If this is an expr used in a stmt context, indent and newline it.
41        Indent();
42        Visit(S);
43        OS << ";\n";
44      } else if (S) {
45        Visit(S);
46      } else {
47        Indent() << "<<<NULL STATEMENT>>>\n";
48      }
49      IndentLevel -= SubIndent;
50    }
51
52    void PrintRawCompoundStmt(CompoundStmt *S);
53    void PrintRawDecl(Decl *D);
54    void PrintRawDeclStmt(DeclStmt *S);
55    void PrintRawIfStmt(IfStmt *If);
56    void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
57
58    void PrintExpr(Expr *E) {
59      if (E)
60        Visit(E);
61      else
62        OS << "<null expr>";
63    }
64
65    llvm::raw_ostream &Indent(int Delta = 0) const {
66      for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
67        OS << "  ";
68      return OS;
69    }
70
71    bool PrintOffsetOfDesignator(Expr *E);
72    void VisitUnaryOffsetOf(UnaryOperator *Node);
73
74    void Visit(Stmt* S) {
75      if (Helper && Helper->handledStmt(S,OS))
76          return;
77      else StmtVisitor<StmtPrinter>::Visit(S);
78    }
79
80    void VisitStmt(Stmt *Node);
81#define STMT(CLASS, PARENT) \
82    void Visit##CLASS(CLASS *Node);
83#include "clang/AST/StmtNodes.def"
84  };
85}
86
87//===----------------------------------------------------------------------===//
88//  Stmt printing methods.
89//===----------------------------------------------------------------------===//
90
91void StmtPrinter::VisitStmt(Stmt *Node) {
92  Indent() << "<<unknown stmt type>>\n";
93}
94
95/// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
96/// with no newline after the }.
97void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
98  OS << "{\n";
99  for (CompoundStmt::body_iterator I = Node->body_begin(), E = Node->body_end();
100       I != E; ++I)
101    PrintStmt(*I);
102
103  Indent() << "}";
104}
105
106void StmtPrinter::PrintRawDecl(Decl *D) {
107  // FIXME: Need to complete/beautify this... this code simply shows the
108  // nodes are where they need to be.
109  if (TypedefDecl *localType = dyn_cast<TypedefDecl>(D)) {
110    OS << "typedef " << localType->getUnderlyingType().getAsString();
111    OS << " " << localType->getNameAsString();
112  } else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
113    // Emit storage class for vardecls.
114    if (VarDecl *V = dyn_cast<VarDecl>(VD)) {
115      switch (V->getStorageClass()) {
116        default: assert(0 && "Unknown storage class!");
117        case VarDecl::None:     break;
118        case VarDecl::Extern:   OS << "extern "; break;
119        case VarDecl::Static:   OS << "static "; break;
120        case VarDecl::Auto:     OS << "auto "; break;
121        case VarDecl::Register: OS << "register "; break;
122      }
123    }
124
125    std::string Name = VD->getNameAsString();
126    VD->getType().getAsStringInternal(Name);
127    OS << Name;
128
129    // If this is a vardecl with an initializer, emit it.
130    if (VarDecl *V = dyn_cast<VarDecl>(VD)) {
131      if (V->getInit()) {
132        OS << " = ";
133        PrintExpr(V->getInit());
134      }
135    }
136  } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
137    // print a free standing tag decl (e.g. "struct x;").
138    OS << TD->getKindName();
139    OS << " ";
140    if (const IdentifierInfo *II = TD->getIdentifier())
141      OS << II->getName();
142    else
143      OS << "<anonymous>";
144    // FIXME: print tag bodies.
145  } else {
146    assert(0 && "Unexpected decl");
147  }
148}
149
150void StmtPrinter::PrintRawDeclStmt(DeclStmt *S) {
151  bool isFirst = false;
152
153  for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end();
154       I != E; ++I) {
155
156    if (!isFirst) OS << ", ";
157    else isFirst = false;
158
159    PrintRawDecl(*I);
160  }
161}
162
163void StmtPrinter::VisitNullStmt(NullStmt *Node) {
164  Indent() << ";\n";
165}
166
167void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
168  for (DeclStmt::decl_iterator I = Node->decl_begin(), E = Node->decl_end();
169       I!=E; ++I) {
170    Indent();
171    PrintRawDecl(*I);
172    OS << ";\n";
173  }
174}
175
176void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
177  Indent();
178  PrintRawCompoundStmt(Node);
179  OS << "\n";
180}
181
182void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
183  Indent(-1) << "case ";
184  PrintExpr(Node->getLHS());
185  if (Node->getRHS()) {
186    OS << " ... ";
187    PrintExpr(Node->getRHS());
188  }
189  OS << ":\n";
190
191  PrintStmt(Node->getSubStmt(), 0);
192}
193
194void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
195  Indent(-1) << "default:\n";
196  PrintStmt(Node->getSubStmt(), 0);
197}
198
199void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
200  Indent(-1) << Node->getName() << ":\n";
201  PrintStmt(Node->getSubStmt(), 0);
202}
203
204void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
205  OS << "if ";
206  PrintExpr(If->getCond());
207
208  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
209    OS << ' ';
210    PrintRawCompoundStmt(CS);
211    OS << (If->getElse() ? ' ' : '\n');
212  } else {
213    OS << '\n';
214    PrintStmt(If->getThen());
215    if (If->getElse()) Indent();
216  }
217
218  if (Stmt *Else = If->getElse()) {
219    OS << "else";
220
221    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
222      OS << ' ';
223      PrintRawCompoundStmt(CS);
224      OS << '\n';
225    } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
226      OS << ' ';
227      PrintRawIfStmt(ElseIf);
228    } else {
229      OS << '\n';
230      PrintStmt(If->getElse());
231    }
232  }
233}
234
235void StmtPrinter::VisitIfStmt(IfStmt *If) {
236  Indent();
237  PrintRawIfStmt(If);
238}
239
240void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
241  Indent() << "switch (";
242  PrintExpr(Node->getCond());
243  OS << ")";
244
245  // Pretty print compoundstmt bodies (very common).
246  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
247    OS << " ";
248    PrintRawCompoundStmt(CS);
249    OS << "\n";
250  } else {
251    OS << "\n";
252    PrintStmt(Node->getBody());
253  }
254}
255
256void StmtPrinter::VisitSwitchCase(SwitchCase*) {
257  assert(0 && "SwitchCase is an abstract class");
258}
259
260void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
261  Indent() << "while (";
262  PrintExpr(Node->getCond());
263  OS << ")\n";
264  PrintStmt(Node->getBody());
265}
266
267void StmtPrinter::VisitDoStmt(DoStmt *Node) {
268  Indent() << "do ";
269  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
270    PrintRawCompoundStmt(CS);
271    OS << " ";
272  } else {
273    OS << "\n";
274    PrintStmt(Node->getBody());
275    Indent();
276  }
277
278  OS << "while ";
279  PrintExpr(Node->getCond());
280  OS << ";\n";
281}
282
283void StmtPrinter::VisitForStmt(ForStmt *Node) {
284  Indent() << "for (";
285  if (Node->getInit()) {
286    if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getInit()))
287      PrintRawDeclStmt(DS);
288    else
289      PrintExpr(cast<Expr>(Node->getInit()));
290  }
291  OS << ";";
292  if (Node->getCond()) {
293    OS << " ";
294    PrintExpr(Node->getCond());
295  }
296  OS << ";";
297  if (Node->getInc()) {
298    OS << " ";
299    PrintExpr(Node->getInc());
300  }
301  OS << ") ";
302
303  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
304    PrintRawCompoundStmt(CS);
305    OS << "\n";
306  } else {
307    OS << "\n";
308    PrintStmt(Node->getBody());
309  }
310}
311
312void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
313  Indent() << "for (";
314  if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getElement()))
315    PrintRawDeclStmt(DS);
316  else
317    PrintExpr(cast<Expr>(Node->getElement()));
318  OS << " in ";
319  PrintExpr(Node->getCollection());
320  OS << ") ";
321
322  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
323    PrintRawCompoundStmt(CS);
324    OS << "\n";
325  } else {
326    OS << "\n";
327    PrintStmt(Node->getBody());
328  }
329}
330
331void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
332  Indent() << "goto " << Node->getLabel()->getName() << ";\n";
333}
334
335void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
336  Indent() << "goto *";
337  PrintExpr(Node->getTarget());
338  OS << ";\n";
339}
340
341void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
342  Indent() << "continue;\n";
343}
344
345void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
346  Indent() << "break;\n";
347}
348
349
350void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
351  Indent() << "return";
352  if (Node->getRetValue()) {
353    OS << " ";
354    PrintExpr(Node->getRetValue());
355  }
356  OS << ";\n";
357}
358
359
360void StmtPrinter::VisitAsmStmt(AsmStmt *Node) {
361  Indent() << "asm ";
362
363  if (Node->isVolatile())
364    OS << "volatile ";
365
366  OS << "(";
367  VisitStringLiteral(Node->getAsmString());
368
369  // Outputs
370  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
371      Node->getNumClobbers() != 0)
372    OS << " : ";
373
374  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
375    if (i != 0)
376      OS << ", ";
377
378    if (!Node->getOutputName(i).empty()) {
379      OS << '[';
380      OS << Node->getOutputName(i);
381      OS << "] ";
382    }
383
384    VisitStringLiteral(Node->getOutputConstraint(i));
385    OS << " ";
386    Visit(Node->getOutputExpr(i));
387  }
388
389  // Inputs
390  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
391    OS << " : ";
392
393  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
394    if (i != 0)
395      OS << ", ";
396
397    if (!Node->getInputName(i).empty()) {
398      OS << '[';
399      OS << Node->getInputName(i);
400      OS << "] ";
401    }
402
403    VisitStringLiteral(Node->getInputConstraint(i));
404    OS << " ";
405    Visit(Node->getInputExpr(i));
406  }
407
408  // Clobbers
409  if (Node->getNumClobbers() != 0)
410    OS << " : ";
411
412  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
413    if (i != 0)
414      OS << ", ";
415
416    VisitStringLiteral(Node->getClobber(i));
417  }
418
419  OS << ");\n";
420}
421
422void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
423  Indent() << "@try";
424  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
425    PrintRawCompoundStmt(TS);
426    OS << "\n";
427  }
428
429  for (ObjCAtCatchStmt *catchStmt =
430         static_cast<ObjCAtCatchStmt *>(Node->getCatchStmts());
431       catchStmt;
432       catchStmt =
433         static_cast<ObjCAtCatchStmt *>(catchStmt->getNextCatchStmt())) {
434    Indent() << "@catch(";
435    if (catchStmt->getCatchParamStmt()) {
436      if (DeclStmt *DS = dyn_cast<DeclStmt>(catchStmt->getCatchParamStmt()))
437        PrintRawDeclStmt(DS);
438    }
439    OS << ")";
440    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody()))
441      {
442        PrintRawCompoundStmt(CS);
443        OS << "\n";
444      }
445  }
446
447  if (ObjCAtFinallyStmt *FS =static_cast<ObjCAtFinallyStmt *>(
448          Node->getFinallyStmt())) {
449    Indent() << "@finally";
450    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
451    OS << "\n";
452  }
453}
454
455void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
456}
457
458void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
459  Indent() << "@catch (...) { /* todo */ } \n";
460}
461
462void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
463  Indent() << "@throw";
464  if (Node->getThrowExpr()) {
465    OS << " ";
466    PrintExpr(Node->getThrowExpr());
467  }
468  OS << ";\n";
469}
470
471void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
472  Indent() << "@synchronized (";
473  PrintExpr(Node->getSynchExpr());
474  OS << ")";
475  PrintRawCompoundStmt(Node->getSynchBody());
476  OS << "\n";
477}
478
479void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
480  OS << "catch (";
481  if (Decl *ExDecl = Node->getExceptionDecl())
482    PrintRawDecl(ExDecl);
483  else
484    OS << "...";
485  OS << ") ";
486  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
487}
488
489void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
490  Indent();
491  PrintRawCXXCatchStmt(Node);
492  OS << "\n";
493}
494
495void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
496  Indent() << "try ";
497  PrintRawCompoundStmt(Node->getTryBlock());
498  for(unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
499    OS << " ";
500    PrintRawCXXCatchStmt(Node->getHandler(i));
501  }
502  OS << "\n";
503}
504
505//===----------------------------------------------------------------------===//
506//  Expr printing methods.
507//===----------------------------------------------------------------------===//
508
509void StmtPrinter::VisitExpr(Expr *Node) {
510  OS << "<<unknown expr type>>";
511}
512
513void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
514  OS << Node->getDecl()->getNameAsString();
515}
516
517void StmtPrinter::VisitQualifiedDeclRefExpr(QualifiedDeclRefExpr *Node) {
518  // FIXME: Should we keep enough information in QualifiedDeclRefExpr
519  // to produce the same qualification that the user wrote?
520  llvm::SmallVector<DeclContext *, 4> Contexts;
521
522  NamedDecl *D = Node->getDecl();
523
524  // Build up a stack of contexts.
525  DeclContext *Ctx = D->getDeclContext();
526  for (; Ctx; Ctx = Ctx->getParent())
527    if (!Ctx->isTransparentContext())
528      Contexts.push_back(Ctx);
529
530  while (!Contexts.empty()) {
531    DeclContext *Ctx = Contexts.back();
532    if (isa<TranslationUnitDecl>(Ctx))
533      OS << "::";
534    else if (NamedDecl *ND = dyn_cast<NamedDecl>(Ctx))
535      OS << ND->getNameAsString() << "::";
536    Contexts.pop_back();
537  }
538
539  OS << D->getNameAsString();
540}
541
542void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
543  if (Node->getBase()) {
544    PrintExpr(Node->getBase());
545    OS << (Node->isArrow() ? "->" : ".");
546  }
547  OS << Node->getDecl()->getNameAsString();
548}
549
550void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
551  if (Node->getBase()) {
552    PrintExpr(Node->getBase());
553    OS << ".";
554  }
555  OS << Node->getProperty()->getNameAsCString();
556}
557
558void StmtPrinter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *Node) {
559  if (Node->getBase()) {
560    PrintExpr(Node->getBase());
561    OS << ".";
562  }
563  // FIXME: Setter/Getter names
564}
565
566void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
567  switch (Node->getIdentType()) {
568    default:
569      assert(0 && "unknown case");
570    case PredefinedExpr::Func:
571      OS << "__func__";
572      break;
573    case PredefinedExpr::Function:
574      OS << "__FUNCTION__";
575      break;
576    case PredefinedExpr::PrettyFunction:
577      OS << "__PRETTY_FUNCTION__";
578      break;
579  }
580}
581
582void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
583  unsigned value = Node->getValue();
584  if (Node->isWide())
585    OS << "L";
586  switch (value) {
587  case '\\':
588    OS << "'\\\\'";
589    break;
590  case '\'':
591    OS << "'\\''";
592    break;
593  case '\a':
594    // TODO: K&R: the meaning of '\\a' is different in traditional C
595    OS << "'\\a'";
596    break;
597  case '\b':
598    OS << "'\\b'";
599    break;
600  // Nonstandard escape sequence.
601  /*case '\e':
602    OS << "'\\e'";
603    break;*/
604  case '\f':
605    OS << "'\\f'";
606    break;
607  case '\n':
608    OS << "'\\n'";
609    break;
610  case '\r':
611    OS << "'\\r'";
612    break;
613  case '\t':
614    OS << "'\\t'";
615    break;
616  case '\v':
617    OS << "'\\v'";
618    break;
619  default:
620    if (value < 256 && isprint(value)) {
621      OS << "'" << (char)value << "'";
622    } else if (value < 256) {
623      OS << "'\\x" << llvm::format("%x", value) << "'";
624    } else {
625      // FIXME what to really do here?
626      OS << value;
627    }
628  }
629}
630
631void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
632  bool isSigned = Node->getType()->isSignedIntegerType();
633  OS << Node->getValue().toString(10, isSigned);
634
635  // Emit suffixes.  Integer literals are always a builtin integer type.
636  switch (Node->getType()->getAsBuiltinType()->getKind()) {
637  default: assert(0 && "Unexpected type for integer literal!");
638  case BuiltinType::Int:       break; // no suffix.
639  case BuiltinType::UInt:      OS << 'U'; break;
640  case BuiltinType::Long:      OS << 'L'; break;
641  case BuiltinType::ULong:     OS << "UL"; break;
642  case BuiltinType::LongLong:  OS << "LL"; break;
643  case BuiltinType::ULongLong: OS << "ULL"; break;
644  }
645}
646void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
647  // FIXME: print value more precisely.
648  OS << Node->getValueAsApproximateDouble();
649}
650
651void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
652  PrintExpr(Node->getSubExpr());
653  OS << "i";
654}
655
656void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
657  if (Str->isWide()) OS << 'L';
658  OS << '"';
659
660  // FIXME: this doesn't print wstrings right.
661  for (unsigned i = 0, e = Str->getByteLength(); i != e; ++i) {
662    unsigned char Char = Str->getStrData()[i];
663
664    switch (Char) {
665    default:
666      if (isprint(Char))
667        OS << (char)Char;
668      else  // Output anything hard as an octal escape.
669        OS << '\\'
670        << (char)('0'+ ((Char >> 6) & 7))
671        << (char)('0'+ ((Char >> 3) & 7))
672        << (char)('0'+ ((Char >> 0) & 7));
673      break;
674    // Handle some common non-printable cases to make dumps prettier.
675    case '\\': OS << "\\\\"; break;
676    case '"': OS << "\\\""; break;
677    case '\n': OS << "\\n"; break;
678    case '\t': OS << "\\t"; break;
679    case '\a': OS << "\\a"; break;
680    case '\b': OS << "\\b"; break;
681    }
682  }
683  OS << '"';
684}
685void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
686  OS << "(";
687  PrintExpr(Node->getSubExpr());
688  OS << ")";
689}
690void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
691  if (!Node->isPostfix()) {
692    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
693
694    // Print a space if this is an "identifier operator" like __real.
695    switch (Node->getOpcode()) {
696    default: break;
697    case UnaryOperator::Real:
698    case UnaryOperator::Imag:
699    case UnaryOperator::Extension:
700      OS << ' ';
701      break;
702    }
703  }
704  PrintExpr(Node->getSubExpr());
705
706  if (Node->isPostfix())
707    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
708}
709
710bool StmtPrinter::PrintOffsetOfDesignator(Expr *E) {
711  if (isa<CompoundLiteralExpr>(E)) {
712    // Base case, print the type and comma.
713    OS << E->getType().getAsString() << ", ";
714    return true;
715  } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
716    PrintOffsetOfDesignator(ASE->getLHS());
717    OS << "[";
718    PrintExpr(ASE->getRHS());
719    OS << "]";
720    return false;
721  } else {
722    MemberExpr *ME = cast<MemberExpr>(E);
723    bool IsFirst = PrintOffsetOfDesignator(ME->getBase());
724    OS << (IsFirst ? "" : ".") << ME->getMemberDecl()->getNameAsString();
725    return false;
726  }
727}
728
729void StmtPrinter::VisitUnaryOffsetOf(UnaryOperator *Node) {
730  OS << "__builtin_offsetof(";
731  PrintOffsetOfDesignator(Node->getSubExpr());
732  OS << ")";
733}
734
735void StmtPrinter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *Node) {
736  OS << (Node->isSizeOf() ? "sizeof" : "__alignof");
737  if (Node->isArgumentType())
738    OS << "(" << Node->getArgumentType().getAsString() << ")";
739  else {
740    OS << " ";
741    PrintExpr(Node->getArgumentExpr());
742  }
743}
744void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
745  PrintExpr(Node->getLHS());
746  OS << "[";
747  PrintExpr(Node->getRHS());
748  OS << "]";
749}
750
751void StmtPrinter::VisitCallExpr(CallExpr *Call) {
752  PrintExpr(Call->getCallee());
753  OS << "(";
754  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
755    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
756      // Don't print any defaulted arguments
757      break;
758    }
759
760    if (i) OS << ", ";
761    PrintExpr(Call->getArg(i));
762  }
763  OS << ")";
764}
765void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
766  // FIXME: Suppress printing implicit bases (like "this")
767  PrintExpr(Node->getBase());
768  OS << (Node->isArrow() ? "->" : ".");
769  // FIXME: Suppress printing references to unnamed objects
770  // representing anonymous unions/structs
771  OS << Node->getMemberDecl()->getNameAsString();
772}
773void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
774  PrintExpr(Node->getBase());
775  OS << ".";
776  OS << Node->getAccessor().getName();
777}
778void StmtPrinter::VisitCastExpr(CastExpr *) {
779  assert(0 && "CastExpr is an abstract class");
780}
781void StmtPrinter::VisitExplicitCastExpr(ExplicitCastExpr *) {
782  assert(0 && "ExplicitCastExpr is an abstract class");
783}
784void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
785  OS << "(" << Node->getType().getAsString() << ")";
786  PrintExpr(Node->getSubExpr());
787}
788void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
789  OS << "(" << Node->getType().getAsString() << ")";
790  PrintExpr(Node->getInitializer());
791}
792void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
793  // No need to print anything, simply forward to the sub expression.
794  PrintExpr(Node->getSubExpr());
795}
796void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
797  PrintExpr(Node->getLHS());
798  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
799  PrintExpr(Node->getRHS());
800}
801void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
802  PrintExpr(Node->getLHS());
803  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
804  PrintExpr(Node->getRHS());
805}
806void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
807  PrintExpr(Node->getCond());
808
809  if (Node->getLHS()) {
810    OS << " ? ";
811    PrintExpr(Node->getLHS());
812    OS << " : ";
813  }
814  else { // Handle GCC extention where LHS can be NULL.
815    OS << " ?: ";
816  }
817
818  PrintExpr(Node->getRHS());
819}
820
821// GNU extensions.
822
823void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
824  OS << "&&" << Node->getLabel()->getName();
825}
826
827void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
828  OS << "(";
829  PrintRawCompoundStmt(E->getSubStmt());
830  OS << ")";
831}
832
833void StmtPrinter::VisitTypesCompatibleExpr(TypesCompatibleExpr *Node) {
834  OS << "__builtin_types_compatible_p(";
835  OS << Node->getArgType1().getAsString() << ",";
836  OS << Node->getArgType2().getAsString() << ")";
837}
838
839void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
840  OS << "__builtin_choose_expr(";
841  PrintExpr(Node->getCond());
842  OS << ", ";
843  PrintExpr(Node->getLHS());
844  OS << ", ";
845  PrintExpr(Node->getRHS());
846  OS << ")";
847}
848
849void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
850  OS << "__null";
851}
852
853void StmtPrinter::VisitOverloadExpr(OverloadExpr *Node) {
854  OS << "__builtin_overload(";
855  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
856    if (i) OS << ", ";
857    PrintExpr(Node->getExpr(i));
858  }
859  OS << ")";
860}
861
862void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
863  OS << "__builtin_shufflevector(";
864  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
865    if (i) OS << ", ";
866    PrintExpr(Node->getExpr(i));
867  }
868  OS << ")";
869}
870
871void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
872  OS << "{ ";
873  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
874    if (i) OS << ", ";
875    if (Node->getInit(i))
876      PrintExpr(Node->getInit(i));
877    else
878      OS << "0";
879  }
880  OS << " }";
881}
882
883void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
884  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
885                      DEnd = Node->designators_end();
886       D != DEnd; ++D) {
887    if (D->isFieldDesignator()) {
888      if (D->getDotLoc().isInvalid())
889        OS << D->getFieldName()->getName() << ":";
890      else
891        OS << "." << D->getFieldName()->getName();
892    } else {
893      OS << "[";
894      if (D->isArrayDesignator()) {
895        PrintExpr(Node->getArrayIndex(*D));
896      } else {
897        PrintExpr(Node->getArrayRangeStart(*D));
898        OS << " ... ";
899        PrintExpr(Node->getArrayRangeEnd(*D));
900      }
901      OS << "]";
902    }
903  }
904
905  OS << " = ";
906  PrintExpr(Node->getInit());
907}
908
909void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
910  OS << "/*implicit*/" << Node->getType().getAsString() << "()";
911}
912
913void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
914  OS << "va_arg(";
915  PrintExpr(Node->getSubExpr());
916  OS << ", ";
917  OS << Node->getType().getAsString();
918  OS << ")";
919}
920
921// C++
922void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
923  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
924    "",
925#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
926    Spelling,
927#include "clang/Basic/OperatorKinds.def"
928  };
929
930  OverloadedOperatorKind Kind = Node->getOperator();
931  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
932    if (Node->getNumArgs() == 1) {
933      OS << OpStrings[Kind] << ' ';
934      PrintExpr(Node->getArg(0));
935    } else {
936      PrintExpr(Node->getArg(0));
937      OS << ' ' << OpStrings[Kind];
938    }
939  } else if (Kind == OO_Call) {
940    PrintExpr(Node->getArg(0));
941    OS << '(';
942    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
943      if (ArgIdx > 1)
944        OS << ", ";
945      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
946        PrintExpr(Node->getArg(ArgIdx));
947    }
948    OS << ')';
949  } else if (Kind == OO_Subscript) {
950    PrintExpr(Node->getArg(0));
951    OS << '[';
952    PrintExpr(Node->getArg(1));
953    OS << ']';
954  } else if (Node->getNumArgs() == 1) {
955    OS << OpStrings[Kind] << ' ';
956    PrintExpr(Node->getArg(0));
957  } else if (Node->getNumArgs() == 2) {
958    PrintExpr(Node->getArg(0));
959    OS << ' ' << OpStrings[Kind] << ' ';
960    PrintExpr(Node->getArg(1));
961  } else {
962    assert(false && "unknown overloaded operator");
963  }
964}
965
966void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
967  VisitCallExpr(cast<CallExpr>(Node));
968}
969
970void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
971  OS << Node->getCastName() << '<';
972  OS << Node->getTypeAsWritten().getAsString() << ">(";
973  PrintExpr(Node->getSubExpr());
974  OS << ")";
975}
976
977void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
978  VisitCXXNamedCastExpr(Node);
979}
980
981void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
982  VisitCXXNamedCastExpr(Node);
983}
984
985void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
986  VisitCXXNamedCastExpr(Node);
987}
988
989void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
990  VisitCXXNamedCastExpr(Node);
991}
992
993void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
994  OS << "typeid(";
995  if (Node->isTypeOperand()) {
996    OS << Node->getTypeOperand().getAsString();
997  } else {
998    PrintExpr(Node->getExprOperand());
999  }
1000  OS << ")";
1001}
1002
1003void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1004  OS << (Node->getValue() ? "true" : "false");
1005}
1006
1007void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1008  OS << "this";
1009}
1010
1011void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1012  if (Node->getSubExpr() == 0)
1013    OS << "throw";
1014  else {
1015    OS << "throw ";
1016    PrintExpr(Node->getSubExpr());
1017  }
1018}
1019
1020void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1021  // Nothing to print: we picked up the default argument
1022}
1023
1024void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1025  OS << Node->getType().getAsString();
1026  OS << "(";
1027  PrintExpr(Node->getSubExpr());
1028  OS << ")";
1029}
1030
1031void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1032  OS << Node->getType().getAsString();
1033  OS << "(";
1034  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1035                                         ArgEnd = Node->arg_end();
1036       Arg != ArgEnd; ++Arg) {
1037    if (Arg != Node->arg_begin())
1038      OS << ", ";
1039    PrintExpr(*Arg);
1040  }
1041  OS << ")";
1042}
1043
1044void StmtPrinter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *Node) {
1045  OS << Node->getType().getAsString() << "()";
1046}
1047
1048void
1049StmtPrinter::VisitCXXConditionDeclExpr(CXXConditionDeclExpr *E) {
1050  PrintRawDecl(E->getVarDecl());
1051}
1052
1053void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1054  if (E->isGlobalNew())
1055    OS << "::";
1056  OS << "new ";
1057  unsigned NumPlace = E->getNumPlacementArgs();
1058  if (NumPlace > 0) {
1059    OS << "(";
1060    PrintExpr(E->getPlacementArg(0));
1061    for (unsigned i = 1; i < NumPlace; ++i) {
1062      OS << ", ";
1063      PrintExpr(E->getPlacementArg(i));
1064    }
1065    OS << ") ";
1066  }
1067  if (E->isParenTypeId())
1068    OS << "(";
1069  std::string TypeS;
1070  if (Expr *Size = E->getArraySize()) {
1071    llvm::raw_string_ostream s(TypeS);
1072    Size->printPretty(s);
1073    s.flush();
1074    TypeS = "[" + TypeS + "]";
1075  }
1076  E->getAllocatedType().getAsStringInternal(TypeS);
1077  OS << TypeS;
1078  if (E->isParenTypeId())
1079    OS << ")";
1080
1081  if (E->hasInitializer()) {
1082    OS << "(";
1083    unsigned NumCons = E->getNumConstructorArgs();
1084    if (NumCons > 0) {
1085      PrintExpr(E->getConstructorArg(0));
1086      for (unsigned i = 1; i < NumCons; ++i) {
1087        OS << ", ";
1088        PrintExpr(E->getConstructorArg(i));
1089      }
1090    }
1091    OS << ")";
1092  }
1093}
1094
1095void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1096  if (E->isGlobalDelete())
1097    OS << "::";
1098  OS << "delete ";
1099  if (E->isArrayForm())
1100    OS << "[] ";
1101  PrintExpr(E->getArgument());
1102}
1103
1104void StmtPrinter::VisitUnresolvedFunctionNameExpr(UnresolvedFunctionNameExpr *E) {
1105  OS << E->getName().getAsString();
1106}
1107
1108static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1109  switch (UTT) {
1110  default: assert(false && "Unknown type trait");
1111  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1112  case UTT_HasNothrowCopy:        return "__has_nothrow_copy";
1113  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1114  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1115  case UTT_HasTrivialCopy:        return "__has_trivial_copy";
1116  case UTT_HasTrivialConstructor: return "__has_trivial_constructor";
1117  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1118  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1119  case UTT_IsAbstract:            return "__is_abstract";
1120  case UTT_IsClass:               return "__is_class";
1121  case UTT_IsEmpty:               return "__is_empty";
1122  case UTT_IsEnum:                return "__is_enum";
1123  case UTT_IsPOD:                 return "__is_pod";
1124  case UTT_IsPolymorphic:         return "__is_polymorphic";
1125  case UTT_IsUnion:               return "__is_union";
1126  }
1127}
1128
1129void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1130  OS << getTypeTraitName(E->getTrait()) << "("
1131     << E->getQueriedType().getAsString() << ")";
1132}
1133
1134// Obj-C
1135
1136void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1137  OS << "@";
1138  VisitStringLiteral(Node->getString());
1139}
1140
1141void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1142  OS << "@encode(" << Node->getEncodedType().getAsString() << ')';
1143}
1144
1145void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1146  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1147}
1148
1149void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1150  OS << "@protocol(" << Node->getProtocol()->getNameAsString() << ')';
1151}
1152
1153void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1154  OS << "[";
1155  Expr *receiver = Mess->getReceiver();
1156  if (receiver) PrintExpr(receiver);
1157  else OS << Mess->getClassName()->getName();
1158  OS << ' ';
1159  Selector selector = Mess->getSelector();
1160  if (selector.isUnarySelector()) {
1161    OS << selector.getIdentifierInfoForSlot(0)->getName();
1162  } else {
1163    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1164      if (i < selector.getNumArgs()) {
1165        if (i > 0) OS << ' ';
1166        if (selector.getIdentifierInfoForSlot(i))
1167          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1168        else
1169           OS << ":";
1170      }
1171      else OS << ", "; // Handle variadic methods.
1172
1173      PrintExpr(Mess->getArg(i));
1174    }
1175  }
1176  OS << "]";
1177}
1178
1179void StmtPrinter::VisitObjCSuperExpr(ObjCSuperExpr *) {
1180  OS << "super";
1181}
1182
1183void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1184  BlockDecl *BD = Node->getBlockDecl();
1185  OS << "^";
1186
1187  const FunctionType *AFT = Node->getFunctionType();
1188
1189  if (isa<FunctionTypeNoProto>(AFT)) {
1190    OS << "()";
1191  } else if (!BD->param_empty() || cast<FunctionTypeProto>(AFT)->isVariadic()) {
1192    OS << '(';
1193    std::string ParamStr;
1194    for (BlockDecl::param_iterator AI = BD->param_begin(),
1195         E = BD->param_end(); AI != E; ++AI) {
1196      if (AI != BD->param_begin()) OS << ", ";
1197      ParamStr = (*AI)->getNameAsString();
1198      (*AI)->getType().getAsStringInternal(ParamStr);
1199      OS << ParamStr;
1200    }
1201
1202    const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
1203    if (FT->isVariadic()) {
1204      if (!BD->param_empty()) OS << ", ";
1205      OS << "...";
1206    }
1207    OS << ')';
1208  }
1209}
1210
1211void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
1212  OS << Node->getDecl()->getNameAsString();
1213}
1214//===----------------------------------------------------------------------===//
1215// Stmt method implementations
1216//===----------------------------------------------------------------------===//
1217
1218void Stmt::dumpPretty() const {
1219  llvm::raw_ostream &OS = llvm::errs();
1220  printPretty(OS);
1221  OS.flush();
1222}
1223
1224void Stmt::printPretty(llvm::raw_ostream &OS, PrinterHelper* Helper) const {
1225  if (this == 0) {
1226    OS << "<NULL>";
1227    return;
1228  }
1229
1230  StmtPrinter P(OS, Helper);
1231  P.Visit(const_cast<Stmt*>(this));
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// PrinterHelper
1236//===----------------------------------------------------------------------===//
1237
1238// Implement virtual destructor.
1239PrinterHelper::~PrinterHelper() {}
1240