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