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