StmtPrinter.cpp revision 61eee0ca33b29e102f11bab77c8b74cc00e2392b
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 "llvm/Support/Format.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// StmtPrinter Visitor
27//===----------------------------------------------------------------------===//
28
29namespace  {
30  class StmtPrinter : public StmtVisitor<StmtPrinter> {
31    llvm::raw_ostream &OS;
32    ASTContext &Context;
33    unsigned IndentLevel;
34    clang::PrinterHelper* Helper;
35    PrintingPolicy Policy;
36
37  public:
38    StmtPrinter(llvm::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    llvm::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  llvm::SmallVector<Decl*, 2> Decls;
128  for ( ; Begin != End; ++Begin)
129    Decls.push_back(*Begin);
130
131  Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
132}
133
134void StmtPrinter::VisitNullStmt(NullStmt *Node) {
135  Indent() << ";\n";
136}
137
138void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
139  Indent();
140  PrintRawDeclStmt(Node);
141  OS << ";\n";
142}
143
144void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
145  Indent();
146  PrintRawCompoundStmt(Node);
147  OS << "\n";
148}
149
150void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
151  Indent(-1) << "case ";
152  PrintExpr(Node->getLHS());
153  if (Node->getRHS()) {
154    OS << " ... ";
155    PrintExpr(Node->getRHS());
156  }
157  OS << ":\n";
158
159  PrintStmt(Node->getSubStmt(), 0);
160}
161
162void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
163  Indent(-1) << "default:\n";
164  PrintStmt(Node->getSubStmt(), 0);
165}
166
167void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
168  Indent(-1) << Node->getName() << ":\n";
169  PrintStmt(Node->getSubStmt(), 0);
170}
171
172void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
173  OS << "if (";
174  PrintExpr(If->getCond());
175  OS << ')';
176
177  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
178    OS << ' ';
179    PrintRawCompoundStmt(CS);
180    OS << (If->getElse() ? ' ' : '\n');
181  } else {
182    OS << '\n';
183    PrintStmt(If->getThen());
184    if (If->getElse()) Indent();
185  }
186
187  if (Stmt *Else = If->getElse()) {
188    OS << "else";
189
190    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
191      OS << ' ';
192      PrintRawCompoundStmt(CS);
193      OS << '\n';
194    } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
195      OS << ' ';
196      PrintRawIfStmt(ElseIf);
197    } else {
198      OS << '\n';
199      PrintStmt(If->getElse());
200    }
201  }
202}
203
204void StmtPrinter::VisitIfStmt(IfStmt *If) {
205  Indent();
206  PrintRawIfStmt(If);
207}
208
209void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
210  Indent() << "switch (";
211  PrintExpr(Node->getCond());
212  OS << ")";
213
214  // Pretty print compoundstmt bodies (very common).
215  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
216    OS << " ";
217    PrintRawCompoundStmt(CS);
218    OS << "\n";
219  } else {
220    OS << "\n";
221    PrintStmt(Node->getBody());
222  }
223}
224
225void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
226  Indent() << "while (";
227  PrintExpr(Node->getCond());
228  OS << ")\n";
229  PrintStmt(Node->getBody());
230}
231
232void StmtPrinter::VisitDoStmt(DoStmt *Node) {
233  Indent() << "do ";
234  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
235    PrintRawCompoundStmt(CS);
236    OS << " ";
237  } else {
238    OS << "\n";
239    PrintStmt(Node->getBody());
240    Indent();
241  }
242
243  OS << "while (";
244  PrintExpr(Node->getCond());
245  OS << ");\n";
246}
247
248void StmtPrinter::VisitForStmt(ForStmt *Node) {
249  Indent() << "for (";
250  if (Node->getInit()) {
251    if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getInit()))
252      PrintRawDeclStmt(DS);
253    else
254      PrintExpr(cast<Expr>(Node->getInit()));
255  }
256  OS << ";";
257  if (Node->getCond()) {
258    OS << " ";
259    PrintExpr(Node->getCond());
260  }
261  OS << ";";
262  if (Node->getInc()) {
263    OS << " ";
264    PrintExpr(Node->getInc());
265  }
266  OS << ") ";
267
268  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
269    PrintRawCompoundStmt(CS);
270    OS << "\n";
271  } else {
272    OS << "\n";
273    PrintStmt(Node->getBody());
274  }
275}
276
277void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
278  Indent() << "for (";
279  if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getElement()))
280    PrintRawDeclStmt(DS);
281  else
282    PrintExpr(cast<Expr>(Node->getElement()));
283  OS << " in ";
284  PrintExpr(Node->getCollection());
285  OS << ") ";
286
287  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
288    PrintRawCompoundStmt(CS);
289    OS << "\n";
290  } else {
291    OS << "\n";
292    PrintStmt(Node->getBody());
293  }
294}
295
296void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
297  Indent() << "for (";
298  PrintingPolicy SubPolicy(Policy);
299  SubPolicy.SuppressInitializers = true;
300  Node->getLoopVariable()->print(OS, SubPolicy, IndentLevel);
301  OS << " : ";
302  PrintExpr(Node->getRangeInit());
303  OS << ") {\n";
304  PrintStmt(Node->getBody());
305  Indent() << "}\n";
306}
307
308void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
309  Indent() << "goto " << Node->getLabel()->getName() << ";\n";
310}
311
312void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
313  Indent() << "goto *";
314  PrintExpr(Node->getTarget());
315  OS << ";\n";
316}
317
318void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
319  Indent() << "continue;\n";
320}
321
322void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
323  Indent() << "break;\n";
324}
325
326
327void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
328  Indent() << "return";
329  if (Node->getRetValue()) {
330    OS << " ";
331    PrintExpr(Node->getRetValue());
332  }
333  OS << ";\n";
334}
335
336
337void StmtPrinter::VisitAsmStmt(AsmStmt *Node) {
338  Indent() << "asm ";
339
340  if (Node->isVolatile())
341    OS << "volatile ";
342
343  OS << "(";
344  VisitStringLiteral(Node->getAsmString());
345
346  // Outputs
347  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
348      Node->getNumClobbers() != 0)
349    OS << " : ";
350
351  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
352    if (i != 0)
353      OS << ", ";
354
355    if (!Node->getOutputName(i).empty()) {
356      OS << '[';
357      OS << Node->getOutputName(i);
358      OS << "] ";
359    }
360
361    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
362    OS << " ";
363    Visit(Node->getOutputExpr(i));
364  }
365
366  // Inputs
367  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
368    OS << " : ";
369
370  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
371    if (i != 0)
372      OS << ", ";
373
374    if (!Node->getInputName(i).empty()) {
375      OS << '[';
376      OS << Node->getInputName(i);
377      OS << "] ";
378    }
379
380    VisitStringLiteral(Node->getInputConstraintLiteral(i));
381    OS << " ";
382    Visit(Node->getInputExpr(i));
383  }
384
385  // Clobbers
386  if (Node->getNumClobbers() != 0)
387    OS << " : ";
388
389  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
390    if (i != 0)
391      OS << ", ";
392
393    VisitStringLiteral(Node->getClobber(i));
394  }
395
396  OS << ");\n";
397}
398
399void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
400  Indent() << "@try";
401  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
402    PrintRawCompoundStmt(TS);
403    OS << "\n";
404  }
405
406  for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
407    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
408    Indent() << "@catch(";
409    if (catchStmt->getCatchParamDecl()) {
410      if (Decl *DS = catchStmt->getCatchParamDecl())
411        PrintRawDecl(DS);
412    }
413    OS << ")";
414    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
415      PrintRawCompoundStmt(CS);
416      OS << "\n";
417    }
418  }
419
420  if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
421        Node->getFinallyStmt())) {
422    Indent() << "@finally";
423    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
424    OS << "\n";
425  }
426}
427
428void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
429}
430
431void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
432  Indent() << "@catch (...) { /* todo */ } \n";
433}
434
435void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
436  Indent() << "@throw";
437  if (Node->getThrowExpr()) {
438    OS << " ";
439    PrintExpr(Node->getThrowExpr());
440  }
441  OS << ";\n";
442}
443
444void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
445  Indent() << "@synchronized (";
446  PrintExpr(Node->getSynchExpr());
447  OS << ")";
448  PrintRawCompoundStmt(Node->getSynchBody());
449  OS << "\n";
450}
451
452void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
453  OS << "catch (";
454  if (Decl *ExDecl = Node->getExceptionDecl())
455    PrintRawDecl(ExDecl);
456  else
457    OS << "...";
458  OS << ") ";
459  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
460}
461
462void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
463  Indent();
464  PrintRawCXXCatchStmt(Node);
465  OS << "\n";
466}
467
468void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
469  Indent() << "try ";
470  PrintRawCompoundStmt(Node->getTryBlock());
471  for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
472    OS << " ";
473    PrintRawCXXCatchStmt(Node->getHandler(i));
474  }
475  OS << "\n";
476}
477
478void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
479  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
480  PrintRawCompoundStmt(Node->getTryBlock());
481  SEHExceptStmt *E = Node->getExceptHandler();
482  SEHFinallyStmt *F = Node->getFinallyHandler();
483  if(E)
484    PrintRawSEHExceptHandler(E);
485  else {
486    assert(F && "Must have a finally block...");
487    PrintRawSEHFinallyStmt(F);
488  }
489  OS << "\n";
490}
491
492void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
493  OS << "__finally ";
494  PrintRawCompoundStmt(Node->getBlock());
495  OS << "\n";
496}
497
498void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
499  OS << "__except (";
500  VisitExpr(Node->getFilterExpr());
501  OS << ")\n";
502  PrintRawCompoundStmt(Node->getBlock());
503  OS << "\n";
504}
505
506void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
507  Indent();
508  PrintRawSEHExceptHandler(Node);
509  OS << "\n";
510}
511
512void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
513  Indent();
514  PrintRawSEHFinallyStmt(Node);
515  OS << "\n";
516}
517
518//===----------------------------------------------------------------------===//
519//  Expr printing methods.
520//===----------------------------------------------------------------------===//
521
522void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
523  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
524    Qualifier->print(OS, Policy);
525  OS << Node->getNameInfo();
526  if (Node->hasExplicitTemplateArgs())
527    OS << TemplateSpecializationType::PrintTemplateArgumentList(
528                                                    Node->getTemplateArgs(),
529                                                    Node->getNumTemplateArgs(),
530                                                    Policy);
531}
532
533void StmtPrinter::VisitDependentScopeDeclRefExpr(
534                                           DependentScopeDeclRefExpr *Node) {
535  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
536    Qualifier->print(OS, Policy);
537  OS << Node->getNameInfo();
538  if (Node->hasExplicitTemplateArgs())
539    OS << TemplateSpecializationType::PrintTemplateArgumentList(
540                                                   Node->getTemplateArgs(),
541                                                   Node->getNumTemplateArgs(),
542                                                   Policy);
543}
544
545void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
546  if (Node->getQualifier())
547    Node->getQualifier()->print(OS, Policy);
548  OS << Node->getNameInfo();
549  if (Node->hasExplicitTemplateArgs())
550    OS << TemplateSpecializationType::PrintTemplateArgumentList(
551                                                   Node->getTemplateArgs(),
552                                                   Node->getNumTemplateArgs(),
553                                                   Policy);
554}
555
556void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
557  if (Node->getBase()) {
558    PrintExpr(Node->getBase());
559    OS << (Node->isArrow() ? "->" : ".");
560  }
561  OS << Node->getDecl();
562}
563
564void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
565  if (Node->isSuperReceiver())
566    OS << "super.";
567  else if (Node->getBase()) {
568    PrintExpr(Node->getBase());
569    OS << ".";
570  }
571
572  if (Node->isImplicitProperty())
573    OS << Node->getImplicitPropertyGetter()->getSelector().getAsString();
574  else
575    OS << Node->getExplicitProperty()->getName();
576}
577
578void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
579  switch (Node->getIdentType()) {
580    default:
581      assert(0 && "unknown case");
582    case PredefinedExpr::Func:
583      OS << "__func__";
584      break;
585    case PredefinedExpr::Function:
586      OS << "__FUNCTION__";
587      break;
588    case PredefinedExpr::PrettyFunction:
589      OS << "__PRETTY_FUNCTION__";
590      break;
591  }
592}
593
594void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
595  unsigned value = Node->getValue();
596  if (Node->isWide())
597    OS << "L";
598  switch (value) {
599  case '\\':
600    OS << "'\\\\'";
601    break;
602  case '\'':
603    OS << "'\\''";
604    break;
605  case '\a':
606    // TODO: K&R: the meaning of '\\a' is different in traditional C
607    OS << "'\\a'";
608    break;
609  case '\b':
610    OS << "'\\b'";
611    break;
612  // Nonstandard escape sequence.
613  /*case '\e':
614    OS << "'\\e'";
615    break;*/
616  case '\f':
617    OS << "'\\f'";
618    break;
619  case '\n':
620    OS << "'\\n'";
621    break;
622  case '\r':
623    OS << "'\\r'";
624    break;
625  case '\t':
626    OS << "'\\t'";
627    break;
628  case '\v':
629    OS << "'\\v'";
630    break;
631  default:
632    if (value < 256 && isprint(value)) {
633      OS << "'" << (char)value << "'";
634    } else if (value < 256) {
635      OS << "'\\x" << llvm::format("%x", value) << "'";
636    } else {
637      // FIXME what to really do here?
638      OS << value;
639    }
640  }
641}
642
643void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
644  bool isSigned = Node->getType()->isSignedIntegerType();
645  OS << Node->getValue().toString(10, isSigned);
646
647  // Emit suffixes.  Integer literals are always a builtin integer type.
648  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
649  default: assert(0 && "Unexpected type for integer literal!");
650  case BuiltinType::Int:       break; // no suffix.
651  case BuiltinType::UInt:      OS << 'U'; break;
652  case BuiltinType::Long:      OS << 'L'; break;
653  case BuiltinType::ULong:     OS << "UL"; break;
654  case BuiltinType::LongLong:  OS << "LL"; break;
655  case BuiltinType::ULongLong: OS << "ULL"; break;
656  }
657}
658void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
659  // FIXME: print value more precisely.
660  OS << Node->getValueAsApproximateDouble();
661}
662
663void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
664  PrintExpr(Node->getSubExpr());
665  OS << "i";
666}
667
668void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
669  if (Str->isWide()) OS << 'L';
670  OS << '"';
671
672  // FIXME: this doesn't print wstrings right.
673  llvm::StringRef StrData = Str->getString();
674  for (llvm::StringRef::iterator I = StrData.begin(), E = StrData.end();
675                                                             I != E; ++I) {
676    unsigned char Char = *I;
677
678    switch (Char) {
679    default:
680      if (isprint(Char))
681        OS << (char)Char;
682      else  // Output anything hard as an octal escape.
683        OS << '\\'
684        << (char)('0'+ ((Char >> 6) & 7))
685        << (char)('0'+ ((Char >> 3) & 7))
686        << (char)('0'+ ((Char >> 0) & 7));
687      break;
688    // Handle some common non-printable cases to make dumps prettier.
689    case '\\': OS << "\\\\"; break;
690    case '"': OS << "\\\""; break;
691    case '\n': OS << "\\n"; break;
692    case '\t': OS << "\\t"; break;
693    case '\a': OS << "\\a"; break;
694    case '\b': OS << "\\b"; break;
695    }
696  }
697  OS << '"';
698}
699void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
700  OS << "(";
701  PrintExpr(Node->getSubExpr());
702  OS << ")";
703}
704void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
705  if (!Node->isPostfix()) {
706    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
707
708    // Print a space if this is an "identifier operator" like __real, or if
709    // it might be concatenated incorrectly like '+'.
710    switch (Node->getOpcode()) {
711    default: break;
712    case UO_Real:
713    case UO_Imag:
714    case UO_Extension:
715      OS << ' ';
716      break;
717    case UO_Plus:
718    case UO_Minus:
719      if (isa<UnaryOperator>(Node->getSubExpr()))
720        OS << ' ';
721      break;
722    }
723  }
724  PrintExpr(Node->getSubExpr());
725
726  if (Node->isPostfix())
727    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
728}
729
730void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
731  OS << "__builtin_offsetof(";
732  OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
733  bool PrintedSomething = false;
734  for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
735    OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
736    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
737      // Array node
738      OS << "[";
739      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
740      OS << "]";
741      PrintedSomething = true;
742      continue;
743    }
744
745    // Skip implicit base indirections.
746    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
747      continue;
748
749    // Field or identifier node.
750    IdentifierInfo *Id = ON.getFieldName();
751    if (!Id)
752      continue;
753
754    if (PrintedSomething)
755      OS << ".";
756    else
757      PrintedSomething = true;
758    OS << Id->getName();
759  }
760  OS << ")";
761}
762
763void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
764  switch(Node->getKind()) {
765  case UETT_SizeOf:
766    OS << "sizeof";
767    break;
768  case UETT_AlignOf:
769    OS << "__alignof";
770    break;
771  case UETT_VecStep:
772    OS << "vec_step";
773    break;
774  }
775  if (Node->isArgumentType())
776    OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
777  else {
778    OS << " ";
779    PrintExpr(Node->getArgumentExpr());
780  }
781}
782
783void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
784  OS << "_Generic(";
785  PrintExpr(Node->getControllingExpr());
786  for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
787    OS << ", ";
788    QualType T = Node->getAssocType(i);
789    if (T.isNull())
790      OS << "default";
791    else
792      OS << T.getAsString(Policy);
793    OS << ": ";
794    PrintExpr(Node->getAssocExpr(i));
795  }
796  OS << ")";
797}
798
799void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
800  PrintExpr(Node->getLHS());
801  OS << "[";
802  PrintExpr(Node->getRHS());
803  OS << "]";
804}
805
806void StmtPrinter::PrintCallArgs(CallExpr *Call) {
807  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
808    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
809      // Don't print any defaulted arguments
810      break;
811    }
812
813    if (i) OS << ", ";
814    PrintExpr(Call->getArg(i));
815  }
816}
817
818void StmtPrinter::VisitCallExpr(CallExpr *Call) {
819  PrintExpr(Call->getCallee());
820  OS << "(";
821  PrintCallArgs(Call);
822  OS << ")";
823}
824void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
825  // FIXME: Suppress printing implicit bases (like "this")
826  PrintExpr(Node->getBase());
827  if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
828    if (FD->isAnonymousStructOrUnion())
829      return;
830  OS << (Node->isArrow() ? "->" : ".");
831  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
832    Qualifier->print(OS, Policy);
833
834  OS << Node->getMemberNameInfo();
835
836  if (Node->hasExplicitTemplateArgs())
837    OS << TemplateSpecializationType::PrintTemplateArgumentList(
838                                                    Node->getTemplateArgs(),
839                                                    Node->getNumTemplateArgs(),
840                                                                Policy);
841}
842void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
843  PrintExpr(Node->getBase());
844  OS << (Node->isArrow() ? "->isa" : ".isa");
845}
846
847void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
848  PrintExpr(Node->getBase());
849  OS << ".";
850  OS << Node->getAccessor().getName();
851}
852void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
853  OS << "(" << Node->getType().getAsString(Policy) << ")";
854  PrintExpr(Node->getSubExpr());
855}
856void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
857  OS << "(" << Node->getType().getAsString(Policy) << ")";
858  PrintExpr(Node->getInitializer());
859}
860void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
861  // No need to print anything, simply forward to the sub expression.
862  PrintExpr(Node->getSubExpr());
863}
864void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
865  PrintExpr(Node->getLHS());
866  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
867  PrintExpr(Node->getRHS());
868}
869void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
870  PrintExpr(Node->getLHS());
871  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
872  PrintExpr(Node->getRHS());
873}
874void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
875  PrintExpr(Node->getCond());
876  OS << " ? ";
877  PrintExpr(Node->getLHS());
878  OS << " : ";
879  PrintExpr(Node->getRHS());
880}
881
882// GNU extensions.
883
884void
885StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
886  PrintExpr(Node->getCommon());
887  OS << " ?: ";
888  PrintExpr(Node->getFalseExpr());
889}
890void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
891  OS << "&&" << Node->getLabel()->getName();
892}
893
894void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
895  OS << "(";
896  PrintRawCompoundStmt(E->getSubStmt());
897  OS << ")";
898}
899
900void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
901  OS << "__builtin_choose_expr(";
902  PrintExpr(Node->getCond());
903  OS << ", ";
904  PrintExpr(Node->getLHS());
905  OS << ", ";
906  PrintExpr(Node->getRHS());
907  OS << ")";
908}
909
910void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
911  OS << "__null";
912}
913
914void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
915  OS << "__builtin_shufflevector(";
916  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
917    if (i) OS << ", ";
918    PrintExpr(Node->getExpr(i));
919  }
920  OS << ")";
921}
922
923void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
924  if (Node->getSyntacticForm()) {
925    Visit(Node->getSyntacticForm());
926    return;
927  }
928
929  OS << "{ ";
930  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
931    if (i) OS << ", ";
932    if (Node->getInit(i))
933      PrintExpr(Node->getInit(i));
934    else
935      OS << "0";
936  }
937  OS << " }";
938}
939
940void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
941  OS << "( ";
942  for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
943    if (i) OS << ", ";
944    PrintExpr(Node->getExpr(i));
945  }
946  OS << " )";
947}
948
949void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
950  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
951                      DEnd = Node->designators_end();
952       D != DEnd; ++D) {
953    if (D->isFieldDesignator()) {
954      if (D->getDotLoc().isInvalid())
955        OS << D->getFieldName()->getName() << ":";
956      else
957        OS << "." << D->getFieldName()->getName();
958    } else {
959      OS << "[";
960      if (D->isArrayDesignator()) {
961        PrintExpr(Node->getArrayIndex(*D));
962      } else {
963        PrintExpr(Node->getArrayRangeStart(*D));
964        OS << " ... ";
965        PrintExpr(Node->getArrayRangeEnd(*D));
966      }
967      OS << "]";
968    }
969  }
970
971  OS << " = ";
972  PrintExpr(Node->getInit());
973}
974
975void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
976  if (Policy.LangOpts.CPlusPlus)
977    OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
978  else {
979    OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
980    if (Node->getType()->isRecordType())
981      OS << "{}";
982    else
983      OS << 0;
984  }
985}
986
987void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
988  OS << "__builtin_va_arg(";
989  PrintExpr(Node->getSubExpr());
990  OS << ", ";
991  OS << Node->getType().getAsString(Policy);
992  OS << ")";
993}
994
995// C++
996void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
997  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
998    "",
999#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1000    Spelling,
1001#include "clang/Basic/OperatorKinds.def"
1002  };
1003
1004  OverloadedOperatorKind Kind = Node->getOperator();
1005  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1006    if (Node->getNumArgs() == 1) {
1007      OS << OpStrings[Kind] << ' ';
1008      PrintExpr(Node->getArg(0));
1009    } else {
1010      PrintExpr(Node->getArg(0));
1011      OS << ' ' << OpStrings[Kind];
1012    }
1013  } else if (Kind == OO_Call) {
1014    PrintExpr(Node->getArg(0));
1015    OS << '(';
1016    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1017      if (ArgIdx > 1)
1018        OS << ", ";
1019      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1020        PrintExpr(Node->getArg(ArgIdx));
1021    }
1022    OS << ')';
1023  } else if (Kind == OO_Subscript) {
1024    PrintExpr(Node->getArg(0));
1025    OS << '[';
1026    PrintExpr(Node->getArg(1));
1027    OS << ']';
1028  } else if (Node->getNumArgs() == 1) {
1029    OS << OpStrings[Kind] << ' ';
1030    PrintExpr(Node->getArg(0));
1031  } else if (Node->getNumArgs() == 2) {
1032    PrintExpr(Node->getArg(0));
1033    OS << ' ' << OpStrings[Kind] << ' ';
1034    PrintExpr(Node->getArg(1));
1035  } else {
1036    assert(false && "unknown overloaded operator");
1037  }
1038}
1039
1040void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1041  VisitCallExpr(cast<CallExpr>(Node));
1042}
1043
1044void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1045  PrintExpr(Node->getCallee());
1046  OS << "<<<";
1047  PrintCallArgs(Node->getConfig());
1048  OS << ">>>(";
1049  PrintCallArgs(Node);
1050  OS << ")";
1051}
1052
1053void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1054  OS << Node->getCastName() << '<';
1055  OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1056  PrintExpr(Node->getSubExpr());
1057  OS << ")";
1058}
1059
1060void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1061  VisitCXXNamedCastExpr(Node);
1062}
1063
1064void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1065  VisitCXXNamedCastExpr(Node);
1066}
1067
1068void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1069  VisitCXXNamedCastExpr(Node);
1070}
1071
1072void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1073  VisitCXXNamedCastExpr(Node);
1074}
1075
1076void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1077  OS << "typeid(";
1078  if (Node->isTypeOperand()) {
1079    OS << Node->getTypeOperand().getAsString(Policy);
1080  } else {
1081    PrintExpr(Node->getExprOperand());
1082  }
1083  OS << ")";
1084}
1085
1086void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1087  OS << "__uuidof(";
1088  if (Node->isTypeOperand()) {
1089    OS << Node->getTypeOperand().getAsString(Policy);
1090  } else {
1091    PrintExpr(Node->getExprOperand());
1092  }
1093  OS << ")";
1094}
1095
1096void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1097  OS << (Node->getValue() ? "true" : "false");
1098}
1099
1100void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1101  OS << "nullptr";
1102}
1103
1104void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1105  OS << "this";
1106}
1107
1108void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1109  if (Node->getSubExpr() == 0)
1110    OS << "throw";
1111  else {
1112    OS << "throw ";
1113    PrintExpr(Node->getSubExpr());
1114  }
1115}
1116
1117void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1118  // Nothing to print: we picked up the default argument
1119}
1120
1121void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1122  OS << Node->getType().getAsString(Policy);
1123  OS << "(";
1124  PrintExpr(Node->getSubExpr());
1125  OS << ")";
1126}
1127
1128void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1129  PrintExpr(Node->getSubExpr());
1130}
1131
1132void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1133  OS << Node->getType().getAsString(Policy);
1134  OS << "(";
1135  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1136                                         ArgEnd = Node->arg_end();
1137       Arg != ArgEnd; ++Arg) {
1138    if (Arg != Node->arg_begin())
1139      OS << ", ";
1140    PrintExpr(*Arg);
1141  }
1142  OS << ")";
1143}
1144
1145void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1146  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1147    OS << TSInfo->getType().getAsString(Policy) << "()";
1148  else
1149    OS << Node->getType().getAsString(Policy) << "()";
1150}
1151
1152void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1153  if (E->isGlobalNew())
1154    OS << "::";
1155  OS << "new ";
1156  unsigned NumPlace = E->getNumPlacementArgs();
1157  if (NumPlace > 0) {
1158    OS << "(";
1159    PrintExpr(E->getPlacementArg(0));
1160    for (unsigned i = 1; i < NumPlace; ++i) {
1161      OS << ", ";
1162      PrintExpr(E->getPlacementArg(i));
1163    }
1164    OS << ") ";
1165  }
1166  if (E->isParenTypeId())
1167    OS << "(";
1168  std::string TypeS;
1169  if (Expr *Size = E->getArraySize()) {
1170    llvm::raw_string_ostream s(TypeS);
1171    Size->printPretty(s, Context, Helper, Policy);
1172    s.flush();
1173    TypeS = "[" + TypeS + "]";
1174  }
1175  E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1176  OS << TypeS;
1177  if (E->isParenTypeId())
1178    OS << ")";
1179
1180  if (E->hasInitializer()) {
1181    OS << "(";
1182    unsigned NumCons = E->getNumConstructorArgs();
1183    if (NumCons > 0) {
1184      PrintExpr(E->getConstructorArg(0));
1185      for (unsigned i = 1; i < NumCons; ++i) {
1186        OS << ", ";
1187        PrintExpr(E->getConstructorArg(i));
1188      }
1189    }
1190    OS << ")";
1191  }
1192}
1193
1194void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1195  if (E->isGlobalDelete())
1196    OS << "::";
1197  OS << "delete ";
1198  if (E->isArrayForm())
1199    OS << "[] ";
1200  PrintExpr(E->getArgument());
1201}
1202
1203void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1204  PrintExpr(E->getBase());
1205  if (E->isArrow())
1206    OS << "->";
1207  else
1208    OS << '.';
1209  if (E->getQualifier())
1210    E->getQualifier()->print(OS, Policy);
1211
1212  std::string TypeS;
1213  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1214    OS << II->getName();
1215  else
1216    E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1217  OS << TypeS;
1218}
1219
1220void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1221  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1222    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1223      // Don't print any defaulted arguments
1224      break;
1225    }
1226
1227    if (i) OS << ", ";
1228    PrintExpr(E->getArg(i));
1229  }
1230}
1231
1232void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1233  // Just forward to the sub expression.
1234  PrintExpr(E->getSubExpr());
1235}
1236
1237void
1238StmtPrinter::VisitCXXUnresolvedConstructExpr(
1239                                           CXXUnresolvedConstructExpr *Node) {
1240  OS << Node->getTypeAsWritten().getAsString(Policy);
1241  OS << "(";
1242  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1243                                             ArgEnd = Node->arg_end();
1244       Arg != ArgEnd; ++Arg) {
1245    if (Arg != Node->arg_begin())
1246      OS << ", ";
1247    PrintExpr(*Arg);
1248  }
1249  OS << ")";
1250}
1251
1252void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1253                                         CXXDependentScopeMemberExpr *Node) {
1254  if (!Node->isImplicitAccess()) {
1255    PrintExpr(Node->getBase());
1256    OS << (Node->isArrow() ? "->" : ".");
1257  }
1258  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1259    Qualifier->print(OS, Policy);
1260  else if (Node->hasExplicitTemplateArgs())
1261    // FIXME: Track use of "template" keyword explicitly?
1262    OS << "template ";
1263
1264  OS << Node->getMemberNameInfo();
1265
1266  if (Node->hasExplicitTemplateArgs()) {
1267    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1268                                                    Node->getTemplateArgs(),
1269                                                    Node->getNumTemplateArgs(),
1270                                                    Policy);
1271  }
1272}
1273
1274void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1275  if (!Node->isImplicitAccess()) {
1276    PrintExpr(Node->getBase());
1277    OS << (Node->isArrow() ? "->" : ".");
1278  }
1279  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1280    Qualifier->print(OS, Policy);
1281
1282  // FIXME: this might originally have been written with 'template'
1283
1284  OS << Node->getMemberNameInfo();
1285
1286  if (Node->hasExplicitTemplateArgs()) {
1287    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1288                                                    Node->getTemplateArgs(),
1289                                                    Node->getNumTemplateArgs(),
1290                                                    Policy);
1291  }
1292}
1293
1294static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1295  switch (UTT) {
1296  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1297  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1298  case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1299  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1300  case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1301  case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1302  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1303  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1304  case UTT_IsAbstract:            return "__is_abstract";
1305  case UTT_IsArithmetic:            return "__is_arithmetic";
1306  case UTT_IsArray:                 return "__is_array";
1307  case UTT_IsClass:               return "__is_class";
1308  case UTT_IsCompleteType:          return "__is_complete_type";
1309  case UTT_IsCompound:              return "__is_compound";
1310  case UTT_IsConst:                 return "__is_const";
1311  case UTT_IsEmpty:               return "__is_empty";
1312  case UTT_IsEnum:                return "__is_enum";
1313  case UTT_IsFloatingPoint:         return "__is_floating_point";
1314  case UTT_IsFunction:              return "__is_function";
1315  case UTT_IsFundamental:           return "__is_fundamental";
1316  case UTT_IsIntegral:              return "__is_integral";
1317  case UTT_IsLiteral:               return "__is_literal";
1318  case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1319  case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1320  case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1321  case UTT_IsMemberPointer:         return "__is_member_pointer";
1322  case UTT_IsObject:                return "__is_object";
1323  case UTT_IsPOD:                 return "__is_pod";
1324  case UTT_IsPointer:               return "__is_pointer";
1325  case UTT_IsPolymorphic:         return "__is_polymorphic";
1326  case UTT_IsReference:             return "__is_reference";
1327  case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1328  case UTT_IsScalar:                return "__is_scalar";
1329  case UTT_IsSigned:                return "__is_signed";
1330  case UTT_IsStandardLayout:        return "__is_standard_layout";
1331  case UTT_IsTrivial:               return "__is_trivial";
1332  case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1333  case UTT_IsUnion:               return "__is_union";
1334  case UTT_IsUnsigned:              return "__is_unsigned";
1335  case UTT_IsVoid:                  return "__is_void";
1336  case UTT_IsVolatile:              return "__is_volatile";
1337  }
1338  llvm_unreachable("Type trait not covered by switch statement");
1339}
1340
1341static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1342  switch (BTT) {
1343  case BTT_IsBaseOf:         return "__is_base_of";
1344  case BTT_IsConvertible:    return "__is_convertible";
1345  case BTT_IsSame:           return "__is_same";
1346  case BTT_TypeCompatible:   return "__builtin_types_compatible_p";
1347  case BTT_IsConvertibleTo:  return "__is_convertible_to";
1348  }
1349  llvm_unreachable("Binary type trait not covered by switch");
1350}
1351
1352static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1353  switch (ATT) {
1354  case ATT_ArrayRank:        return "__array_rank";
1355  case ATT_ArrayExtent:      return "__array_extent";
1356  }
1357  llvm_unreachable("Array type trait not covered by switch");
1358}
1359
1360static const char *getExpressionTraitName(ExpressionTrait ET) {
1361  switch (ET) {
1362  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1363  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1364  }
1365  llvm_unreachable("Expression type trait not covered by switch");
1366}
1367
1368void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1369  OS << getTypeTraitName(E->getTrait()) << "("
1370     << E->getQueriedType().getAsString(Policy) << ")";
1371}
1372
1373void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1374  OS << getTypeTraitName(E->getTrait()) << "("
1375     << E->getLhsType().getAsString(Policy) << ","
1376     << E->getRhsType().getAsString(Policy) << ")";
1377}
1378
1379void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1380  OS << getTypeTraitName(E->getTrait()) << "("
1381     << E->getQueriedType().getAsString(Policy) << ")";
1382}
1383
1384void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1385    OS << getExpressionTraitName(E->getTrait()) << "(";
1386    PrintExpr(E->getQueriedExpression());
1387    OS << ")";
1388}
1389
1390void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1391  OS << "noexcept(";
1392  PrintExpr(E->getOperand());
1393  OS << ")";
1394}
1395
1396void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1397  PrintExpr(E->getPattern());
1398  OS << "...";
1399}
1400
1401void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1402  OS << "sizeof...(" << E->getPack()->getNameAsString() << ")";
1403}
1404
1405void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1406                                       SubstNonTypeTemplateParmPackExpr *Node) {
1407  OS << Node->getParameterPack()->getNameAsString();
1408}
1409
1410// Obj-C
1411
1412void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1413  OS << "@";
1414  VisitStringLiteral(Node->getString());
1415}
1416
1417void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1418  OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1419}
1420
1421void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1422  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1423}
1424
1425void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1426  OS << "@protocol(" << Node->getProtocol() << ')';
1427}
1428
1429void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1430  OS << "[";
1431  switch (Mess->getReceiverKind()) {
1432  case ObjCMessageExpr::Instance:
1433    PrintExpr(Mess->getInstanceReceiver());
1434    break;
1435
1436  case ObjCMessageExpr::Class:
1437    OS << Mess->getClassReceiver().getAsString(Policy);
1438    break;
1439
1440  case ObjCMessageExpr::SuperInstance:
1441  case ObjCMessageExpr::SuperClass:
1442    OS << "Super";
1443    break;
1444  }
1445
1446  OS << ' ';
1447  Selector selector = Mess->getSelector();
1448  if (selector.isUnarySelector()) {
1449    OS << selector.getNameForSlot(0);
1450  } else {
1451    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1452      if (i < selector.getNumArgs()) {
1453        if (i > 0) OS << ' ';
1454        if (selector.getIdentifierInfoForSlot(i))
1455          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1456        else
1457           OS << ":";
1458      }
1459      else OS << ", "; // Handle variadic methods.
1460
1461      PrintExpr(Mess->getArg(i));
1462    }
1463  }
1464  OS << "]";
1465}
1466
1467
1468void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1469  BlockDecl *BD = Node->getBlockDecl();
1470  OS << "^";
1471
1472  const FunctionType *AFT = Node->getFunctionType();
1473
1474  if (isa<FunctionNoProtoType>(AFT)) {
1475    OS << "()";
1476  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1477    OS << '(';
1478    std::string ParamStr;
1479    for (BlockDecl::param_iterator AI = BD->param_begin(),
1480         E = BD->param_end(); AI != E; ++AI) {
1481      if (AI != BD->param_begin()) OS << ", ";
1482      ParamStr = (*AI)->getNameAsString();
1483      (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1484      OS << ParamStr;
1485    }
1486
1487    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1488    if (FT->isVariadic()) {
1489      if (!BD->param_empty()) OS << ", ";
1490      OS << "...";
1491    }
1492    OS << ')';
1493  }
1494}
1495
1496void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
1497  OS << Node->getDecl();
1498}
1499
1500void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {}
1501
1502void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1503  OS << "__builtin_astype(";
1504  PrintExpr(Node->getSrcExpr());
1505  OS << ", " << Node->getType().getAsString();
1506  OS << ")";
1507}
1508
1509//===----------------------------------------------------------------------===//
1510// Stmt method implementations
1511//===----------------------------------------------------------------------===//
1512
1513void Stmt::dumpPretty(ASTContext& Context) const {
1514  printPretty(llvm::errs(), Context, 0,
1515              PrintingPolicy(Context.getLangOptions()));
1516}
1517
1518void Stmt::printPretty(llvm::raw_ostream &OS, ASTContext& Context,
1519                       PrinterHelper* Helper,
1520                       const PrintingPolicy &Policy,
1521                       unsigned Indentation) const {
1522  if (this == 0) {
1523    OS << "<NULL>";
1524    return;
1525  }
1526
1527  if (Policy.Dump && &Context) {
1528    dump(OS, Context.getSourceManager());
1529    return;
1530  }
1531
1532  StmtPrinter P(OS, Context, Helper, Policy, Indentation);
1533  P.Visit(const_cast<Stmt*>(this));
1534}
1535
1536//===----------------------------------------------------------------------===//
1537// PrinterHelper
1538//===----------------------------------------------------------------------===//
1539
1540// Implement virtual destructor.
1541PrinterHelper::~PrinterHelper() {}
1542