1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
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 contains code to print types from Clang's type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/Type.h"
19 #include "clang/AST/PrettyPrinter.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
25 
26 namespace {
27   class TypePrinter {
28     PrintingPolicy Policy;
29 
30   public:
31     explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
32 
33     void print(const Type *ty, Qualifiers qs, std::string &buffer);
34     void print(QualType T, std::string &S);
35     void AppendScope(DeclContext *DC, std::string &S);
36     void printTag(TagDecl *T, std::string &S);
37 #define ABSTRACT_TYPE(CLASS, PARENT)
38 #define TYPE(CLASS, PARENT) \
39     void print##CLASS(const CLASS##Type *T, std::string &S);
40 #include "clang/AST/TypeNodes.def"
41   };
42 }
43 
44 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
45   if (TypeQuals & Qualifiers::Const) {
46     if (!S.empty()) S += ' ';
47     S += "const";
48   }
49   if (TypeQuals & Qualifiers::Volatile) {
50     if (!S.empty()) S += ' ';
51     S += "volatile";
52   }
53   if (TypeQuals & Qualifiers::Restrict) {
54     if (!S.empty()) S += ' ';
55     S += "restrict";
56   }
57 }
58 
59 void TypePrinter::print(QualType t, std::string &buffer) {
60   SplitQualType split = t.split();
61   print(split.first, split.second, buffer);
62 }
63 
64 void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
65   if (!T) {
66     buffer += "NULL TYPE";
67     return;
68   }
69 
70   if (Policy.SuppressSpecifiers && T->isSpecifierType())
71     return;
72 
73   // Print qualifiers as appropriate.
74 
75   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
76   // so that we get "const int" instead of "int const", but we can't do this if
77   // the type is complex.  For example if the type is "int*", we *must* print
78   // "int * const", printing "const int *" is different.  Only do this when the
79   // type expands to a simple string.
80   bool CanPrefixQualifiers = false;
81 
82   Type::TypeClass TC = T->getTypeClass();
83   if (const AutoType *AT = dyn_cast<AutoType>(T))
84     TC = AT->desugar()->getTypeClass();
85   if (const SubstTemplateTypeParmType *Subst
86                                       = dyn_cast<SubstTemplateTypeParmType>(T))
87     TC = Subst->getReplacementType()->getTypeClass();
88 
89   switch (TC) {
90     case Type::Builtin:
91     case Type::Complex:
92     case Type::UnresolvedUsing:
93     case Type::Typedef:
94     case Type::TypeOfExpr:
95     case Type::TypeOf:
96     case Type::Decltype:
97     case Type::Record:
98     case Type::Enum:
99     case Type::Elaborated:
100     case Type::TemplateTypeParm:
101     case Type::SubstTemplateTypeParmPack:
102     case Type::TemplateSpecialization:
103     case Type::InjectedClassName:
104     case Type::DependentName:
105     case Type::DependentTemplateSpecialization:
106     case Type::ObjCObject:
107     case Type::ObjCInterface:
108       CanPrefixQualifiers = true;
109       break;
110 
111     case Type::ObjCObjectPointer:
112       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
113         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
114       break;
115 
116     case Type::Pointer:
117     case Type::BlockPointer:
118     case Type::LValueReference:
119     case Type::RValueReference:
120     case Type::MemberPointer:
121     case Type::ConstantArray:
122     case Type::IncompleteArray:
123     case Type::VariableArray:
124     case Type::DependentSizedArray:
125     case Type::DependentSizedExtVector:
126     case Type::Vector:
127     case Type::ExtVector:
128     case Type::FunctionProto:
129     case Type::FunctionNoProto:
130     case Type::Paren:
131     case Type::Attributed:
132     case Type::PackExpansion:
133     case Type::SubstTemplateTypeParm:
134     case Type::Auto:
135       CanPrefixQualifiers = false;
136       break;
137   }
138 
139   if (!CanPrefixQualifiers && !Quals.empty()) {
140     std::string qualsBuffer;
141     Quals.getAsStringInternal(qualsBuffer, Policy);
142 
143     if (!buffer.empty()) {
144       qualsBuffer += ' ';
145       qualsBuffer += buffer;
146     }
147     std::swap(buffer, qualsBuffer);
148   }
149 
150   switch (T->getTypeClass()) {
151 #define ABSTRACT_TYPE(CLASS, PARENT)
152 #define TYPE(CLASS, PARENT) case Type::CLASS: \
153     print##CLASS(cast<CLASS##Type>(T), buffer); \
154     break;
155 #include "clang/AST/TypeNodes.def"
156   }
157 
158   // If we're adding the qualifiers as a prefix, do it now.
159   if (CanPrefixQualifiers && !Quals.empty()) {
160     std::string qualsBuffer;
161     Quals.getAsStringInternal(qualsBuffer, Policy);
162 
163     if (!buffer.empty()) {
164       qualsBuffer += ' ';
165       qualsBuffer += buffer;
166     }
167     std::swap(buffer, qualsBuffer);
168   }
169 }
170 
171 void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
172   if (S.empty()) {
173     S = T->getName(Policy.LangOpts);
174   } else {
175     // Prefix the basic type, e.g. 'int X'.
176     S = ' ' + S;
177     S = T->getName(Policy.LangOpts) + S;
178   }
179 }
180 
181 void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
182   print(T->getElementType(), S);
183   S = "_Complex " + S;
184 }
185 
186 void TypePrinter::printPointer(const PointerType *T, std::string &S) {
187   S = '*' + S;
188 
189   // Handle things like 'int (*A)[4];' correctly.
190   // FIXME: this should include vectors, but vectors use attributes I guess.
191   if (isa<ArrayType>(T->getPointeeType()))
192     S = '(' + S + ')';
193 
194   print(T->getPointeeType(), S);
195 }
196 
197 void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
198   S = '^' + S;
199   print(T->getPointeeType(), S);
200 }
201 
202 void TypePrinter::printLValueReference(const LValueReferenceType *T,
203                                        std::string &S) {
204   S = '&' + S;
205 
206   // Handle things like 'int (&A)[4];' correctly.
207   // FIXME: this should include vectors, but vectors use attributes I guess.
208   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
209     S = '(' + S + ')';
210 
211   print(T->getPointeeTypeAsWritten(), S);
212 }
213 
214 void TypePrinter::printRValueReference(const RValueReferenceType *T,
215                                        std::string &S) {
216   S = "&&" + S;
217 
218   // Handle things like 'int (&&A)[4];' correctly.
219   // FIXME: this should include vectors, but vectors use attributes I guess.
220   if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
221     S = '(' + S + ')';
222 
223   print(T->getPointeeTypeAsWritten(), S);
224 }
225 
226 void TypePrinter::printMemberPointer(const MemberPointerType *T,
227                                      std::string &S) {
228   std::string C;
229   print(QualType(T->getClass(), 0), C);
230   C += "::*";
231   S = C + S;
232 
233   // Handle things like 'int (Cls::*A)[4];' correctly.
234   // FIXME: this should include vectors, but vectors use attributes I guess.
235   if (isa<ArrayType>(T->getPointeeType()))
236     S = '(' + S + ')';
237 
238   print(T->getPointeeType(), S);
239 }
240 
241 void TypePrinter::printConstantArray(const ConstantArrayType *T,
242                                      std::string &S) {
243   S += '[';
244   S += llvm::utostr(T->getSize().getZExtValue());
245   S += ']';
246 
247   print(T->getElementType(), S);
248 }
249 
250 void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
251                                        std::string &S) {
252   S += "[]";
253   print(T->getElementType(), S);
254 }
255 
256 void TypePrinter::printVariableArray(const VariableArrayType *T,
257                                      std::string &S) {
258   S += '[';
259 
260   if (T->getIndexTypeQualifiers().hasQualifiers()) {
261     AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
262     S += ' ';
263   }
264 
265   if (T->getSizeModifier() == VariableArrayType::Static)
266     S += "static";
267   else if (T->getSizeModifier() == VariableArrayType::Star)
268     S += '*';
269 
270   if (T->getSizeExpr()) {
271     std::string SStr;
272     llvm::raw_string_ostream s(SStr);
273     T->getSizeExpr()->printPretty(s, 0, Policy);
274     S += s.str();
275   }
276   S += ']';
277 
278   print(T->getElementType(), S);
279 }
280 
281 void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T,
282                                            std::string &S) {
283   S += '[';
284 
285   if (T->getSizeExpr()) {
286     std::string SStr;
287     llvm::raw_string_ostream s(SStr);
288     T->getSizeExpr()->printPretty(s, 0, Policy);
289     S += s.str();
290   }
291   S += ']';
292 
293   print(T->getElementType(), S);
294 }
295 
296 void TypePrinter::printDependentSizedExtVector(
297                                           const DependentSizedExtVectorType *T,
298                                                std::string &S) {
299   print(T->getElementType(), S);
300 
301   S += " __attribute__((ext_vector_type(";
302   if (T->getSizeExpr()) {
303     std::string SStr;
304     llvm::raw_string_ostream s(SStr);
305     T->getSizeExpr()->printPretty(s, 0, Policy);
306     S += s.str();
307   }
308   S += ")))";
309 }
310 
311 void TypePrinter::printVector(const VectorType *T, std::string &S) {
312   switch (T->getVectorKind()) {
313   case VectorType::AltiVecPixel:
314     S = "__vector __pixel " + S;
315     break;
316   case VectorType::AltiVecBool:
317     print(T->getElementType(), S);
318     S = "__vector __bool " + S;
319     break;
320   case VectorType::AltiVecVector:
321     print(T->getElementType(), S);
322     S = "__vector " + S;
323     break;
324   case VectorType::NeonVector:
325     print(T->getElementType(), S);
326     S = ("__attribute__((neon_vector_type(" +
327          llvm::utostr_32(T->getNumElements()) + "))) " + S);
328     break;
329   case VectorType::NeonPolyVector:
330     print(T->getElementType(), S);
331     S = ("__attribute__((neon_polyvector_type(" +
332          llvm::utostr_32(T->getNumElements()) + "))) " + S);
333     break;
334   case VectorType::GenericVector: {
335     // FIXME: We prefer to print the size directly here, but have no way
336     // to get the size of the type.
337     print(T->getElementType(), S);
338     std::string V = "__attribute__((__vector_size__(";
339     V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
340     std::string ET;
341     print(T->getElementType(), ET);
342     V += " * sizeof(" + ET + ")))) ";
343     S = V + S;
344     break;
345   }
346   }
347 }
348 
349 void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) {
350   S += " __attribute__((ext_vector_type(";
351   S += llvm::utostr_32(T->getNumElements());
352   S += ")))";
353   print(T->getElementType(), S);
354 }
355 
356 void TypePrinter::printFunctionProto(const FunctionProtoType *T,
357                                      std::string &S) {
358   // If needed for precedence reasons, wrap the inner part in grouping parens.
359   if (!S.empty())
360     S = "(" + S + ")";
361 
362   S += "(";
363   std::string Tmp;
364   PrintingPolicy ParamPolicy(Policy);
365   ParamPolicy.SuppressSpecifiers = false;
366   for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
367     if (i) S += ", ";
368     print(T->getArgType(i), Tmp);
369     S += Tmp;
370     Tmp.clear();
371   }
372 
373   if (T->isVariadic()) {
374     if (T->getNumArgs())
375       S += ", ";
376     S += "...";
377   } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
378     // Do not emit int() if we have a proto, emit 'int(void)'.
379     S += "void";
380   }
381 
382   S += ")";
383 
384   FunctionType::ExtInfo Info = T->getExtInfo();
385   switch(Info.getCC()) {
386   case CC_Default:
387   default: break;
388   case CC_C:
389     S += " __attribute__((cdecl))";
390     break;
391   case CC_X86StdCall:
392     S += " __attribute__((stdcall))";
393     break;
394   case CC_X86FastCall:
395     S += " __attribute__((fastcall))";
396     break;
397   case CC_X86ThisCall:
398     S += " __attribute__((thiscall))";
399     break;
400   case CC_X86Pascal:
401     S += " __attribute__((pascal))";
402     break;
403   case CC_AAPCS:
404     S += " __attribute__((pcs(\"aapcs\")))";
405     break;
406   case CC_AAPCS_VFP:
407     S += " __attribute__((pcs(\"aapcs-vfp\")))";
408     break;
409   }
410   if (Info.getNoReturn())
411     S += " __attribute__((noreturn))";
412   if (Info.getRegParm())
413     S += " __attribute__((regparm (" +
414         llvm::utostr_32(Info.getRegParm()) + ")))";
415 
416   AppendTypeQualList(S, T->getTypeQuals());
417 
418   switch (T->getRefQualifier()) {
419   case RQ_None:
420     break;
421 
422   case RQ_LValue:
423     S += " &";
424     break;
425 
426   case RQ_RValue:
427     S += " &&";
428     break;
429   }
430 
431   if (T->hasDynamicExceptionSpec()) {
432     S += " throw(";
433     if (T->getExceptionSpecType() == EST_MSAny)
434       S += "...";
435     else
436       for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
437         if (I)
438           S += ", ";
439 
440         std::string ExceptionType;
441         print(T->getExceptionType(I), ExceptionType);
442         S += ExceptionType;
443       }
444     S += ")";
445   } else if (isNoexceptExceptionSpec(T->getExceptionSpecType())) {
446     S += " noexcept";
447     if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
448       S += "(";
449       llvm::raw_string_ostream EOut(S);
450       T->getNoexceptExpr()->printPretty(EOut, 0, Policy);
451       EOut.flush();
452       S += EOut.str();
453       S += ")";
454     }
455   }
456 
457   print(T->getResultType(), S);
458 }
459 
460 void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
461                                        std::string &S) {
462   // If needed for precedence reasons, wrap the inner part in grouping parens.
463   if (!S.empty())
464     S = "(" + S + ")";
465 
466   S += "()";
467   if (T->getNoReturnAttr())
468     S += " __attribute__((noreturn))";
469   print(T->getResultType(), S);
470 }
471 
472 static void printTypeSpec(const NamedDecl *D, std::string &S) {
473   IdentifierInfo *II = D->getIdentifier();
474   if (S.empty())
475     S = II->getName().str();
476   else
477     S = II->getName().str() + ' ' + S;
478 }
479 
480 void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
481                                        std::string &S) {
482   printTypeSpec(T->getDecl(), S);
483 }
484 
485 void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
486   printTypeSpec(T->getDecl(), S);
487 }
488 
489 void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
490   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
491     S = ' ' + S;
492   std::string Str;
493   llvm::raw_string_ostream s(Str);
494   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
495   S = "typeof " + s.str() + S;
496 }
497 
498 void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
499   if (!S.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
500     S = ' ' + S;
501   std::string Tmp;
502   print(T->getUnderlyingType(), Tmp);
503   S = "typeof(" + Tmp + ")" + S;
504 }
505 
506 void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
507   if (!S.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
508     S = ' ' + S;
509   std::string Str;
510   llvm::raw_string_ostream s(Str);
511   T->getUnderlyingExpr()->printPretty(s, 0, Policy);
512   S = "decltype(" + s.str() + ")" + S;
513 }
514 
515 void TypePrinter::printAuto(const AutoType *T, std::string &S) {
516   // If the type has been deduced, do not print 'auto'.
517   if (T->isDeduced()) {
518     print(T->getDeducedType(), S);
519   } else {
520     if (!S.empty())    // Prefix the basic type, e.g. 'auto X'.
521       S = ' ' + S;
522     S = "auto" + S;
523   }
524 }
525 
526 /// Appends the given scope to the end of a string.
527 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
528   if (DC->isTranslationUnit()) return;
529   AppendScope(DC->getParent(), Buffer);
530 
531   unsigned OldSize = Buffer.size();
532 
533   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
534     if (NS->getIdentifier())
535       Buffer += NS->getNameAsString();
536     else
537       Buffer += "<anonymous>";
538   } else if (ClassTemplateSpecializationDecl *Spec
539                = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
540     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
541     std::string TemplateArgsStr
542       = TemplateSpecializationType::PrintTemplateArgumentList(
543                                             TemplateArgs.data(),
544                                             TemplateArgs.size(),
545                                             Policy);
546     Buffer += Spec->getIdentifier()->getName();
547     Buffer += TemplateArgsStr;
548   } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
549     if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
550       Buffer += Typedef->getIdentifier()->getName();
551     else if (Tag->getIdentifier())
552       Buffer += Tag->getIdentifier()->getName();
553   }
554 
555   if (Buffer.size() != OldSize)
556     Buffer += "::";
557 }
558 
559 void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
560   if (Policy.SuppressTag)
561     return;
562 
563   std::string Buffer;
564   bool HasKindDecoration = false;
565 
566   // bool SuppressTagKeyword
567   //   = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
568 
569   // We don't print tags unless this is an elaborated type.
570   // In C, we just assume every RecordType is an elaborated type.
571   if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
572         D->getTypedefForAnonDecl())) {
573     HasKindDecoration = true;
574     Buffer += D->getKindName();
575     Buffer += ' ';
576   }
577 
578   // Compute the full nested-name-specifier for this type.
579   // In C, this will always be empty except when the type
580   // being printed is anonymous within other Record.
581   if (!Policy.SuppressScope)
582     AppendScope(D->getDeclContext(), Buffer);
583 
584   if (const IdentifierInfo *II = D->getIdentifier())
585     Buffer += II->getNameStart();
586   else if (TypedefDecl *Typedef = D->getTypedefForAnonDecl()) {
587     assert(Typedef->getIdentifier() && "Typedef without identifier?");
588     Buffer += Typedef->getIdentifier()->getNameStart();
589   } else {
590     // Make an unambiguous representation for anonymous types, e.g.
591     //   <anonymous enum at /usr/include/string.h:120:9>
592     llvm::raw_string_ostream OS(Buffer);
593     OS << "<anonymous";
594 
595     if (Policy.AnonymousTagLocations) {
596       // Suppress the redundant tag keyword if we just printed one.
597       // We don't have to worry about ElaboratedTypes here because you can't
598       // refer to an anonymous type with one.
599       if (!HasKindDecoration)
600         OS << " " << D->getKindName();
601 
602       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
603           D->getLocation());
604       if (PLoc.isValid()) {
605         OS << " at " << PLoc.getFilename()
606            << ':' << PLoc.getLine()
607            << ':' << PLoc.getColumn();
608       }
609     }
610 
611     OS << '>';
612   }
613 
614   // If this is a class template specialization, print the template
615   // arguments.
616   if (ClassTemplateSpecializationDecl *Spec
617         = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
618     const TemplateArgument *Args;
619     unsigned NumArgs;
620     if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
621       const TemplateSpecializationType *TST =
622         cast<TemplateSpecializationType>(TAW->getType());
623       Args = TST->getArgs();
624       NumArgs = TST->getNumArgs();
625     } else {
626       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
627       Args = TemplateArgs.data();
628       NumArgs = TemplateArgs.size();
629     }
630     Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
631                                                                     NumArgs,
632                                                                     Policy);
633   }
634 
635   if (!InnerString.empty()) {
636     Buffer += ' ';
637     Buffer += InnerString;
638   }
639 
640   std::swap(Buffer, InnerString);
641 }
642 
643 void TypePrinter::printRecord(const RecordType *T, std::string &S) {
644   printTag(T->getDecl(), S);
645 }
646 
647 void TypePrinter::printEnum(const EnumType *T, std::string &S) {
648   printTag(T->getDecl(), S);
649 }
650 
651 void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
652                                         std::string &S) {
653   if (!S.empty())    // Prefix the basic type, e.g. 'parmname X'.
654     S = ' ' + S;
655 
656   if (!T->getName())
657     S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
658         llvm::utostr_32(T->getIndex()) + S;
659   else
660     S = T->getName()->getName().str() + S;
661 }
662 
663 void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
664                                              std::string &S) {
665   print(T->getReplacementType(), S);
666 }
667 
668 void TypePrinter::printSubstTemplateTypeParmPack(
669                                         const SubstTemplateTypeParmPackType *T,
670                                              std::string &S) {
671   printTemplateTypeParm(T->getReplacedParameter(), S);
672 }
673 
674 void TypePrinter::printTemplateSpecialization(
675                                             const TemplateSpecializationType *T,
676                                               std::string &S) {
677   std::string SpecString;
678 
679   {
680     llvm::raw_string_ostream OS(SpecString);
681     T->getTemplateName().print(OS, Policy);
682   }
683 
684   SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
685                                                                   T->getArgs(),
686                                                                 T->getNumArgs(),
687                                                                       Policy);
688   if (S.empty())
689     S.swap(SpecString);
690   else
691     S = SpecString + ' ' + S;
692 }
693 
694 void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
695                                          std::string &S) {
696   printTemplateSpecialization(T->getInjectedTST(), S);
697 }
698 
699 void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
700   std::string MyString;
701 
702   {
703     llvm::raw_string_ostream OS(MyString);
704     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
705     if (T->getKeyword() != ETK_None)
706       OS << " ";
707     NestedNameSpecifier* Qualifier = T->getQualifier();
708     if (Qualifier)
709       Qualifier->print(OS, Policy);
710   }
711 
712   std::string TypeStr;
713   PrintingPolicy InnerPolicy(Policy);
714   InnerPolicy.SuppressTagKeyword = true;
715   InnerPolicy.SuppressScope = true;
716   TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
717 
718   MyString += TypeStr;
719   if (S.empty())
720     S.swap(MyString);
721   else
722     S = MyString + ' ' + S;
723 }
724 
725 void TypePrinter::printParen(const ParenType *T, std::string &S) {
726   if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
727     S = '(' + S + ')';
728   print(T->getInnerType(), S);
729 }
730 
731 void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
732   std::string MyString;
733 
734   {
735     llvm::raw_string_ostream OS(MyString);
736     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
737     if (T->getKeyword() != ETK_None)
738       OS << " ";
739 
740     T->getQualifier()->print(OS, Policy);
741 
742     OS << T->getIdentifier()->getName();
743   }
744 
745   if (S.empty())
746     S.swap(MyString);
747   else
748     S = MyString + ' ' + S;
749 }
750 
751 void TypePrinter::printDependentTemplateSpecialization(
752         const DependentTemplateSpecializationType *T, std::string &S) {
753   std::string MyString;
754   {
755     llvm::raw_string_ostream OS(MyString);
756 
757     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
758     if (T->getKeyword() != ETK_None)
759       OS << " ";
760 
761     if (T->getQualifier())
762       T->getQualifier()->print(OS, Policy);
763     OS << T->getIdentifier()->getName();
764     OS << TemplateSpecializationType::PrintTemplateArgumentList(
765                                                             T->getArgs(),
766                                                             T->getNumArgs(),
767                                                             Policy);
768   }
769 
770   if (S.empty())
771     S.swap(MyString);
772   else
773     S = MyString + ' ' + S;
774 }
775 
776 void TypePrinter::printPackExpansion(const PackExpansionType *T,
777                                      std::string &S) {
778   print(T->getPattern(), S);
779   S += "...";
780 }
781 
782 void TypePrinter::printAttributed(const AttributedType *T,
783                                   std::string &S) {
784   // Prefer the macro forms of the GC qualifiers.
785   if (T->getAttrKind() == AttributedType::attr_objc_gc)
786     return print(T->getEquivalentType(), S);
787 
788   print(T->getModifiedType(), S);
789 
790   // TODO: not all attributes are GCC-style attributes.
791   S += " __attribute__((";
792   switch (T->getAttrKind()) {
793   case AttributedType::attr_address_space:
794     S += "address_space(";
795     S += T->getEquivalentType().getAddressSpace();
796     S += ")";
797     break;
798 
799   case AttributedType::attr_vector_size: {
800     S += "__vector_size__(";
801     if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
802       S += vector->getNumElements();
803       S += " * sizeof(";
804 
805       std::string tmp;
806       print(vector->getElementType(), tmp);
807       S += tmp;
808       S += ")";
809     }
810     S += ")";
811     break;
812   }
813 
814   case AttributedType::attr_neon_vector_type:
815   case AttributedType::attr_neon_polyvector_type: {
816     if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
817       S += "neon_vector_type(";
818     else
819       S += "neon_polyvector_type(";
820     const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
821     S += llvm::utostr_32(vector->getNumElements());
822     S += ")";
823     break;
824   }
825 
826   case AttributedType::attr_regparm: {
827     S += "regparm(";
828     QualType t = T->getEquivalentType();
829     while (!t->isFunctionType())
830       t = t->getPointeeType();
831     S += t->getAs<FunctionType>()->getRegParmType();
832     S += ")";
833     break;
834   }
835 
836   case AttributedType::attr_objc_gc: {
837     S += "objc_gc(";
838 
839     QualType tmp = T->getEquivalentType();
840     while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
841       QualType next = tmp->getPointeeType();
842       if (next == tmp) break;
843       tmp = next;
844     }
845 
846     if (tmp.isObjCGCWeak())
847       S += "weak";
848     else
849       S += "strong";
850     S += ")";
851     break;
852   }
853 
854   case AttributedType::attr_noreturn: S += "noreturn"; break;
855   case AttributedType::attr_cdecl: S += "cdecl"; break;
856   case AttributedType::attr_fastcall: S += "fastcall"; break;
857   case AttributedType::attr_stdcall: S += "stdcall"; break;
858   case AttributedType::attr_thiscall: S += "thiscall"; break;
859   case AttributedType::attr_pascal: S += "pascal"; break;
860   case AttributedType::attr_pcs: {
861    S += "pcs(";
862    QualType t = T->getEquivalentType();
863    while (!t->isFunctionType())
864      t = t->getPointeeType();
865    S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
866          "\"aapcs\"" : "\"aapcs-vfp\"");
867    S += ")";
868    break;
869   }
870   }
871   S += "))";
872 }
873 
874 void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
875                                      std::string &S) {
876   if (!S.empty())    // Prefix the basic type, e.g. 'typedefname X'.
877     S = ' ' + S;
878 
879   std::string ObjCQIString = T->getDecl()->getNameAsString();
880   S = ObjCQIString + S;
881 }
882 
883 void TypePrinter::printObjCObject(const ObjCObjectType *T,
884                                   std::string &S) {
885   if (T->qual_empty())
886     return print(T->getBaseType(), S);
887 
888   std::string tmp;
889   print(T->getBaseType(), tmp);
890   tmp += '<';
891   bool isFirst = true;
892   for (ObjCObjectType::qual_iterator
893          I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
894     if (isFirst)
895       isFirst = false;
896     else
897       tmp += ',';
898     tmp += (*I)->getNameAsString();
899   }
900   tmp += '>';
901 
902   if (!S.empty()) {
903     tmp += ' ';
904     tmp += S;
905   }
906   std::swap(tmp, S);
907 }
908 
909 void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
910                                          std::string &S) {
911   std::string ObjCQIString;
912 
913   T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
914                                                                Policy);
915   if (!ObjCQIString.empty())
916     ObjCQIString += ' ';
917 
918   if (T->isObjCIdType() || T->isObjCQualifiedIdType())
919     ObjCQIString += "id";
920   else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
921     ObjCQIString += "Class";
922   else if (T->isObjCSelType())
923     ObjCQIString += "SEL";
924   else
925     ObjCQIString += T->getInterfaceDecl()->getNameAsString();
926 
927   if (!T->qual_empty()) {
928     ObjCQIString += '<';
929     for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
930                                               E = T->qual_end();
931          I != E; ++I) {
932       ObjCQIString += (*I)->getNameAsString();
933       if (I+1 != E)
934         ObjCQIString += ',';
935     }
936     ObjCQIString += '>';
937   }
938 
939   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
940     ObjCQIString += " *"; // Don't forget the implicit pointer.
941   else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
942     S = ' ' + S;
943 
944   S = ObjCQIString + S;
945 }
946 
947 std::string TemplateSpecializationType::
948   PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
949                             const PrintingPolicy &Policy) {
950   return PrintTemplateArgumentList(Args.getArgumentArray(),
951                                    Args.size(),
952                                    Policy);
953 }
954 
955 std::string
956 TemplateSpecializationType::PrintTemplateArgumentList(
957                                                 const TemplateArgument *Args,
958                                                 unsigned NumArgs,
959                                                   const PrintingPolicy &Policy,
960                                                       bool SkipBrackets) {
961   std::string SpecString;
962   if (!SkipBrackets)
963     SpecString += '<';
964 
965   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
966     if (SpecString.size() > !SkipBrackets)
967       SpecString += ", ";
968 
969     // Print the argument into a string.
970     std::string ArgString;
971     if (Args[Arg].getKind() == TemplateArgument::Pack) {
972       ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
973                                             Args[Arg].pack_size(),
974                                             Policy, true);
975     } else {
976       llvm::raw_string_ostream ArgOut(ArgString);
977       Args[Arg].print(Policy, ArgOut);
978     }
979 
980     // If this is the first argument and its string representation
981     // begins with the global scope specifier ('::foo'), add a space
982     // to avoid printing the diagraph '<:'.
983     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
984       SpecString += ' ';
985 
986     SpecString += ArgString;
987   }
988 
989   // If the last character of our string is '>', add another space to
990   // keep the two '>''s separate tokens. We don't *have* to do this in
991   // C++0x, but it's still good hygiene.
992   if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
993     SpecString += ' ';
994 
995   if (!SkipBrackets)
996     SpecString += '>';
997 
998   return SpecString;
999 }
1000 
1001 // Sadly, repeat all that with TemplateArgLoc.
1002 std::string TemplateSpecializationType::
1003 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
1004                           const PrintingPolicy &Policy) {
1005   std::string SpecString;
1006   SpecString += '<';
1007   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1008     if (SpecString.size() > 1)
1009       SpecString += ", ";
1010 
1011     // Print the argument into a string.
1012     std::string ArgString;
1013     if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1014       ArgString = PrintTemplateArgumentList(
1015                                            Args[Arg].getArgument().pack_begin(),
1016                                             Args[Arg].getArgument().pack_size(),
1017                                             Policy, true);
1018     } else {
1019       llvm::raw_string_ostream ArgOut(ArgString);
1020       Args[Arg].getArgument().print(Policy, ArgOut);
1021     }
1022 
1023     // If this is the first argument and its string representation
1024     // begins with the global scope specifier ('::foo'), add a space
1025     // to avoid printing the diagraph '<:'.
1026     if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1027       SpecString += ' ';
1028 
1029     SpecString += ArgString;
1030   }
1031 
1032   // If the last character of our string is '>', add another space to
1033   // keep the two '>''s separate tokens. We don't *have* to do this in
1034   // C++0x, but it's still good hygiene.
1035   if (SpecString[SpecString.size() - 1] == '>')
1036     SpecString += ' ';
1037 
1038   SpecString += '>';
1039 
1040   return SpecString;
1041 }
1042 
1043 void QualType::dump(const char *msg) const {
1044   std::string R = "identifier";
1045   LangOptions LO;
1046   getAsStringInternal(R, PrintingPolicy(LO));
1047   if (msg)
1048     llvm::errs() << msg << ": ";
1049   llvm::errs() << R << "\n";
1050 }
1051 void QualType::dump() const {
1052   dump("");
1053 }
1054 
1055 void Type::dump() const {
1056   QualType(this, 0).dump();
1057 }
1058 
1059 std::string Qualifiers::getAsString() const {
1060   LangOptions LO;
1061   return getAsString(PrintingPolicy(LO));
1062 }
1063 
1064 // Appends qualifiers to the given string, separated by spaces.  Will
1065 // prefix a space if the string is non-empty.  Will not append a final
1066 // space.
1067 void Qualifiers::getAsStringInternal(std::string &S,
1068                                      const PrintingPolicy&) const {
1069   AppendTypeQualList(S, getCVRQualifiers());
1070   if (unsigned addrspace = getAddressSpace()) {
1071     if (!S.empty()) S += ' ';
1072     S += "__attribute__((address_space(";
1073     S += llvm::utostr_32(addrspace);
1074     S += ")))";
1075   }
1076   if (Qualifiers::GC gc = getObjCGCAttr()) {
1077     if (!S.empty()) S += ' ';
1078     if (gc == Qualifiers::Weak)
1079       S += "__weak";
1080     else
1081       S += "__strong";
1082   }
1083 }
1084 
1085 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1086   std::string buffer;
1087   LangOptions options;
1088   getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1089   return buffer;
1090 }
1091 
1092 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1093                                    std::string &buffer,
1094                                    const PrintingPolicy &policy) {
1095   TypePrinter(policy).print(ty, qs, buffer);
1096 }
1097