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