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