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