1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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;
28 PrintingPolicy Policy;
31 explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
33 void Print(QualType T, std::string &S);
34 void AppendScope(DeclContext *DC, std::string &S);
35 void PrintTag(TagDecl *T, std::string &S);
36 #define ABSTRACT_TYPE(CLASS, PARENT)
37 #define TYPE(CLASS, PARENT) \
38 void Print##CLASS(const CLASS##Type *T, std::string &S);
39 #include "clang/AST/TypeNodes.def"
43 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
44 if (TypeQuals & Qualifiers::Const) {
45 if (!S.empty()) S += ' ';
48 if (TypeQuals & Qualifiers::Volatile) {
49 if (!S.empty()) S += ' ';
52 if (TypeQuals & Qualifiers::Restrict) {
53 if (!S.empty()) S += ' ';
58 void TypePrinter::Print(QualType T, std::string &S) {
64 if (Policy.SuppressSpecifiers && T->isSpecifierType())
67 // Print qualifiers as appropriate.
68 Qualifiers Quals = T.getLocalQualifiers();
71 Quals.getAsStringInternal(TQS, Policy);
80 switch (T->getTypeClass()) {
81 #define ABSTRACT_TYPE(CLASS, PARENT)
82 #define TYPE(CLASS, PARENT) case Type::CLASS: \
83 Print##CLASS(cast<CLASS##Type>(T.getTypePtr()), S); \
85 #include "clang/AST/TypeNodes.def"
89 void TypePrinter::PrintBuiltin(const BuiltinType *T, std::string &S) {
91 S = T->getName(Policy.LangOpts);
93 // Prefix the basic type, e.g. 'int X'.
95 S = T->getName(Policy.LangOpts) + S;
99 void TypePrinter::PrintComplex(const ComplexType *T, std::string &S) {
100 Print(T->getElementType(), S);
104 void TypePrinter::PrintPointer(const PointerType *T, std::string &S) {
107 // Handle things like 'int (*A)[4];' correctly.
108 // FIXME: this should include vectors, but vectors use attributes I guess.
109 if (isa<ArrayType>(T->getPointeeType()))
112 Print(T->getPointeeType(), S);
115 void TypePrinter::PrintBlockPointer(const BlockPointerType *T, std::string &S) {
117 Print(T->getPointeeType(), S);
120 void TypePrinter::PrintLValueReference(const LValueReferenceType *T,
124 // Handle things like 'int (&A)[4];' correctly.
125 // FIXME: this should include vectors, but vectors use attributes I guess.
126 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
129 Print(T->getPointeeTypeAsWritten(), S);
132 void TypePrinter::PrintRValueReference(const RValueReferenceType *T,
136 // Handle things like 'int (&&A)[4];' correctly.
137 // FIXME: this should include vectors, but vectors use attributes I guess.
138 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
141 Print(T->getPointeeTypeAsWritten(), S);
144 void TypePrinter::PrintMemberPointer(const MemberPointerType *T,
147 Print(QualType(T->getClass(), 0), C);
151 // Handle things like 'int (Cls::*A)[4];' correctly.
152 // FIXME: this should include vectors, but vectors use attributes I guess.
153 if (isa<ArrayType>(T->getPointeeType()))
156 Print(T->getPointeeType(), S);
159 void TypePrinter::PrintConstantArray(const ConstantArrayType *T,
162 S += llvm::utostr(T->getSize().getZExtValue());
165 Print(T->getElementType(), S);
168 void TypePrinter::PrintIncompleteArray(const IncompleteArrayType *T,
171 Print(T->getElementType(), S);
174 void TypePrinter::PrintVariableArray(const VariableArrayType *T,
178 if (T->getIndexTypeQualifiers().hasQualifiers()) {
179 AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
183 if (T->getSizeModifier() == VariableArrayType::Static)
185 else if (T->getSizeModifier() == VariableArrayType::Star)
188 if (T->getSizeExpr()) {
190 llvm::raw_string_ostream s(SStr);
191 T->getSizeExpr()->printPretty(s, 0, Policy);
196 Print(T->getElementType(), S);
199 void TypePrinter::PrintDependentSizedArray(const DependentSizedArrayType *T,
203 if (T->getSizeExpr()) {
205 llvm::raw_string_ostream s(SStr);
206 T->getSizeExpr()->printPretty(s, 0, Policy);
211 Print(T->getElementType(), S);
214 void TypePrinter::PrintDependentSizedExtVector(
215 const DependentSizedExtVectorType *T,
217 Print(T->getElementType(), S);
219 S += " __attribute__((ext_vector_type(";
220 if (T->getSizeExpr()) {
222 llvm::raw_string_ostream s(SStr);
223 T->getSizeExpr()->printPretty(s, 0, Policy);
229 void TypePrinter::PrintVector(const VectorType *T, std::string &S) {
230 if (T->getAltiVecSpecific() != VectorType::NotAltiVec) {
231 if (T->getAltiVecSpecific() == VectorType::Pixel)
232 S = "__vector __pixel " + S;
234 Print(T->getElementType(), S);
235 S = ((T->getAltiVecSpecific() == VectorType::Bool)
236 ? "__vector __bool " : "__vector ") + S;
239 // FIXME: We prefer to print the size directly here, but have no way
240 // to get the size of the type.
241 Print(T->getElementType(), S);
242 std::string V = "__attribute__((__vector_size__(";
243 V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
245 Print(T->getElementType(), ET);
246 V += " * sizeof(" + ET + ")))) ";
251 void TypePrinter::PrintExtVector(const ExtVectorType *T, std::string &S) {
252 S += " __attribute__((ext_vector_type(";
253 S += llvm::utostr_32(T->getNumElements());
255 Print(T->getElementType(), S);
258 void TypePrinter::PrintFunctionProto(const FunctionProtoType *T,
260 // If needed for precedence reasons, wrap the inner part in grouping parens.
266 PrintingPolicy ParamPolicy(Policy);
267 ParamPolicy.SuppressSpecifiers = false;
268 for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
270 Print(T->getArgType(i), Tmp);
275 if (T->isVariadic()) {
279 } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
280 // Do not emit int() if we have a proto, emit 'int(void)'.
286 FunctionType::ExtInfo Info = T->getExtInfo();
287 switch(Info.getCC()) {
291 S += " __attribute__((cdecl))";
294 S += " __attribute__((stdcall))";
297 S += " __attribute__((fastcall))";
300 S += " __attribute__((thiscall))";
303 S += " __attribute__((pascal))";
306 if (Info.getNoReturn())
307 S += " __attribute__((noreturn))";
308 if (Info.getRegParm())
309 S += " __attribute__((regparm (" +
310 llvm::utostr_32(Info.getRegParm()) + ")))";
312 if (T->hasExceptionSpec()) {
314 if (T->hasAnyExceptionSpec())
317 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
321 std::string ExceptionType;
322 Print(T->getExceptionType(I), ExceptionType);
328 AppendTypeQualList(S, T->getTypeQuals());
330 Print(T->getResultType(), S);
333 void TypePrinter::PrintFunctionNoProto(const FunctionNoProtoType *T,
335 // If needed for precedence reasons, wrap the inner part in grouping parens.
340 if (T->getNoReturnAttr())
341 S += " __attribute__((noreturn))";
342 Print(T->getResultType(), S);
345 static void PrintTypeSpec(const NamedDecl *D, std::string &S) {
346 IdentifierInfo *II = D->getIdentifier();
348 S = II->getName().str();
350 S = II->getName().str() + ' ' + S;
353 void TypePrinter::PrintUnresolvedUsing(const UnresolvedUsingType *T,
355 PrintTypeSpec(T->getDecl(), S);
358 void TypePrinter::PrintTypedef(const TypedefType *T, std::string &S) {
359 PrintTypeSpec(T->getDecl(), S);
362 void TypePrinter::PrintTypeOfExpr(const TypeOfExprType *T, std::string &S) {
363 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(e) X'.
366 llvm::raw_string_ostream s(Str);
367 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
368 S = "typeof " + s.str() + S;
371 void TypePrinter::PrintTypeOf(const TypeOfType *T, std::string &S) {
372 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(t) X'.
375 Print(T->getUnderlyingType(), Tmp);
376 S = "typeof(" + Tmp + ")" + S;
379 void TypePrinter::PrintDecltype(const DecltypeType *T, std::string &S) {
380 if (!S.empty()) // Prefix the basic type, e.g. 'decltype(t) X'.
383 llvm::raw_string_ostream s(Str);
384 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
385 S = "decltype(" + s.str() + ")" + S;
388 /// Appends the given scope to the end of a string.
389 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
390 if (DC->isTranslationUnit()) return;
391 AppendScope(DC->getParent(), Buffer);
393 unsigned OldSize = Buffer.size();
395 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
396 if (NS->getIdentifier())
397 Buffer += NS->getNameAsString();
399 Buffer += "<anonymous>";
400 } else if (ClassTemplateSpecializationDecl *Spec
401 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
402 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
403 std::string TemplateArgsStr
404 = TemplateSpecializationType::PrintTemplateArgumentList(
405 TemplateArgs.getFlatArgumentList(),
406 TemplateArgs.flat_size(),
408 Buffer += Spec->getIdentifier()->getName();
409 Buffer += TemplateArgsStr;
410 } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
411 if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
412 Buffer += Typedef->getIdentifier()->getName();
413 else if (Tag->getIdentifier())
414 Buffer += Tag->getIdentifier()->getName();
417 if (Buffer.size() != OldSize)
421 void TypePrinter::PrintTag(TagDecl *D, std::string &InnerString) {
422 if (Policy.SuppressTag)
426 bool HasKindDecoration = false;
428 // We don't print tags unless this is an elaborated type.
429 // In C, we just assume every RecordType is an elaborated type.
430 if (!Policy.LangOpts.CPlusPlus && !D->getTypedefForAnonDecl()) {
431 HasKindDecoration = true;
432 Buffer += D->getKindName();
436 // Compute the full nested-name-specifier for this type.
437 // In C, this will always be empty except when the type
438 // being printed is anonymous within other Record.
439 if (!Policy.SuppressScope)
440 AppendScope(D->getDeclContext(), Buffer);
442 if (const IdentifierInfo *II = D->getIdentifier())
443 Buffer += II->getNameStart();
444 else if (TypedefDecl *Typedef = D->getTypedefForAnonDecl()) {
445 assert(Typedef->getIdentifier() && "Typedef without identifier?");
446 Buffer += Typedef->getIdentifier()->getNameStart();
448 // Make an unambiguous representation for anonymous types, e.g.
449 // <anonymous enum at /usr/include/string.h:120:9>
450 llvm::raw_string_ostream OS(Buffer);
453 if (Policy.AnonymousTagLocations) {
454 // Suppress the redundant tag keyword if we just printed one.
455 // We don't have to worry about ElaboratedTypes here because you can't
456 // refer to an anonymous type with one.
457 if (!HasKindDecoration)
458 OS << " " << D->getKindName();
460 if (D->getLocation().isValid()) {
461 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
463 OS << " at " << PLoc.getFilename()
464 << ':' << PLoc.getLine()
465 << ':' << PLoc.getColumn();
472 // If this is a class template specialization, print the template
474 if (ClassTemplateSpecializationDecl *Spec
475 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
476 const TemplateArgument *Args;
478 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
479 const TemplateSpecializationType *TST =
480 cast<TemplateSpecializationType>(TAW->getType());
481 Args = TST->getArgs();
482 NumArgs = TST->getNumArgs();
484 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
485 Args = TemplateArgs.getFlatArgumentList();
486 NumArgs = TemplateArgs.flat_size();
488 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
493 if (!InnerString.empty()) {
495 Buffer += InnerString;
498 std::swap(Buffer, InnerString);
501 void TypePrinter::PrintRecord(const RecordType *T, std::string &S) {
502 PrintTag(T->getDecl(), S);
505 void TypePrinter::PrintEnum(const EnumType *T, std::string &S) {
506 PrintTag(T->getDecl(), S);
509 void TypePrinter::PrintTemplateTypeParm(const TemplateTypeParmType *T,
511 if (!S.empty()) // Prefix the basic type, e.g. 'parmname X'.
515 S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
516 llvm::utostr_32(T->getIndex()) + S;
518 S = T->getName()->getName().str() + S;
521 void TypePrinter::PrintSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
523 Print(T->getReplacementType(), S);
526 void TypePrinter::PrintTemplateSpecialization(
527 const TemplateSpecializationType *T,
529 std::string SpecString;
532 llvm::raw_string_ostream OS(SpecString);
533 T->getTemplateName().print(OS, Policy);
536 SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
543 S = SpecString + ' ' + S;
546 void TypePrinter::PrintInjectedClassName(const InjectedClassNameType *T,
548 PrintTemplateSpecialization(T->getInjectedTST(), S);
551 void TypePrinter::PrintElaborated(const ElaboratedType *T, std::string &S) {
552 std::string MyString;
555 llvm::raw_string_ostream OS(MyString);
556 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
557 if (T->getKeyword() != ETK_None)
559 NestedNameSpecifier* Qualifier = T->getQualifier();
561 Qualifier->print(OS, Policy);
565 PrintingPolicy InnerPolicy(Policy);
566 InnerPolicy.SuppressScope = true;
567 TypePrinter(InnerPolicy).Print(T->getNamedType(), TypeStr);
573 S = MyString + ' ' + S;
576 void TypePrinter::PrintDependentName(const DependentNameType *T, std::string &S) {
577 std::string MyString;
580 llvm::raw_string_ostream OS(MyString);
581 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
582 if (T->getKeyword() != ETK_None)
585 T->getQualifier()->print(OS, Policy);
587 OS << T->getIdentifier()->getName();
593 S = MyString + ' ' + S;
596 void TypePrinter::PrintDependentTemplateSpecialization(
597 const DependentTemplateSpecializationType *T, std::string &S) {
598 std::string MyString;
600 llvm::raw_string_ostream OS(MyString);
602 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
603 if (T->getKeyword() != ETK_None)
606 T->getQualifier()->print(OS, Policy);
607 OS << T->getIdentifier()->getName();
608 OS << TemplateSpecializationType::PrintTemplateArgumentList(
617 S = MyString + ' ' + S;
620 void TypePrinter::PrintObjCInterface(const ObjCInterfaceType *T,
622 if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
625 std::string ObjCQIString = T->getDecl()->getNameAsString();
626 S = ObjCQIString + S;
629 void TypePrinter::PrintObjCObject(const ObjCObjectType *T,
632 return Print(T->getBaseType(), S);
635 Print(T->getBaseType(), tmp);
638 for (ObjCObjectType::qual_iterator
639 I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
644 tmp += (*I)->getNameAsString();
655 void TypePrinter::PrintObjCObjectPointer(const ObjCObjectPointerType *T,
657 std::string ObjCQIString;
659 if (T->isObjCIdType() || T->isObjCQualifiedIdType())
661 else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
662 ObjCQIString = "Class";
663 else if (T->isObjCSelType())
664 ObjCQIString = "SEL";
666 ObjCQIString = T->getInterfaceDecl()->getNameAsString();
668 if (!T->qual_empty()) {
670 for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
673 ObjCQIString += (*I)->getNameAsString();
680 T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
683 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
684 ObjCQIString += " *"; // Don't forget the implicit pointer.
685 else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
688 S = ObjCQIString + S;
691 static void PrintTemplateArgument(std::string &Buffer,
692 const TemplateArgument &Arg,
693 const PrintingPolicy &Policy) {
694 switch (Arg.getKind()) {
695 case TemplateArgument::Null:
696 assert(false && "Null template argument");
699 case TemplateArgument::Type:
700 Arg.getAsType().getAsStringInternal(Buffer, Policy);
703 case TemplateArgument::Declaration:
704 Buffer = cast<NamedDecl>(Arg.getAsDecl())->getNameAsString();
707 case TemplateArgument::Template: {
708 llvm::raw_string_ostream s(Buffer);
709 Arg.getAsTemplate().print(s, Policy);
713 case TemplateArgument::Integral:
714 Buffer = Arg.getAsIntegral()->toString(10, true);
717 case TemplateArgument::Expression: {
718 llvm::raw_string_ostream s(Buffer);
719 Arg.getAsExpr()->printPretty(s, 0, Policy);
723 case TemplateArgument::Pack:
724 assert(0 && "FIXME: Implement!");
729 std::string TemplateSpecializationType::
730 PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
731 const PrintingPolicy &Policy) {
732 return PrintTemplateArgumentList(Args.getArgumentArray(),
738 TemplateSpecializationType::PrintTemplateArgumentList(
739 const TemplateArgument *Args,
741 const PrintingPolicy &Policy) {
742 std::string SpecString;
744 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
748 // Print the argument into a string.
749 std::string ArgString;
750 PrintTemplateArgument(ArgString, Args[Arg], Policy);
752 // If this is the first argument and its string representation
753 // begins with the global scope specifier ('::foo'), add a space
754 // to avoid printing the diagraph '<:'.
755 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
758 SpecString += ArgString;
761 // If the last character of our string is '>', add another space to
762 // keep the two '>''s separate tokens. We don't *have* to do this in
763 // C++0x, but it's still good hygiene.
764 if (SpecString[SpecString.size() - 1] == '>')
772 // Sadly, repeat all that with TemplateArgLoc.
773 std::string TemplateSpecializationType::
774 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
775 const PrintingPolicy &Policy) {
776 std::string SpecString;
778 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
782 // Print the argument into a string.
783 std::string ArgString;
784 PrintTemplateArgument(ArgString, Args[Arg].getArgument(), Policy);
786 // If this is the first argument and its string representation
787 // begins with the global scope specifier ('::foo'), add a space
788 // to avoid printing the diagraph '<:'.
789 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
792 SpecString += ArgString;
795 // If the last character of our string is '>', add another space to
796 // keep the two '>''s separate tokens. We don't *have* to do this in
797 // C++0x, but it's still good hygiene.
798 if (SpecString[SpecString.size() - 1] == '>')
806 void QualType::dump(const char *msg) const {
807 std::string R = "identifier";
809 getAsStringInternal(R, PrintingPolicy(LO));
811 llvm::errs() << msg << ": ";
812 llvm::errs() << R << "\n";
814 void QualType::dump() const {
818 void Type::dump() const {
819 QualType(this, 0).dump();
822 std::string Qualifiers::getAsString() const {
824 return getAsString(PrintingPolicy(LO));
827 // Appends qualifiers to the given string, separated by spaces. Will
828 // prefix a space if the string is non-empty. Will not append a final
830 void Qualifiers::getAsStringInternal(std::string &S,
831 const PrintingPolicy&) const {
832 AppendTypeQualList(S, getCVRQualifiers());
833 if (unsigned AddressSpace = getAddressSpace()) {
834 if (!S.empty()) S += ' ';
835 S += "__attribute__((address_space(";
836 S += llvm::utostr_32(AddressSpace);
839 if (Qualifiers::GC GCAttrType = getObjCGCAttr()) {
840 if (!S.empty()) S += ' ';
841 S += "__attribute__((objc_gc(";
842 if (GCAttrType == Qualifiers::Weak)
850 std::string QualType::getAsString() const {
853 getAsStringInternal(S, PrintingPolicy(LO));
857 void QualType::getAsStringInternal(std::string &S,
858 const PrintingPolicy &Policy) const {
859 TypePrinter Printer(Policy);
860 Printer.Print(*this, S);