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