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"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/TemplateBase.h"
19 #include "clang/AST/Type.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
25 // Returns a desugared version of the QualType, and marks ShouldAKA as true
26 // whenever we remove significant sugar from the type.
27 static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
28 QualifierCollector QC;
31 const Type *Ty = QC.strip(QT);
33 // Don't aka just because we saw an elaborated type...
34 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
38 // ... or a paren type ...
39 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
43 // ...or a substituted template type parameter ...
44 if (const SubstTemplateTypeParmType *ST =
45 dyn_cast<SubstTemplateTypeParmType>(Ty)) {
49 // ...or an attributed type...
50 if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
54 // ... or an auto type.
55 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
62 // Don't desugar template specializations, unless it's an alias template.
63 if (const TemplateSpecializationType *TST
64 = dyn_cast<TemplateSpecializationType>(Ty))
65 if (!TST->isTypeAlias())
68 // Don't desugar magic Objective-C types.
69 if (QualType(Ty,0) == Context.getObjCIdType() ||
70 QualType(Ty,0) == Context.getObjCClassType() ||
71 QualType(Ty,0) == Context.getObjCSelType() ||
72 QualType(Ty,0) == Context.getObjCProtoType())
75 // Don't desugar va_list.
76 if (QualType(Ty,0) == Context.getBuiltinVaListType())
79 // Otherwise, do a single-step desugar.
82 switch (Ty->getTypeClass()) {
83 #define ABSTRACT_TYPE(Class, Base)
84 #define TYPE(Class, Base) \
86 const Class##Type *CTy = cast<Class##Type>(Ty); \
87 if (CTy->isSugared()) { \
89 Underlying = CTy->desugar(); \
93 #include "clang/AST/TypeNodes.def"
96 // If it wasn't sugared, we're done.
100 // If the desugared type is a vector type, we don't want to expand
101 // it, it will turn into an attribute mess. People want their "vec4".
102 if (isa<VectorType>(Underlying))
105 // Don't desugar through the primary typedef of an anonymous type.
106 if (const TagType *UTT = Underlying->getAs<TagType>())
107 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
108 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
111 // Record that we actually looked through an opaque type here.
116 // If we have a pointer-like type, desugar the pointee as well.
117 // FIXME: Handle other pointer-like types.
118 if (const PointerType *Ty = QT->getAs<PointerType>()) {
119 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
121 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
122 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
124 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
125 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
129 return QC.apply(Context, QT);
132 /// \brief Convert the given type to a string suitable for printing as part of
135 /// There are four main criteria when determining whether we should have an
136 /// a.k.a. clause when pretty-printing a type:
138 /// 1) Some types provide very minimal sugar that doesn't impede the
139 /// user's understanding --- for example, elaborated type
140 /// specifiers. If this is all the sugar we see, we don't want an
142 /// 2) Some types are technically sugared but are much more familiar
143 /// when seen in their sugared form --- for example, va_list,
144 /// vector types, and the magic Objective C types. We don't
145 /// want to desugar these, even if we do produce an a.k.a. clause.
146 /// 3) Some types may have already been desugared previously in this diagnostic.
147 /// if this is the case, doing another "aka" would just be clutter.
148 /// 4) Two different types within the same diagnostic have the same output
149 /// string. In this case, force an a.k.a with the desugared type when
150 /// doing so will provide additional information.
152 /// \param Context the context in which the type was allocated
153 /// \param Ty the type to print
154 /// \param QualTypeVals pointer values to QualTypes which are used in the
155 /// diagnostic message
157 ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
158 const DiagnosticsEngine::ArgumentValue *PrevArgs,
159 unsigned NumPrevArgs,
160 ArrayRef<intptr_t> QualTypeVals) {
161 // FIXME: Playing with std::string is really slow.
162 bool ForceAKA = false;
163 QualType CanTy = Ty.getCanonicalType();
164 std::string S = Ty.getAsString(Context.getPrintingPolicy());
165 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
167 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
169 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
170 if (CompareTy.isNull())
173 continue; // Same types
174 QualType CompareCanTy = CompareTy.getCanonicalType();
175 if (CompareCanTy == CanTy)
176 continue; // Same canonical types
177 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
179 QualType CompareDesugar = Desugar(Context, CompareTy, aka);
180 std::string CompareDesugarStr =
181 CompareDesugar.getAsString(Context.getPrintingPolicy());
182 if (CompareS != S && CompareDesugarStr != S)
183 continue; // The type string is different than the comparison string
184 // and the desugared comparison string.
185 std::string CompareCanS =
186 CompareCanTy.getAsString(Context.getPrintingPolicy());
188 if (CompareCanS == CanS)
189 continue; // No new info from canonical type
195 // Check to see if we already desugared this type in this
196 // diagnostic. If so, don't do it again.
197 bool Repeated = false;
198 for (unsigned i = 0; i != NumPrevArgs; ++i) {
199 // TODO: Handle ak_declcontext case.
200 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
201 void *Ptr = (void*)PrevArgs[i].second;
202 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
210 // Consider producing an a.k.a. clause if removing all the direct
211 // sugar gives us something "significantly different".
213 bool ShouldAKA = false;
214 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
215 if (ShouldAKA || ForceAKA) {
216 if (DesugaredTy == Ty) {
217 DesugaredTy = Ty.getCanonicalType();
219 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
221 S = "'" + S + "' (aka '" + akaStr + "')";
231 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
232 QualType ToType, bool PrintTree,
233 bool PrintFromType, bool ElideType,
234 bool ShowColors, raw_ostream &OS);
236 void clang::FormatASTNodeDiagnosticArgument(
237 DiagnosticsEngine::ArgumentKind Kind,
239 const char *Modifier,
241 const char *Argument,
243 const DiagnosticsEngine::ArgumentValue *PrevArgs,
244 unsigned NumPrevArgs,
245 SmallVectorImpl<char> &Output,
247 ArrayRef<intptr_t> QualTypeVals) {
248 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
250 size_t OldEnd = Output.size();
251 llvm::raw_svector_ostream OS(Output);
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, OS)) {
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 template 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 OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs,
293 case DiagnosticsEngine::ak_declarationname: {
294 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
296 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
300 assert(ModLen == 0 && ArgLen == 0 &&
301 "Invalid modifier for DeclarationName argument");
303 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
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(OS, Context.getPrintingPolicy(), Qualified);
320 case DiagnosticsEngine::ak_nestednamespec: {
321 NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
322 NNS->print(OS, Context.getPrintingPolicy());
326 case DiagnosticsEngine::ak_declcontext: {
327 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
328 assert(DC && "Should never have a null declaration context");
330 if (DC->isTranslationUnit()) {
331 // FIXME: Get these strings from some localized place
332 if (Context.getLangOpts().CPlusPlus)
333 OS << "the global namespace";
335 OS << "the global scope";
336 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
337 OS << ConvertTypeToDiagnosticString(Context,
338 Context.getTypeDeclType(Type),
339 PrevArgs, NumPrevArgs,
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(OS, Context.getPrintingPolicy(), true);
363 Output.insert(Output.begin()+OldEnd, '\'');
364 Output.push_back('\'');
368 /// TemplateDiff - A class that constructs a pretty string for a pair of
369 /// QualTypes. For the pair of types, a diff tree will be created containing
370 /// all the information about the templates and template arguments. Afterwards,
371 /// the tree is transformed to a string according to the options passed in.
374 /// Context - The ASTContext which is used for comparing template arguments.
377 /// Policy - Used during expression printing.
378 PrintingPolicy Policy;
380 /// ElideType - Option to elide identical types.
383 /// PrintTree - Format output string as a tree.
386 /// ShowColor - Diagnostics support color, so bolding will be used.
389 /// FromType - When single type printing is selected, this is the type to be
390 /// be printed. When tree printing is selected, this type will show up first
394 /// ToType - The type that FromType is compared to. Only in tree printing
395 /// will this type be outputed.
398 /// OS - The stream used to construct the output strings.
401 /// IsBold - Keeps track of the bold formatting for the output string.
404 /// DiffTree - A tree representation the differences between two types.
407 /// DiffKind - The difference in a DiffNode and which fields are used.
409 /// Incomplete or invalid node.
411 /// Another level of templates, uses TemplateDecl and Qualifiers
413 /// Type difference, uses QualType
415 /// Expression difference, uses Expr
417 /// Template argument difference, uses TemplateDecl
419 /// Integer difference, uses APSInt and Expr
421 /// Declaration difference, uses ValueDecl
425 /// DiffNode - The root node stores the original type. Each child node
426 /// stores template arguments of their parents. For templated types, the
427 /// template decl is also stored.
431 /// NextNode - The index of the next sibling node or 0.
434 /// ChildNode - The index of the first child node or 0.
437 /// ParentNode - The index of the parent node.
440 /// FromType, ToType - The type arguments.
441 QualType FromType, ToType;
443 /// FromExpr, ToExpr - The expression arguments.
444 Expr *FromExpr, *ToExpr;
446 /// FromTD, ToTD - The template decl for template template
447 /// arguments or the type arguments that are templates.
448 TemplateDecl *FromTD, *ToTD;
450 /// FromQual, ToQual - Qualifiers for template types.
451 Qualifiers FromQual, ToQual;
453 /// FromInt, ToInt - APSInt's for integral arguments.
454 llvm::APSInt FromInt, ToInt;
456 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
457 bool IsValidFromInt, IsValidToInt;
459 /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
460 ValueDecl *FromValueDecl, *ToValueDecl;
462 /// FromDefault, ToDefault - Whether the argument is a default argument.
463 bool FromDefault, ToDefault;
465 /// Same - Whether the two arguments evaluate to the same value.
468 DiffNode(unsigned ParentNode = 0)
469 : Kind(Invalid), NextNode(0), ChildNode(0), ParentNode(ParentNode),
470 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
471 IsValidFromInt(false), IsValidToInt(false), FromValueDecl(0),
472 ToValueDecl(0), FromDefault(false), ToDefault(false), Same(false) { }
475 /// FlatTree - A flattened tree used to store the DiffNodes.
476 SmallVector<DiffNode, 16> FlatTree;
478 /// CurrentNode - The index of the current node being used.
479 unsigned CurrentNode;
481 /// NextFreeNode - The index of the next unused node. Used when creating
483 unsigned NextFreeNode;
485 /// ReadNode - The index of the current node being read.
490 CurrentNode(0), NextFreeNode(1) {
491 FlatTree.push_back(DiffNode());
494 // Node writing functions.
495 /// SetNode - Sets FromTD and ToTD of the current node.
496 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
497 FlatTree[CurrentNode].FromTD = FromTD;
498 FlatTree[CurrentNode].ToTD = ToTD;
501 /// SetNode - Sets FromType and ToType of the current node.
502 void SetNode(QualType FromType, QualType ToType) {
503 FlatTree[CurrentNode].FromType = FromType;
504 FlatTree[CurrentNode].ToType = ToType;
507 /// SetNode - Set FromExpr and ToExpr of the current node.
508 void SetNode(Expr *FromExpr, Expr *ToExpr) {
509 FlatTree[CurrentNode].FromExpr = FromExpr;
510 FlatTree[CurrentNode].ToExpr = ToExpr;
513 /// SetNode - Set FromInt and ToInt of the current node.
514 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
515 bool IsValidFromInt, bool IsValidToInt) {
516 FlatTree[CurrentNode].FromInt = FromInt;
517 FlatTree[CurrentNode].ToInt = ToInt;
518 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
519 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
522 /// SetNode - Set FromQual and ToQual of the current node.
523 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
524 FlatTree[CurrentNode].FromQual = FromQual;
525 FlatTree[CurrentNode].ToQual = ToQual;
528 /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
529 void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl) {
530 FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
531 FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
534 /// SetSame - Sets the same flag of the current node.
535 void SetSame(bool Same) {
536 FlatTree[CurrentNode].Same = Same;
539 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
540 void SetDefault(bool FromDefault, bool ToDefault) {
541 FlatTree[CurrentNode].FromDefault = FromDefault;
542 FlatTree[CurrentNode].ToDefault = ToDefault;
545 /// SetKind - Sets the current node's type.
546 void SetKind(DiffKind Kind) {
547 FlatTree[CurrentNode].Kind = Kind;
550 /// Up - Changes the node to the parent of the current node.
552 CurrentNode = FlatTree[CurrentNode].ParentNode;
555 /// AddNode - Adds a child node to the current node, then sets that node
556 /// node as the current node.
558 FlatTree.push_back(DiffNode(CurrentNode));
559 DiffNode &Node = FlatTree[CurrentNode];
560 if (Node.ChildNode == 0) {
561 // If a child node doesn't exist, add one.
562 Node.ChildNode = NextFreeNode;
564 // If a child node exists, find the last child node and add a
567 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
568 i = FlatTree[i].NextNode) {
570 FlatTree[i].NextNode = NextFreeNode;
572 CurrentNode = NextFreeNode;
576 // Node reading functions.
577 /// StartTraverse - Prepares the tree for recursive traversal.
578 void StartTraverse() {
580 CurrentNode = NextFreeNode;
584 /// Parent - Move the current read node to its parent.
586 ReadNode = FlatTree[ReadNode].ParentNode;
589 /// GetNode - Gets the FromType and ToType.
590 void GetNode(QualType &FromType, QualType &ToType) {
591 FromType = FlatTree[ReadNode].FromType;
592 ToType = FlatTree[ReadNode].ToType;
595 /// GetNode - Gets the FromExpr and ToExpr.
596 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
597 FromExpr = FlatTree[ReadNode].FromExpr;
598 ToExpr = FlatTree[ReadNode].ToExpr;
601 /// GetNode - Gets the FromTD and ToTD.
602 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
603 FromTD = FlatTree[ReadNode].FromTD;
604 ToTD = FlatTree[ReadNode].ToTD;
607 /// GetNode - Gets the FromInt and ToInt.
608 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
609 bool &IsValidFromInt, bool &IsValidToInt) {
610 FromInt = FlatTree[ReadNode].FromInt;
611 ToInt = FlatTree[ReadNode].ToInt;
612 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
613 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
616 /// GetNode - Gets the FromQual and ToQual.
617 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
618 FromQual = FlatTree[ReadNode].FromQual;
619 ToQual = FlatTree[ReadNode].ToQual;
622 /// GetNode - Gets the FromValueDecl and ToValueDecl.
623 void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl) {
624 FromValueDecl = FlatTree[ReadNode].FromValueDecl;
625 ToValueDecl = FlatTree[ReadNode].ToValueDecl;
628 /// NodeIsSame - Returns true the arguments are the same.
630 return FlatTree[ReadNode].Same;
633 /// HasChildrend - Returns true if the node has children.
635 return FlatTree[ReadNode].ChildNode != 0;
638 /// MoveToChild - Moves from the current node to its child.
640 ReadNode = FlatTree[ReadNode].ChildNode;
643 /// AdvanceSibling - If there is a next sibling, advance to it and return
644 /// true. Otherwise, return false.
645 bool AdvanceSibling() {
646 if (FlatTree[ReadNode].NextNode == 0)
649 ReadNode = FlatTree[ReadNode].NextNode;
653 /// HasNextSibling - Return true if the node has a next sibling.
654 bool HasNextSibling() {
655 return FlatTree[ReadNode].NextNode != 0;
658 /// FromDefault - Return true if the from argument is the default.
660 return FlatTree[ReadNode].FromDefault;
663 /// ToDefault - Return true if the to argument is the default.
665 return FlatTree[ReadNode].ToDefault;
668 /// Empty - Returns true if the tree has no information.
670 return GetKind() == Invalid;
673 /// GetKind - Returns the current node's type.
675 return FlatTree[ReadNode].Kind;
681 /// TSTiterator - an iterator that is used to enter a
682 /// TemplateSpecializationType and read TemplateArguments inside template
683 /// parameter packs in order with the rest of the TemplateArguments.
685 typedef const TemplateArgument& reference;
686 typedef const TemplateArgument* pointer;
688 /// TST - the template specialization whose arguments this iterator
690 const TemplateSpecializationType *TST;
692 /// DesugarTST - desugared template specialization used to extract
693 /// default argument information
694 const TemplateSpecializationType *DesugarTST;
696 /// Index - the index of the template argument in TST.
699 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
700 /// points to a TemplateArgument within a parameter pack.
701 TemplateArgument::pack_iterator CurrentTA;
703 /// EndTA - the end iterator of a parameter pack
704 TemplateArgument::pack_iterator EndTA;
706 /// TSTiterator - Constructs an iterator and sets it to the first template
708 TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST)
710 DesugarTST(GetTemplateSpecializationType(Context, TST->desugar())),
711 Index(0), CurrentTA(0), EndTA(0) {
714 // Set to first template argument. If not a parameter pack, done.
715 TemplateArgument TA = TST->getArg(0);
716 if (TA.getKind() != TemplateArgument::Pack) return;
718 // Start looking into the parameter pack.
719 CurrentTA = TA.pack_begin();
720 EndTA = TA.pack_end();
722 // Found a valid template argument.
723 if (CurrentTA != EndTA) return;
725 // Parameter pack is empty, use the increment to get to a valid
726 // template argument.
730 /// isEnd - Returns true if the iterator is one past the end.
732 return Index >= TST->getNumArgs();
735 /// &operator++ - Increment the iterator to the next template argument.
736 TSTiterator &operator++() {
737 // After the end, Index should be the default argument position in
738 // DesugarTST, if it exists.
744 // If in a parameter pack, advance in the parameter pack.
745 if (CurrentTA != EndTA) {
747 if (CurrentTA != EndTA)
751 // Loop until a template argument is found, or the end is reached.
753 // Advance to the next template argument. Break if reached the end.
754 if (++Index == TST->getNumArgs()) break;
756 // If the TemplateArgument is not a parameter pack, done.
757 TemplateArgument TA = TST->getArg(Index);
758 if (TA.getKind() != TemplateArgument::Pack) break;
760 // Handle parameter packs.
761 CurrentTA = TA.pack_begin();
762 EndTA = TA.pack_end();
764 // If the parameter pack is empty, try to advance again.
765 if (CurrentTA != EndTA) break;
770 /// operator* - Returns the appropriate TemplateArgument.
771 reference operator*() const {
772 assert(!isEnd() && "Index exceeds number of arguments.");
773 if (CurrentTA == EndTA)
774 return TST->getArg(Index);
779 /// operator-> - Allow access to the underlying TemplateArgument.
780 pointer operator->() const {
784 /// getDesugar - Returns the deduced template argument from DesguarTST
785 reference getDesugar() const {
786 return DesugarTST->getArg(Index);
790 // These functions build up the template diff tree, including functions to
791 // retrieve and compare template arguments.
793 static const TemplateSpecializationType * GetTemplateSpecializationType(
794 ASTContext &Context, QualType Ty) {
795 if (const TemplateSpecializationType *TST =
796 Ty->getAs<TemplateSpecializationType>())
799 const RecordType *RT = Ty->getAs<RecordType>();
804 const ClassTemplateSpecializationDecl *CTSD =
805 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
810 Ty = Context.getTemplateSpecializationType(
811 TemplateName(CTSD->getSpecializedTemplate()),
812 CTSD->getTemplateArgs().data(),
813 CTSD->getTemplateArgs().size(),
814 Ty.getLocalUnqualifiedType().getCanonicalType());
816 return Ty->getAs<TemplateSpecializationType>();
819 /// DiffTemplate - recursively visits template arguments and stores the
820 /// argument info into a tree.
821 void DiffTemplate(const TemplateSpecializationType *FromTST,
822 const TemplateSpecializationType *ToTST) {
823 // Begin descent into diffing template tree.
824 TemplateParameterList *Params =
825 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
826 unsigned TotalArgs = 0;
827 for (TSTiterator FromIter(Context, FromTST), ToIter(Context, ToTST);
828 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
831 // Get the parameter at index TotalArgs. If index is larger
832 // than the total number of parameters, then there is an
833 // argument pack, so re-use the last parameter.
834 NamedDecl *ParamND = Params->getParam(
835 (TotalArgs < Params->size()) ? TotalArgs
836 : Params->size() - 1);
838 if (TemplateTypeParmDecl *DefaultTTPD =
839 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
840 QualType FromType, ToType;
841 FromType = GetType(FromIter, DefaultTTPD);
842 ToType = GetType(ToIter, DefaultTTPD);
843 Tree.SetNode(FromType, ToType);
844 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
845 ToIter.isEnd() && !ToType.isNull());
846 Tree.SetKind(DiffTree::Type);
847 if (!FromType.isNull() && !ToType.isNull()) {
848 if (Context.hasSameType(FromType, ToType)) {
851 Qualifiers FromQual = FromType.getQualifiers(),
852 ToQual = ToType.getQualifiers();
853 const TemplateSpecializationType *FromArgTST =
854 GetTemplateSpecializationType(Context, FromType);
855 const TemplateSpecializationType *ToArgTST =
856 GetTemplateSpecializationType(Context, ToType);
858 if (FromArgTST && ToArgTST &&
859 hasSameTemplate(FromArgTST, ToArgTST)) {
860 FromQual -= QualType(FromArgTST, 0).getQualifiers();
861 ToQual -= QualType(ToArgTST, 0).getQualifiers();
862 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
863 ToArgTST->getTemplateName().getAsTemplateDecl());
864 Tree.SetNode(FromQual, ToQual);
865 Tree.SetKind(DiffTree::Template);
866 DiffTemplate(FromArgTST, ToArgTST);
872 // Handle Expressions
873 if (NonTypeTemplateParmDecl *DefaultNTTPD =
874 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
875 Expr *FromExpr = 0, *ToExpr = 0;
876 llvm::APSInt FromInt, ToInt;
877 ValueDecl *FromValueDecl = 0, *ToValueDecl = 0;
878 unsigned ParamWidth = 128; // Safe default
879 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType())
880 ParamWidth = Context.getIntWidth(DefaultNTTPD->getType());
881 bool HasFromInt = !FromIter.isEnd() &&
882 FromIter->getKind() == TemplateArgument::Integral;
883 bool HasToInt = !ToIter.isEnd() &&
884 ToIter->getKind() == TemplateArgument::Integral;
885 bool HasFromValueDecl =
887 FromIter->getKind() == TemplateArgument::Declaration;
888 bool HasToValueDecl =
890 ToIter->getKind() == TemplateArgument::Declaration;
892 assert(((!HasFromInt && !HasToInt) ||
893 (!HasFromValueDecl && !HasToValueDecl)) &&
894 "Template argument cannot be both integer and declaration");
897 FromInt = FromIter->getAsIntegral();
898 else if (HasFromValueDecl)
899 FromValueDecl = FromIter->getAsDecl();
901 FromExpr = GetExpr(FromIter, DefaultNTTPD);
904 ToInt = ToIter->getAsIntegral();
905 else if (HasToValueDecl)
906 ToValueDecl = ToIter->getAsDecl();
908 ToExpr = GetExpr(ToIter, DefaultNTTPD);
910 if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
911 Tree.SetNode(FromExpr, ToExpr);
912 Tree.SetDefault(FromIter.isEnd() && FromExpr,
913 ToIter.isEnd() && ToExpr);
914 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType()) {
916 FromInt = GetInt(FromIter, FromExpr);
918 ToInt = GetInt(ToIter, ToExpr);
919 Tree.SetNode(FromInt, ToInt, FromExpr, ToExpr);
920 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
921 Tree.SetKind(DiffTree::Integer);
923 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr));
924 Tree.SetKind(DiffTree::Expression);
926 } else if (HasFromInt || HasToInt) {
927 if (!HasFromInt && FromExpr) {
928 FromInt = GetInt(FromIter, FromExpr);
931 if (!HasToInt && ToExpr) {
932 ToInt = GetInt(ToIter, ToExpr);
935 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
936 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
937 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
938 ToIter.isEnd() && HasToInt);
939 Tree.SetKind(DiffTree::Integer);
941 if (!HasFromValueDecl && FromExpr)
942 FromValueDecl = GetValueDecl(FromIter, FromExpr);
943 if (!HasToValueDecl && ToExpr)
944 ToValueDecl = GetValueDecl(ToIter, ToExpr);
945 Tree.SetNode(FromValueDecl, ToValueDecl);
946 Tree.SetSame(FromValueDecl && ToValueDecl &&
947 FromValueDecl->getCanonicalDecl() ==
948 ToValueDecl->getCanonicalDecl());
949 Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
950 ToIter.isEnd() && ToValueDecl);
951 Tree.SetKind(DiffTree::Declaration);
956 if (TemplateTemplateParmDecl *DefaultTTPD =
957 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
958 TemplateDecl *FromDecl, *ToDecl;
959 FromDecl = GetTemplateDecl(FromIter, DefaultTTPD);
960 ToDecl = GetTemplateDecl(ToIter, DefaultTTPD);
961 Tree.SetNode(FromDecl, ToDecl);
963 FromDecl && ToDecl &&
964 FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
965 Tree.SetKind(DiffTree::TemplateTemplate);
974 /// makeTemplateList - Dump every template alias into the vector.
975 static void makeTemplateList(
976 SmallVector<const TemplateSpecializationType*, 1> &TemplateList,
977 const TemplateSpecializationType *TST) {
979 TemplateList.push_back(TST);
980 if (!TST->isTypeAlias())
982 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
986 /// hasSameBaseTemplate - Returns true when the base templates are the same,
987 /// even if the template arguments are not.
988 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
989 const TemplateSpecializationType *ToTST) {
990 return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
991 ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
994 /// hasSameTemplate - Returns true if both types are specialized from the
995 /// same template declaration. If they come from different template aliases,
996 /// do a parallel ascension search to determine the highest template alias in
997 /// common and set the arguments to them.
998 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
999 const TemplateSpecializationType *&ToTST) {
1000 // Check the top templates if they are the same.
1001 if (hasSameBaseTemplate(FromTST, ToTST))
1004 // Create vectors of template aliases.
1005 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
1008 makeTemplateList(FromTemplateList, FromTST);
1009 makeTemplateList(ToTemplateList, ToTST);
1011 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
1012 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
1013 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
1015 // Check if the lowest template types are the same. If not, return.
1016 if (!hasSameBaseTemplate(*FromIter, *ToIter))
1019 // Begin searching up the template aliases. The bottom most template
1020 // matches so move up until one pair does not match. Use the template
1021 // right before that one.
1022 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
1023 if (!hasSameBaseTemplate(*FromIter, *ToIter))
1027 FromTST = FromIter[-1];
1033 /// GetType - Retrieves the template type arguments, including default
1035 QualType GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD) {
1036 bool isVariadic = DefaultTTPD->isParameterPack();
1039 return Iter->getAsType();
1041 return DefaultTTPD->getDefaultArgument();
1046 /// GetExpr - Retrieves the template expression argument, including default
1048 Expr *GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD) {
1050 bool isVariadic = DefaultNTTPD->isParameterPack();
1053 ArgExpr = Iter->getAsExpr();
1054 else if (!isVariadic)
1055 ArgExpr = DefaultNTTPD->getDefaultArgument();
1058 while (SubstNonTypeTemplateParmExpr *SNTTPE =
1059 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
1060 ArgExpr = SNTTPE->getReplacement();
1065 /// GetInt - Retrieves the template integer argument, including evaluating
1066 /// default arguments.
1067 llvm::APInt GetInt(const TSTiterator &Iter, Expr *ArgExpr) {
1068 // Default, value-depenedent expressions require fetching
1069 // from the desugared TemplateArgument
1070 if (Iter.isEnd() && ArgExpr->isValueDependent())
1071 switch (Iter.getDesugar().getKind()) {
1072 case TemplateArgument::Integral:
1073 return Iter.getDesugar().getAsIntegral();
1074 case TemplateArgument::Expression:
1075 ArgExpr = Iter.getDesugar().getAsExpr();
1076 return ArgExpr->EvaluateKnownConstInt(Context);
1078 assert(0 && "Unexpected template argument kind");
1080 return ArgExpr->EvaluateKnownConstInt(Context);
1083 /// GetValueDecl - Retrieves the template integer argument, including
1084 /// default expression argument.
1085 ValueDecl *GetValueDecl(const TSTiterator &Iter, Expr *ArgExpr) {
1086 // Default, value-depenedent expressions require fetching
1087 // from the desugared TemplateArgument
1088 if (Iter.isEnd() && ArgExpr->isValueDependent())
1089 switch (Iter.getDesugar().getKind()) {
1090 case TemplateArgument::Declaration:
1091 return Iter.getDesugar().getAsDecl();
1092 case TemplateArgument::Expression:
1093 ArgExpr = Iter.getDesugar().getAsExpr();
1094 return cast<DeclRefExpr>(ArgExpr)->getDecl();
1096 assert(0 && "Unexpected template argument kind");
1098 return cast<DeclRefExpr>(ArgExpr)->getDecl();
1101 /// GetTemplateDecl - Retrieves the template template arguments, including
1102 /// default arguments.
1103 TemplateDecl *GetTemplateDecl(const TSTiterator &Iter,
1104 TemplateTemplateParmDecl *DefaultTTPD) {
1105 bool isVariadic = DefaultTTPD->isParameterPack();
1107 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
1108 TemplateDecl *DefaultTD = 0;
1109 if (TA.getKind() != TemplateArgument::Null)
1110 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
1113 return Iter->getAsTemplate().getAsTemplateDecl();
1120 /// IsSameConvertedInt - Returns true if both integers are equal when
1121 /// converted to an integer type with the given width.
1122 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1123 const llvm::APSInt &Y) {
1124 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1125 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1126 return ConvertedX == ConvertedY;
1129 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
1130 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1131 Expr *FromExpr, Expr *ToExpr) {
1132 if (FromExpr == ToExpr)
1135 if (!FromExpr || !ToExpr)
1138 FromExpr = FromExpr->IgnoreParens();
1139 ToExpr = ToExpr->IgnoreParens();
1141 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1142 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1144 if (FromDRE || ToDRE) {
1145 if (!FromDRE || !ToDRE)
1147 return FromDRE->getDecl() == ToDRE->getDecl();
1150 Expr::EvalResult FromResult, ToResult;
1151 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1152 !ToExpr->EvaluateAsRValue(ToResult, Context))
1155 APValue &FromVal = FromResult.Val;
1156 APValue &ToVal = ToResult.Val;
1158 if (FromVal.getKind() != ToVal.getKind()) return false;
1160 switch (FromVal.getKind()) {
1162 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
1163 case APValue::LValue: {
1164 APValue::LValueBase FromBase = FromVal.getLValueBase();
1165 APValue::LValueBase ToBase = ToVal.getLValueBase();
1166 if (FromBase.isNull() && ToBase.isNull())
1168 if (FromBase.isNull() || ToBase.isNull())
1170 return FromBase.get<const ValueDecl*>() ==
1171 ToBase.get<const ValueDecl*>();
1173 case APValue::MemberPointer:
1174 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1176 llvm_unreachable("Unknown template argument expression.");
1180 // These functions converts the tree representation of the template
1181 // differences into the internal character vector.
1183 /// TreeToString - Converts the Tree object into a character stream which
1184 /// will later be turned into the output string.
1185 void TreeToString(int Indent = 1) {
1188 OS.indent(2 * Indent);
1192 // Handle cases where the difference is not templates with different
1194 switch (Tree.GetKind()) {
1195 case DiffTree::Invalid:
1196 llvm_unreachable("Template diffing failed with bad DiffNode");
1197 case DiffTree::Type: {
1198 QualType FromType, ToType;
1199 Tree.GetNode(FromType, ToType);
1200 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1204 case DiffTree::Expression: {
1205 Expr *FromExpr, *ToExpr;
1206 Tree.GetNode(FromExpr, ToExpr);
1207 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1211 case DiffTree::TemplateTemplate: {
1212 TemplateDecl *FromTD, *ToTD;
1213 Tree.GetNode(FromTD, ToTD);
1214 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1215 Tree.ToDefault(), Tree.NodeIsSame());
1218 case DiffTree::Integer: {
1219 llvm::APSInt FromInt, ToInt;
1220 Expr *FromExpr, *ToExpr;
1221 bool IsValidFromInt, IsValidToInt;
1222 Tree.GetNode(FromExpr, ToExpr);
1223 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1224 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1225 FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1229 case DiffTree::Declaration: {
1230 ValueDecl *FromValueDecl, *ToValueDecl;
1231 Tree.GetNode(FromValueDecl, ToValueDecl);
1232 PrintValueDecl(FromValueDecl, ToValueDecl, Tree.FromDefault(),
1233 Tree.ToDefault(), Tree.NodeIsSame());
1236 case DiffTree::Template: {
1237 // Node is root of template. Recurse on children.
1238 TemplateDecl *FromTD, *ToTD;
1239 Tree.GetNode(FromTD, ToTD);
1241 if (!Tree.HasChildren()) {
1242 // If we're dealing with a template specialization with zero
1243 // arguments, there are no children; special-case this.
1244 OS << FromTD->getNameAsString() << "<>";
1248 Qualifiers FromQual, ToQual;
1249 Tree.GetNode(FromQual, ToQual);
1250 PrintQualifiers(FromQual, ToQual);
1252 OS << FromTD->getNameAsString() << '<';
1254 unsigned NumElideArgs = 0;
1257 if (Tree.NodeIsSame()) {
1261 if (NumElideArgs > 0) {
1262 PrintElideArgs(NumElideArgs, Indent);
1267 TreeToString(Indent);
1268 if (Tree.HasNextSibling())
1270 } while (Tree.AdvanceSibling());
1271 if (NumElideArgs > 0)
1272 PrintElideArgs(NumElideArgs, Indent);
1281 // To signal to the text printer that a certain text needs to be bolded,
1282 // a special character is injected into the character stream which the
1283 // text printer will later strip out.
1285 /// Bold - Start bolding text.
1287 assert(!IsBold && "Attempting to bold text that is already bold.");
1290 OS << ToggleHighlight;
1293 /// Unbold - Stop bolding text.
1295 assert(IsBold && "Attempting to remove bold from unbold text.");
1298 OS << ToggleHighlight;
1301 // Functions to print out the arguments and highlighting the difference.
1303 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1304 /// typenames that are the same and attempt to disambiguate them by using
1305 /// canonical typenames.
1306 void PrintTypeNames(QualType FromType, QualType ToType,
1307 bool FromDefault, bool ToDefault, bool Same) {
1308 assert((!FromType.isNull() || !ToType.isNull()) &&
1309 "Only one template argument may be missing.");
1312 OS << FromType.getAsString();
1316 if (!FromType.isNull() && !ToType.isNull() &&
1317 FromType.getLocalUnqualifiedType() ==
1318 ToType.getLocalUnqualifiedType()) {
1319 Qualifiers FromQual = FromType.getLocalQualifiers(),
1320 ToQual = ToType.getLocalQualifiers(),
1322 PrintQualifiers(FromQual, ToQual);
1323 FromType.getLocalUnqualifiedType().print(OS, Policy);
1327 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1328 : FromType.getAsString();
1329 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1330 : ToType.getAsString();
1331 // Switch to canonical typename if it is better.
1332 // TODO: merge this with other aka printing above.
1333 if (FromTypeStr == ToTypeStr) {
1334 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1335 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1336 if (FromCanTypeStr != ToCanTypeStr) {
1337 FromTypeStr = FromCanTypeStr;
1338 ToTypeStr = ToCanTypeStr;
1342 if (PrintTree) OS << '[';
1343 OS << (FromDefault ? "(default) " : "");
1348 OS << " != " << (ToDefault ? "(default) " : "");
1357 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1359 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1360 bool FromDefault, bool ToDefault, bool Same) {
1361 assert((FromExpr || ToExpr) &&
1362 "Only one template argument may be missing.");
1364 PrintExpr(FromExpr);
1365 } else if (!PrintTree) {
1366 OS << (FromDefault ? "(default) " : "");
1368 PrintExpr(FromExpr);
1371 OS << (FromDefault ? "[(default) " : "[");
1373 PrintExpr(FromExpr);
1375 OS << " != " << (ToDefault ? "(default) " : "");
1383 /// PrintExpr - Actual formatting and printing of expressions.
1384 void PrintExpr(const Expr *E) {
1386 OS << "(no argument)";
1388 E->printPretty(OS, 0, Policy); return;
1391 /// PrintTemplateTemplate - Handles printing of template template arguments,
1392 /// highlighting argument differences.
1393 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1394 bool FromDefault, bool ToDefault, bool Same) {
1395 assert((FromTD || ToTD) && "Only one template argument may be missing.");
1397 std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
1398 std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
1399 if (FromTD && ToTD && FromName == ToName) {
1400 FromName = FromTD->getQualifiedNameAsString();
1401 ToName = ToTD->getQualifiedNameAsString();
1405 OS << "template " << FromTD->getNameAsString();
1406 } else if (!PrintTree) {
1407 OS << (FromDefault ? "(default) template " : "template ");
1412 OS << (FromDefault ? "[(default) template " : "[template ");
1416 OS << " != " << (ToDefault ? "(default) template " : "template ");
1424 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1425 /// argument differences.
1426 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1427 bool IsValidFromInt, bool IsValidToInt, Expr *FromExpr,
1428 Expr *ToExpr, bool FromDefault, bool ToDefault, bool Same) {
1429 assert((IsValidFromInt || IsValidToInt) &&
1430 "Only one integral argument may be missing.");
1433 OS << FromInt.toString(10);
1434 } else if (!PrintTree) {
1435 OS << (FromDefault ? "(default) " : "");
1436 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
1438 OS << (FromDefault ? "[(default) " : "[");
1439 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
1440 OS << " != " << (ToDefault ? "(default) " : "");
1441 PrintAPSInt(ToInt, ToExpr, IsValidToInt);
1446 /// PrintAPSInt - If valid, print the APSInt. If the expression is
1447 /// gives more information, print it too.
1448 void PrintAPSInt(llvm::APSInt Val, Expr *E, bool Valid) {
1451 if (HasExtraInfo(E)) {
1457 OS << Val.toString(10);
1459 OS << "(no argument)";
1464 /// HasExtraInfo - Returns true if E is not an integer literal or the
1465 /// negation of an integer literal
1466 bool HasExtraInfo(Expr *E) {
1467 if (!E) return false;
1468 if (isa<IntegerLiteral>(E)) return false;
1470 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
1471 if (UO->getOpcode() == UO_Minus)
1472 if (isa<IntegerLiteral>(UO->getSubExpr()))
1478 /// PrintDecl - Handles printing of Decl arguments, highlighting
1479 /// argument differences.
1480 void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
1481 bool FromDefault, bool ToDefault, bool Same) {
1482 assert((FromValueDecl || ToValueDecl) &&
1483 "Only one Decl argument may be NULL");
1486 OS << FromValueDecl->getName();
1487 } else if (!PrintTree) {
1488 OS << (FromDefault ? "(default) " : "");
1490 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1493 OS << (FromDefault ? "[(default) " : "[");
1495 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1497 OS << " != " << (ToDefault ? "(default) " : "");
1499 OS << (ToValueDecl ? ToValueDecl->getName() : "(no argument)");
1506 // Prints the appropriate placeholder for elided template arguments.
1507 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1510 for (unsigned i = 0; i < Indent; ++i)
1513 if (NumElideArgs == 0) return;
1514 if (NumElideArgs == 1)
1517 OS << "[" << NumElideArgs << " * ...]";
1520 // Prints and highlights differences in Qualifiers.
1521 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1522 // Both types have no qualifiers
1523 if (FromQual.empty() && ToQual.empty())
1526 // Both types have same qualifiers
1527 if (FromQual == ToQual) {
1528 PrintQualifier(FromQual, /*ApplyBold*/false);
1532 // Find common qualifiers and strip them from FromQual and ToQual.
1533 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1536 // The qualifiers are printed before the template name.
1538 // The common qualifiers are printed. Then, qualifiers only in this type
1539 // are printed and highlighted. Finally, qualifiers only in the other
1540 // type are printed and highlighted inside parentheses after "missing".
1542 // Qualifiers are printed next to each other, inside brackets, and
1543 // separated by "!=". The printing order is:
1544 // common qualifiers, highlighted from qualifiers, "!=",
1545 // common qualifiers, highlighted to qualifiers
1548 if (CommonQual.empty() && FromQual.empty()) {
1550 OS << "(no qualifiers) ";
1553 PrintQualifier(CommonQual, /*ApplyBold*/false);
1554 PrintQualifier(FromQual, /*ApplyBold*/true);
1557 if (CommonQual.empty() && ToQual.empty()) {
1559 OS << "(no qualifiers)";
1562 PrintQualifier(CommonQual, /*ApplyBold*/false,
1563 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1564 PrintQualifier(ToQual, /*ApplyBold*/true,
1565 /*appendSpaceIfNonEmpty*/false);
1569 PrintQualifier(CommonQual, /*ApplyBold*/false);
1570 PrintQualifier(FromQual, /*ApplyBold*/true);
1574 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1575 bool AppendSpaceIfNonEmpty = true) {
1576 if (Q.empty()) return;
1577 if (ApplyBold) Bold();
1578 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1579 if (ApplyBold) Unbold();
1584 TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
1585 QualType ToType, bool PrintTree, bool PrintFromType,
1586 bool ElideType, bool ShowColor)
1588 Policy(Context.getLangOpts()),
1589 ElideType(ElideType),
1590 PrintTree(PrintTree),
1591 ShowColor(ShowColor),
1592 // When printing a single type, the FromType is the one printed.
1593 FromType(PrintFromType ? FromType : ToType),
1594 ToType(PrintFromType ? ToType : FromType),
1599 /// DiffTemplate - Start the template type diffing.
1600 void DiffTemplate() {
1601 Qualifiers FromQual = FromType.getQualifiers(),
1602 ToQual = ToType.getQualifiers();
1604 const TemplateSpecializationType *FromOrigTST =
1605 GetTemplateSpecializationType(Context, FromType);
1606 const TemplateSpecializationType *ToOrigTST =
1607 GetTemplateSpecializationType(Context, ToType);
1609 // Only checking templates.
1610 if (!FromOrigTST || !ToOrigTST)
1613 // Different base templates.
1614 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1618 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1619 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
1620 Tree.SetNode(FromType, ToType);
1621 Tree.SetNode(FromQual, ToQual);
1622 Tree.SetKind(DiffTree::Template);
1624 // Same base template, but different arguments.
1625 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1626 ToOrigTST->getTemplateName().getAsTemplateDecl());
1628 DiffTemplate(FromOrigTST, ToOrigTST);
1631 /// Emit - When the two types given are templated types with the same
1632 /// base template, a string representation of the type difference will be
1633 /// emitted to the stream and return true. Otherwise, return false.
1635 Tree.StartTraverse();
1640 assert(!IsBold && "Bold is applied to end of string.");
1643 }; // end class TemplateDiff
1646 /// FormatTemplateTypeDiff - A helper static function to start the template
1647 /// diff and return the properly formatted string. Returns true if the diff
1649 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1650 QualType ToType, bool PrintTree,
1651 bool PrintFromType, bool ElideType,
1652 bool ShowColors, raw_ostream &OS) {
1654 PrintFromType = true;
1655 TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
1656 ElideType, ShowColors);