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