StmtPrinter.cpp revision 731de313f759bdb412d38df3d2a0f149437ef401
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/ASTContext.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "llvm/ADT/SmallString.h"
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// StmtPrinter Visitor
28//===----------------------------------------------------------------------===//
29
30namespace  {
31  class StmtPrinter : public StmtVisitor<StmtPrinter> {
32    raw_ostream &OS;
33    unsigned IndentLevel;
34    clang::PrinterHelper* Helper;
35    PrintingPolicy Policy;
36
37  public:
38    StmtPrinter(raw_ostream &os, PrinterHelper* helper,
39                const PrintingPolicy &Policy,
40                unsigned Indentation = 0)
41      : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy) {}
42
43    void PrintStmt(Stmt *S) {
44      PrintStmt(S, Policy.Indentation);
45    }
46
47    void PrintStmt(Stmt *S, int SubIndent) {
48      IndentLevel += SubIndent;
49      if (S && isa<Expr>(S)) {
50        // If this is an expr used in a stmt context, indent and newline it.
51        Indent();
52        Visit(S);
53        OS << ";\n";
54      } else if (S) {
55        Visit(S);
56      } else {
57        Indent() << "<<<NULL STATEMENT>>>\n";
58      }
59      IndentLevel -= SubIndent;
60    }
61
62    void PrintRawCompoundStmt(CompoundStmt *S);
63    void PrintRawDecl(Decl *D);
64    void PrintRawDeclStmt(const DeclStmt *S);
65    void PrintRawIfStmt(IfStmt *If);
66    void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
67    void PrintCallArgs(CallExpr *E);
68    void PrintRawSEHExceptHandler(SEHExceptStmt *S);
69    void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
70
71    void PrintExpr(Expr *E) {
72      if (E)
73        Visit(E);
74      else
75        OS << "<null expr>";
76    }
77
78    raw_ostream &Indent(int Delta = 0) {
79      for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
80        OS << "  ";
81      return OS;
82    }
83
84    void Visit(Stmt* S) {
85      if (Helper && Helper->handledStmt(S,OS))
86          return;
87      else StmtVisitor<StmtPrinter>::Visit(S);
88    }
89
90    void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
91      Indent() << "<<unknown stmt type>>\n";
92    }
93    void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
94      OS << "<<unknown expr type>>";
95    }
96    void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
97
98#define ABSTRACT_STMT(CLASS)
99#define STMT(CLASS, PARENT) \
100    void Visit##CLASS(CLASS *Node);
101#include "clang/AST/StmtNodes.inc"
102  };
103}
104
105//===----------------------------------------------------------------------===//
106//  Stmt printing methods.
107//===----------------------------------------------------------------------===//
108
109/// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
110/// with no newline after the }.
111void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
112  OS << "{\n";
113  for (CompoundStmt::body_iterator I = Node->body_begin(), E = Node->body_end();
114       I != E; ++I)
115    PrintStmt(*I);
116
117  Indent() << "}";
118}
119
120void StmtPrinter::PrintRawDecl(Decl *D) {
121  D->print(OS, Policy, IndentLevel);
122}
123
124void StmtPrinter::PrintRawDeclStmt(const DeclStmt *S) {
125  DeclStmt::const_decl_iterator Begin = S->decl_begin(), End = S->decl_end();
126  SmallVector<Decl*, 2> Decls;
127  for ( ; Begin != End; ++Begin)
128    Decls.push_back(*Begin);
129
130  Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
131}
132
133void StmtPrinter::VisitNullStmt(NullStmt *Node) {
134  Indent() << ";\n";
135}
136
137void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
138  Indent();
139  PrintRawDeclStmt(Node);
140  OS << ";\n";
141}
142
143void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
144  Indent();
145  PrintRawCompoundStmt(Node);
146  OS << "\n";
147}
148
149void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
150  Indent(-1) << "case ";
151  PrintExpr(Node->getLHS());
152  if (Node->getRHS()) {
153    OS << " ... ";
154    PrintExpr(Node->getRHS());
155  }
156  OS << ":\n";
157
158  PrintStmt(Node->getSubStmt(), 0);
159}
160
161void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
162  Indent(-1) << "default:\n";
163  PrintStmt(Node->getSubStmt(), 0);
164}
165
166void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
167  Indent(-1) << Node->getName() << ":\n";
168  PrintStmt(Node->getSubStmt(), 0);
169}
170
171void StmtPrinter::VisitAttributedStmt(AttributedStmt *Node) {
172  OS << "[[";
173  bool first = true;
174  for (ArrayRef<const Attr*>::iterator it = Node->getAttrs().begin(),
175                                       end = Node->getAttrs().end();
176                                       it != end; ++it) {
177    if (!first) {
178      OS << ", ";
179      first = false;
180    }
181    // TODO: check this
182    (*it)->printPretty(OS, Policy);
183  }
184  OS << "]] ";
185  PrintStmt(Node->getSubStmt(), 0);
186}
187
188void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
189  OS << "if (";
190  if (const DeclStmt *DS = If->getConditionVariableDeclStmt())
191    PrintRawDeclStmt(DS);
192  else
193    PrintExpr(If->getCond());
194  OS << ')';
195
196  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
197    OS << ' ';
198    PrintRawCompoundStmt(CS);
199    OS << (If->getElse() ? ' ' : '\n');
200  } else {
201    OS << '\n';
202    PrintStmt(If->getThen());
203    if (If->getElse()) Indent();
204  }
205
206  if (Stmt *Else = If->getElse()) {
207    OS << "else";
208
209    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
210      OS << ' ';
211      PrintRawCompoundStmt(CS);
212      OS << '\n';
213    } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
214      OS << ' ';
215      PrintRawIfStmt(ElseIf);
216    } else {
217      OS << '\n';
218      PrintStmt(If->getElse());
219    }
220  }
221}
222
223void StmtPrinter::VisitIfStmt(IfStmt *If) {
224  Indent();
225  PrintRawIfStmt(If);
226}
227
228void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
229  Indent() << "switch (";
230  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
231    PrintRawDeclStmt(DS);
232  else
233    PrintExpr(Node->getCond());
234  OS << ")";
235
236  // Pretty print compoundstmt bodies (very common).
237  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
238    OS << " ";
239    PrintRawCompoundStmt(CS);
240    OS << "\n";
241  } else {
242    OS << "\n";
243    PrintStmt(Node->getBody());
244  }
245}
246
247void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
248  Indent() << "while (";
249  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
250    PrintRawDeclStmt(DS);
251  else
252    PrintExpr(Node->getCond());
253  OS << ")\n";
254  PrintStmt(Node->getBody());
255}
256
257void StmtPrinter::VisitDoStmt(DoStmt *Node) {
258  Indent() << "do ";
259  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
260    PrintRawCompoundStmt(CS);
261    OS << " ";
262  } else {
263    OS << "\n";
264    PrintStmt(Node->getBody());
265    Indent();
266  }
267
268  OS << "while (";
269  PrintExpr(Node->getCond());
270  OS << ");\n";
271}
272
273void StmtPrinter::VisitForStmt(ForStmt *Node) {
274  Indent() << "for (";
275  if (Node->getInit()) {
276    if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getInit()))
277      PrintRawDeclStmt(DS);
278    else
279      PrintExpr(cast<Expr>(Node->getInit()));
280  }
281  OS << ";";
282  if (Node->getCond()) {
283    OS << " ";
284    PrintExpr(Node->getCond());
285  }
286  OS << ";";
287  if (Node->getInc()) {
288    OS << " ";
289    PrintExpr(Node->getInc());
290  }
291  OS << ") ";
292
293  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
294    PrintRawCompoundStmt(CS);
295    OS << "\n";
296  } else {
297    OS << "\n";
298    PrintStmt(Node->getBody());
299  }
300}
301
302void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
303  Indent() << "for (";
304  if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getElement()))
305    PrintRawDeclStmt(DS);
306  else
307    PrintExpr(cast<Expr>(Node->getElement()));
308  OS << " in ";
309  PrintExpr(Node->getCollection());
310  OS << ") ";
311
312  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
313    PrintRawCompoundStmt(CS);
314    OS << "\n";
315  } else {
316    OS << "\n";
317    PrintStmt(Node->getBody());
318  }
319}
320
321void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
322  Indent() << "for (";
323  PrintingPolicy SubPolicy(Policy);
324  SubPolicy.SuppressInitializers = true;
325  Node->getLoopVariable()->print(OS, SubPolicy, IndentLevel);
326  OS << " : ";
327  PrintExpr(Node->getRangeInit());
328  OS << ") {\n";
329  PrintStmt(Node->getBody());
330  Indent() << "}\n";
331}
332
333void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
334  Indent();
335  if (Node->isIfExists())
336    OS << "__if_exists (";
337  else
338    OS << "__if_not_exists (";
339
340  if (NestedNameSpecifier *Qualifier
341        = Node->getQualifierLoc().getNestedNameSpecifier())
342    Qualifier->print(OS, Policy);
343
344  OS << Node->getNameInfo() << ") ";
345
346  PrintRawCompoundStmt(Node->getSubStmt());
347}
348
349void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
350  Indent() << "goto " << Node->getLabel()->getName() << ";\n";
351}
352
353void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
354  Indent() << "goto *";
355  PrintExpr(Node->getTarget());
356  OS << ";\n";
357}
358
359void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
360  Indent() << "continue;\n";
361}
362
363void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
364  Indent() << "break;\n";
365}
366
367
368void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
369  Indent() << "return";
370  if (Node->getRetValue()) {
371    OS << " ";
372    PrintExpr(Node->getRetValue());
373  }
374  OS << ";\n";
375}
376
377
378void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) {
379  Indent() << "asm ";
380
381  if (Node->isVolatile())
382    OS << "volatile ";
383
384  OS << "(";
385  VisitStringLiteral(Node->getAsmString());
386
387  // Outputs
388  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
389      Node->getNumClobbers() != 0)
390    OS << " : ";
391
392  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
393    if (i != 0)
394      OS << ", ";
395
396    if (!Node->getOutputName(i).empty()) {
397      OS << '[';
398      OS << Node->getOutputName(i);
399      OS << "] ";
400    }
401
402    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
403    OS << " ";
404    Visit(Node->getOutputExpr(i));
405  }
406
407  // Inputs
408  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
409    OS << " : ";
410
411  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
412    if (i != 0)
413      OS << ", ";
414
415    if (!Node->getInputName(i).empty()) {
416      OS << '[';
417      OS << Node->getInputName(i);
418      OS << "] ";
419    }
420
421    VisitStringLiteral(Node->getInputConstraintLiteral(i));
422    OS << " ";
423    Visit(Node->getInputExpr(i));
424  }
425
426  // Clobbers
427  if (Node->getNumClobbers() != 0)
428    OS << " : ";
429
430  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
431    if (i != 0)
432      OS << ", ";
433
434    VisitStringLiteral(Node->getClobberStringLiteral(i));
435  }
436
437  OS << ");\n";
438}
439
440void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
441  // FIXME: Implement MS style inline asm statement printer.
442  Indent() << "__asm ";
443  if (Node->hasBraces())
444    OS << "{\n";
445  OS << *(Node->getAsmString()) << "\n";
446  if (Node->hasBraces())
447    Indent() << "}\n";
448}
449
450void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
451  Indent() << "@try";
452  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
453    PrintRawCompoundStmt(TS);
454    OS << "\n";
455  }
456
457  for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
458    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
459    Indent() << "@catch(";
460    if (catchStmt->getCatchParamDecl()) {
461      if (Decl *DS = catchStmt->getCatchParamDecl())
462        PrintRawDecl(DS);
463    }
464    OS << ")";
465    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
466      PrintRawCompoundStmt(CS);
467      OS << "\n";
468    }
469  }
470
471  if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
472        Node->getFinallyStmt())) {
473    Indent() << "@finally";
474    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
475    OS << "\n";
476  }
477}
478
479void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
480}
481
482void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
483  Indent() << "@catch (...) { /* todo */ } \n";
484}
485
486void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
487  Indent() << "@throw";
488  if (Node->getThrowExpr()) {
489    OS << " ";
490    PrintExpr(Node->getThrowExpr());
491  }
492  OS << ";\n";
493}
494
495void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
496  Indent() << "@synchronized (";
497  PrintExpr(Node->getSynchExpr());
498  OS << ")";
499  PrintRawCompoundStmt(Node->getSynchBody());
500  OS << "\n";
501}
502
503void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
504  Indent() << "@autoreleasepool";
505  PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
506  OS << "\n";
507}
508
509void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
510  OS << "catch (";
511  if (Decl *ExDecl = Node->getExceptionDecl())
512    PrintRawDecl(ExDecl);
513  else
514    OS << "...";
515  OS << ") ";
516  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
517}
518
519void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
520  Indent();
521  PrintRawCXXCatchStmt(Node);
522  OS << "\n";
523}
524
525void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
526  Indent() << "try ";
527  PrintRawCompoundStmt(Node->getTryBlock());
528  for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
529    OS << " ";
530    PrintRawCXXCatchStmt(Node->getHandler(i));
531  }
532  OS << "\n";
533}
534
535void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
536  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
537  PrintRawCompoundStmt(Node->getTryBlock());
538  SEHExceptStmt *E = Node->getExceptHandler();
539  SEHFinallyStmt *F = Node->getFinallyHandler();
540  if(E)
541    PrintRawSEHExceptHandler(E);
542  else {
543    assert(F && "Must have a finally block...");
544    PrintRawSEHFinallyStmt(F);
545  }
546  OS << "\n";
547}
548
549void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
550  OS << "__finally ";
551  PrintRawCompoundStmt(Node->getBlock());
552  OS << "\n";
553}
554
555void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
556  OS << "__except (";
557  VisitExpr(Node->getFilterExpr());
558  OS << ")\n";
559  PrintRawCompoundStmt(Node->getBlock());
560  OS << "\n";
561}
562
563void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
564  Indent();
565  PrintRawSEHExceptHandler(Node);
566  OS << "\n";
567}
568
569void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
570  Indent();
571  PrintRawSEHFinallyStmt(Node);
572  OS << "\n";
573}
574
575//===----------------------------------------------------------------------===//
576//  Expr printing methods.
577//===----------------------------------------------------------------------===//
578
579void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
580  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
581    Qualifier->print(OS, Policy);
582  if (Node->hasTemplateKeyword())
583    OS << "template ";
584  OS << Node->getNameInfo();
585  if (Node->hasExplicitTemplateArgs())
586    OS << TemplateSpecializationType::PrintTemplateArgumentList(
587                                                    Node->getTemplateArgs(),
588                                                    Node->getNumTemplateArgs(),
589                                                    Policy);
590}
591
592void StmtPrinter::VisitDependentScopeDeclRefExpr(
593                                           DependentScopeDeclRefExpr *Node) {
594  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
595    Qualifier->print(OS, Policy);
596  if (Node->hasTemplateKeyword())
597    OS << "template ";
598  OS << Node->getNameInfo();
599  if (Node->hasExplicitTemplateArgs())
600    OS << TemplateSpecializationType::PrintTemplateArgumentList(
601                                                   Node->getTemplateArgs(),
602                                                   Node->getNumTemplateArgs(),
603                                                   Policy);
604}
605
606void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
607  if (Node->getQualifier())
608    Node->getQualifier()->print(OS, Policy);
609  if (Node->hasTemplateKeyword())
610    OS << "template ";
611  OS << Node->getNameInfo();
612  if (Node->hasExplicitTemplateArgs())
613    OS << TemplateSpecializationType::PrintTemplateArgumentList(
614                                                   Node->getTemplateArgs(),
615                                                   Node->getNumTemplateArgs(),
616                                                   Policy);
617}
618
619void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
620  if (Node->getBase()) {
621    PrintExpr(Node->getBase());
622    OS << (Node->isArrow() ? "->" : ".");
623  }
624  OS << *Node->getDecl();
625}
626
627void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
628  if (Node->isSuperReceiver())
629    OS << "super.";
630  else if (Node->getBase()) {
631    PrintExpr(Node->getBase());
632    OS << ".";
633  }
634
635  if (Node->isImplicitProperty())
636    OS << Node->getImplicitPropertyGetter()->getSelector().getAsString();
637  else
638    OS << Node->getExplicitProperty()->getName();
639}
640
641void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
642
643  PrintExpr(Node->getBaseExpr());
644  OS << "[";
645  PrintExpr(Node->getKeyExpr());
646  OS << "]";
647}
648
649void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
650  switch (Node->getIdentType()) {
651    default:
652      llvm_unreachable("unknown case");
653    case PredefinedExpr::Func:
654      OS << "__func__";
655      break;
656    case PredefinedExpr::Function:
657      OS << "__FUNCTION__";
658      break;
659    case PredefinedExpr::LFunction:
660      OS << "L__FUNCTION__";
661      break;
662    case PredefinedExpr::PrettyFunction:
663      OS << "__PRETTY_FUNCTION__";
664      break;
665  }
666}
667
668void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
669  unsigned value = Node->getValue();
670
671  switch (Node->getKind()) {
672  case CharacterLiteral::Ascii: break; // no prefix.
673  case CharacterLiteral::Wide:  OS << 'L'; break;
674  case CharacterLiteral::UTF16: OS << 'u'; break;
675  case CharacterLiteral::UTF32: OS << 'U'; break;
676  }
677
678  switch (value) {
679  case '\\':
680    OS << "'\\\\'";
681    break;
682  case '\'':
683    OS << "'\\''";
684    break;
685  case '\a':
686    // TODO: K&R: the meaning of '\\a' is different in traditional C
687    OS << "'\\a'";
688    break;
689  case '\b':
690    OS << "'\\b'";
691    break;
692  // Nonstandard escape sequence.
693  /*case '\e':
694    OS << "'\\e'";
695    break;*/
696  case '\f':
697    OS << "'\\f'";
698    break;
699  case '\n':
700    OS << "'\\n'";
701    break;
702  case '\r':
703    OS << "'\\r'";
704    break;
705  case '\t':
706    OS << "'\\t'";
707    break;
708  case '\v':
709    OS << "'\\v'";
710    break;
711  default:
712    if (value < 256 && isprint(value)) {
713      OS << "'" << (char)value << "'";
714    } else if (value < 256) {
715      OS << "'\\x";
716      OS.write_hex(value) << "'";
717    } else {
718      // FIXME what to really do here?
719      OS << value;
720    }
721  }
722}
723
724void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
725  bool isSigned = Node->getType()->isSignedIntegerType();
726  OS << Node->getValue().toString(10, isSigned);
727
728  // Emit suffixes.  Integer literals are always a builtin integer type.
729  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
730  default: llvm_unreachable("Unexpected type for integer literal!");
731  // FIXME: The Short and UShort cases are to handle cases where a short
732  // integeral literal is formed during template instantiation.  They should
733  // be removed when template instantiation no longer needs integer literals.
734  case BuiltinType::Short:
735  case BuiltinType::UShort:
736  case BuiltinType::Int:       break; // no suffix.
737  case BuiltinType::UInt:      OS << 'U'; break;
738  case BuiltinType::Long:      OS << 'L'; break;
739  case BuiltinType::ULong:     OS << "UL"; break;
740  case BuiltinType::LongLong:  OS << "LL"; break;
741  case BuiltinType::ULongLong: OS << "ULL"; break;
742  case BuiltinType::Int128:    OS << "i128"; break;
743  case BuiltinType::UInt128:   OS << "Ui128"; break;
744  }
745}
746
747static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
748                                 bool PrintSuffix) {
749  SmallString<16> Str;
750  Node->getValue().toString(Str);
751  OS << Str;
752  if (Str.find_first_not_of("-0123456789") == StringRef::npos)
753    OS << '.'; // Trailing dot in order to separate from ints.
754
755  if (!PrintSuffix)
756    return;
757
758  // Emit suffixes.  Float literals are always a builtin float type.
759  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
760  default: llvm_unreachable("Unexpected type for float literal!");
761  case BuiltinType::Half:       break; // FIXME: suffix?
762  case BuiltinType::Double:     break; // no suffix.
763  case BuiltinType::Float:      OS << 'F'; break;
764  case BuiltinType::LongDouble: OS << 'L'; break;
765  }
766}
767
768void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
769  PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
770}
771
772void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
773  PrintExpr(Node->getSubExpr());
774  OS << "i";
775}
776
777void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
778  Str->outputString(OS);
779}
780void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
781  OS << "(";
782  PrintExpr(Node->getSubExpr());
783  OS << ")";
784}
785void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
786  if (!Node->isPostfix()) {
787    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
788
789    // Print a space if this is an "identifier operator" like __real, or if
790    // it might be concatenated incorrectly like '+'.
791    switch (Node->getOpcode()) {
792    default: break;
793    case UO_Real:
794    case UO_Imag:
795    case UO_Extension:
796      OS << ' ';
797      break;
798    case UO_Plus:
799    case UO_Minus:
800      if (isa<UnaryOperator>(Node->getSubExpr()))
801        OS << ' ';
802      break;
803    }
804  }
805  PrintExpr(Node->getSubExpr());
806
807  if (Node->isPostfix())
808    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
809}
810
811void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
812  OS << "__builtin_offsetof(";
813  OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
814  bool PrintedSomething = false;
815  for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
816    OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
817    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
818      // Array node
819      OS << "[";
820      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
821      OS << "]";
822      PrintedSomething = true;
823      continue;
824    }
825
826    // Skip implicit base indirections.
827    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
828      continue;
829
830    // Field or identifier node.
831    IdentifierInfo *Id = ON.getFieldName();
832    if (!Id)
833      continue;
834
835    if (PrintedSomething)
836      OS << ".";
837    else
838      PrintedSomething = true;
839    OS << Id->getName();
840  }
841  OS << ")";
842}
843
844void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
845  switch(Node->getKind()) {
846  case UETT_SizeOf:
847    OS << "sizeof";
848    break;
849  case UETT_AlignOf:
850    if (Policy.LangOpts.CPlusPlus)
851      OS << "alignof";
852    else if (Policy.LangOpts.C11)
853      OS << "_Alignof";
854    else
855      OS << "__alignof";
856    break;
857  case UETT_VecStep:
858    OS << "vec_step";
859    break;
860  }
861  if (Node->isArgumentType())
862    OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
863  else {
864    OS << " ";
865    PrintExpr(Node->getArgumentExpr());
866  }
867}
868
869void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
870  OS << "_Generic(";
871  PrintExpr(Node->getControllingExpr());
872  for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
873    OS << ", ";
874    QualType T = Node->getAssocType(i);
875    if (T.isNull())
876      OS << "default";
877    else
878      OS << T.getAsString(Policy);
879    OS << ": ";
880    PrintExpr(Node->getAssocExpr(i));
881  }
882  OS << ")";
883}
884
885void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
886  PrintExpr(Node->getLHS());
887  OS << "[";
888  PrintExpr(Node->getRHS());
889  OS << "]";
890}
891
892void StmtPrinter::PrintCallArgs(CallExpr *Call) {
893  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
894    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
895      // Don't print any defaulted arguments
896      break;
897    }
898
899    if (i) OS << ", ";
900    PrintExpr(Call->getArg(i));
901  }
902}
903
904void StmtPrinter::VisitCallExpr(CallExpr *Call) {
905  PrintExpr(Call->getCallee());
906  OS << "(";
907  PrintCallArgs(Call);
908  OS << ")";
909}
910void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
911  // FIXME: Suppress printing implicit bases (like "this")
912  PrintExpr(Node->getBase());
913
914  MemberExpr *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
915  FieldDecl  *ParentDecl   = ParentMember
916    ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl()) : NULL;
917
918  if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
919    OS << (Node->isArrow() ? "->" : ".");
920
921  if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
922    if (FD->isAnonymousStructOrUnion())
923      return;
924
925  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
926    Qualifier->print(OS, Policy);
927  if (Node->hasTemplateKeyword())
928    OS << "template ";
929  OS << Node->getMemberNameInfo();
930  if (Node->hasExplicitTemplateArgs())
931    OS << TemplateSpecializationType::PrintTemplateArgumentList(
932                                                    Node->getTemplateArgs(),
933                                                    Node->getNumTemplateArgs(),
934                                                                Policy);
935}
936void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
937  PrintExpr(Node->getBase());
938  OS << (Node->isArrow() ? "->isa" : ".isa");
939}
940
941void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
942  PrintExpr(Node->getBase());
943  OS << ".";
944  OS << Node->getAccessor().getName();
945}
946void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
947  OS << "(" << Node->getTypeAsWritten().getAsString(Policy) << ")";
948  PrintExpr(Node->getSubExpr());
949}
950void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
951  OS << "(" << Node->getType().getAsString(Policy) << ")";
952  PrintExpr(Node->getInitializer());
953}
954void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
955  // No need to print anything, simply forward to the sub expression.
956  PrintExpr(Node->getSubExpr());
957}
958void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
959  PrintExpr(Node->getLHS());
960  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
961  PrintExpr(Node->getRHS());
962}
963void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
964  PrintExpr(Node->getLHS());
965  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
966  PrintExpr(Node->getRHS());
967}
968void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
969  PrintExpr(Node->getCond());
970  OS << " ? ";
971  PrintExpr(Node->getLHS());
972  OS << " : ";
973  PrintExpr(Node->getRHS());
974}
975
976// GNU extensions.
977
978void
979StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
980  PrintExpr(Node->getCommon());
981  OS << " ?: ";
982  PrintExpr(Node->getFalseExpr());
983}
984void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
985  OS << "&&" << Node->getLabel()->getName();
986}
987
988void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
989  OS << "(";
990  PrintRawCompoundStmt(E->getSubStmt());
991  OS << ")";
992}
993
994void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
995  OS << "__builtin_choose_expr(";
996  PrintExpr(Node->getCond());
997  OS << ", ";
998  PrintExpr(Node->getLHS());
999  OS << ", ";
1000  PrintExpr(Node->getRHS());
1001  OS << ")";
1002}
1003
1004void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1005  OS << "__null";
1006}
1007
1008void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1009  OS << "__builtin_shufflevector(";
1010  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
1011    if (i) OS << ", ";
1012    PrintExpr(Node->getExpr(i));
1013  }
1014  OS << ")";
1015}
1016
1017void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1018  if (Node->getSyntacticForm()) {
1019    Visit(Node->getSyntacticForm());
1020    return;
1021  }
1022
1023  OS << "{ ";
1024  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1025    if (i) OS << ", ";
1026    if (Node->getInit(i))
1027      PrintExpr(Node->getInit(i));
1028    else
1029      OS << "0";
1030  }
1031  OS << " }";
1032}
1033
1034void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1035  OS << "( ";
1036  for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1037    if (i) OS << ", ";
1038    PrintExpr(Node->getExpr(i));
1039  }
1040  OS << " )";
1041}
1042
1043void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1044  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1045                      DEnd = Node->designators_end();
1046       D != DEnd; ++D) {
1047    if (D->isFieldDesignator()) {
1048      if (D->getDotLoc().isInvalid())
1049        OS << D->getFieldName()->getName() << ":";
1050      else
1051        OS << "." << D->getFieldName()->getName();
1052    } else {
1053      OS << "[";
1054      if (D->isArrayDesignator()) {
1055        PrintExpr(Node->getArrayIndex(*D));
1056      } else {
1057        PrintExpr(Node->getArrayRangeStart(*D));
1058        OS << " ... ";
1059        PrintExpr(Node->getArrayRangeEnd(*D));
1060      }
1061      OS << "]";
1062    }
1063  }
1064
1065  OS << " = ";
1066  PrintExpr(Node->getInit());
1067}
1068
1069void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1070  if (Policy.LangOpts.CPlusPlus)
1071    OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
1072  else {
1073    OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
1074    if (Node->getType()->isRecordType())
1075      OS << "{}";
1076    else
1077      OS << 0;
1078  }
1079}
1080
1081void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1082  OS << "__builtin_va_arg(";
1083  PrintExpr(Node->getSubExpr());
1084  OS << ", ";
1085  OS << Node->getType().getAsString(Policy);
1086  OS << ")";
1087}
1088
1089void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1090  PrintExpr(Node->getSyntacticForm());
1091}
1092
1093void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1094  const char *Name = 0;
1095  switch (Node->getOp()) {
1096#define BUILTIN(ID, TYPE, ATTRS)
1097#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1098  case AtomicExpr::AO ## ID: \
1099    Name = #ID "("; \
1100    break;
1101#include "clang/Basic/Builtins.def"
1102  }
1103  OS << Name;
1104
1105  // AtomicExpr stores its subexpressions in a permuted order.
1106  PrintExpr(Node->getPtr());
1107  OS << ", ";
1108  if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1109      Node->getOp() != AtomicExpr::AO__atomic_load_n) {
1110    PrintExpr(Node->getVal1());
1111    OS << ", ";
1112  }
1113  if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1114      Node->isCmpXChg()) {
1115    PrintExpr(Node->getVal2());
1116    OS << ", ";
1117  }
1118  if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1119      Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1120    PrintExpr(Node->getWeak());
1121    OS << ", ";
1122  }
1123  if (Node->getOp() != AtomicExpr::AO__c11_atomic_init)
1124    PrintExpr(Node->getOrder());
1125  if (Node->isCmpXChg()) {
1126    OS << ", ";
1127    PrintExpr(Node->getOrderFail());
1128  }
1129  OS << ")";
1130}
1131
1132// C++
1133void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1134  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1135    "",
1136#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1137    Spelling,
1138#include "clang/Basic/OperatorKinds.def"
1139  };
1140
1141  OverloadedOperatorKind Kind = Node->getOperator();
1142  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1143    if (Node->getNumArgs() == 1) {
1144      OS << OpStrings[Kind] << ' ';
1145      PrintExpr(Node->getArg(0));
1146    } else {
1147      PrintExpr(Node->getArg(0));
1148      OS << ' ' << OpStrings[Kind];
1149    }
1150  } else if (Kind == OO_Arrow) {
1151    PrintExpr(Node->getArg(0));
1152  } else if (Kind == OO_Call) {
1153    PrintExpr(Node->getArg(0));
1154    OS << '(';
1155    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1156      if (ArgIdx > 1)
1157        OS << ", ";
1158      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1159        PrintExpr(Node->getArg(ArgIdx));
1160    }
1161    OS << ')';
1162  } else if (Kind == OO_Subscript) {
1163    PrintExpr(Node->getArg(0));
1164    OS << '[';
1165    PrintExpr(Node->getArg(1));
1166    OS << ']';
1167  } else if (Node->getNumArgs() == 1) {
1168    OS << OpStrings[Kind] << ' ';
1169    PrintExpr(Node->getArg(0));
1170  } else if (Node->getNumArgs() == 2) {
1171    PrintExpr(Node->getArg(0));
1172    OS << ' ' << OpStrings[Kind] << ' ';
1173    PrintExpr(Node->getArg(1));
1174  } else {
1175    llvm_unreachable("unknown overloaded operator");
1176  }
1177}
1178
1179void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1180  VisitCallExpr(cast<CallExpr>(Node));
1181}
1182
1183void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1184  PrintExpr(Node->getCallee());
1185  OS << "<<<";
1186  PrintCallArgs(Node->getConfig());
1187  OS << ">>>(";
1188  PrintCallArgs(Node);
1189  OS << ")";
1190}
1191
1192void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1193  OS << Node->getCastName() << '<';
1194  OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1195  PrintExpr(Node->getSubExpr());
1196  OS << ")";
1197}
1198
1199void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1200  VisitCXXNamedCastExpr(Node);
1201}
1202
1203void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1204  VisitCXXNamedCastExpr(Node);
1205}
1206
1207void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1208  VisitCXXNamedCastExpr(Node);
1209}
1210
1211void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1212  VisitCXXNamedCastExpr(Node);
1213}
1214
1215void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1216  OS << "typeid(";
1217  if (Node->isTypeOperand()) {
1218    OS << Node->getTypeOperand().getAsString(Policy);
1219  } else {
1220    PrintExpr(Node->getExprOperand());
1221  }
1222  OS << ")";
1223}
1224
1225void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1226  OS << "__uuidof(";
1227  if (Node->isTypeOperand()) {
1228    OS << Node->getTypeOperand().getAsString(Policy);
1229  } else {
1230    PrintExpr(Node->getExprOperand());
1231  }
1232  OS << ")";
1233}
1234
1235void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1236  switch (Node->getLiteralOperatorKind()) {
1237  case UserDefinedLiteral::LOK_Raw:
1238    OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1239    break;
1240  case UserDefinedLiteral::LOK_Template: {
1241    DeclRefExpr *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1242    const TemplateArgumentList *Args =
1243      cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1244    assert(Args);
1245    const TemplateArgument &Pack = Args->get(0);
1246    for (TemplateArgument::pack_iterator I = Pack.pack_begin(),
1247                                         E = Pack.pack_end(); I != E; ++I) {
1248      char C = (char)I->getAsIntegral().getZExtValue();
1249      OS << C;
1250    }
1251    break;
1252  }
1253  case UserDefinedLiteral::LOK_Integer: {
1254    // Print integer literal without suffix.
1255    IntegerLiteral *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1256    OS << Int->getValue().toString(10, /*isSigned*/false);
1257    break;
1258  }
1259  case UserDefinedLiteral::LOK_Floating: {
1260    // Print floating literal without suffix.
1261    FloatingLiteral *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1262    PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1263    break;
1264  }
1265  case UserDefinedLiteral::LOK_String:
1266  case UserDefinedLiteral::LOK_Character:
1267    PrintExpr(Node->getCookedLiteral());
1268    break;
1269  }
1270  OS << Node->getUDSuffix()->getName();
1271}
1272
1273void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1274  OS << (Node->getValue() ? "true" : "false");
1275}
1276
1277void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1278  OS << "nullptr";
1279}
1280
1281void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1282  OS << "this";
1283}
1284
1285void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1286  if (Node->getSubExpr() == 0)
1287    OS << "throw";
1288  else {
1289    OS << "throw ";
1290    PrintExpr(Node->getSubExpr());
1291  }
1292}
1293
1294void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1295  // Nothing to print: we picked up the default argument
1296}
1297
1298void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1299  OS << Node->getType().getAsString(Policy);
1300  OS << "(";
1301  PrintExpr(Node->getSubExpr());
1302  OS << ")";
1303}
1304
1305void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1306  PrintExpr(Node->getSubExpr());
1307}
1308
1309void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1310  OS << Node->getType().getAsString(Policy);
1311  OS << "(";
1312  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1313                                         ArgEnd = Node->arg_end();
1314       Arg != ArgEnd; ++Arg) {
1315    if (Arg != Node->arg_begin())
1316      OS << ", ";
1317    PrintExpr(*Arg);
1318  }
1319  OS << ")";
1320}
1321
1322void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1323  OS << '[';
1324  bool NeedComma = false;
1325  switch (Node->getCaptureDefault()) {
1326  case LCD_None:
1327    break;
1328
1329  case LCD_ByCopy:
1330    OS << '=';
1331    NeedComma = true;
1332    break;
1333
1334  case LCD_ByRef:
1335    OS << '&';
1336    NeedComma = true;
1337    break;
1338  }
1339  for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1340                                 CEnd = Node->explicit_capture_end();
1341       C != CEnd;
1342       ++C) {
1343    if (NeedComma)
1344      OS << ", ";
1345    NeedComma = true;
1346
1347    switch (C->getCaptureKind()) {
1348    case LCK_This:
1349      OS << "this";
1350      break;
1351
1352    case LCK_ByRef:
1353      if (Node->getCaptureDefault() != LCD_ByRef)
1354        OS << '&';
1355      OS << C->getCapturedVar()->getName();
1356      break;
1357
1358    case LCK_ByCopy:
1359      if (Node->getCaptureDefault() != LCD_ByCopy)
1360        OS << '=';
1361      OS << C->getCapturedVar()->getName();
1362      break;
1363    }
1364  }
1365  OS << ']';
1366
1367  if (Node->hasExplicitParameters()) {
1368    OS << " (";
1369    CXXMethodDecl *Method = Node->getCallOperator();
1370    NeedComma = false;
1371    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
1372                                    PEnd = Method->param_end();
1373         P != PEnd; ++P) {
1374      if (NeedComma) {
1375        OS << ", ";
1376      } else {
1377        NeedComma = true;
1378      }
1379      std::string ParamStr = (*P)->getNameAsString();
1380      (*P)->getOriginalType().getAsStringInternal(ParamStr, Policy);
1381      OS << ParamStr;
1382    }
1383    if (Method->isVariadic()) {
1384      if (NeedComma)
1385        OS << ", ";
1386      OS << "...";
1387    }
1388    OS << ')';
1389
1390    if (Node->isMutable())
1391      OS << " mutable";
1392
1393    const FunctionProtoType *Proto
1394      = Method->getType()->getAs<FunctionProtoType>();
1395    {
1396      std::string ExceptionSpec;
1397      Proto->printExceptionSpecification(ExceptionSpec, Policy);
1398      OS << ExceptionSpec;
1399    }
1400
1401    // FIXME: Attributes
1402
1403    // Print the trailing return type if it was specified in the source.
1404    if (Node->hasExplicitResultType())
1405      OS << " -> " << Proto->getResultType().getAsString(Policy);
1406  }
1407
1408  // Print the body.
1409  CompoundStmt *Body = Node->getBody();
1410  OS << ' ';
1411  PrintStmt(Body);
1412}
1413
1414void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1415  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1416    OS << TSInfo->getType().getAsString(Policy) << "()";
1417  else
1418    OS << Node->getType().getAsString(Policy) << "()";
1419}
1420
1421void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1422  if (E->isGlobalNew())
1423    OS << "::";
1424  OS << "new ";
1425  unsigned NumPlace = E->getNumPlacementArgs();
1426  if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
1427    OS << "(";
1428    PrintExpr(E->getPlacementArg(0));
1429    for (unsigned i = 1; i < NumPlace; ++i) {
1430      if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
1431        break;
1432      OS << ", ";
1433      PrintExpr(E->getPlacementArg(i));
1434    }
1435    OS << ") ";
1436  }
1437  if (E->isParenTypeId())
1438    OS << "(";
1439  std::string TypeS;
1440  if (Expr *Size = E->getArraySize()) {
1441    llvm::raw_string_ostream s(TypeS);
1442    Size->printPretty(s, Helper, Policy);
1443    s.flush();
1444    TypeS = "[" + TypeS + "]";
1445  }
1446  E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1447  OS << TypeS;
1448  if (E->isParenTypeId())
1449    OS << ")";
1450
1451  CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
1452  if (InitStyle) {
1453    if (InitStyle == CXXNewExpr::CallInit)
1454      OS << "(";
1455    PrintExpr(E->getInitializer());
1456    if (InitStyle == CXXNewExpr::CallInit)
1457      OS << ")";
1458  }
1459}
1460
1461void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1462  if (E->isGlobalDelete())
1463    OS << "::";
1464  OS << "delete ";
1465  if (E->isArrayForm())
1466    OS << "[] ";
1467  PrintExpr(E->getArgument());
1468}
1469
1470void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1471  PrintExpr(E->getBase());
1472  if (E->isArrow())
1473    OS << "->";
1474  else
1475    OS << '.';
1476  if (E->getQualifier())
1477    E->getQualifier()->print(OS, Policy);
1478  OS << "~";
1479
1480  std::string TypeS;
1481  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1482    OS << II->getName();
1483  else
1484    E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1485  OS << TypeS;
1486}
1487
1488void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1489  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1490    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1491      // Don't print any defaulted arguments
1492      break;
1493    }
1494
1495    if (i) OS << ", ";
1496    PrintExpr(E->getArg(i));
1497  }
1498}
1499
1500void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1501  // Just forward to the sub expression.
1502  PrintExpr(E->getSubExpr());
1503}
1504
1505void
1506StmtPrinter::VisitCXXUnresolvedConstructExpr(
1507                                           CXXUnresolvedConstructExpr *Node) {
1508  OS << Node->getTypeAsWritten().getAsString(Policy);
1509  OS << "(";
1510  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1511                                             ArgEnd = Node->arg_end();
1512       Arg != ArgEnd; ++Arg) {
1513    if (Arg != Node->arg_begin())
1514      OS << ", ";
1515    PrintExpr(*Arg);
1516  }
1517  OS << ")";
1518}
1519
1520void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1521                                         CXXDependentScopeMemberExpr *Node) {
1522  if (!Node->isImplicitAccess()) {
1523    PrintExpr(Node->getBase());
1524    OS << (Node->isArrow() ? "->" : ".");
1525  }
1526  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1527    Qualifier->print(OS, Policy);
1528  if (Node->hasTemplateKeyword())
1529    OS << "template ";
1530  OS << Node->getMemberNameInfo();
1531  if (Node->hasExplicitTemplateArgs()) {
1532    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1533                                                    Node->getTemplateArgs(),
1534                                                    Node->getNumTemplateArgs(),
1535                                                    Policy);
1536  }
1537}
1538
1539void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1540  if (!Node->isImplicitAccess()) {
1541    PrintExpr(Node->getBase());
1542    OS << (Node->isArrow() ? "->" : ".");
1543  }
1544  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1545    Qualifier->print(OS, Policy);
1546  if (Node->hasTemplateKeyword())
1547    OS << "template ";
1548  OS << Node->getMemberNameInfo();
1549  if (Node->hasExplicitTemplateArgs()) {
1550    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1551                                                    Node->getTemplateArgs(),
1552                                                    Node->getNumTemplateArgs(),
1553                                                    Policy);
1554  }
1555}
1556
1557static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1558  switch (UTT) {
1559  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1560  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1561  case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1562  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1563  case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1564  case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1565  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1566  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1567  case UTT_IsAbstract:            return "__is_abstract";
1568  case UTT_IsArithmetic:            return "__is_arithmetic";
1569  case UTT_IsArray:                 return "__is_array";
1570  case UTT_IsClass:               return "__is_class";
1571  case UTT_IsCompleteType:          return "__is_complete_type";
1572  case UTT_IsCompound:              return "__is_compound";
1573  case UTT_IsConst:                 return "__is_const";
1574  case UTT_IsEmpty:               return "__is_empty";
1575  case UTT_IsEnum:                return "__is_enum";
1576  case UTT_IsFinal:                 return "__is_final";
1577  case UTT_IsFloatingPoint:         return "__is_floating_point";
1578  case UTT_IsFunction:              return "__is_function";
1579  case UTT_IsFundamental:           return "__is_fundamental";
1580  case UTT_IsIntegral:              return "__is_integral";
1581  case UTT_IsInterfaceClass:        return "__is_interface_class";
1582  case UTT_IsLiteral:               return "__is_literal";
1583  case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1584  case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1585  case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1586  case UTT_IsMemberPointer:         return "__is_member_pointer";
1587  case UTT_IsObject:                return "__is_object";
1588  case UTT_IsPOD:                 return "__is_pod";
1589  case UTT_IsPointer:               return "__is_pointer";
1590  case UTT_IsPolymorphic:         return "__is_polymorphic";
1591  case UTT_IsReference:             return "__is_reference";
1592  case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1593  case UTT_IsScalar:                return "__is_scalar";
1594  case UTT_IsSigned:                return "__is_signed";
1595  case UTT_IsStandardLayout:        return "__is_standard_layout";
1596  case UTT_IsTrivial:               return "__is_trivial";
1597  case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1598  case UTT_IsUnion:               return "__is_union";
1599  case UTT_IsUnsigned:              return "__is_unsigned";
1600  case UTT_IsVoid:                  return "__is_void";
1601  case UTT_IsVolatile:              return "__is_volatile";
1602  }
1603  llvm_unreachable("Type trait not covered by switch statement");
1604}
1605
1606static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1607  switch (BTT) {
1608  case BTT_IsBaseOf:              return "__is_base_of";
1609  case BTT_IsConvertible:         return "__is_convertible";
1610  case BTT_IsSame:                return "__is_same";
1611  case BTT_TypeCompatible:        return "__builtin_types_compatible_p";
1612  case BTT_IsConvertibleTo:       return "__is_convertible_to";
1613  case BTT_IsTriviallyAssignable: return "__is_trivially_assignable";
1614  }
1615  llvm_unreachable("Binary type trait not covered by switch");
1616}
1617
1618static const char *getTypeTraitName(TypeTrait TT) {
1619  switch (TT) {
1620  case clang::TT_IsTriviallyConstructible:return "__is_trivially_constructible";
1621  }
1622  llvm_unreachable("Type trait not covered by switch");
1623}
1624
1625static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1626  switch (ATT) {
1627  case ATT_ArrayRank:        return "__array_rank";
1628  case ATT_ArrayExtent:      return "__array_extent";
1629  }
1630  llvm_unreachable("Array type trait not covered by switch");
1631}
1632
1633static const char *getExpressionTraitName(ExpressionTrait ET) {
1634  switch (ET) {
1635  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1636  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1637  }
1638  llvm_unreachable("Expression type trait not covered by switch");
1639}
1640
1641void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1642  OS << getTypeTraitName(E->getTrait()) << "("
1643     << E->getQueriedType().getAsString(Policy) << ")";
1644}
1645
1646void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1647  OS << getTypeTraitName(E->getTrait()) << "("
1648     << E->getLhsType().getAsString(Policy) << ","
1649     << E->getRhsType().getAsString(Policy) << ")";
1650}
1651
1652void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
1653  OS << getTypeTraitName(E->getTrait()) << "(";
1654  for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
1655    if (I > 0)
1656      OS << ", ";
1657    OS << E->getArg(I)->getType().getAsString(Policy);
1658  }
1659  OS << ")";
1660}
1661
1662void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1663  OS << getTypeTraitName(E->getTrait()) << "("
1664     << E->getQueriedType().getAsString(Policy) << ")";
1665}
1666
1667void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1668    OS << getExpressionTraitName(E->getTrait()) << "(";
1669    PrintExpr(E->getQueriedExpression());
1670    OS << ")";
1671}
1672
1673void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1674  OS << "noexcept(";
1675  PrintExpr(E->getOperand());
1676  OS << ")";
1677}
1678
1679void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1680  PrintExpr(E->getPattern());
1681  OS << "...";
1682}
1683
1684void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1685  OS << "sizeof...(" << *E->getPack() << ")";
1686}
1687
1688void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1689                                       SubstNonTypeTemplateParmPackExpr *Node) {
1690  OS << *Node->getParameterPack();
1691}
1692
1693void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1694                                       SubstNonTypeTemplateParmExpr *Node) {
1695  Visit(Node->getReplacement());
1696}
1697
1698void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
1699  OS << *E->getParameterPack();
1700}
1701
1702void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1703  PrintExpr(Node->GetTemporaryExpr());
1704}
1705
1706// Obj-C
1707
1708void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1709  OS << "@";
1710  VisitStringLiteral(Node->getString());
1711}
1712
1713void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1714  OS << "@";
1715  Visit(E->getSubExpr());
1716}
1717
1718void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1719  OS << "@[ ";
1720  StmtRange ch = E->children();
1721  if (ch.first != ch.second) {
1722    while (1) {
1723      Visit(*ch.first);
1724      ++ch.first;
1725      if (ch.first == ch.second) break;
1726      OS << ", ";
1727    }
1728  }
1729  OS << " ]";
1730}
1731
1732void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1733  OS << "@{ ";
1734  for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
1735    if (I > 0)
1736      OS << ", ";
1737
1738    ObjCDictionaryElement Element = E->getKeyValueElement(I);
1739    Visit(Element.Key);
1740    OS << " : ";
1741    Visit(Element.Value);
1742    if (Element.isPackExpansion())
1743      OS << "...";
1744  }
1745  OS << " }";
1746}
1747
1748void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1749  OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1750}
1751
1752void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1753  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1754}
1755
1756void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1757  OS << "@protocol(" << *Node->getProtocol() << ')';
1758}
1759
1760void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1761  OS << "[";
1762  switch (Mess->getReceiverKind()) {
1763  case ObjCMessageExpr::Instance:
1764    PrintExpr(Mess->getInstanceReceiver());
1765    break;
1766
1767  case ObjCMessageExpr::Class:
1768    OS << Mess->getClassReceiver().getAsString(Policy);
1769    break;
1770
1771  case ObjCMessageExpr::SuperInstance:
1772  case ObjCMessageExpr::SuperClass:
1773    OS << "Super";
1774    break;
1775  }
1776
1777  OS << ' ';
1778  Selector selector = Mess->getSelector();
1779  if (selector.isUnarySelector()) {
1780    OS << selector.getNameForSlot(0);
1781  } else {
1782    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1783      if (i < selector.getNumArgs()) {
1784        if (i > 0) OS << ' ';
1785        if (selector.getIdentifierInfoForSlot(i))
1786          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1787        else
1788           OS << ":";
1789      }
1790      else OS << ", "; // Handle variadic methods.
1791
1792      PrintExpr(Mess->getArg(i));
1793    }
1794  }
1795  OS << "]";
1796}
1797
1798void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
1799  OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
1800}
1801
1802void
1803StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1804  PrintExpr(E->getSubExpr());
1805}
1806
1807void
1808StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1809  OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1810     << ")";
1811  PrintExpr(E->getSubExpr());
1812}
1813
1814void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1815  BlockDecl *BD = Node->getBlockDecl();
1816  OS << "^";
1817
1818  const FunctionType *AFT = Node->getFunctionType();
1819
1820  if (isa<FunctionNoProtoType>(AFT)) {
1821    OS << "()";
1822  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1823    OS << '(';
1824    std::string ParamStr;
1825    for (BlockDecl::param_iterator AI = BD->param_begin(),
1826         E = BD->param_end(); AI != E; ++AI) {
1827      if (AI != BD->param_begin()) OS << ", ";
1828      ParamStr = (*AI)->getNameAsString();
1829      (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1830      OS << ParamStr;
1831    }
1832
1833    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1834    if (FT->isVariadic()) {
1835      if (!BD->param_empty()) OS << ", ";
1836      OS << "...";
1837    }
1838    OS << ')';
1839  }
1840}
1841
1842void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
1843  PrintExpr(Node->getSourceExpr());
1844}
1845
1846void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1847  OS << "__builtin_astype(";
1848  PrintExpr(Node->getSrcExpr());
1849  OS << ", " << Node->getType().getAsString();
1850  OS << ")";
1851}
1852
1853//===----------------------------------------------------------------------===//
1854// Stmt method implementations
1855//===----------------------------------------------------------------------===//
1856
1857void Stmt::dumpPretty(ASTContext &Context) const {
1858  printPretty(llvm::errs(), 0, PrintingPolicy(Context.getLangOpts()));
1859}
1860
1861void Stmt::printPretty(raw_ostream &OS,
1862                       PrinterHelper *Helper,
1863                       const PrintingPolicy &Policy,
1864                       unsigned Indentation) const {
1865  if (this == 0) {
1866    OS << "<NULL>";
1867    return;
1868  }
1869
1870  if (Policy.DumpSourceManager) {
1871    dump(OS, *Policy.DumpSourceManager);
1872    return;
1873  }
1874
1875  StmtPrinter P(OS, Helper, Policy, Indentation);
1876  P.Visit(const_cast<Stmt*>(this));
1877}
1878
1879//===----------------------------------------------------------------------===//
1880// PrinterHelper
1881//===----------------------------------------------------------------------===//
1882
1883// Implement virtual destructor.
1884PrinterHelper::~PrinterHelper() {}
1885