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