When printing a qualified type, look through a substituted template
[clang.git] / lib / AST / TypePrinter.cpp
blob5e6046acdc578313b6cbbcc3aa8bc2fdadd03591
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.
12 //===----------------------------------------------------------------------===//
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;
26 namespace {
27 class TypePrinter {
28 PrintingPolicy Policy;
30 public:
31 explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
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"
44 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
45 if (TypeQuals & Qualifiers::Const) {
46 if (!S.empty()) S += ' ';
47 S += "const";
49 if (TypeQuals & Qualifiers::Volatile) {
50 if (!S.empty()) S += ' ';
51 S += "volatile";
53 if (TypeQuals & Qualifiers::Restrict) {
54 if (!S.empty()) S += ' ';
55 S += "restrict";
59 void TypePrinter::print(QualType t, std::string &buffer) {
60 SplitQualType split = t.split();
61 print(split.first, split.second, buffer);
64 void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
65 if (!T) {
66 buffer += "NULL TYPE";
67 return;
70 if (Policy.SuppressSpecifiers && T->isSpecifierType())
71 return;
73 // Print qualifiers as appropriate.
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;
82 Type::TypeClass TC = T->getTypeClass();
83 if (const SubstTemplateTypeParmType *Subst
84 = dyn_cast<SubstTemplateTypeParmType>(T))
85 TC = Subst->getReplacementType()->getTypeClass();
87 switch (TC) {
88 case Type::Builtin:
89 case Type::Complex:
90 case Type::UnresolvedUsing:
91 case Type::Typedef:
92 case Type::TypeOfExpr:
93 case Type::TypeOf:
94 case Type::Decltype:
95 case Type::Record:
96 case Type::Enum:
97 case Type::Elaborated:
98 case Type::TemplateTypeParm:
99 case Type::SubstTemplateTypeParmPack:
100 case Type::TemplateSpecialization:
101 case Type::InjectedClassName:
102 case Type::DependentName:
103 case Type::DependentTemplateSpecialization:
104 case Type::ObjCObject:
105 case Type::ObjCInterface:
106 CanPrefixQualifiers = true;
107 break;
109 case Type::ObjCObjectPointer:
110 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
111 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
112 break;
114 case Type::Pointer:
115 case Type::BlockPointer:
116 case Type::LValueReference:
117 case Type::RValueReference:
118 case Type::MemberPointer:
119 case Type::ConstantArray:
120 case Type::IncompleteArray:
121 case Type::VariableArray:
122 case Type::DependentSizedArray:
123 case Type::DependentSizedExtVector:
124 case Type::Vector:
125 case Type::ExtVector:
126 case Type::FunctionProto:
127 case Type::FunctionNoProto:
128 case Type::Paren:
129 case Type::Attributed:
130 case Type::PackExpansion:
131 case Type::SubstTemplateTypeParm:
132 CanPrefixQualifiers = false;
133 break;
136 if (!CanPrefixQualifiers && !Quals.empty()) {
137 std::string qualsBuffer;
138 Quals.getAsStringInternal(qualsBuffer, Policy);
140 if (!buffer.empty()) {
141 qualsBuffer += ' ';
142 qualsBuffer += buffer;
144 std::swap(buffer, qualsBuffer);
147 switch (T->getTypeClass()) {
148 #define ABSTRACT_TYPE(CLASS, PARENT)
149 #define TYPE(CLASS, PARENT) case Type::CLASS: \
150 print##CLASS(cast<CLASS##Type>(T), buffer); \
151 break;
152 #include "clang/AST/TypeNodes.def"
155 // If we're adding the qualifiers as a prefix, do it now.
156 if (CanPrefixQualifiers && !Quals.empty()) {
157 std::string qualsBuffer;
158 Quals.getAsStringInternal(qualsBuffer, Policy);
160 if (!buffer.empty()) {
161 qualsBuffer += ' ';
162 qualsBuffer += buffer;
164 std::swap(buffer, qualsBuffer);
168 void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
169 if (S.empty()) {
170 S = T->getName(Policy.LangOpts);
171 } else {
172 // Prefix the basic type, e.g. 'int X'.
173 S = ' ' + S;
174 S = T->getName(Policy.LangOpts) + S;
178 void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
179 print(T->getElementType(), S);
180 S = "_Complex " + S;
183 void TypePrinter::printPointer(const PointerType *T, std::string &S) {
184 S = '*' + S;
186 // Handle things like 'int (*A)[4];' correctly.
187 // FIXME: this should include vectors, but vectors use attributes I guess.
188 if (isa<ArrayType>(T->getPointeeType()))
189 S = '(' + S + ')';
191 print(T->getPointeeType(), S);
194 void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
195 S = '^' + S;
196 print(T->getPointeeType(), S);
199 void TypePrinter::printLValueReference(const LValueReferenceType *T,
200 std::string &S) {
201 S = '&' + S;
203 // Handle things like 'int (&A)[4];' correctly.
204 // FIXME: this should include vectors, but vectors use attributes I guess.
205 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
206 S = '(' + S + ')';
208 print(T->getPointeeTypeAsWritten(), S);
211 void TypePrinter::printRValueReference(const RValueReferenceType *T,
212 std::string &S) {
213 S = "&&" + S;
215 // Handle things like 'int (&&A)[4];' correctly.
216 // FIXME: this should include vectors, but vectors use attributes I guess.
217 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
218 S = '(' + S + ')';
220 print(T->getPointeeTypeAsWritten(), S);
223 void TypePrinter::printMemberPointer(const MemberPointerType *T,
224 std::string &S) {
225 std::string C;
226 print(QualType(T->getClass(), 0), C);
227 C += "::*";
228 S = C + S;
230 // Handle things like 'int (Cls::*A)[4];' correctly.
231 // FIXME: this should include vectors, but vectors use attributes I guess.
232 if (isa<ArrayType>(T->getPointeeType()))
233 S = '(' + S + ')';
235 print(T->getPointeeType(), S);
238 void TypePrinter::printConstantArray(const ConstantArrayType *T,
239 std::string &S) {
240 S += '[';
241 S += llvm::utostr(T->getSize().getZExtValue());
242 S += ']';
244 print(T->getElementType(), S);
247 void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
248 std::string &S) {
249 S += "[]";
250 print(T->getElementType(), S);
253 void TypePrinter::printVariableArray(const VariableArrayType *T,
254 std::string &S) {
255 S += '[';
257 if (T->getIndexTypeQualifiers().hasQualifiers()) {
258 AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
259 S += ' ';
262 if (T->getSizeModifier() == VariableArrayType::Static)
263 S += "static";
264 else if (T->getSizeModifier() == VariableArrayType::Star)
265 S += '*';
267 if (T->getSizeExpr()) {
268 std::string SStr;
269 llvm::raw_string_ostream s(SStr);
270 T->getSizeExpr()->printPretty(s, 0, Policy);
271 S += s.str();
273 S += ']';
275 print(T->getElementType(), S);
278 void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T,
279 std::string &S) {
280 S += '[';
282 if (T->getSizeExpr()) {
283 std::string SStr;
284 llvm::raw_string_ostream s(SStr);
285 T->getSizeExpr()->printPretty(s, 0, Policy);
286 S += s.str();
288 S += ']';
290 print(T->getElementType(), S);
293 void TypePrinter::printDependentSizedExtVector(
294 const DependentSizedExtVectorType *T,
295 std::string &S) {
296 print(T->getElementType(), S);
298 S += " __attribute__((ext_vector_type(";
299 if (T->getSizeExpr()) {
300 std::string SStr;
301 llvm::raw_string_ostream s(SStr);
302 T->getSizeExpr()->printPretty(s, 0, Policy);
303 S += s.str();
305 S += ")))";
308 void TypePrinter::printVector(const VectorType *T, std::string &S) {
309 switch (T->getVectorKind()) {
310 case VectorType::AltiVecPixel:
311 S = "__vector __pixel " + S;
312 break;
313 case VectorType::AltiVecBool:
314 print(T->getElementType(), S);
315 S = "__vector __bool " + S;
316 break;
317 case VectorType::AltiVecVector:
318 print(T->getElementType(), S);
319 S = "__vector " + S;
320 break;
321 case VectorType::NeonVector:
322 print(T->getElementType(), S);
323 S = ("__attribute__((neon_vector_type(" +
324 llvm::utostr_32(T->getNumElements()) + "))) " + S);
325 break;
326 case VectorType::NeonPolyVector:
327 print(T->getElementType(), S);
328 S = ("__attribute__((neon_polyvector_type(" +
329 llvm::utostr_32(T->getNumElements()) + "))) " + S);
330 break;
331 case VectorType::GenericVector: {
332 // FIXME: We prefer to print the size directly here, but have no way
333 // to get the size of the type.
334 print(T->getElementType(), S);
335 std::string V = "__attribute__((__vector_size__(";
336 V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
337 std::string ET;
338 print(T->getElementType(), ET);
339 V += " * sizeof(" + ET + ")))) ";
340 S = V + S;
341 break;
346 void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) {
347 S += " __attribute__((ext_vector_type(";
348 S += llvm::utostr_32(T->getNumElements());
349 S += ")))";
350 print(T->getElementType(), S);
353 void TypePrinter::printFunctionProto(const FunctionProtoType *T,
354 std::string &S) {
355 // If needed for precedence reasons, wrap the inner part in grouping parens.
356 if (!S.empty())
357 S = "(" + S + ")";
359 S += "(";
360 std::string Tmp;
361 PrintingPolicy ParamPolicy(Policy);
362 ParamPolicy.SuppressSpecifiers = false;
363 for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
364 if (i) S += ", ";
365 print(T->getArgType(i), Tmp);
366 S += Tmp;
367 Tmp.clear();
370 if (T->isVariadic()) {
371 if (T->getNumArgs())
372 S += ", ";
373 S += "...";
374 } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
375 // Do not emit int() if we have a proto, emit 'int(void)'.
376 S += "void";
379 S += ")";
381 FunctionType::ExtInfo Info = T->getExtInfo();
382 switch(Info.getCC()) {
383 case CC_Default:
384 default: break;
385 case CC_C:
386 S += " __attribute__((cdecl))";
387 break;
388 case CC_X86StdCall:
389 S += " __attribute__((stdcall))";
390 break;
391 case CC_X86FastCall:
392 S += " __attribute__((fastcall))";
393 break;
394 case CC_X86ThisCall:
395 S += " __attribute__((thiscall))";
396 break;
397 case CC_X86Pascal:
398 S += " __attribute__((pascal))";
399 break;
401 if (Info.getNoReturn())
402 S += " __attribute__((noreturn))";
403 if (Info.getRegParm())
404 S += " __attribute__((regparm (" +
405 llvm::utostr_32(Info.getRegParm()) + ")))";
407 AppendTypeQualList(S, T->getTypeQuals());
409 switch (T->getRefQualifier()) {
410 case RQ_None:
411 break;
413 case RQ_LValue:
414 S += " &";
415 break;
417 case RQ_RValue:
418 S += " &&";
419 break;
422 if (T->hasExceptionSpec()) {
423 S += " throw(";
424 if (T->hasAnyExceptionSpec())
425 S += "...";
426 else
427 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
428 if (I)
429 S += ", ";
431 std::string ExceptionType;
432 print(T->getExceptionType(I), ExceptionType);
433 S += ExceptionType;
435 S += ")";
438 print(T->getResultType(), S);
441 void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
442 std::string &S) {
443 // If needed for precedence reasons, wrap the inner part in grouping parens.
444 if (!S.empty())
445 S = "(" + S + ")";
447 S += "()";
448 if (T->getNoReturnAttr())
449 S += " __attribute__((noreturn))";
450 print(T->getResultType(), S);
453 static void printTypeSpec(const NamedDecl *D, std::string &S) {
454 IdentifierInfo *II = D->getIdentifier();
455 if (S.empty())
456 S = II->getName().str();
457 else
458 S = II->getName().str() + ' ' + S;
461 void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
462 std::string &S) {
463 printTypeSpec(T->getDecl(), S);
466 void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
467 printTypeSpec(T->getDecl(), S);
470 void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
471 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(e) X'.
472 S = ' ' + S;
473 std::string Str;
474 llvm::raw_string_ostream s(Str);
475 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
476 S = "typeof " + s.str() + S;
479 void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
480 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(t) X'.
481 S = ' ' + S;
482 std::string Tmp;
483 print(T->getUnderlyingType(), Tmp);
484 S = "typeof(" + Tmp + ")" + S;
487 void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
488 if (!S.empty()) // Prefix the basic type, e.g. 'decltype(t) X'.
489 S = ' ' + S;
490 std::string Str;
491 llvm::raw_string_ostream s(Str);
492 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
493 S = "decltype(" + s.str() + ")" + S;
496 /// Appends the given scope to the end of a string.
497 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
498 if (DC->isTranslationUnit()) return;
499 AppendScope(DC->getParent(), Buffer);
501 unsigned OldSize = Buffer.size();
503 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
504 if (NS->getIdentifier())
505 Buffer += NS->getNameAsString();
506 else
507 Buffer += "<anonymous>";
508 } else if (ClassTemplateSpecializationDecl *Spec
509 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
510 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
511 std::string TemplateArgsStr
512 = TemplateSpecializationType::PrintTemplateArgumentList(
513 TemplateArgs.data(),
514 TemplateArgs.size(),
515 Policy);
516 Buffer += Spec->getIdentifier()->getName();
517 Buffer += TemplateArgsStr;
518 } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
519 if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
520 Buffer += Typedef->getIdentifier()->getName();
521 else if (Tag->getIdentifier())
522 Buffer += Tag->getIdentifier()->getName();
525 if (Buffer.size() != OldSize)
526 Buffer += "::";
529 void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
530 if (Policy.SuppressTag)
531 return;
533 std::string Buffer;
534 bool HasKindDecoration = false;
536 // We don't print tags unless this is an elaborated type.
537 // In C, we just assume every RecordType is an elaborated type.
538 if (!Policy.LangOpts.CPlusPlus && !D->getTypedefForAnonDecl()) {
539 HasKindDecoration = true;
540 Buffer += D->getKindName();
541 Buffer += ' ';
544 // Compute the full nested-name-specifier for this type.
545 // In C, this will always be empty except when the type
546 // being printed is anonymous within other Record.
547 if (!Policy.SuppressScope)
548 AppendScope(D->getDeclContext(), Buffer);
550 if (const IdentifierInfo *II = D->getIdentifier())
551 Buffer += II->getNameStart();
552 else if (TypedefDecl *Typedef = D->getTypedefForAnonDecl()) {
553 assert(Typedef->getIdentifier() && "Typedef without identifier?");
554 Buffer += Typedef->getIdentifier()->getNameStart();
555 } else {
556 // Make an unambiguous representation for anonymous types, e.g.
557 // <anonymous enum at /usr/include/string.h:120:9>
558 llvm::raw_string_ostream OS(Buffer);
559 OS << "<anonymous";
561 if (Policy.AnonymousTagLocations) {
562 // Suppress the redundant tag keyword if we just printed one.
563 // We don't have to worry about ElaboratedTypes here because you can't
564 // refer to an anonymous type with one.
565 if (!HasKindDecoration)
566 OS << " " << D->getKindName();
568 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
569 D->getLocation());
570 if (PLoc.isValid()) {
571 OS << " at " << PLoc.getFilename()
572 << ':' << PLoc.getLine()
573 << ':' << PLoc.getColumn();
577 OS << '>';
580 // If this is a class template specialization, print the template
581 // arguments.
582 if (ClassTemplateSpecializationDecl *Spec
583 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
584 const TemplateArgument *Args;
585 unsigned NumArgs;
586 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
587 const TemplateSpecializationType *TST =
588 cast<TemplateSpecializationType>(TAW->getType());
589 Args = TST->getArgs();
590 NumArgs = TST->getNumArgs();
591 } else {
592 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
593 Args = TemplateArgs.data();
594 NumArgs = TemplateArgs.size();
596 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
597 NumArgs,
598 Policy);
601 if (!InnerString.empty()) {
602 Buffer += ' ';
603 Buffer += InnerString;
606 std::swap(Buffer, InnerString);
609 void TypePrinter::printRecord(const RecordType *T, std::string &S) {
610 printTag(T->getDecl(), S);
613 void TypePrinter::printEnum(const EnumType *T, std::string &S) {
614 printTag(T->getDecl(), S);
617 void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
618 std::string &S) {
619 if (!S.empty()) // Prefix the basic type, e.g. 'parmname X'.
620 S = ' ' + S;
622 if (!T->getName())
623 S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
624 llvm::utostr_32(T->getIndex()) + S;
625 else
626 S = T->getName()->getName().str() + S;
629 void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
630 std::string &S) {
631 print(T->getReplacementType(), S);
634 void TypePrinter::printSubstTemplateTypeParmPack(
635 const SubstTemplateTypeParmPackType *T,
636 std::string &S) {
637 printTemplateTypeParm(T->getReplacedParameter(), S);
640 void TypePrinter::printTemplateSpecialization(
641 const TemplateSpecializationType *T,
642 std::string &S) {
643 std::string SpecString;
646 llvm::raw_string_ostream OS(SpecString);
647 T->getTemplateName().print(OS, Policy);
650 SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
651 T->getArgs(),
652 T->getNumArgs(),
653 Policy);
654 if (S.empty())
655 S.swap(SpecString);
656 else
657 S = SpecString + ' ' + S;
660 void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
661 std::string &S) {
662 printTemplateSpecialization(T->getInjectedTST(), S);
665 void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
666 std::string MyString;
669 llvm::raw_string_ostream OS(MyString);
670 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
671 if (T->getKeyword() != ETK_None)
672 OS << " ";
673 NestedNameSpecifier* Qualifier = T->getQualifier();
674 if (Qualifier)
675 Qualifier->print(OS, Policy);
678 std::string TypeStr;
679 PrintingPolicy InnerPolicy(Policy);
680 InnerPolicy.SuppressScope = true;
681 TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
683 MyString += TypeStr;
684 if (S.empty())
685 S.swap(MyString);
686 else
687 S = MyString + ' ' + S;
690 void TypePrinter::printParen(const ParenType *T, std::string &S) {
691 if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
692 S = '(' + S + ')';
693 print(T->getInnerType(), S);
696 void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
697 std::string MyString;
700 llvm::raw_string_ostream OS(MyString);
701 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
702 if (T->getKeyword() != ETK_None)
703 OS << " ";
705 T->getQualifier()->print(OS, Policy);
707 OS << T->getIdentifier()->getName();
710 if (S.empty())
711 S.swap(MyString);
712 else
713 S = MyString + ' ' + S;
716 void TypePrinter::printDependentTemplateSpecialization(
717 const DependentTemplateSpecializationType *T, std::string &S) {
718 std::string MyString;
720 llvm::raw_string_ostream OS(MyString);
722 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
723 if (T->getKeyword() != ETK_None)
724 OS << " ";
726 T->getQualifier()->print(OS, Policy);
727 OS << T->getIdentifier()->getName();
728 OS << TemplateSpecializationType::PrintTemplateArgumentList(
729 T->getArgs(),
730 T->getNumArgs(),
731 Policy);
734 if (S.empty())
735 S.swap(MyString);
736 else
737 S = MyString + ' ' + S;
740 void TypePrinter::printPackExpansion(const PackExpansionType *T,
741 std::string &S) {
742 print(T->getPattern(), S);
743 S += "...";
746 void TypePrinter::printAttributed(const AttributedType *T,
747 std::string &S) {
748 print(T->getModifiedType(), S);
750 // TODO: not all attributes are GCC-style attributes.
751 S += "__attribute__((";
752 switch (T->getAttrKind()) {
753 case AttributedType::attr_address_space:
754 S += "address_space(";
755 S += T->getEquivalentType().getAddressSpace();
756 S += ")";
757 break;
759 case AttributedType::attr_vector_size: {
760 S += "__vector_size__(";
761 if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
762 S += vector->getNumElements();
763 S += " * sizeof(";
765 std::string tmp;
766 print(vector->getElementType(), tmp);
767 S += tmp;
768 S += ")";
770 S += ")";
771 break;
774 case AttributedType::attr_neon_vector_type:
775 case AttributedType::attr_neon_polyvector_type: {
776 if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
777 S += "neon_vector_type(";
778 else
779 S += "neon_polyvector_type(";
780 const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
781 S += llvm::utostr_32(vector->getNumElements());
782 S += ")";
783 break;
786 case AttributedType::attr_regparm: {
787 S += "regparm(";
788 QualType t = T->getEquivalentType();
789 while (!t->isFunctionType())
790 t = t->getPointeeType();
791 S += t->getAs<FunctionType>()->getRegParmType();
792 S += ")";
793 break;
796 case AttributedType::attr_objc_gc: {
797 S += "objc_gc(";
799 QualType tmp = T->getEquivalentType();
800 while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
801 QualType next = tmp->getPointeeType();
802 if (next == tmp) break;
803 tmp = next;
806 if (tmp.isObjCGCWeak())
807 S += "weak";
808 else
809 S += "strong";
810 S += ")";
811 break;
814 case AttributedType::attr_noreturn: S += "noreturn"; break;
815 case AttributedType::attr_cdecl: S += "cdecl"; break;
816 case AttributedType::attr_fastcall: S += "fastcall"; break;
817 case AttributedType::attr_stdcall: S += "stdcall"; break;
818 case AttributedType::attr_thiscall: S += "thiscall"; break;
819 case AttributedType::attr_pascal: S += "pascal"; break;
821 S += "))";
824 void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
825 std::string &S) {
826 if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
827 S = ' ' + S;
829 std::string ObjCQIString = T->getDecl()->getNameAsString();
830 S = ObjCQIString + S;
833 void TypePrinter::printObjCObject(const ObjCObjectType *T,
834 std::string &S) {
835 if (T->qual_empty())
836 return print(T->getBaseType(), S);
838 std::string tmp;
839 print(T->getBaseType(), tmp);
840 tmp += '<';
841 bool isFirst = true;
842 for (ObjCObjectType::qual_iterator
843 I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
844 if (isFirst)
845 isFirst = false;
846 else
847 tmp += ',';
848 tmp += (*I)->getNameAsString();
850 tmp += '>';
852 if (!S.empty()) {
853 tmp += ' ';
854 tmp += S;
856 std::swap(tmp, S);
859 void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
860 std::string &S) {
861 std::string ObjCQIString;
863 T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
864 Policy);
865 if (!ObjCQIString.empty())
866 ObjCQIString += ' ';
868 if (T->isObjCIdType() || T->isObjCQualifiedIdType())
869 ObjCQIString += "id";
870 else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
871 ObjCQIString += "Class";
872 else if (T->isObjCSelType())
873 ObjCQIString += "SEL";
874 else
875 ObjCQIString += T->getInterfaceDecl()->getNameAsString();
877 if (!T->qual_empty()) {
878 ObjCQIString += '<';
879 for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
880 E = T->qual_end();
881 I != E; ++I) {
882 ObjCQIString += (*I)->getNameAsString();
883 if (I+1 != E)
884 ObjCQIString += ',';
886 ObjCQIString += '>';
889 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
890 ObjCQIString += " *"; // Don't forget the implicit pointer.
891 else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
892 S = ' ' + S;
894 S = ObjCQIString + S;
897 std::string TemplateSpecializationType::
898 PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
899 const PrintingPolicy &Policy) {
900 return PrintTemplateArgumentList(Args.getArgumentArray(),
901 Args.size(),
902 Policy);
905 std::string
906 TemplateSpecializationType::PrintTemplateArgumentList(
907 const TemplateArgument *Args,
908 unsigned NumArgs,
909 const PrintingPolicy &Policy,
910 bool SkipBrackets) {
911 std::string SpecString;
912 if (!SkipBrackets)
913 SpecString += '<';
915 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
916 if (SpecString.size() > !SkipBrackets)
917 SpecString += ", ";
919 // Print the argument into a string.
920 std::string ArgString;
921 if (Args[Arg].getKind() == TemplateArgument::Pack) {
922 ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
923 Args[Arg].pack_size(),
924 Policy, true);
925 } else {
926 llvm::raw_string_ostream ArgOut(ArgString);
927 Args[Arg].print(Policy, ArgOut);
930 // If this is the first argument and its string representation
931 // begins with the global scope specifier ('::foo'), add a space
932 // to avoid printing the diagraph '<:'.
933 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
934 SpecString += ' ';
936 SpecString += ArgString;
939 // If the last character of our string is '>', add another space to
940 // keep the two '>''s separate tokens. We don't *have* to do this in
941 // C++0x, but it's still good hygiene.
942 if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
943 SpecString += ' ';
945 if (!SkipBrackets)
946 SpecString += '>';
948 return SpecString;
951 // Sadly, repeat all that with TemplateArgLoc.
952 std::string TemplateSpecializationType::
953 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
954 const PrintingPolicy &Policy) {
955 std::string SpecString;
956 SpecString += '<';
957 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
958 if (SpecString.size() > 1)
959 SpecString += ", ";
961 // Print the argument into a string.
962 std::string ArgString;
963 if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
964 ArgString = PrintTemplateArgumentList(
965 Args[Arg].getArgument().pack_begin(),
966 Args[Arg].getArgument().pack_size(),
967 Policy, true);
968 } else {
969 llvm::raw_string_ostream ArgOut(ArgString);
970 Args[Arg].getArgument().print(Policy, ArgOut);
973 // If this is the first argument and its string representation
974 // begins with the global scope specifier ('::foo'), add a space
975 // to avoid printing the diagraph '<:'.
976 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
977 SpecString += ' ';
979 SpecString += ArgString;
982 // If the last character of our string is '>', add another space to
983 // keep the two '>''s separate tokens. We don't *have* to do this in
984 // C++0x, but it's still good hygiene.
985 if (SpecString[SpecString.size() - 1] == '>')
986 SpecString += ' ';
988 SpecString += '>';
990 return SpecString;
993 void QualType::dump(const char *msg) const {
994 std::string R = "identifier";
995 LangOptions LO;
996 getAsStringInternal(R, PrintingPolicy(LO));
997 if (msg)
998 llvm::errs() << msg << ": ";
999 llvm::errs() << R << "\n";
1001 void QualType::dump() const {
1002 dump("");
1005 void Type::dump() const {
1006 QualType(this, 0).dump();
1009 std::string Qualifiers::getAsString() const {
1010 LangOptions LO;
1011 return getAsString(PrintingPolicy(LO));
1014 // Appends qualifiers to the given string, separated by spaces. Will
1015 // prefix a space if the string is non-empty. Will not append a final
1016 // space.
1017 void Qualifiers::getAsStringInternal(std::string &S,
1018 const PrintingPolicy&) const {
1019 AppendTypeQualList(S, getCVRQualifiers());
1020 if (unsigned AddressSpace = getAddressSpace()) {
1021 if (!S.empty()) S += ' ';
1022 S += "__attribute__((address_space(";
1023 S += llvm::utostr_32(AddressSpace);
1024 S += ")))";
1026 if (Qualifiers::GC GCAttrType = getObjCGCAttr()) {
1027 if (!S.empty()) S += ' ';
1028 S += "__attribute__((objc_gc(";
1029 if (GCAttrType == Qualifiers::Weak)
1030 S += "weak";
1031 else
1032 S += "strong";
1033 S += ")))";
1037 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1038 std::string buffer;
1039 LangOptions options;
1040 getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1041 return buffer;
1044 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1045 std::string &buffer,
1046 const PrintingPolicy &policy) {
1047 TypePrinter(policy).print(ty, qs, buffer);