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