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