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