1 //===--- ASTDiagnostic.cpp - Diagnostic Printing Hooks for AST Nodes ------===//
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 file implements a diagnostic formatting hook for AST elements.
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/TemplateBase.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Type.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
26 // Returns a desugared version of the QualType, and marks ShouldAKA as true
27 // whenever we remove significant sugar from the type.
28 static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
29 QualifierCollector QC;
32 const Type *Ty = QC.strip(QT);
34 // Don't aka just because we saw an elaborated type...
35 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
39 // ... or a paren type ...
40 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
44 // ...or a substituted template type parameter ...
45 if (const SubstTemplateTypeParmType *ST =
46 dyn_cast<SubstTemplateTypeParmType>(Ty)) {
50 // ...or an attributed type...
51 if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
55 // ... or an auto type.
56 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
63 // Don't desugar template specializations, unless it's an alias template.
64 if (const TemplateSpecializationType *TST
65 = dyn_cast<TemplateSpecializationType>(Ty))
66 if (!TST->isTypeAlias())
69 // Don't desugar magic Objective-C types.
70 if (QualType(Ty,0) == Context.getObjCIdType() ||
71 QualType(Ty,0) == Context.getObjCClassType() ||
72 QualType(Ty,0) == Context.getObjCSelType() ||
73 QualType(Ty,0) == Context.getObjCProtoType())
76 // Don't desugar va_list.
77 if (QualType(Ty,0) == Context.getBuiltinVaListType())
80 // Otherwise, do a single-step desugar.
83 switch (Ty->getTypeClass()) {
84 #define ABSTRACT_TYPE(Class, Base)
85 #define TYPE(Class, Base) \
87 const Class##Type *CTy = cast<Class##Type>(Ty); \
88 if (CTy->isSugared()) { \
90 Underlying = CTy->desugar(); \
94 #include "clang/AST/TypeNodes.def"
97 // If it wasn't sugared, we're done.
101 // If the desugared type is a vector type, we don't want to expand
102 // it, it will turn into an attribute mess. People want their "vec4".
103 if (isa<VectorType>(Underlying))
106 // Don't desugar through the primary typedef of an anonymous type.
107 if (const TagType *UTT = Underlying->getAs<TagType>())
108 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
109 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
112 // Record that we actually looked through an opaque type here.
117 // If we have a pointer-like type, desugar the pointee as well.
118 // FIXME: Handle other pointer-like types.
119 if (const PointerType *Ty = QT->getAs<PointerType>()) {
120 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
122 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
123 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
125 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
126 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
130 return QC.apply(Context, QT);
133 /// \brief Convert the given type to a string suitable for printing as part of
136 /// There are four main criteria when determining whether we should have an
137 /// a.k.a. clause when pretty-printing a type:
139 /// 1) Some types provide very minimal sugar that doesn't impede the
140 /// user's understanding --- for example, elaborated type
141 /// specifiers. If this is all the sugar we see, we don't want an
143 /// 2) Some types are technically sugared but are much more familiar
144 /// when seen in their sugared form --- for example, va_list,
145 /// vector types, and the magic Objective C types. We don't
146 /// want to desugar these, even if we do produce an a.k.a. clause.
147 /// 3) Some types may have already been desugared previously in this diagnostic.
148 /// if this is the case, doing another "aka" would just be clutter.
149 /// 4) Two different types within the same diagnostic have the same output
150 /// string. In this case, force an a.k.a with the desugared type when
151 /// doing so will provide additional information.
153 /// \param Context the context in which the type was allocated
154 /// \param Ty the type to print
155 /// \param QualTypeVals pointer values to QualTypes which are used in the
156 /// diagnostic message
158 ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
159 const DiagnosticsEngine::ArgumentValue *PrevArgs,
160 unsigned NumPrevArgs,
161 ArrayRef<intptr_t> QualTypeVals) {
162 // FIXME: Playing with std::string is really slow.
163 bool ForceAKA = false;
164 QualType CanTy = Ty.getCanonicalType();
165 std::string S = Ty.getAsString(Context.getPrintingPolicy());
166 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
168 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
170 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
171 if (CompareTy.isNull())
174 continue; // Same types
175 QualType CompareCanTy = CompareTy.getCanonicalType();
176 if (CompareCanTy == CanTy)
177 continue; // Same canonical types
178 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
180 QualType CompareDesugar = Desugar(Context, CompareTy, aka);
181 std::string CompareDesugarStr =
182 CompareDesugar.getAsString(Context.getPrintingPolicy());
183 if (CompareS != S && CompareDesugarStr != S)
184 continue; // The type string is different than the comparison string
185 // and the desugared comparison string.
186 std::string CompareCanS =
187 CompareCanTy.getAsString(Context.getPrintingPolicy());
189 if (CompareCanS == CanS)
190 continue; // No new info from canonical type
196 // Check to see if we already desugared this type in this
197 // diagnostic. If so, don't do it again.
198 bool Repeated = false;
199 for (unsigned i = 0; i != NumPrevArgs; ++i) {
200 // TODO: Handle ak_declcontext case.
201 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
202 void *Ptr = (void*)PrevArgs[i].second;
203 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
211 // Consider producing an a.k.a. clause if removing all the direct
212 // sugar gives us something "significantly different".
214 bool ShouldAKA = false;
215 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
216 if (ShouldAKA || ForceAKA) {
217 if (DesugaredTy == Ty) {
218 DesugaredTy = Ty.getCanonicalType();
220 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
222 S = "'" + S + "' (aka '" + akaStr + "')";
232 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
233 QualType ToType, bool PrintTree,
234 bool PrintFromType, bool ElideType,
235 bool ShowColors, std::string &S);
237 void clang::FormatASTNodeDiagnosticArgument(
238 DiagnosticsEngine::ArgumentKind Kind,
240 const char *Modifier,
242 const char *Argument,
244 const DiagnosticsEngine::ArgumentValue *PrevArgs,
245 unsigned NumPrevArgs,
246 SmallVectorImpl<char> &Output,
248 ArrayRef<intptr_t> QualTypeVals) {
249 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
252 bool NeedQuotes = true;
255 default: llvm_unreachable("unknown ArgumentKind");
256 case DiagnosticsEngine::ak_qualtype_pair: {
257 TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
259 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
261 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
263 if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
264 TDT.PrintFromType, TDT.ElideType,
265 TDT.ShowColors, S)) {
266 NeedQuotes = !TDT.PrintTree;
267 TDT.TemplateDiffUsed = true;
271 // Don't fall-back during tree printing. The caller will handle
276 // Attempting to do a templete diff on non-templates. Set the variables
277 // and continue with regular type printing of the appropriate type.
278 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
283 case DiagnosticsEngine::ak_qualtype: {
284 assert(ModLen == 0 && ArgLen == 0 &&
285 "Invalid modifier for QualType argument");
287 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
288 S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs,
293 case DiagnosticsEngine::ak_declarationname: {
294 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
297 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
299 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
303 assert(ModLen == 0 && ArgLen == 0 &&
304 "Invalid modifier for DeclarationName argument");
307 case DiagnosticsEngine::ak_nameddecl: {
309 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
312 assert(ModLen == 0 && ArgLen == 0 &&
313 "Invalid modifier for NamedDecl* argument");
316 const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
317 ND->getNameForDiagnostic(S, Context.getPrintingPolicy(), Qualified);
320 case DiagnosticsEngine::ak_nestednamespec: {
321 llvm::raw_string_ostream OS(S);
322 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
323 Context.getPrintingPolicy());
327 case DiagnosticsEngine::ak_declcontext: {
328 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
329 assert(DC && "Should never have a null declaration context");
331 if (DC->isTranslationUnit()) {
332 // FIXME: Get these strings from some localized place
333 if (Context.getLangOpts().CPlusPlus)
334 S = "the global namespace";
336 S = "the global scope";
337 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
338 S = ConvertTypeToDiagnosticString(Context,
339 Context.getTypeDeclType(Type),
340 PrevArgs, NumPrevArgs, QualTypeVals);
342 // FIXME: Get these strings from some localized place
343 NamedDecl *ND = cast<NamedDecl>(DC);
344 if (isa<NamespaceDecl>(ND))
346 else if (isa<ObjCMethodDecl>(ND))
348 else if (isa<FunctionDecl>(ND))
352 ND->getNameForDiagnostic(S, Context.getPrintingPolicy(), true);
361 Output.push_back('\'');
363 Output.append(S.begin(), S.end());
366 Output.push_back('\'');
369 /// TemplateDiff - A class that constructs a pretty string for a pair of
370 /// QualTypes. For the pair of types, a diff tree will be created containing
371 /// all the information about the templates and template arguments. Afterwards,
372 /// the tree is transformed to a string according to the options passed in.
375 /// Context - The ASTContext which is used for comparing template arguments.
378 /// Policy - Used during expression printing.
379 PrintingPolicy Policy;
381 /// ElideType - Option to elide identical types.
384 /// PrintTree - Format output string as a tree.
387 /// ShowColor - Diagnostics support color, so bolding will be used.
390 /// FromType - When single type printing is selected, this is the type to be
391 /// be printed. When tree printing is selected, this type will show up first
395 /// ToType - The type that FromType is compared to. Only in tree printing
396 /// will this type be outputed.
399 /// Str - Storage for the output stream.
400 llvm::SmallString<128> Str;
402 /// OS - The stream used to construct the output strings.
403 llvm::raw_svector_ostream OS;
405 /// IsBold - Keeps track of the bold formatting for the output string.
408 /// DiffTree - A tree representation the differences between two types.
410 /// DiffNode - The root node stores the original type. Each child node
411 /// stores template arguments of their parents. For templated types, the
412 /// template decl is also stored.
414 /// NextNode - The index of the next sibling node or 0.
417 /// ChildNode - The index of the first child node or 0.
420 /// ParentNode - The index of the parent node.
423 /// FromType, ToType - The type arguments.
424 QualType FromType, ToType;
426 /// FromExpr, ToExpr - The expression arguments.
427 Expr *FromExpr, *ToExpr;
429 /// FromTD, ToTD - The template decl for template template
430 /// arguments or the type arguments that are templates.
431 TemplateDecl *FromTD, *ToTD;
433 /// FromQual, ToQual - Qualifiers for template types.
434 Qualifiers FromQual, ToQual;
436 /// FromInt, ToInt - APSInt's for integral arguments.
437 llvm::APSInt FromInt, ToInt;
439 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
440 bool IsValidFromInt, IsValidToInt;
442 /// FromDefault, ToDefault - Whether the argument is a default argument.
443 bool FromDefault, ToDefault;
445 /// Same - Whether the two arguments evaluate to the same value.
448 DiffNode(unsigned ParentNode = 0)
449 : NextNode(0), ChildNode(0), ParentNode(ParentNode),
450 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
451 FromDefault(false), ToDefault(false), Same(false) { }
454 /// FlatTree - A flattened tree used to store the DiffNodes.
455 llvm::SmallVector<DiffNode, 16> FlatTree;
457 /// CurrentNode - The index of the current node being used.
458 unsigned CurrentNode;
460 /// NextFreeNode - The index of the next unused node. Used when creating
462 unsigned NextFreeNode;
464 /// ReadNode - The index of the current node being read.
469 CurrentNode(0), NextFreeNode(1) {
470 FlatTree.push_back(DiffNode());
473 // Node writing functions.
474 /// SetNode - Sets FromTD and ToTD of the current node.
475 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
476 FlatTree[CurrentNode].FromTD = FromTD;
477 FlatTree[CurrentNode].ToTD = ToTD;
480 /// SetNode - Sets FromType and ToType of the current node.
481 void SetNode(QualType FromType, QualType ToType) {
482 FlatTree[CurrentNode].FromType = FromType;
483 FlatTree[CurrentNode].ToType = ToType;
486 /// SetNode - Set FromExpr and ToExpr of the current node.
487 void SetNode(Expr *FromExpr, Expr *ToExpr) {
488 FlatTree[CurrentNode].FromExpr = FromExpr;
489 FlatTree[CurrentNode].ToExpr = ToExpr;
492 /// SetNode - Set FromInt and ToInt of the current node.
493 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
494 bool IsValidFromInt, bool IsValidToInt) {
495 FlatTree[CurrentNode].FromInt = FromInt;
496 FlatTree[CurrentNode].ToInt = ToInt;
497 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
498 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
501 /// SetNode - Set FromQual and ToQual of the current node.
502 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
503 FlatTree[CurrentNode].FromQual = FromQual;
504 FlatTree[CurrentNode].ToQual = ToQual;
507 /// SetSame - Sets the same flag of the current node.
508 void SetSame(bool Same) {
509 FlatTree[CurrentNode].Same = Same;
512 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
513 void SetDefault(bool FromDefault, bool ToDefault) {
514 FlatTree[CurrentNode].FromDefault = FromDefault;
515 FlatTree[CurrentNode].ToDefault = ToDefault;
518 /// Up - Changes the node to the parent of the current node.
520 CurrentNode = FlatTree[CurrentNode].ParentNode;
523 /// AddNode - Adds a child node to the current node, then sets that node
524 /// node as the current node.
526 FlatTree.push_back(DiffNode(CurrentNode));
527 DiffNode &Node = FlatTree[CurrentNode];
528 if (Node.ChildNode == 0) {
529 // If a child node doesn't exist, add one.
530 Node.ChildNode = NextFreeNode;
532 // If a child node exists, find the last child node and add a
535 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
536 i = FlatTree[i].NextNode) {
538 FlatTree[i].NextNode = NextFreeNode;
540 CurrentNode = NextFreeNode;
544 // Node reading functions.
545 /// StartTraverse - Prepares the tree for recursive traversal.
546 void StartTraverse() {
548 CurrentNode = NextFreeNode;
552 /// Parent - Move the current read node to its parent.
554 ReadNode = FlatTree[ReadNode].ParentNode;
557 /// NodeIsTemplate - Returns true if a template decl is set, and types are
559 bool NodeIsTemplate() {
560 return (FlatTree[ReadNode].FromTD &&
561 !FlatTree[ReadNode].ToType.isNull()) ||
562 (FlatTree[ReadNode].ToTD && !FlatTree[ReadNode].ToType.isNull());
565 /// NodeIsQualType - Returns true if a Qualtype is set.
566 bool NodeIsQualType() {
567 return !FlatTree[ReadNode].FromType.isNull() ||
568 !FlatTree[ReadNode].ToType.isNull();
571 /// NodeIsExpr - Returns true if an expr is set.
573 return FlatTree[ReadNode].FromExpr || FlatTree[ReadNode].ToExpr;
576 /// NodeIsTemplateTemplate - Returns true if the argument is a template
578 bool NodeIsTemplateTemplate() {
579 return FlatTree[ReadNode].FromType.isNull() &&
580 FlatTree[ReadNode].ToType.isNull() &&
581 (FlatTree[ReadNode].FromTD || FlatTree[ReadNode].ToTD);
584 /// NodeIsAPSInt - Returns true if the arugments are stored in APSInt's.
585 bool NodeIsAPSInt() {
586 return FlatTree[ReadNode].IsValidFromInt ||
587 FlatTree[ReadNode].IsValidToInt;
590 /// GetNode - Gets the FromType and ToType.
591 void GetNode(QualType &FromType, QualType &ToType) {
592 FromType = FlatTree[ReadNode].FromType;
593 ToType = FlatTree[ReadNode].ToType;
596 /// GetNode - Gets the FromExpr and ToExpr.
597 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
598 FromExpr = FlatTree[ReadNode].FromExpr;
599 ToExpr = FlatTree[ReadNode].ToExpr;
602 /// GetNode - Gets the FromTD and ToTD.
603 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
604 FromTD = FlatTree[ReadNode].FromTD;
605 ToTD = FlatTree[ReadNode].ToTD;
608 /// GetNode - Gets the FromInt and ToInt.
609 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
610 bool &IsValidFromInt, bool &IsValidToInt) {
611 FromInt = FlatTree[ReadNode].FromInt;
612 ToInt = FlatTree[ReadNode].ToInt;
613 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
614 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
617 /// GetNode - Gets the FromQual and ToQual.
618 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
619 FromQual = FlatTree[ReadNode].FromQual;
620 ToQual = FlatTree[ReadNode].ToQual;
623 /// NodeIsSame - Returns true the arguments are the same.
625 return FlatTree[ReadNode].Same;
628 /// HasChildrend - Returns true if the node has children.
630 return FlatTree[ReadNode].ChildNode != 0;
633 /// MoveToChild - Moves from the current node to its child.
635 ReadNode = FlatTree[ReadNode].ChildNode;
638 /// AdvanceSibling - If there is a next sibling, advance to it and return
639 /// true. Otherwise, return false.
640 bool AdvanceSibling() {
641 if (FlatTree[ReadNode].NextNode == 0)
644 ReadNode = FlatTree[ReadNode].NextNode;
648 /// HasNextSibling - Return true if the node has a next sibling.
649 bool HasNextSibling() {
650 return FlatTree[ReadNode].NextNode != 0;
653 /// FromDefault - Return true if the from argument is the default.
655 return FlatTree[ReadNode].FromDefault;
658 /// ToDefault - Return true if the to argument is the default.
660 return FlatTree[ReadNode].ToDefault;
663 /// Empty - Returns true if the tree has no information.
665 return !FlatTree[0].FromTD && !FlatTree[0].ToTD &&
666 !FlatTree[0].FromExpr && !FlatTree[0].ToExpr &&
667 FlatTree[0].FromType.isNull() && FlatTree[0].ToType.isNull();
673 /// TSTiterator - an iterator that is used to enter a
674 /// TemplateSpecializationType and read TemplateArguments inside template
675 /// parameter packs in order with the rest of the TemplateArguments.
677 typedef const TemplateArgument& reference;
678 typedef const TemplateArgument* pointer;
680 /// TST - the template specialization whose arguments this iterator
682 const TemplateSpecializationType *TST;
684 /// Index - the index of the template argument in TST.
687 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
688 /// points to a TemplateArgument within a parameter pack.
689 TemplateArgument::pack_iterator CurrentTA;
691 /// EndTA - the end iterator of a parameter pack
692 TemplateArgument::pack_iterator EndTA;
694 /// TSTiterator - Constructs an iterator and sets it to the first template
696 TSTiterator(const TemplateSpecializationType *TST)
697 : TST(TST), Index(0), CurrentTA(0), EndTA(0) {
700 // Set to first template argument. If not a parameter pack, done.
701 TemplateArgument TA = TST->getArg(0);
702 if (TA.getKind() != TemplateArgument::Pack) return;
704 // Start looking into the parameter pack.
705 CurrentTA = TA.pack_begin();
706 EndTA = TA.pack_end();
708 // Found a valid template argument.
709 if (CurrentTA != EndTA) return;
711 // Parameter pack is empty, use the increment to get to a valid
712 // template argument.
716 /// isEnd - Returns true if the iterator is one past the end.
718 return Index == TST->getNumArgs();
721 /// &operator++ - Increment the iterator to the next template argument.
722 TSTiterator &operator++() {
723 assert(!isEnd() && "Iterator incremented past end of arguments.");
725 // If in a parameter pack, advance in the parameter pack.
726 if (CurrentTA != EndTA) {
728 if (CurrentTA != EndTA)
732 // Loop until a template argument is found, or the end is reached.
734 // Advance to the next template argument. Break if reached the end.
735 if (++Index == TST->getNumArgs()) break;
737 // If the TemplateArgument is not a parameter pack, done.
738 TemplateArgument TA = TST->getArg(Index);
739 if (TA.getKind() != TemplateArgument::Pack) break;
741 // Handle parameter packs.
742 CurrentTA = TA.pack_begin();
743 EndTA = TA.pack_end();
745 // If the parameter pack is empty, try to advance again.
746 if (CurrentTA != EndTA) break;
751 /// operator* - Returns the appropriate TemplateArgument.
752 reference operator*() const {
753 assert(!isEnd() && "Index exceeds number of arguments.");
754 if (CurrentTA == EndTA)
755 return TST->getArg(Index);
760 /// operator-> - Allow access to the underlying TemplateArgument.
761 pointer operator->() const {
766 // These functions build up the template diff tree, including functions to
767 // retrieve and compare template arguments.
769 static const TemplateSpecializationType * GetTemplateSpecializationType(
770 ASTContext &Context, QualType Ty) {
771 if (const TemplateSpecializationType *TST =
772 Ty->getAs<TemplateSpecializationType>())
775 const RecordType *RT = Ty->getAs<RecordType>();
780 const ClassTemplateSpecializationDecl *CTSD =
781 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
786 Ty = Context.getTemplateSpecializationType(
787 TemplateName(CTSD->getSpecializedTemplate()),
788 CTSD->getTemplateArgs().data(),
789 CTSD->getTemplateArgs().size(),
790 Ty.getCanonicalType());
792 return Ty->getAs<TemplateSpecializationType>();
795 /// DiffTemplate - recursively visits template arguments and stores the
796 /// argument info into a tree.
797 void DiffTemplate(const TemplateSpecializationType *FromTST,
798 const TemplateSpecializationType *ToTST) {
799 // Begin descent into diffing template tree.
800 TemplateParameterList *Params =
801 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
802 unsigned TotalArgs = 0;
803 for (TSTiterator FromIter(FromTST), ToIter(ToTST);
804 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
807 // Get the parameter at index TotalArgs. If index is larger
808 // than the total number of parameters, then there is an
809 // argument pack, so re-use the last parameter.
810 NamedDecl *ParamND = Params->getParam(
811 (TotalArgs < Params->size()) ? TotalArgs
812 : Params->size() - 1);
814 if (TemplateTypeParmDecl *DefaultTTPD =
815 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
816 QualType FromType, ToType;
817 GetType(FromIter, DefaultTTPD, FromType);
818 GetType(ToIter, DefaultTTPD, ToType);
819 Tree.SetNode(FromType, ToType);
820 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
821 ToIter.isEnd() && !ToType.isNull());
822 if (!FromType.isNull() && !ToType.isNull()) {
823 if (Context.hasSameType(FromType, ToType)) {
826 Qualifiers FromQual = FromType.getQualifiers(),
827 ToQual = ToType.getQualifiers();
828 const TemplateSpecializationType *FromArgTST =
829 GetTemplateSpecializationType(Context, FromType);
830 const TemplateSpecializationType *ToArgTST =
831 GetTemplateSpecializationType(Context, ToType);
833 if (FromArgTST && ToArgTST &&
834 hasSameTemplate(FromArgTST, ToArgTST)) {
835 FromQual -= QualType(FromArgTST, 0).getQualifiers();
836 ToQual -= QualType(ToArgTST, 0).getQualifiers();
837 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
838 ToArgTST->getTemplateName().getAsTemplateDecl());
839 Tree.SetNode(FromQual, ToQual);
840 DiffTemplate(FromArgTST, ToArgTST);
846 // Handle Expressions
847 if (NonTypeTemplateParmDecl *DefaultNTTPD =
848 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
849 Expr *FromExpr, *ToExpr;
850 llvm::APSInt FromInt, ToInt;
851 bool HasFromInt = !FromIter.isEnd() &&
852 FromIter->getKind() == TemplateArgument::Integral;
853 bool HasToInt = !ToIter.isEnd() &&
854 ToIter->getKind() == TemplateArgument::Integral;
855 //bool IsValidFromInt = false, IsValidToInt = false;
857 FromInt = FromIter->getAsIntegral();
859 GetExpr(FromIter, DefaultNTTPD, FromExpr);
862 ToInt = ToIter->getAsIntegral();
864 GetExpr(ToIter, DefaultNTTPD, ToExpr);
866 if (!HasFromInt && !HasToInt) {
867 Tree.SetNode(FromExpr, ToExpr);
868 Tree.SetSame(IsEqualExpr(Context, FromExpr, ToExpr));
869 Tree.SetDefault(FromIter.isEnd() && FromExpr,
870 ToIter.isEnd() && ToExpr);
872 if (!HasFromInt && FromExpr) {
873 FromInt = FromExpr->EvaluateKnownConstInt(Context);
876 if (!HasToInt && ToExpr) {
877 ToInt = ToExpr->EvaluateKnownConstInt(Context);
880 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
881 Tree.SetSame(llvm::APSInt::isSameValue(FromInt, ToInt));
882 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
883 ToIter.isEnd() && HasToInt);
888 if (TemplateTemplateParmDecl *DefaultTTPD =
889 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
890 TemplateDecl *FromDecl, *ToDecl;
891 GetTemplateDecl(FromIter, DefaultTTPD, FromDecl);
892 GetTemplateDecl(ToIter, DefaultTTPD, ToDecl);
893 Tree.SetNode(FromDecl, ToDecl);
894 Tree.SetSame(FromDecl && ToDecl &&
895 FromDecl->getIdentifier() == ToDecl->getIdentifier());
898 if (!FromIter.isEnd()) ++FromIter;
899 if (!ToIter.isEnd()) ++ToIter;
904 /// makeTemplateList - Dump every template alias into the vector.
905 static void makeTemplateList(
906 SmallVector<const TemplateSpecializationType*, 1> &TemplateList,
907 const TemplateSpecializationType *TST) {
909 TemplateList.push_back(TST);
910 if (!TST->isTypeAlias())
912 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
916 /// hasSameBaseTemplate - Returns true when the base templates are the same,
917 /// even if the template arguments are not.
918 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
919 const TemplateSpecializationType *ToTST) {
920 return FromTST->getTemplateName().getAsTemplateDecl()->getIdentifier() ==
921 ToTST->getTemplateName().getAsTemplateDecl()->getIdentifier();
924 /// hasSameTemplate - Returns true if both types are specialized from the
925 /// same template declaration. If they come from different template aliases,
926 /// do a parallel ascension search to determine the highest template alias in
927 /// common and set the arguments to them.
928 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
929 const TemplateSpecializationType *&ToTST) {
930 // Check the top templates if they are the same.
931 if (hasSameBaseTemplate(FromTST, ToTST))
934 // Create vectors of template aliases.
935 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
938 makeTemplateList(FromTemplateList, FromTST);
939 makeTemplateList(ToTemplateList, ToTST);
941 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
942 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
943 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
945 // Check if the lowest template types are the same. If not, return.
946 if (!hasSameBaseTemplate(*FromIter, *ToIter))
949 // Begin searching up the template aliases. The bottom most template
950 // matches so move up until one pair does not match. Use the template
951 // right before that one.
952 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
953 if (!hasSameBaseTemplate(*FromIter, *ToIter))
957 FromTST = FromIter[-1];
963 /// GetType - Retrieves the template type arguments, including default
965 void GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD,
967 ArgType = QualType();
968 bool isVariadic = DefaultTTPD->isParameterPack();
971 ArgType = Iter->getAsType();
972 else if (!isVariadic)
973 ArgType = DefaultTTPD->getDefaultArgument();
976 /// GetExpr - Retrieves the template expression argument, including default
978 void GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD,
981 bool isVariadic = DefaultNTTPD->isParameterPack();
984 ArgExpr = Iter->getAsExpr();
985 else if (!isVariadic)
986 ArgExpr = DefaultNTTPD->getDefaultArgument();
989 while (SubstNonTypeTemplateParmExpr *SNTTPE =
990 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
991 ArgExpr = SNTTPE->getReplacement();
994 /// GetTemplateDecl - Retrieves the template template arguments, including
995 /// default arguments.
996 void GetTemplateDecl(const TSTiterator &Iter,
997 TemplateTemplateParmDecl *DefaultTTPD,
998 TemplateDecl *&ArgDecl) {
1000 bool isVariadic = DefaultTTPD->isParameterPack();
1002 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
1003 TemplateDecl *DefaultTD = 0;
1004 if (TA.getKind() != TemplateArgument::Null)
1005 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
1008 ArgDecl = Iter->getAsTemplate().getAsTemplateDecl();
1009 else if (!isVariadic)
1010 ArgDecl = DefaultTD;
1013 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
1014 static bool IsEqualExpr(ASTContext &Context, Expr *FromExpr, Expr *ToExpr) {
1015 if (FromExpr == ToExpr)
1018 if (!FromExpr || !ToExpr)
1021 FromExpr = FromExpr->IgnoreParens();
1022 ToExpr = ToExpr->IgnoreParens();
1024 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1025 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1027 if (FromDRE || ToDRE) {
1028 if (!FromDRE || !ToDRE)
1030 return FromDRE->getDecl() == ToDRE->getDecl();
1033 Expr::EvalResult FromResult, ToResult;
1034 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1035 !ToExpr->EvaluateAsRValue(ToResult, Context))
1036 assert(0 && "Template arguments must be known at compile time.");
1038 APValue &FromVal = FromResult.Val;
1039 APValue &ToVal = ToResult.Val;
1041 if (FromVal.getKind() != ToVal.getKind()) return false;
1043 switch (FromVal.getKind()) {
1045 return FromVal.getInt() == ToVal.getInt();
1046 case APValue::LValue: {
1047 APValue::LValueBase FromBase = FromVal.getLValueBase();
1048 APValue::LValueBase ToBase = ToVal.getLValueBase();
1049 if (FromBase.isNull() && ToBase.isNull())
1051 if (FromBase.isNull() || ToBase.isNull())
1053 return FromBase.get<const ValueDecl*>() ==
1054 ToBase.get<const ValueDecl*>();
1056 case APValue::MemberPointer:
1057 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1059 llvm_unreachable("Unknown template argument expression.");
1063 // These functions converts the tree representation of the template
1064 // differences into the internal character vector.
1066 /// TreeToString - Converts the Tree object into a character stream which
1067 /// will later be turned into the output string.
1068 void TreeToString(int Indent = 1) {
1071 for (int i = 0; i < Indent; ++i)
1076 // Handle cases where the difference is not templates with different
1078 if (!Tree.NodeIsTemplate()) {
1079 if (Tree.NodeIsQualType()) {
1080 QualType FromType, ToType;
1081 Tree.GetNode(FromType, ToType);
1082 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1086 if (Tree.NodeIsExpr()) {
1087 Expr *FromExpr, *ToExpr;
1088 Tree.GetNode(FromExpr, ToExpr);
1089 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1093 if (Tree.NodeIsTemplateTemplate()) {
1094 TemplateDecl *FromTD, *ToTD;
1095 Tree.GetNode(FromTD, ToTD);
1096 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1097 Tree.ToDefault(), Tree.NodeIsSame());
1101 if (Tree.NodeIsAPSInt()) {
1102 llvm::APSInt FromInt, ToInt;
1103 bool IsValidFromInt, IsValidToInt;
1104 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1105 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1106 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1109 llvm_unreachable("Unable to deduce template difference.");
1112 // Node is root of template. Recurse on children.
1113 TemplateDecl *FromTD, *ToTD;
1114 Tree.GetNode(FromTD, ToTD);
1116 assert(Tree.HasChildren() && "Template difference not found in diff tree.");
1118 Qualifiers FromQual, ToQual;
1119 Tree.GetNode(FromQual, ToQual);
1120 PrintQualifiers(FromQual, ToQual);
1122 OS << FromTD->getNameAsString() << '<';
1124 unsigned NumElideArgs = 0;
1127 if (Tree.NodeIsSame()) {
1131 if (NumElideArgs > 0) {
1132 PrintElideArgs(NumElideArgs, Indent);
1137 TreeToString(Indent);
1138 if (Tree.HasNextSibling())
1140 } while (Tree.AdvanceSibling());
1141 if (NumElideArgs > 0)
1142 PrintElideArgs(NumElideArgs, Indent);
1148 // To signal to the text printer that a certain text needs to be bolded,
1149 // a special character is injected into the character stream which the
1150 // text printer will later strip out.
1152 /// Bold - Start bolding text.
1154 assert(!IsBold && "Attempting to bold text that is already bold.");
1157 OS << ToggleHighlight;
1160 /// Unbold - Stop bolding text.
1162 assert(IsBold && "Attempting to remove bold from unbold text.");
1165 OS << ToggleHighlight;
1168 // Functions to print out the arguments and highlighting the difference.
1170 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1171 /// typenames that are the same and attempt to disambiguate them by using
1172 /// canonical typenames.
1173 void PrintTypeNames(QualType FromType, QualType ToType,
1174 bool FromDefault, bool ToDefault, bool Same) {
1175 assert((!FromType.isNull() || !ToType.isNull()) &&
1176 "Only one template argument may be missing.");
1179 OS << FromType.getAsString();
1183 if (!FromType.isNull() && !ToType.isNull() &&
1184 FromType.getLocalUnqualifiedType() ==
1185 ToType.getLocalUnqualifiedType()) {
1186 Qualifiers FromQual = FromType.getLocalQualifiers(),
1187 ToQual = ToType.getLocalQualifiers(),
1189 PrintQualifiers(FromQual, ToQual);
1190 FromType.getLocalUnqualifiedType().print(OS, Policy);
1194 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1195 : FromType.getAsString();
1196 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1197 : ToType.getAsString();
1198 // Switch to canonical typename if it is better.
1199 // TODO: merge this with other aka printing above.
1200 if (FromTypeStr == ToTypeStr) {
1201 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1202 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1203 if (FromCanTypeStr != ToCanTypeStr) {
1204 FromTypeStr = FromCanTypeStr;
1205 ToTypeStr = ToCanTypeStr;
1209 if (PrintTree) OS << '[';
1210 OS << (FromDefault ? "(default) " : "");
1215 OS << " != " << (ToDefault ? "(default) " : "");
1224 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1226 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1227 bool FromDefault, bool ToDefault, bool Same) {
1228 assert((FromExpr || ToExpr) &&
1229 "Only one template argument may be missing.");
1231 PrintExpr(FromExpr);
1232 } else if (!PrintTree) {
1233 OS << (FromDefault ? "(default) " : "");
1235 PrintExpr(FromExpr);
1238 OS << (FromDefault ? "[(default) " : "[");
1240 PrintExpr(FromExpr);
1242 OS << " != " << (ToDefault ? "(default) " : "");
1250 /// PrintExpr - Actual formatting and printing of expressions.
1251 void PrintExpr(const Expr *E) {
1253 OS << "(no argument)";
1255 E->printPretty(OS, 0, Policy); return;
1258 /// PrintTemplateTemplate - Handles printing of template template arguments,
1259 /// highlighting argument differences.
1260 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1261 bool FromDefault, bool ToDefault, bool Same) {
1262 assert((FromTD || ToTD) && "Only one template argument may be missing.");
1264 OS << "template " << FromTD->getNameAsString();
1265 } else if (!PrintTree) {
1266 OS << (FromDefault ? "(default) template " : "template ");
1268 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1271 OS << (FromDefault ? "[(default) template " : "[template ");
1273 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1275 OS << " != " << (ToDefault ? "(default) template " : "template ");
1277 OS << (ToTD ? ToTD->getNameAsString() : "(no argument)");
1283 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1284 /// argument differences.
1285 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1286 bool IsValidFromInt, bool IsValidToInt, bool FromDefault,
1287 bool ToDefault, bool Same) {
1288 assert((IsValidFromInt || IsValidToInt) &&
1289 "Only one integral argument may be missing.");
1292 OS << FromInt.toString(10);
1293 } else if (!PrintTree) {
1294 OS << (FromDefault ? "(default) " : "");
1296 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1299 OS << (FromDefault ? "[(default) " : "[");
1301 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1303 OS << " != " << (ToDefault ? "(default) " : "");
1305 OS << (IsValidToInt ? ToInt.toString(10) : "(no argument)");
1311 // Prints the appropriate placeholder for elided template arguments.
1312 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1315 for (unsigned i = 0; i < Indent; ++i)
1318 if (NumElideArgs == 0) return;
1319 if (NumElideArgs == 1)
1322 OS << "[" << NumElideArgs << " * ...]";
1325 // Prints and highlights differences in Qualifiers.
1326 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1327 // Both types have no qualifiers
1328 if (FromQual.empty() && ToQual.empty())
1331 // Both types have same qualifiers
1332 if (FromQual == ToQual) {
1333 PrintQualifier(FromQual, /*ApplyBold*/false);
1337 // Find common qualifiers and strip them from FromQual and ToQual.
1338 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1341 // The qualifiers are printed before the template name.
1343 // The common qualifiers are printed. Then, qualifiers only in this type
1344 // are printed and highlighted. Finally, qualifiers only in the other
1345 // type are printed and highlighted inside parentheses after "missing".
1347 // Qualifiers are printed next to each other, inside brackets, and
1348 // separated by "!=". The printing order is:
1349 // common qualifiers, highlighted from qualifiers, "!=",
1350 // common qualifiers, highlighted to qualifiers
1353 if (CommonQual.empty() && FromQual.empty()) {
1355 OS << "(no qualifiers) ";
1358 PrintQualifier(CommonQual, /*ApplyBold*/false);
1359 PrintQualifier(FromQual, /*ApplyBold*/true);
1362 if (CommonQual.empty() && ToQual.empty()) {
1364 OS << "(no qualifiers)";
1367 PrintQualifier(CommonQual, /*ApplyBold*/false,
1368 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1369 PrintQualifier(ToQual, /*ApplyBold*/true,
1370 /*appendSpaceIfNonEmpty*/false);
1374 PrintQualifier(CommonQual, /*ApplyBold*/false);
1375 PrintQualifier(FromQual, /*ApplyBold*/true);
1379 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1380 bool AppendSpaceIfNonEmpty = true) {
1381 if (Q.empty()) return;
1382 if (ApplyBold) Bold();
1383 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1384 if (ApplyBold) Unbold();
1389 TemplateDiff(ASTContext &Context, QualType FromType, QualType ToType,
1390 bool PrintTree, bool PrintFromType, bool ElideType,
1393 Policy(Context.getLangOpts()),
1394 ElideType(ElideType),
1395 PrintTree(PrintTree),
1396 ShowColor(ShowColor),
1397 // When printing a single type, the FromType is the one printed.
1398 FromType(PrintFromType ? FromType : ToType),
1399 ToType(PrintFromType ? ToType : FromType),
1404 /// DiffTemplate - Start the template type diffing.
1405 void DiffTemplate() {
1406 Qualifiers FromQual = FromType.getQualifiers(),
1407 ToQual = ToType.getQualifiers();
1409 const TemplateSpecializationType *FromOrigTST =
1410 GetTemplateSpecializationType(Context, FromType);
1411 const TemplateSpecializationType *ToOrigTST =
1412 GetTemplateSpecializationType(Context, ToType);
1414 // Only checking templates.
1415 if (!FromOrigTST || !ToOrigTST)
1418 // Different base templates.
1419 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1423 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1424 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
1425 Tree.SetNode(FromType, ToType);
1426 Tree.SetNode(FromQual, ToQual);
1428 // Same base template, but different arguments.
1429 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1430 ToOrigTST->getTemplateName().getAsTemplateDecl());
1432 DiffTemplate(FromOrigTST, ToOrigTST);
1435 /// MakeString - When the two types given are templated types with the same
1436 /// base template, a string representation of the type difference will be
1437 /// loaded into S and return true. Otherwise, return false.
1438 bool MakeString(std::string &S) {
1439 Tree.StartTraverse();
1444 assert(!IsBold && "Bold is applied to end of string.");
1448 }; // end class TemplateDiff
1451 /// FormatTemplateTypeDiff - A helper static function to start the template
1452 /// diff and return the properly formatted string. Returns true if the diff
1454 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1455 QualType ToType, bool PrintTree,
1456 bool PrintFromType, bool ElideType,
1457 bool ShowColors, std::string &S) {
1459 PrintFromType = true;
1460 TemplateDiff TD(Context, FromType, ToType, PrintTree, PrintFromType,
1461 ElideType, ShowColors);
1463 return TD.MakeString(S);