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 "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
27 PrintingPolicy Policy;
30 explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
32 void Print(QualType T, std::string &S);
33 void AppendScope(DeclContext *DC, std::string &S);
34 void PrintTag(TagDecl *T, std::string &S);
35 #define ABSTRACT_TYPE(CLASS, PARENT)
36 #define TYPE(CLASS, PARENT) \
37 void Print##CLASS(const CLASS##Type *T, std::string &S);
38 #include "clang/AST/TypeNodes.def"
42 static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
43 if (TypeQuals & Qualifiers::Const) {
44 if (!S.empty()) S += ' ';
47 if (TypeQuals & Qualifiers::Volatile) {
48 if (!S.empty()) S += ' ';
51 if (TypeQuals & Qualifiers::Restrict) {
52 if (!S.empty()) S += ' ';
57 void TypePrinter::Print(QualType T, std::string &S) {
63 if (Policy.SuppressSpecifiers && T->isSpecifierType())
66 // Print qualifiers as appropriate.
67 Qualifiers Quals = T.getLocalQualifiers();
70 Quals.getAsStringInternal(TQS, Policy);
79 switch (T->getTypeClass()) {
80 #define ABSTRACT_TYPE(CLASS, PARENT)
81 #define TYPE(CLASS, PARENT) case Type::CLASS: \
82 Print##CLASS(cast<CLASS##Type>(T.getTypePtr()), S); \
84 #include "clang/AST/TypeNodes.def"
88 void TypePrinter::PrintBuiltin(const BuiltinType *T, std::string &S) {
90 S = T->getName(Policy.LangOpts);
92 // Prefix the basic type, e.g. 'int X'.
94 S = T->getName(Policy.LangOpts) + S;
98 void TypePrinter::PrintComplex(const ComplexType *T, std::string &S) {
99 Print(T->getElementType(), S);
103 void TypePrinter::PrintPointer(const PointerType *T, std::string &S) {
106 // Handle things like 'int (*A)[4];' correctly.
107 // FIXME: this should include vectors, but vectors use attributes I guess.
108 if (isa<ArrayType>(T->getPointeeType()))
111 Print(T->getPointeeType(), S);
114 void TypePrinter::PrintBlockPointer(const BlockPointerType *T, std::string &S) {
116 Print(T->getPointeeType(), S);
119 void TypePrinter::PrintLValueReference(const LValueReferenceType *T,
123 // Handle things like 'int (&A)[4];' correctly.
124 // FIXME: this should include vectors, but vectors use attributes I guess.
125 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
128 Print(T->getPointeeTypeAsWritten(), S);
131 void TypePrinter::PrintRValueReference(const RValueReferenceType *T,
135 // Handle things like 'int (&&A)[4];' correctly.
136 // FIXME: this should include vectors, but vectors use attributes I guess.
137 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
140 Print(T->getPointeeTypeAsWritten(), S);
143 void TypePrinter::PrintMemberPointer(const MemberPointerType *T,
146 Print(QualType(T->getClass(), 0), C);
150 // Handle things like 'int (Cls::*A)[4];' correctly.
151 // FIXME: this should include vectors, but vectors use attributes I guess.
152 if (isa<ArrayType>(T->getPointeeType()))
155 Print(T->getPointeeType(), S);
158 void TypePrinter::PrintConstantArray(const ConstantArrayType *T,
161 S += llvm::utostr(T->getSize().getZExtValue());
164 Print(T->getElementType(), S);
167 void TypePrinter::PrintIncompleteArray(const IncompleteArrayType *T,
170 Print(T->getElementType(), S);
173 void TypePrinter::PrintVariableArray(const VariableArrayType *T,
177 if (T->getIndexTypeQualifiers().hasQualifiers()) {
178 AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
182 if (T->getSizeModifier() == VariableArrayType::Static)
184 else if (T->getSizeModifier() == VariableArrayType::Star)
187 if (T->getSizeExpr()) {
189 llvm::raw_string_ostream s(SStr);
190 T->getSizeExpr()->printPretty(s, 0, Policy);
195 Print(T->getElementType(), S);
198 void TypePrinter::PrintDependentSizedArray(const DependentSizedArrayType *T,
202 if (T->getSizeExpr()) {
204 llvm::raw_string_ostream s(SStr);
205 T->getSizeExpr()->printPretty(s, 0, Policy);
210 Print(T->getElementType(), S);
213 void TypePrinter::PrintDependentSizedExtVector(
214 const DependentSizedExtVectorType *T,
216 Print(T->getElementType(), S);
218 S += " __attribute__((ext_vector_type(";
219 if (T->getSizeExpr()) {
221 llvm::raw_string_ostream s(SStr);
222 T->getSizeExpr()->printPretty(s, 0, Policy);
228 void TypePrinter::PrintVector(const VectorType *T, std::string &S) {
229 if (T->isAltiVec()) {
231 S = "__vector __pixel " + S;
233 Print(T->getElementType(), S);
237 // FIXME: We prefer to print the size directly here, but have no way
238 // to get the size of the type.
239 Print(T->getElementType(), S);
240 std::string V = "__attribute__((__vector_size__(";
241 V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
243 Print(T->getElementType(), ET);
244 V += " * sizeof(" + ET + ")))) ";
249 void TypePrinter::PrintExtVector(const ExtVectorType *T, std::string &S) {
250 S += " __attribute__((ext_vector_type(";
251 S += llvm::utostr_32(T->getNumElements());
253 Print(T->getElementType(), S);
256 void TypePrinter::PrintFunctionProto(const FunctionProtoType *T,
258 // If needed for precedence reasons, wrap the inner part in grouping parens.
264 PrintingPolicy ParamPolicy(Policy);
265 ParamPolicy.SuppressSpecifiers = false;
266 for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
268 Print(T->getArgType(i), Tmp);
273 if (T->isVariadic()) {
277 } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
278 // Do not emit int() if we have a proto, emit 'int(void)'.
284 switch(T->getCallConv()) {
288 S += " __attribute__((cdecl))";
291 S += " __attribute__((stdcall))";
294 S += " __attribute__((fastcall))";
297 if (T->getNoReturnAttr())
298 S += " __attribute__((noreturn))";
301 if (T->hasExceptionSpec()) {
303 if (T->hasAnyExceptionSpec())
306 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) {
310 std::string ExceptionType;
311 Print(T->getExceptionType(I), ExceptionType);
317 AppendTypeQualList(S, T->getTypeQuals());
319 Print(T->getResultType(), S);
322 void TypePrinter::PrintFunctionNoProto(const FunctionNoProtoType *T,
324 // If needed for precedence reasons, wrap the inner part in grouping parens.
329 if (T->getNoReturnAttr())
330 S += " __attribute__((noreturn))";
331 Print(T->getResultType(), S);
334 static void PrintTypeSpec(const NamedDecl *D, std::string &S) {
335 IdentifierInfo *II = D->getIdentifier();
337 S = II->getName().str();
339 S = II->getName().str() + ' ' + S;
342 void TypePrinter::PrintUnresolvedUsing(const UnresolvedUsingType *T,
344 PrintTypeSpec(T->getDecl(), S);
347 void TypePrinter::PrintTypedef(const TypedefType *T, std::string &S) {
348 PrintTypeSpec(T->getDecl(), S);
351 void TypePrinter::PrintTypeOfExpr(const TypeOfExprType *T, std::string &S) {
352 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(e) X'.
355 llvm::raw_string_ostream s(Str);
356 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
357 S = "typeof " + s.str() + S;
360 void TypePrinter::PrintTypeOf(const TypeOfType *T, std::string &S) {
361 if (!S.empty()) // Prefix the basic type, e.g. 'typeof(t) X'.
364 Print(T->getUnderlyingType(), Tmp);
365 S = "typeof(" + Tmp + ")" + S;
368 void TypePrinter::PrintDecltype(const DecltypeType *T, std::string &S) {
369 if (!S.empty()) // Prefix the basic type, e.g. 'decltype(t) X'.
372 llvm::raw_string_ostream s(Str);
373 T->getUnderlyingExpr()->printPretty(s, 0, Policy);
374 S = "decltype(" + s.str() + ")" + S;
377 /// Appends the given scope to the end of a string.
378 void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
379 if (DC->isTranslationUnit()) return;
380 AppendScope(DC->getParent(), Buffer);
382 unsigned OldSize = Buffer.size();
384 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
385 if (NS->getIdentifier())
386 Buffer += NS->getNameAsString();
388 Buffer += "<anonymous>";
389 } else if (ClassTemplateSpecializationDecl *Spec
390 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
391 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
392 std::string TemplateArgsStr
393 = TemplateSpecializationType::PrintTemplateArgumentList(
394 TemplateArgs.getFlatArgumentList(),
395 TemplateArgs.flat_size(),
397 Buffer += Spec->getIdentifier()->getName();
398 Buffer += TemplateArgsStr;
399 } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
400 if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
401 Buffer += Typedef->getIdentifier()->getName();
402 else if (Tag->getIdentifier())
403 Buffer += Tag->getIdentifier()->getName();
406 if (Buffer.size() != OldSize)
410 void TypePrinter::PrintTag(TagDecl *D, std::string &InnerString) {
411 if (Policy.SuppressTag)
416 // We don't print tags unless this is an elaborated type.
417 // In C, we just assume every RecordType is an elaborated type.
418 if (!Policy.LangOpts.CPlusPlus && !D->getTypedefForAnonDecl()) {
419 Buffer += D->getKindName();
423 if (!Policy.SuppressScope)
424 // Compute the full nested-name-specifier for this type. In C,
425 // this will always be empty.
426 AppendScope(D->getDeclContext(), Buffer);
429 if (const IdentifierInfo *II = D->getIdentifier())
430 ID = II->getNameStart();
431 else if (TypedefDecl *Typedef = D->getTypedefForAnonDecl()) {
432 assert(Typedef->getIdentifier() && "Typedef without identifier?");
433 ID = Typedef->getIdentifier()->getNameStart();
438 // If this is a class template specialization, print the template
440 if (ClassTemplateSpecializationDecl *Spec
441 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
442 const TemplateArgument *Args;
444 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
445 const TemplateSpecializationType *TST =
446 cast<TemplateSpecializationType>(TAW->getType());
447 Args = TST->getArgs();
448 NumArgs = TST->getNumArgs();
450 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
451 Args = TemplateArgs.getFlatArgumentList();
452 NumArgs = TemplateArgs.flat_size();
454 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
459 if (!InnerString.empty()) {
461 Buffer += InnerString;
464 std::swap(Buffer, InnerString);
467 void TypePrinter::PrintRecord(const RecordType *T, std::string &S) {
468 PrintTag(T->getDecl(), S);
471 void TypePrinter::PrintEnum(const EnumType *T, std::string &S) {
472 PrintTag(T->getDecl(), S);
475 void TypePrinter::PrintElaborated(const ElaboratedType *T, std::string &S) {
476 Print(T->getUnderlyingType(), S);
477 S = std::string(T->getNameForTagKind(T->getTagKind())) + ' ' + S;
480 void TypePrinter::PrintTemplateTypeParm(const TemplateTypeParmType *T,
482 if (!S.empty()) // Prefix the basic type, e.g. 'parmname X'.
486 S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
487 llvm::utostr_32(T->getIndex()) + S;
489 S = T->getName()->getName().str() + S;
492 void TypePrinter::PrintSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
494 Print(T->getReplacementType(), S);
497 void TypePrinter::PrintTemplateSpecialization(
498 const TemplateSpecializationType *T,
500 std::string SpecString;
503 llvm::raw_string_ostream OS(SpecString);
504 T->getTemplateName().print(OS, Policy);
507 SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
514 S = SpecString + ' ' + S;
517 void TypePrinter::PrintInjectedClassName(const InjectedClassNameType *T,
519 PrintTemplateSpecialization(T->getUnderlyingTST(), S);
522 void TypePrinter::PrintQualifiedName(const QualifiedNameType *T,
524 std::string MyString;
527 llvm::raw_string_ostream OS(MyString);
528 T->getQualifier()->print(OS, Policy);
532 PrintingPolicy InnerPolicy(Policy);
533 InnerPolicy.SuppressScope = true;
534 TypePrinter(InnerPolicy).Print(T->getNamedType(), TypeStr);
540 S = MyString + ' ' + S;
543 void TypePrinter::PrintTypename(const TypenameType *T, std::string &S) {
544 std::string MyString;
547 llvm::raw_string_ostream OS(MyString);
549 T->getQualifier()->print(OS, Policy);
551 if (const IdentifierInfo *Ident = T->getIdentifier())
552 OS << Ident->getName();
553 else if (const TemplateSpecializationType *Spec = T->getTemplateId()) {
554 Spec->getTemplateName().print(OS, Policy, true);
555 OS << TemplateSpecializationType::PrintTemplateArgumentList(
565 S = MyString + ' ' + S;
568 void TypePrinter::PrintObjCInterface(const ObjCInterfaceType *T,
570 if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
573 std::string ObjCQIString = T->getDecl()->getNameAsString();
574 if (T->getNumProtocols()) {
577 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
584 ObjCQIString += (*I)->getNameAsString();
588 S = ObjCQIString + S;
591 void TypePrinter::PrintObjCObjectPointer(const ObjCObjectPointerType *T,
593 std::string ObjCQIString;
595 if (T->isObjCIdType() || T->isObjCQualifiedIdType())
597 else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
598 ObjCQIString = "Class";
599 else if (T->isObjCSelType())
600 ObjCQIString = "SEL";
602 ObjCQIString = T->getInterfaceDecl()->getNameAsString();
604 if (!T->qual_empty()) {
606 for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
609 ObjCQIString += (*I)->getNameAsString();
616 T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
619 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
620 ObjCQIString += " *"; // Don't forget the implicit pointer.
621 else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
624 S = ObjCQIString + S;
627 static void PrintTemplateArgument(std::string &Buffer,
628 const TemplateArgument &Arg,
629 const PrintingPolicy &Policy) {
630 switch (Arg.getKind()) {
631 case TemplateArgument::Null:
632 assert(false && "Null template argument");
635 case TemplateArgument::Type:
636 Arg.getAsType().getAsStringInternal(Buffer, Policy);
639 case TemplateArgument::Declaration:
640 Buffer = cast<NamedDecl>(Arg.getAsDecl())->getNameAsString();
643 case TemplateArgument::Template: {
644 llvm::raw_string_ostream s(Buffer);
645 Arg.getAsTemplate().print(s, Policy);
649 case TemplateArgument::Integral:
650 Buffer = Arg.getAsIntegral()->toString(10, true);
653 case TemplateArgument::Expression: {
654 llvm::raw_string_ostream s(Buffer);
655 Arg.getAsExpr()->printPretty(s, 0, Policy);
659 case TemplateArgument::Pack:
660 assert(0 && "FIXME: Implement!");
665 std::string TemplateSpecializationType::
666 PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
667 const PrintingPolicy &Policy) {
668 return PrintTemplateArgumentList(Args.getArgumentArray(),
674 TemplateSpecializationType::PrintTemplateArgumentList(
675 const TemplateArgument *Args,
677 const PrintingPolicy &Policy) {
678 std::string SpecString;
680 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
684 // Print the argument into a string.
685 std::string ArgString;
686 PrintTemplateArgument(ArgString, Args[Arg], Policy);
688 // If this is the first argument and its string representation
689 // begins with the global scope specifier ('::foo'), add a space
690 // to avoid printing the diagraph '<:'.
691 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
694 SpecString += ArgString;
697 // If the last character of our string is '>', add another space to
698 // keep the two '>''s separate tokens. We don't *have* to do this in
699 // C++0x, but it's still good hygiene.
700 if (SpecString[SpecString.size() - 1] == '>')
708 // Sadly, repeat all that with TemplateArgLoc.
709 std::string TemplateSpecializationType::
710 PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
711 const PrintingPolicy &Policy) {
712 std::string SpecString;
714 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
718 // Print the argument into a string.
719 std::string ArgString;
720 PrintTemplateArgument(ArgString, Args[Arg].getArgument(), Policy);
722 // If this is the first argument and its string representation
723 // begins with the global scope specifier ('::foo'), add a space
724 // to avoid printing the diagraph '<:'.
725 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
728 SpecString += ArgString;
731 // If the last character of our string is '>', add another space to
732 // keep the two '>''s separate tokens. We don't *have* to do this in
733 // C++0x, but it's still good hygiene.
734 if (SpecString[SpecString.size() - 1] == '>')
742 void QualType::dump(const char *msg) const {
743 std::string R = "identifier";
745 getAsStringInternal(R, PrintingPolicy(LO));
747 llvm::errs() << msg << ": ";
748 llvm::errs() << R << "\n";
750 void QualType::dump() const {
754 void Type::dump() const {
755 QualType(this, 0).dump();
758 std::string Qualifiers::getAsString() const {
760 return getAsString(PrintingPolicy(LO));
763 // Appends qualifiers to the given string, separated by spaces. Will
764 // prefix a space if the string is non-empty. Will not append a final
766 void Qualifiers::getAsStringInternal(std::string &S,
767 const PrintingPolicy&) const {
768 AppendTypeQualList(S, getCVRQualifiers());
769 if (unsigned AddressSpace = getAddressSpace()) {
770 if (!S.empty()) S += ' ';
771 S += "__attribute__((address_space(";
772 S += llvm::utostr_32(AddressSpace);
775 if (Qualifiers::GC GCAttrType = getObjCGCAttr()) {
776 if (!S.empty()) S += ' ';
777 S += "__attribute__((objc_gc(";
778 if (GCAttrType == Qualifiers::Weak)
786 std::string QualType::getAsString() const {
789 getAsStringInternal(S, PrintingPolicy(LO));
793 void QualType::getAsStringInternal(std::string &S,
794 const PrintingPolicy &Policy) const {
795 TypePrinter Printer(Policy);
796 Printer.Print(*this, S);