StmtPrinter.cpp revision a0a3c90abde4b52b96ce70bd062d81041092900c
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_Call) {
1134    PrintExpr(Node->getArg(0));
1135    OS << '(';
1136    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1137      if (ArgIdx > 1)
1138        OS << ", ";
1139      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1140        PrintExpr(Node->getArg(ArgIdx));
1141    }
1142    OS << ')';
1143  } else if (Kind == OO_Subscript) {
1144    PrintExpr(Node->getArg(0));
1145    OS << '[';
1146    PrintExpr(Node->getArg(1));
1147    OS << ']';
1148  } else if (Node->getNumArgs() == 1) {
1149    OS << OpStrings[Kind] << ' ';
1150    PrintExpr(Node->getArg(0));
1151  } else if (Node->getNumArgs() == 2) {
1152    PrintExpr(Node->getArg(0));
1153    OS << ' ' << OpStrings[Kind] << ' ';
1154    PrintExpr(Node->getArg(1));
1155  } else {
1156    llvm_unreachable("unknown overloaded operator");
1157  }
1158}
1159
1160void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1161  VisitCallExpr(cast<CallExpr>(Node));
1162}
1163
1164void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1165  PrintExpr(Node->getCallee());
1166  OS << "<<<";
1167  PrintCallArgs(Node->getConfig());
1168  OS << ">>>(";
1169  PrintCallArgs(Node);
1170  OS << ")";
1171}
1172
1173void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1174  OS << Node->getCastName() << '<';
1175  OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1176  PrintExpr(Node->getSubExpr());
1177  OS << ")";
1178}
1179
1180void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1181  VisitCXXNamedCastExpr(Node);
1182}
1183
1184void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1185  VisitCXXNamedCastExpr(Node);
1186}
1187
1188void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1189  VisitCXXNamedCastExpr(Node);
1190}
1191
1192void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1193  VisitCXXNamedCastExpr(Node);
1194}
1195
1196void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1197  OS << "typeid(";
1198  if (Node->isTypeOperand()) {
1199    OS << Node->getTypeOperand().getAsString(Policy);
1200  } else {
1201    PrintExpr(Node->getExprOperand());
1202  }
1203  OS << ")";
1204}
1205
1206void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1207  OS << "__uuidof(";
1208  if (Node->isTypeOperand()) {
1209    OS << Node->getTypeOperand().getAsString(Policy);
1210  } else {
1211    PrintExpr(Node->getExprOperand());
1212  }
1213  OS << ")";
1214}
1215
1216void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1217  switch (Node->getLiteralOperatorKind()) {
1218  case UserDefinedLiteral::LOK_Raw:
1219    OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1220    break;
1221  case UserDefinedLiteral::LOK_Template: {
1222    DeclRefExpr *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1223    const TemplateArgumentList *Args =
1224      cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1225    assert(Args);
1226    const TemplateArgument &Pack = Args->get(0);
1227    for (TemplateArgument::pack_iterator I = Pack.pack_begin(),
1228                                         E = Pack.pack_end(); I != E; ++I) {
1229      char C = (char)I->getAsIntegral().getZExtValue();
1230      OS << C;
1231    }
1232    break;
1233  }
1234  case UserDefinedLiteral::LOK_Integer: {
1235    // Print integer literal without suffix.
1236    IntegerLiteral *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1237    OS << Int->getValue().toString(10, /*isSigned*/false);
1238    break;
1239  }
1240  case UserDefinedLiteral::LOK_Floating: {
1241    // Print floating literal without suffix.
1242    FloatingLiteral *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1243    PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1244    break;
1245  }
1246  case UserDefinedLiteral::LOK_String:
1247  case UserDefinedLiteral::LOK_Character:
1248    PrintExpr(Node->getCookedLiteral());
1249    break;
1250  }
1251  OS << Node->getUDSuffix()->getName();
1252}
1253
1254void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1255  OS << (Node->getValue() ? "true" : "false");
1256}
1257
1258void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1259  OS << "nullptr";
1260}
1261
1262void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1263  OS << "this";
1264}
1265
1266void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1267  if (Node->getSubExpr() == 0)
1268    OS << "throw";
1269  else {
1270    OS << "throw ";
1271    PrintExpr(Node->getSubExpr());
1272  }
1273}
1274
1275void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1276  // Nothing to print: we picked up the default argument
1277}
1278
1279void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1280  OS << Node->getType().getAsString(Policy);
1281  OS << "(";
1282  PrintExpr(Node->getSubExpr());
1283  OS << ")";
1284}
1285
1286void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1287  PrintExpr(Node->getSubExpr());
1288}
1289
1290void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1291  OS << Node->getType().getAsString(Policy);
1292  OS << "(";
1293  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1294                                         ArgEnd = Node->arg_end();
1295       Arg != ArgEnd; ++Arg) {
1296    if (Arg != Node->arg_begin())
1297      OS << ", ";
1298    PrintExpr(*Arg);
1299  }
1300  OS << ")";
1301}
1302
1303void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1304  OS << '[';
1305  bool NeedComma = false;
1306  switch (Node->getCaptureDefault()) {
1307  case LCD_None:
1308    break;
1309
1310  case LCD_ByCopy:
1311    OS << '=';
1312    NeedComma = true;
1313    break;
1314
1315  case LCD_ByRef:
1316    OS << '&';
1317    NeedComma = true;
1318    break;
1319  }
1320  for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1321                                 CEnd = Node->explicit_capture_end();
1322       C != CEnd;
1323       ++C) {
1324    if (NeedComma)
1325      OS << ", ";
1326    NeedComma = true;
1327
1328    switch (C->getCaptureKind()) {
1329    case LCK_This:
1330      OS << "this";
1331      break;
1332
1333    case LCK_ByRef:
1334      if (Node->getCaptureDefault() != LCD_ByRef)
1335        OS << '&';
1336      OS << C->getCapturedVar()->getName();
1337      break;
1338
1339    case LCK_ByCopy:
1340      if (Node->getCaptureDefault() != LCD_ByCopy)
1341        OS << '=';
1342      OS << C->getCapturedVar()->getName();
1343      break;
1344    }
1345  }
1346  OS << ']';
1347
1348  if (Node->hasExplicitParameters()) {
1349    OS << " (";
1350    CXXMethodDecl *Method = Node->getCallOperator();
1351    NeedComma = false;
1352    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
1353                                    PEnd = Method->param_end();
1354         P != PEnd; ++P) {
1355      if (NeedComma) {
1356        OS << ", ";
1357      } else {
1358        NeedComma = true;
1359      }
1360      std::string ParamStr = (*P)->getNameAsString();
1361      (*P)->getOriginalType().getAsStringInternal(ParamStr, Policy);
1362      OS << ParamStr;
1363    }
1364    if (Method->isVariadic()) {
1365      if (NeedComma)
1366        OS << ", ";
1367      OS << "...";
1368    }
1369    OS << ')';
1370
1371    if (Node->isMutable())
1372      OS << " mutable";
1373
1374    const FunctionProtoType *Proto
1375      = Method->getType()->getAs<FunctionProtoType>();
1376    {
1377      std::string ExceptionSpec;
1378      Proto->printExceptionSpecification(ExceptionSpec, Policy);
1379      OS << ExceptionSpec;
1380    }
1381
1382    // FIXME: Attributes
1383
1384    // Print the trailing return type if it was specified in the source.
1385    if (Node->hasExplicitResultType())
1386      OS << " -> " << Proto->getResultType().getAsString(Policy);
1387  }
1388
1389  // Print the body.
1390  CompoundStmt *Body = Node->getBody();
1391  OS << ' ';
1392  PrintStmt(Body);
1393}
1394
1395void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1396  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1397    OS << TSInfo->getType().getAsString(Policy) << "()";
1398  else
1399    OS << Node->getType().getAsString(Policy) << "()";
1400}
1401
1402void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1403  if (E->isGlobalNew())
1404    OS << "::";
1405  OS << "new ";
1406  unsigned NumPlace = E->getNumPlacementArgs();
1407  if (NumPlace > 0) {
1408    OS << "(";
1409    PrintExpr(E->getPlacementArg(0));
1410    for (unsigned i = 1; i < NumPlace; ++i) {
1411      OS << ", ";
1412      PrintExpr(E->getPlacementArg(i));
1413    }
1414    OS << ") ";
1415  }
1416  if (E->isParenTypeId())
1417    OS << "(";
1418  std::string TypeS;
1419  if (Expr *Size = E->getArraySize()) {
1420    llvm::raw_string_ostream s(TypeS);
1421    Size->printPretty(s, Helper, Policy);
1422    s.flush();
1423    TypeS = "[" + TypeS + "]";
1424  }
1425  E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1426  OS << TypeS;
1427  if (E->isParenTypeId())
1428    OS << ")";
1429
1430  CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
1431  if (InitStyle) {
1432    if (InitStyle == CXXNewExpr::CallInit)
1433      OS << "(";
1434    PrintExpr(E->getInitializer());
1435    if (InitStyle == CXXNewExpr::CallInit)
1436      OS << ")";
1437  }
1438}
1439
1440void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1441  if (E->isGlobalDelete())
1442    OS << "::";
1443  OS << "delete ";
1444  if (E->isArrayForm())
1445    OS << "[] ";
1446  PrintExpr(E->getArgument());
1447}
1448
1449void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1450  PrintExpr(E->getBase());
1451  if (E->isArrow())
1452    OS << "->";
1453  else
1454    OS << '.';
1455  if (E->getQualifier())
1456    E->getQualifier()->print(OS, Policy);
1457
1458  std::string TypeS;
1459  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1460    OS << II->getName();
1461  else
1462    E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1463  OS << TypeS;
1464}
1465
1466void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1467  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1468    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1469      // Don't print any defaulted arguments
1470      break;
1471    }
1472
1473    if (i) OS << ", ";
1474    PrintExpr(E->getArg(i));
1475  }
1476}
1477
1478void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1479  // Just forward to the sub expression.
1480  PrintExpr(E->getSubExpr());
1481}
1482
1483void
1484StmtPrinter::VisitCXXUnresolvedConstructExpr(
1485                                           CXXUnresolvedConstructExpr *Node) {
1486  OS << Node->getTypeAsWritten().getAsString(Policy);
1487  OS << "(";
1488  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1489                                             ArgEnd = Node->arg_end();
1490       Arg != ArgEnd; ++Arg) {
1491    if (Arg != Node->arg_begin())
1492      OS << ", ";
1493    PrintExpr(*Arg);
1494  }
1495  OS << ")";
1496}
1497
1498void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1499                                         CXXDependentScopeMemberExpr *Node) {
1500  if (!Node->isImplicitAccess()) {
1501    PrintExpr(Node->getBase());
1502    OS << (Node->isArrow() ? "->" : ".");
1503  }
1504  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1505    Qualifier->print(OS, Policy);
1506  if (Node->hasTemplateKeyword())
1507    OS << "template ";
1508  OS << Node->getMemberNameInfo();
1509  if (Node->hasExplicitTemplateArgs()) {
1510    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1511                                                    Node->getTemplateArgs(),
1512                                                    Node->getNumTemplateArgs(),
1513                                                    Policy);
1514  }
1515}
1516
1517void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1518  if (!Node->isImplicitAccess()) {
1519    PrintExpr(Node->getBase());
1520    OS << (Node->isArrow() ? "->" : ".");
1521  }
1522  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1523    Qualifier->print(OS, Policy);
1524  if (Node->hasTemplateKeyword())
1525    OS << "template ";
1526  OS << Node->getMemberNameInfo();
1527  if (Node->hasExplicitTemplateArgs()) {
1528    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1529                                                    Node->getTemplateArgs(),
1530                                                    Node->getNumTemplateArgs(),
1531                                                    Policy);
1532  }
1533}
1534
1535static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1536  switch (UTT) {
1537  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1538  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1539  case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1540  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1541  case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1542  case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1543  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1544  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1545  case UTT_IsAbstract:            return "__is_abstract";
1546  case UTT_IsArithmetic:            return "__is_arithmetic";
1547  case UTT_IsArray:                 return "__is_array";
1548  case UTT_IsClass:               return "__is_class";
1549  case UTT_IsCompleteType:          return "__is_complete_type";
1550  case UTT_IsCompound:              return "__is_compound";
1551  case UTT_IsConst:                 return "__is_const";
1552  case UTT_IsEmpty:               return "__is_empty";
1553  case UTT_IsEnum:                return "__is_enum";
1554  case UTT_IsFinal:                 return "__is_final";
1555  case UTT_IsFloatingPoint:         return "__is_floating_point";
1556  case UTT_IsFunction:              return "__is_function";
1557  case UTT_IsFundamental:           return "__is_fundamental";
1558  case UTT_IsIntegral:              return "__is_integral";
1559  case UTT_IsLiteral:               return "__is_literal";
1560  case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1561  case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1562  case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1563  case UTT_IsMemberPointer:         return "__is_member_pointer";
1564  case UTT_IsObject:                return "__is_object";
1565  case UTT_IsPOD:                 return "__is_pod";
1566  case UTT_IsPointer:               return "__is_pointer";
1567  case UTT_IsPolymorphic:         return "__is_polymorphic";
1568  case UTT_IsReference:             return "__is_reference";
1569  case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1570  case UTT_IsScalar:                return "__is_scalar";
1571  case UTT_IsSigned:                return "__is_signed";
1572  case UTT_IsStandardLayout:        return "__is_standard_layout";
1573  case UTT_IsTrivial:               return "__is_trivial";
1574  case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1575  case UTT_IsUnion:               return "__is_union";
1576  case UTT_IsUnsigned:              return "__is_unsigned";
1577  case UTT_IsVoid:                  return "__is_void";
1578  case UTT_IsVolatile:              return "__is_volatile";
1579  }
1580  llvm_unreachable("Type trait not covered by switch statement");
1581}
1582
1583static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1584  switch (BTT) {
1585  case BTT_IsBaseOf:              return "__is_base_of";
1586  case BTT_IsConvertible:         return "__is_convertible";
1587  case BTT_IsSame:                return "__is_same";
1588  case BTT_TypeCompatible:        return "__builtin_types_compatible_p";
1589  case BTT_IsConvertibleTo:       return "__is_convertible_to";
1590  case BTT_IsTriviallyAssignable: return "__is_trivially_assignable";
1591  }
1592  llvm_unreachable("Binary type trait not covered by switch");
1593}
1594
1595static const char *getTypeTraitName(TypeTrait TT) {
1596  switch (TT) {
1597  case clang::TT_IsTriviallyConstructible:return "__is_trivially_constructible";
1598  }
1599  llvm_unreachable("Type trait not covered by switch");
1600}
1601
1602static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1603  switch (ATT) {
1604  case ATT_ArrayRank:        return "__array_rank";
1605  case ATT_ArrayExtent:      return "__array_extent";
1606  }
1607  llvm_unreachable("Array type trait not covered by switch");
1608}
1609
1610static const char *getExpressionTraitName(ExpressionTrait ET) {
1611  switch (ET) {
1612  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1613  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1614  }
1615  llvm_unreachable("Expression type trait not covered by switch");
1616}
1617
1618void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1619  OS << getTypeTraitName(E->getTrait()) << "("
1620     << E->getQueriedType().getAsString(Policy) << ")";
1621}
1622
1623void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1624  OS << getTypeTraitName(E->getTrait()) << "("
1625     << E->getLhsType().getAsString(Policy) << ","
1626     << E->getRhsType().getAsString(Policy) << ")";
1627}
1628
1629void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
1630  OS << getTypeTraitName(E->getTrait()) << "(";
1631  for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
1632    if (I > 0)
1633      OS << ", ";
1634    OS << E->getArg(I)->getType().getAsString(Policy);
1635  }
1636  OS << ")";
1637}
1638
1639void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1640  OS << getTypeTraitName(E->getTrait()) << "("
1641     << E->getQueriedType().getAsString(Policy) << ")";
1642}
1643
1644void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1645    OS << getExpressionTraitName(E->getTrait()) << "(";
1646    PrintExpr(E->getQueriedExpression());
1647    OS << ")";
1648}
1649
1650void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1651  OS << "noexcept(";
1652  PrintExpr(E->getOperand());
1653  OS << ")";
1654}
1655
1656void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1657  PrintExpr(E->getPattern());
1658  OS << "...";
1659}
1660
1661void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1662  OS << "sizeof...(" << *E->getPack() << ")";
1663}
1664
1665void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1666                                       SubstNonTypeTemplateParmPackExpr *Node) {
1667  OS << *Node->getParameterPack();
1668}
1669
1670void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1671                                       SubstNonTypeTemplateParmExpr *Node) {
1672  Visit(Node->getReplacement());
1673}
1674
1675void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
1676  OS << *E->getParameterPack();
1677}
1678
1679void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1680  PrintExpr(Node->GetTemporaryExpr());
1681}
1682
1683// Obj-C
1684
1685void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1686  OS << "@";
1687  VisitStringLiteral(Node->getString());
1688}
1689
1690void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1691  OS << "@";
1692  Visit(E->getSubExpr());
1693}
1694
1695void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1696  OS << "@[ ";
1697  StmtRange ch = E->children();
1698  if (ch.first != ch.second) {
1699    while (1) {
1700      Visit(*ch.first);
1701      ++ch.first;
1702      if (ch.first == ch.second) break;
1703      OS << ", ";
1704    }
1705  }
1706  OS << " ]";
1707}
1708
1709void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1710  OS << "@{ ";
1711  for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
1712    if (I > 0)
1713      OS << ", ";
1714
1715    ObjCDictionaryElement Element = E->getKeyValueElement(I);
1716    Visit(Element.Key);
1717    OS << " : ";
1718    Visit(Element.Value);
1719    if (Element.isPackExpansion())
1720      OS << "...";
1721  }
1722  OS << " }";
1723}
1724
1725void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1726  OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1727}
1728
1729void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1730  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1731}
1732
1733void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1734  OS << "@protocol(" << *Node->getProtocol() << ')';
1735}
1736
1737void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1738  OS << "[";
1739  switch (Mess->getReceiverKind()) {
1740  case ObjCMessageExpr::Instance:
1741    PrintExpr(Mess->getInstanceReceiver());
1742    break;
1743
1744  case ObjCMessageExpr::Class:
1745    OS << Mess->getClassReceiver().getAsString(Policy);
1746    break;
1747
1748  case ObjCMessageExpr::SuperInstance:
1749  case ObjCMessageExpr::SuperClass:
1750    OS << "Super";
1751    break;
1752  }
1753
1754  OS << ' ';
1755  Selector selector = Mess->getSelector();
1756  if (selector.isUnarySelector()) {
1757    OS << selector.getNameForSlot(0);
1758  } else {
1759    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1760      if (i < selector.getNumArgs()) {
1761        if (i > 0) OS << ' ';
1762        if (selector.getIdentifierInfoForSlot(i))
1763          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1764        else
1765           OS << ":";
1766      }
1767      else OS << ", "; // Handle variadic methods.
1768
1769      PrintExpr(Mess->getArg(i));
1770    }
1771  }
1772  OS << "]";
1773}
1774
1775void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
1776  OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
1777}
1778
1779void
1780StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1781  PrintExpr(E->getSubExpr());
1782}
1783
1784void
1785StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1786  OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1787     << ")";
1788  PrintExpr(E->getSubExpr());
1789}
1790
1791void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1792  BlockDecl *BD = Node->getBlockDecl();
1793  OS << "^";
1794
1795  const FunctionType *AFT = Node->getFunctionType();
1796
1797  if (isa<FunctionNoProtoType>(AFT)) {
1798    OS << "()";
1799  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1800    OS << '(';
1801    std::string ParamStr;
1802    for (BlockDecl::param_iterator AI = BD->param_begin(),
1803         E = BD->param_end(); AI != E; ++AI) {
1804      if (AI != BD->param_begin()) OS << ", ";
1805      ParamStr = (*AI)->getNameAsString();
1806      (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1807      OS << ParamStr;
1808    }
1809
1810    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1811    if (FT->isVariadic()) {
1812      if (!BD->param_empty()) OS << ", ";
1813      OS << "...";
1814    }
1815    OS << ')';
1816  }
1817}
1818
1819void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
1820  PrintExpr(Node->getSourceExpr());
1821}
1822
1823void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1824  OS << "__builtin_astype(";
1825  PrintExpr(Node->getSrcExpr());
1826  OS << ", " << Node->getType().getAsString();
1827  OS << ")";
1828}
1829
1830//===----------------------------------------------------------------------===//
1831// Stmt method implementations
1832//===----------------------------------------------------------------------===//
1833
1834void Stmt::dumpPretty(ASTContext &Context) const {
1835  printPretty(llvm::errs(), 0, PrintingPolicy(Context.getLangOpts()));
1836}
1837
1838void Stmt::printPretty(raw_ostream &OS,
1839                       PrinterHelper *Helper,
1840                       const PrintingPolicy &Policy,
1841                       unsigned Indentation) const {
1842  if (this == 0) {
1843    OS << "<NULL>";
1844    return;
1845  }
1846
1847  if (Policy.DumpSourceManager) {
1848    dump(OS, *Policy.DumpSourceManager);
1849    return;
1850  }
1851
1852  StmtPrinter P(OS, Helper, Policy, Indentation);
1853  P.Visit(const_cast<Stmt*>(this));
1854}
1855
1856//===----------------------------------------------------------------------===//
1857// PrinterHelper
1858//===----------------------------------------------------------------------===//
1859
1860// Implement virtual destructor.
1861PrinterHelper::~PrinterHelper() {}
1862