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/ASTLambda.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TemplateBase.h"
21 #include "clang/AST/Type.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 // Returns a desugared version of the QualType, and marks ShouldAKA as true
28 // whenever we remove significant sugar from the type.
29 static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
30 QualifierCollector QC;
33 const Type *Ty = QC.strip(QT);
35 // Don't aka just because we saw an elaborated type...
36 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
40 // ... or a paren type ...
41 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
45 // ...or a substituted template type parameter ...
46 if (const SubstTemplateTypeParmType *ST =
47 dyn_cast<SubstTemplateTypeParmType>(Ty)) {
51 // ...or an attributed type...
52 if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
56 // ...or an adjusted type...
57 if (const AdjustedType *AT = dyn_cast<AdjustedType>(Ty)) {
61 // ... or an auto type.
62 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
69 // Don't desugar template specializations, unless it's an alias template.
70 if (const TemplateSpecializationType *TST
71 = dyn_cast<TemplateSpecializationType>(Ty))
72 if (!TST->isTypeAlias())
75 // Don't desugar magic Objective-C types.
76 if (QualType(Ty,0) == Context.getObjCIdType() ||
77 QualType(Ty,0) == Context.getObjCClassType() ||
78 QualType(Ty,0) == Context.getObjCSelType() ||
79 QualType(Ty,0) == Context.getObjCProtoType())
82 // Don't desugar va_list.
83 if (QualType(Ty,0) == Context.getBuiltinVaListType())
86 // Otherwise, do a single-step desugar.
89 switch (Ty->getTypeClass()) {
90 #define ABSTRACT_TYPE(Class, Base)
91 #define TYPE(Class, Base) \
93 const Class##Type *CTy = cast<Class##Type>(Ty); \
94 if (CTy->isSugared()) { \
96 Underlying = CTy->desugar(); \
100 #include "clang/AST/TypeNodes.def"
103 // If it wasn't sugared, we're done.
107 // If the desugared type is a vector type, we don't want to expand
108 // it, it will turn into an attribute mess. People want their "vec4".
109 if (isa<VectorType>(Underlying))
112 // Don't desugar through the primary typedef of an anonymous type.
113 if (const TagType *UTT = Underlying->getAs<TagType>())
114 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
115 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
118 // Record that we actually looked through an opaque type here.
123 // If we have a pointer-like type, desugar the pointee as well.
124 // FIXME: Handle other pointer-like types.
125 if (const PointerType *Ty = QT->getAs<PointerType>()) {
126 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
128 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
129 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
131 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
132 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
136 return QC.apply(Context, QT);
139 /// \brief Convert the given type to a string suitable for printing as part of
142 /// There are four main criteria when determining whether we should have an
143 /// a.k.a. clause when pretty-printing a type:
145 /// 1) Some types provide very minimal sugar that doesn't impede the
146 /// user's understanding --- for example, elaborated type
147 /// specifiers. If this is all the sugar we see, we don't want an
149 /// 2) Some types are technically sugared but are much more familiar
150 /// when seen in their sugared form --- for example, va_list,
151 /// vector types, and the magic Objective C types. We don't
152 /// want to desugar these, even if we do produce an a.k.a. clause.
153 /// 3) Some types may have already been desugared previously in this diagnostic.
154 /// if this is the case, doing another "aka" would just be clutter.
155 /// 4) Two different types within the same diagnostic have the same output
156 /// string. In this case, force an a.k.a with the desugared type when
157 /// doing so will provide additional information.
159 /// \param Context the context in which the type was allocated
160 /// \param Ty the type to print
161 /// \param QualTypeVals pointer values to QualTypes which are used in the
162 /// diagnostic message
164 ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
165 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
166 ArrayRef<intptr_t> QualTypeVals) {
167 // FIXME: Playing with std::string is really slow.
168 bool ForceAKA = false;
169 QualType CanTy = Ty.getCanonicalType();
170 std::string S = Ty.getAsString(Context.getPrintingPolicy());
171 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
173 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
175 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
176 if (CompareTy.isNull())
179 continue; // Same types
180 QualType CompareCanTy = CompareTy.getCanonicalType();
181 if (CompareCanTy == CanTy)
182 continue; // Same canonical types
183 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
185 QualType CompareDesugar = Desugar(Context, CompareTy, aka);
186 std::string CompareDesugarStr =
187 CompareDesugar.getAsString(Context.getPrintingPolicy());
188 if (CompareS != S && CompareDesugarStr != S)
189 continue; // The type string is different than the comparison string
190 // and the desugared comparison string.
191 std::string CompareCanS =
192 CompareCanTy.getAsString(Context.getPrintingPolicy());
194 if (CompareCanS == CanS)
195 continue; // No new info from canonical type
201 // Check to see if we already desugared this type in this
202 // diagnostic. If so, don't do it again.
203 bool Repeated = false;
204 for (unsigned i = 0, e = PrevArgs.size(); i != e; ++i) {
205 // TODO: Handle ak_declcontext case.
206 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
207 void *Ptr = (void*)PrevArgs[i].second;
208 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
216 // Consider producing an a.k.a. clause if removing all the direct
217 // sugar gives us something "significantly different".
219 bool ShouldAKA = false;
220 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
221 if (ShouldAKA || ForceAKA) {
222 if (DesugaredTy == Ty) {
223 DesugaredTy = Ty.getCanonicalType();
225 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
227 S = "'" + S + "' (aka '" + akaStr + "')";
232 // Give some additional info on vector types. These are either not desugared
233 // or displaying complex __attribute__ expressions so add details of the
234 // type and element count.
235 if (Ty->isVectorType()) {
236 const VectorType *VTy = Ty->getAs<VectorType>();
237 std::string DecoratedString;
238 llvm::raw_string_ostream OS(DecoratedString);
239 const char *Values = VTy->getNumElements() > 1 ? "values" : "value";
240 OS << "'" << S << "' (vector of " << VTy->getNumElements() << " '"
241 << VTy->getElementType().getAsString(Context.getPrintingPolicy())
242 << "' " << Values << ")";
251 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
252 QualType ToType, bool PrintTree,
253 bool PrintFromType, bool ElideType,
254 bool ShowColors, raw_ostream &OS);
256 void clang::FormatASTNodeDiagnosticArgument(
257 DiagnosticsEngine::ArgumentKind Kind,
261 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
262 SmallVectorImpl<char> &Output,
264 ArrayRef<intptr_t> QualTypeVals) {
265 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
267 size_t OldEnd = Output.size();
268 llvm::raw_svector_ostream OS(Output);
269 bool NeedQuotes = true;
272 default: llvm_unreachable("unknown ArgumentKind");
273 case DiagnosticsEngine::ak_qualtype_pair: {
274 TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
276 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
278 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
280 if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
281 TDT.PrintFromType, TDT.ElideType,
282 TDT.ShowColors, OS)) {
283 NeedQuotes = !TDT.PrintTree;
284 TDT.TemplateDiffUsed = true;
288 // Don't fall-back during tree printing. The caller will handle
293 // Attempting to do a template diff on non-templates. Set the variables
294 // and continue with regular type printing of the appropriate type.
295 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
296 Modifier = StringRef();
297 Argument = StringRef();
300 case DiagnosticsEngine::ak_qualtype: {
301 assert(Modifier.empty() && Argument.empty() &&
302 "Invalid modifier for QualType argument");
304 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
305 OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals);
309 case DiagnosticsEngine::ak_declarationname: {
310 if (Modifier == "objcclass" && Argument.empty())
312 else if (Modifier == "objcinstance" && Argument.empty())
315 assert(Modifier.empty() && Argument.empty() &&
316 "Invalid modifier for DeclarationName argument");
318 OS << DeclarationName::getFromOpaqueInteger(Val);
321 case DiagnosticsEngine::ak_nameddecl: {
323 if (Modifier == "q" && Argument.empty())
326 assert(Modifier.empty() && Argument.empty() &&
327 "Invalid modifier for NamedDecl* argument");
330 const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
331 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified);
334 case DiagnosticsEngine::ak_nestednamespec: {
335 NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
336 NNS->print(OS, Context.getPrintingPolicy());
340 case DiagnosticsEngine::ak_declcontext: {
341 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
342 assert(DC && "Should never have a null declaration context");
345 // FIXME: Get the strings for DeclContext from some localized place
346 if (DC->isTranslationUnit()) {
347 if (Context.getLangOpts().CPlusPlus)
348 OS << "the global namespace";
350 OS << "the global scope";
351 } else if (DC->isClosure()) {
352 OS << "block literal";
353 } else if (isLambdaCallOperator(DC)) {
354 OS << "lambda expression";
355 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
356 OS << ConvertTypeToDiagnosticString(Context,
357 Context.getTypeDeclType(Type),
358 PrevArgs, QualTypeVals);
360 assert(isa<NamedDecl>(DC) && "Expected a NamedDecl");
361 NamedDecl *ND = cast<NamedDecl>(DC);
362 if (isa<NamespaceDecl>(ND))
364 else if (isa<ObjCMethodDecl>(ND))
366 else if (isa<FunctionDecl>(ND))
370 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
375 case DiagnosticsEngine::ak_attr: {
376 const Attr *At = reinterpret_cast<Attr *>(Val);
377 assert(At && "Received null Attr object!");
378 OS << '\'' << At->getSpelling() << '\'';
388 Output.insert(Output.begin()+OldEnd, '\'');
389 Output.push_back('\'');
393 /// TemplateDiff - A class that constructs a pretty string for a pair of
394 /// QualTypes. For the pair of types, a diff tree will be created containing
395 /// all the information about the templates and template arguments. Afterwards,
396 /// the tree is transformed to a string according to the options passed in.
399 /// Context - The ASTContext which is used for comparing template arguments.
402 /// Policy - Used during expression printing.
403 PrintingPolicy Policy;
405 /// ElideType - Option to elide identical types.
408 /// PrintTree - Format output string as a tree.
411 /// ShowColor - Diagnostics support color, so bolding will be used.
414 /// FromType - When single type printing is selected, this is the type to be
415 /// be printed. When tree printing is selected, this type will show up first
419 /// ToType - The type that FromType is compared to. Only in tree printing
420 /// will this type be outputed.
423 /// OS - The stream used to construct the output strings.
426 /// IsBold - Keeps track of the bold formatting for the output string.
429 /// DiffTree - A tree representation the differences between two types.
432 /// DiffKind - The difference in a DiffNode and which fields are used.
434 /// Incomplete or invalid node.
436 /// Another level of templates, uses TemplateDecl and Qualifiers
438 /// Type difference, uses QualType
440 /// Expression difference, uses Expr
442 /// Template argument difference, uses TemplateDecl
444 /// Integer difference, uses APSInt and Expr
446 /// Declaration difference, uses ValueDecl
450 /// DiffNode - The root node stores the original type. Each child node
451 /// stores template arguments of their parents. For templated types, the
452 /// template decl is also stored.
456 /// NextNode - The index of the next sibling node or 0.
459 /// ChildNode - The index of the first child node or 0.
462 /// ParentNode - The index of the parent node.
465 /// FromType, ToType - The type arguments.
466 QualType FromType, ToType;
468 /// FromExpr, ToExpr - The expression arguments.
469 Expr *FromExpr, *ToExpr;
471 /// FromNullPtr, ToNullPtr - If the template argument is a nullptr
472 bool FromNullPtr, ToNullPtr;
474 /// FromTD, ToTD - The template decl for template template
475 /// arguments or the type arguments that are templates.
476 TemplateDecl *FromTD, *ToTD;
478 /// FromQual, ToQual - Qualifiers for template types.
479 Qualifiers FromQual, ToQual;
481 /// FromInt, ToInt - APSInt's for integral arguments.
482 llvm::APSInt FromInt, ToInt;
484 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
485 bool IsValidFromInt, IsValidToInt;
487 /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
488 ValueDecl *FromValueDecl, *ToValueDecl;
490 /// FromAddressOf, ToAddressOf - Whether the ValueDecl needs an address of
491 /// operator before it.
492 bool FromAddressOf, ToAddressOf;
494 /// FromDefault, ToDefault - Whether the argument is a default argument.
495 bool FromDefault, ToDefault;
497 /// Same - Whether the two arguments evaluate to the same value.
500 DiffNode(unsigned ParentNode = 0)
501 : Kind(Invalid), NextNode(0), ChildNode(0), ParentNode(ParentNode),
502 FromType(), ToType(), FromExpr(nullptr), ToExpr(nullptr),
503 FromNullPtr(false), ToNullPtr(false),
504 FromTD(nullptr), ToTD(nullptr), IsValidFromInt(false),
505 IsValidToInt(false), FromValueDecl(nullptr), ToValueDecl(nullptr),
506 FromAddressOf(false), ToAddressOf(false), FromDefault(false),
507 ToDefault(false), Same(false) {}
510 /// FlatTree - A flattened tree used to store the DiffNodes.
511 SmallVector<DiffNode, 16> FlatTree;
513 /// CurrentNode - The index of the current node being used.
514 unsigned CurrentNode;
516 /// NextFreeNode - The index of the next unused node. Used when creating
518 unsigned NextFreeNode;
520 /// ReadNode - The index of the current node being read.
525 CurrentNode(0), NextFreeNode(1) {
526 FlatTree.push_back(DiffNode());
529 // Node writing functions.
530 /// SetNode - Sets FromTD and ToTD of the current node.
531 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
532 FlatTree[CurrentNode].FromTD = FromTD;
533 FlatTree[CurrentNode].ToTD = ToTD;
536 /// SetNode - Sets FromType and ToType of the current node.
537 void SetNode(QualType FromType, QualType ToType) {
538 FlatTree[CurrentNode].FromType = FromType;
539 FlatTree[CurrentNode].ToType = ToType;
542 /// SetNode - Set FromExpr and ToExpr of the current node.
543 void SetNode(Expr *FromExpr, Expr *ToExpr) {
544 FlatTree[CurrentNode].FromExpr = FromExpr;
545 FlatTree[CurrentNode].ToExpr = ToExpr;
548 /// SetNode - Set FromInt and ToInt of the current node.
549 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
550 bool IsValidFromInt, bool IsValidToInt) {
551 FlatTree[CurrentNode].FromInt = FromInt;
552 FlatTree[CurrentNode].ToInt = ToInt;
553 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
554 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
557 /// SetNode - Set FromQual and ToQual of the current node.
558 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
559 FlatTree[CurrentNode].FromQual = FromQual;
560 FlatTree[CurrentNode].ToQual = ToQual;
563 /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
564 void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
565 bool FromAddressOf, bool ToAddressOf) {
566 FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
567 FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
568 FlatTree[CurrentNode].FromAddressOf = FromAddressOf;
569 FlatTree[CurrentNode].ToAddressOf = ToAddressOf;
572 /// SetSame - Sets the same flag of the current node.
573 void SetSame(bool Same) {
574 FlatTree[CurrentNode].Same = Same;
577 /// SetNullPtr - Sets the NullPtr flags of the current node.
578 void SetNullPtr(bool FromNullPtr, bool ToNullPtr) {
579 FlatTree[CurrentNode].FromNullPtr = FromNullPtr;
580 FlatTree[CurrentNode].ToNullPtr = ToNullPtr;
583 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
584 void SetDefault(bool FromDefault, bool ToDefault) {
585 FlatTree[CurrentNode].FromDefault = FromDefault;
586 FlatTree[CurrentNode].ToDefault = ToDefault;
589 /// SetKind - Sets the current node's type.
590 void SetKind(DiffKind Kind) {
591 FlatTree[CurrentNode].Kind = Kind;
594 /// Up - Changes the node to the parent of the current node.
596 CurrentNode = FlatTree[CurrentNode].ParentNode;
599 /// AddNode - Adds a child node to the current node, then sets that node
600 /// node as the current node.
602 FlatTree.push_back(DiffNode(CurrentNode));
603 DiffNode &Node = FlatTree[CurrentNode];
604 if (Node.ChildNode == 0) {
605 // If a child node doesn't exist, add one.
606 Node.ChildNode = NextFreeNode;
608 // If a child node exists, find the last child node and add a
611 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
612 i = FlatTree[i].NextNode) {
614 FlatTree[i].NextNode = NextFreeNode;
616 CurrentNode = NextFreeNode;
620 // Node reading functions.
621 /// StartTraverse - Prepares the tree for recursive traversal.
622 void StartTraverse() {
624 CurrentNode = NextFreeNode;
628 /// Parent - Move the current read node to its parent.
630 ReadNode = FlatTree[ReadNode].ParentNode;
633 /// GetNode - Gets the FromType and ToType.
634 void GetNode(QualType &FromType, QualType &ToType) {
635 FromType = FlatTree[ReadNode].FromType;
636 ToType = FlatTree[ReadNode].ToType;
639 /// GetNode - Gets the FromExpr and ToExpr.
640 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
641 FromExpr = FlatTree[ReadNode].FromExpr;
642 ToExpr = FlatTree[ReadNode].ToExpr;
645 /// GetNode - Gets the FromTD and ToTD.
646 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
647 FromTD = FlatTree[ReadNode].FromTD;
648 ToTD = FlatTree[ReadNode].ToTD;
651 /// GetNode - Gets the FromInt and ToInt.
652 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
653 bool &IsValidFromInt, bool &IsValidToInt) {
654 FromInt = FlatTree[ReadNode].FromInt;
655 ToInt = FlatTree[ReadNode].ToInt;
656 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
657 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
660 /// GetNode - Gets the FromQual and ToQual.
661 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
662 FromQual = FlatTree[ReadNode].FromQual;
663 ToQual = FlatTree[ReadNode].ToQual;
666 /// GetNode - Gets the FromValueDecl and ToValueDecl.
667 void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl,
668 bool &FromAddressOf, bool &ToAddressOf) {
669 FromValueDecl = FlatTree[ReadNode].FromValueDecl;
670 ToValueDecl = FlatTree[ReadNode].ToValueDecl;
671 FromAddressOf = FlatTree[ReadNode].FromAddressOf;
672 ToAddressOf = FlatTree[ReadNode].ToAddressOf;
675 /// NodeIsSame - Returns true the arguments are the same.
677 return FlatTree[ReadNode].Same;
680 /// HasChildrend - Returns true if the node has children.
682 return FlatTree[ReadNode].ChildNode != 0;
685 /// MoveToChild - Moves from the current node to its child.
687 ReadNode = FlatTree[ReadNode].ChildNode;
690 /// AdvanceSibling - If there is a next sibling, advance to it and return
691 /// true. Otherwise, return false.
692 bool AdvanceSibling() {
693 if (FlatTree[ReadNode].NextNode == 0)
696 ReadNode = FlatTree[ReadNode].NextNode;
700 /// HasNextSibling - Return true if the node has a next sibling.
701 bool HasNextSibling() {
702 return FlatTree[ReadNode].NextNode != 0;
705 /// FromNullPtr - Returns true if the from argument is null.
707 return FlatTree[ReadNode].FromNullPtr;
710 /// ToNullPtr - Returns true if the to argument is null.
712 return FlatTree[ReadNode].ToNullPtr;
715 /// FromDefault - Return true if the from argument is the default.
717 return FlatTree[ReadNode].FromDefault;
720 /// ToDefault - Return true if the to argument is the default.
722 return FlatTree[ReadNode].ToDefault;
725 /// Empty - Returns true if the tree has no information.
727 return GetKind() == Invalid;
730 /// GetKind - Returns the current node's type.
732 return FlatTree[ReadNode].Kind;
738 /// TSTiterator - an iterator that is used to enter a
739 /// TemplateSpecializationType and read TemplateArguments inside template
740 /// parameter packs in order with the rest of the TemplateArguments.
742 typedef const TemplateArgument& reference;
743 typedef const TemplateArgument* pointer;
745 /// TST - the template specialization whose arguments this iterator
747 const TemplateSpecializationType *TST;
749 /// DesugarTST - desugared template specialization used to extract
750 /// default argument information
751 const TemplateSpecializationType *DesugarTST;
753 /// Index - the index of the template argument in TST.
756 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
757 /// points to a TemplateArgument within a parameter pack.
758 TemplateArgument::pack_iterator CurrentTA;
760 /// EndTA - the end iterator of a parameter pack
761 TemplateArgument::pack_iterator EndTA;
763 /// TSTiterator - Constructs an iterator and sets it to the first template
765 TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST)
767 DesugarTST(GetTemplateSpecializationType(Context, TST->desugar())),
768 Index(0), CurrentTA(nullptr), EndTA(nullptr) {
771 // Set to first template argument. If not a parameter pack, done.
772 TemplateArgument TA = TST->getArg(0);
773 if (TA.getKind() != TemplateArgument::Pack) return;
775 // Start looking into the parameter pack.
776 CurrentTA = TA.pack_begin();
777 EndTA = TA.pack_end();
779 // Found a valid template argument.
780 if (CurrentTA != EndTA) return;
782 // Parameter pack is empty, use the increment to get to a valid
783 // template argument.
787 /// isEnd - Returns true if the iterator is one past the end.
789 return Index >= TST->getNumArgs();
792 /// &operator++ - Increment the iterator to the next template argument.
793 TSTiterator &operator++() {
794 // After the end, Index should be the default argument position in
795 // DesugarTST, if it exists.
801 // If in a parameter pack, advance in the parameter pack.
802 if (CurrentTA != EndTA) {
804 if (CurrentTA != EndTA)
808 // Loop until a template argument is found, or the end is reached.
810 // Advance to the next template argument. Break if reached the end.
811 if (++Index == TST->getNumArgs()) break;
813 // If the TemplateArgument is not a parameter pack, done.
814 TemplateArgument TA = TST->getArg(Index);
815 if (TA.getKind() != TemplateArgument::Pack) break;
817 // Handle parameter packs.
818 CurrentTA = TA.pack_begin();
819 EndTA = TA.pack_end();
821 // If the parameter pack is empty, try to advance again.
822 if (CurrentTA != EndTA) break;
827 /// operator* - Returns the appropriate TemplateArgument.
828 reference operator*() const {
829 assert(!isEnd() && "Index exceeds number of arguments.");
830 if (CurrentTA == EndTA)
831 return TST->getArg(Index);
836 /// operator-> - Allow access to the underlying TemplateArgument.
837 pointer operator->() const {
841 /// getDesugar - Returns the deduced template argument from DesguarTST
842 reference getDesugar() const {
843 return DesugarTST->getArg(Index);
847 // These functions build up the template diff tree, including functions to
848 // retrieve and compare template arguments.
850 static const TemplateSpecializationType * GetTemplateSpecializationType(
851 ASTContext &Context, QualType Ty) {
852 if (const TemplateSpecializationType *TST =
853 Ty->getAs<TemplateSpecializationType>())
856 const RecordType *RT = Ty->getAs<RecordType>();
861 const ClassTemplateSpecializationDecl *CTSD =
862 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
867 Ty = Context.getTemplateSpecializationType(
868 TemplateName(CTSD->getSpecializedTemplate()),
869 CTSD->getTemplateArgs().data(),
870 CTSD->getTemplateArgs().size(),
871 Ty.getLocalUnqualifiedType().getCanonicalType());
873 return Ty->getAs<TemplateSpecializationType>();
876 /// DiffTypes - Fills a DiffNode with information about a type difference.
877 void DiffTypes(const TSTiterator &FromIter, const TSTiterator &ToIter,
878 TemplateTypeParmDecl *FromDefaultTypeDecl,
879 TemplateTypeParmDecl *ToDefaultTypeDecl) {
880 QualType FromType = GetType(FromIter, FromDefaultTypeDecl);
881 QualType ToType = GetType(ToIter, ToDefaultTypeDecl);
883 Tree.SetNode(FromType, ToType);
884 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
885 ToIter.isEnd() && !ToType.isNull());
886 Tree.SetKind(DiffTree::Type);
887 if (FromType.isNull() || ToType.isNull())
890 if (Context.hasSameType(FromType, ToType)) {
895 const TemplateSpecializationType *FromArgTST =
896 GetTemplateSpecializationType(Context, FromType);
900 const TemplateSpecializationType *ToArgTST =
901 GetTemplateSpecializationType(Context, ToType);
905 if (!hasSameTemplate(FromArgTST, ToArgTST))
908 Qualifiers FromQual = FromType.getQualifiers(),
909 ToQual = ToType.getQualifiers();
910 FromQual -= QualType(FromArgTST, 0).getQualifiers();
911 ToQual -= QualType(ToArgTST, 0).getQualifiers();
912 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
913 ToArgTST->getTemplateName().getAsTemplateDecl());
914 Tree.SetNode(FromQual, ToQual);
915 Tree.SetKind(DiffTree::Template);
916 DiffTemplate(FromArgTST, ToArgTST);
919 /// DiffTemplateTemplates - Fills a DiffNode with information about a
920 /// template template difference.
921 void DiffTemplateTemplates(const TSTiterator &FromIter,
922 const TSTiterator &ToIter,
923 TemplateTemplateParmDecl *FromDefaultTemplateDecl,
924 TemplateTemplateParmDecl *ToDefaultTemplateDecl) {
925 TemplateDecl *FromDecl = GetTemplateDecl(FromIter, FromDefaultTemplateDecl);
926 TemplateDecl *ToDecl = GetTemplateDecl(ToIter, ToDefaultTemplateDecl);
927 Tree.SetNode(FromDecl, ToDecl);
928 Tree.SetSame(FromDecl && ToDecl &&
929 FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
930 Tree.SetDefault(FromIter.isEnd() && FromDecl, ToIter.isEnd() && ToDecl);
931 Tree.SetKind(DiffTree::TemplateTemplate);
934 /// InitializeNonTypeDiffVariables - Helper function for DiffNonTypes
935 static void InitializeNonTypeDiffVariables(
936 ASTContext &Context, const TSTiterator &Iter,
937 NonTypeTemplateParmDecl *Default, bool &HasInt, bool &HasValueDecl,
938 bool &IsNullPtr, Expr *&E, llvm::APSInt &Value, ValueDecl *&VD) {
939 HasInt = !Iter.isEnd() && Iter->getKind() == TemplateArgument::Integral;
942 !Iter.isEnd() && Iter->getKind() == TemplateArgument::Declaration;
944 IsNullPtr = !Iter.isEnd() && Iter->getKind() == TemplateArgument::NullPtr;
947 Value = Iter->getAsIntegral();
948 else if (HasValueDecl)
949 VD = Iter->getAsDecl();
951 E = GetExpr(Iter, Default);
953 if (E && Default->getType()->isPointerType())
954 IsNullPtr = CheckForNullPtr(Context, E);
957 /// NeedsAddressOf - Helper function for DiffNonTypes. Returns true if the
958 /// ValueDecl needs a '&' when printed.
959 static bool NeedsAddressOf(ValueDecl *VD, Expr *E,
960 NonTypeTemplateParmDecl *Default) {
965 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
966 if (UO->getOpcode() == UO_AddrOf) {
973 if (!Default->getType()->isReferenceType()) {
980 /// DiffNonTypes - Handles any template parameters not handled by DiffTypes
981 /// of DiffTemplatesTemplates, such as integer and declaration parameters.
982 void DiffNonTypes(const TSTiterator &FromIter, const TSTiterator &ToIter,
983 NonTypeTemplateParmDecl *FromDefaultNonTypeDecl,
984 NonTypeTemplateParmDecl *ToDefaultNonTypeDecl) {
985 Expr *FromExpr = nullptr, *ToExpr = nullptr;
986 llvm::APSInt FromInt, ToInt;
987 ValueDecl *FromValueDecl = nullptr, *ToValueDecl = nullptr;
988 bool HasFromInt = false, HasToInt = false, HasFromValueDecl = false,
989 HasToValueDecl = false, FromNullPtr = false, ToNullPtr = false;
990 InitializeNonTypeDiffVariables(Context, FromIter, FromDefaultNonTypeDecl,
991 HasFromInt, HasFromValueDecl, FromNullPtr,
992 FromExpr, FromInt, FromValueDecl);
993 InitializeNonTypeDiffVariables(Context, ToIter, ToDefaultNonTypeDecl,
994 HasToInt, HasToValueDecl, ToNullPtr,
995 ToExpr, ToInt, ToValueDecl);
997 assert(((!HasFromInt && !HasToInt) ||
998 (!HasFromValueDecl && !HasToValueDecl)) &&
999 "Template argument cannot be both integer and declaration");
1001 unsigned ParamWidth = 128; // Safe default
1002 if (FromDefaultNonTypeDecl->getType()->isIntegralOrEnumerationType())
1003 ParamWidth = Context.getIntWidth(FromDefaultNonTypeDecl->getType());
1005 if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
1006 Tree.SetNode(FromExpr, ToExpr);
1007 Tree.SetDefault(FromIter.isEnd() && FromExpr, ToIter.isEnd() && ToExpr);
1008 if (FromDefaultNonTypeDecl->getType()->isIntegralOrEnumerationType()) {
1010 HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt);
1012 HasToInt = GetInt(Context, ToIter, ToExpr, ToInt);
1014 if (HasFromInt && HasToInt) {
1015 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
1016 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
1017 Tree.SetKind(DiffTree::Integer);
1018 } else if (HasFromInt || HasToInt) {
1019 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
1020 Tree.SetSame(false);
1021 Tree.SetKind(DiffTree::Integer);
1023 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr) ||
1024 (FromNullPtr && ToNullPtr));
1025 Tree.SetNullPtr(FromNullPtr, ToNullPtr);
1026 Tree.SetKind(DiffTree::Expression);
1031 if (HasFromInt || HasToInt) {
1032 if (!HasFromInt && FromExpr)
1033 HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt);
1034 if (!HasToInt && ToExpr)
1035 HasToInt = GetInt(Context, ToIter, ToExpr, ToInt);
1036 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
1037 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
1038 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
1039 ToIter.isEnd() && HasToInt);
1040 Tree.SetKind(DiffTree::Integer);
1044 if (!HasFromValueDecl && FromExpr)
1045 FromValueDecl = GetValueDecl(FromIter, FromExpr);
1046 if (!HasToValueDecl && ToExpr)
1047 ToValueDecl = GetValueDecl(ToIter, ToExpr);
1049 bool FromAddressOf =
1050 NeedsAddressOf(FromValueDecl, FromExpr, FromDefaultNonTypeDecl);
1052 NeedsAddressOf(ToValueDecl, ToExpr, ToDefaultNonTypeDecl);
1054 Tree.SetNullPtr(FromNullPtr, ToNullPtr);
1055 Tree.SetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
1056 Tree.SetSame(FromValueDecl && ToValueDecl &&
1057 FromValueDecl->getCanonicalDecl() ==
1058 ToValueDecl->getCanonicalDecl());
1059 Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
1060 ToIter.isEnd() && ToValueDecl);
1061 Tree.SetKind(DiffTree::Declaration);
1064 /// DiffTemplate - recursively visits template arguments and stores the
1065 /// argument info into a tree.
1066 void DiffTemplate(const TemplateSpecializationType *FromTST,
1067 const TemplateSpecializationType *ToTST) {
1068 // Begin descent into diffing template tree.
1069 TemplateParameterList *ParamsFrom =
1070 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
1071 TemplateParameterList *ParamsTo =
1072 ToTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
1073 unsigned TotalArgs = 0;
1074 for (TSTiterator FromIter(Context, FromTST), ToIter(Context, ToTST);
1075 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
1078 // Get the parameter at index TotalArgs. If index is larger
1079 // than the total number of parameters, then there is an
1080 // argument pack, so re-use the last parameter.
1081 unsigned FromParamIndex = std::min(TotalArgs, ParamsFrom->size() - 1);
1082 unsigned ToParamIndex = std::min(TotalArgs, ParamsTo->size() - 1);
1083 NamedDecl *FromParamND = ParamsFrom->getParam(FromParamIndex);
1084 NamedDecl *ToParamND = ParamsTo->getParam(ToParamIndex);
1086 TemplateTypeParmDecl *FromDefaultTypeDecl =
1087 dyn_cast<TemplateTypeParmDecl>(FromParamND);
1088 TemplateTypeParmDecl *ToDefaultTypeDecl =
1089 dyn_cast<TemplateTypeParmDecl>(ToParamND);
1090 if (FromDefaultTypeDecl && ToDefaultTypeDecl)
1091 DiffTypes(FromIter, ToIter, FromDefaultTypeDecl, ToDefaultTypeDecl);
1093 TemplateTemplateParmDecl *FromDefaultTemplateDecl =
1094 dyn_cast<TemplateTemplateParmDecl>(FromParamND);
1095 TemplateTemplateParmDecl *ToDefaultTemplateDecl =
1096 dyn_cast<TemplateTemplateParmDecl>(ToParamND);
1097 if (FromDefaultTemplateDecl && ToDefaultTemplateDecl)
1098 DiffTemplateTemplates(FromIter, ToIter, FromDefaultTemplateDecl,
1099 ToDefaultTemplateDecl);
1101 NonTypeTemplateParmDecl *FromDefaultNonTypeDecl =
1102 dyn_cast<NonTypeTemplateParmDecl>(FromParamND);
1103 NonTypeTemplateParmDecl *ToDefaultNonTypeDecl =
1104 dyn_cast<NonTypeTemplateParmDecl>(ToParamND);
1105 if (FromDefaultNonTypeDecl && ToDefaultNonTypeDecl)
1106 DiffNonTypes(FromIter, ToIter, FromDefaultNonTypeDecl,
1107 ToDefaultNonTypeDecl);
1115 /// makeTemplateList - Dump every template alias into the vector.
1116 static void makeTemplateList(
1117 SmallVectorImpl<const TemplateSpecializationType *> &TemplateList,
1118 const TemplateSpecializationType *TST) {
1120 TemplateList.push_back(TST);
1121 if (!TST->isTypeAlias())
1123 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1127 /// hasSameBaseTemplate - Returns true when the base templates are the same,
1128 /// even if the template arguments are not.
1129 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
1130 const TemplateSpecializationType *ToTST) {
1131 return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
1132 ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
1135 /// hasSameTemplate - Returns true if both types are specialized from the
1136 /// same template declaration. If they come from different template aliases,
1137 /// do a parallel ascension search to determine the highest template alias in
1138 /// common and set the arguments to them.
1139 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
1140 const TemplateSpecializationType *&ToTST) {
1141 // Check the top templates if they are the same.
1142 if (hasSameBaseTemplate(FromTST, ToTST))
1145 // Create vectors of template aliases.
1146 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
1149 makeTemplateList(FromTemplateList, FromTST);
1150 makeTemplateList(ToTemplateList, ToTST);
1152 SmallVectorImpl<const TemplateSpecializationType *>::reverse_iterator
1153 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
1154 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
1156 // Check if the lowest template types are the same. If not, return.
1157 if (!hasSameBaseTemplate(*FromIter, *ToIter))
1160 // Begin searching up the template aliases. The bottom most template
1161 // matches so move up until one pair does not match. Use the template
1162 // right before that one.
1163 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
1164 if (!hasSameBaseTemplate(*FromIter, *ToIter))
1168 FromTST = FromIter[-1];
1174 /// GetType - Retrieves the template type arguments, including default
1176 static QualType GetType(const TSTiterator &Iter,
1177 TemplateTypeParmDecl *DefaultTTPD) {
1178 bool isVariadic = DefaultTTPD->isParameterPack();
1181 return Iter->getAsType();
1185 QualType ArgType = DefaultTTPD->getDefaultArgument();
1186 if (ArgType->isDependentType())
1187 return Iter.getDesugar().getAsType();
1192 /// GetExpr - Retrieves the template expression argument, including default
1194 static Expr *GetExpr(const TSTiterator &Iter,
1195 NonTypeTemplateParmDecl *DefaultNTTPD) {
1196 Expr *ArgExpr = nullptr;
1197 bool isVariadic = DefaultNTTPD->isParameterPack();
1200 ArgExpr = Iter->getAsExpr();
1201 else if (!isVariadic)
1202 ArgExpr = DefaultNTTPD->getDefaultArgument();
1205 while (SubstNonTypeTemplateParmExpr *SNTTPE =
1206 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
1207 ArgExpr = SNTTPE->getReplacement();
1212 /// GetInt - Retrieves the template integer argument, including evaluating
1213 /// default arguments.
1214 static bool GetInt(ASTContext &Context, const TSTiterator &Iter,
1215 Expr *ArgExpr, llvm::APInt &Int) {
1216 // Default, value-depenedent expressions require fetching
1217 // from the desugared TemplateArgument, otherwise expression needs to
1219 if (Iter.isEnd() && ArgExpr->isValueDependent()) {
1220 switch (Iter.getDesugar().getKind()) {
1221 case TemplateArgument::Integral:
1222 Int = Iter.getDesugar().getAsIntegral();
1224 case TemplateArgument::Expression:
1225 ArgExpr = Iter.getDesugar().getAsExpr();
1226 Int = ArgExpr->EvaluateKnownConstInt(Context);
1229 llvm_unreachable("Unexpected template argument kind");
1231 } else if (ArgExpr->isEvaluatable(Context)) {
1232 Int = ArgExpr->EvaluateKnownConstInt(Context);
1239 /// GetValueDecl - Retrieves the template Decl argument, including
1240 /// default expression argument.
1241 static ValueDecl *GetValueDecl(const TSTiterator &Iter, Expr *ArgExpr) {
1242 // Default, value-depenedent expressions require fetching
1243 // from the desugared TemplateArgument
1244 if (Iter.isEnd() && ArgExpr->isValueDependent())
1245 switch (Iter.getDesugar().getKind()) {
1246 case TemplateArgument::Declaration:
1247 return Iter.getDesugar().getAsDecl();
1248 case TemplateArgument::Expression:
1249 ArgExpr = Iter.getDesugar().getAsExpr();
1250 return cast<DeclRefExpr>(ArgExpr)->getDecl();
1252 llvm_unreachable("Unexpected template argument kind");
1254 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr);
1256 UnaryOperator *UO = dyn_cast<UnaryOperator>(ArgExpr->IgnoreParens());
1259 DRE = cast<DeclRefExpr>(UO->getSubExpr());
1262 return DRE->getDecl();
1265 /// CheckForNullPtr - returns true if the expression can be evaluated as
1267 static bool CheckForNullPtr(ASTContext &Context, Expr *E) {
1268 assert(E && "Expected expression");
1270 E = E->IgnoreParenCasts();
1271 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1274 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
1278 VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
1279 if (!VD || !VD->hasInit())
1282 return VD->getInit()->IgnoreParenCasts()->isNullPointerConstant(
1283 Context, Expr::NPC_ValueDependentIsNull);
1286 /// GetTemplateDecl - Retrieves the template template arguments, including
1287 /// default arguments.
1288 static TemplateDecl *GetTemplateDecl(const TSTiterator &Iter,
1289 TemplateTemplateParmDecl *DefaultTTPD) {
1290 bool isVariadic = DefaultTTPD->isParameterPack();
1292 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
1293 TemplateDecl *DefaultTD = nullptr;
1294 if (TA.getKind() != TemplateArgument::Null)
1295 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
1298 return Iter->getAsTemplate().getAsTemplateDecl();
1305 /// IsSameConvertedInt - Returns true if both integers are equal when
1306 /// converted to an integer type with the given width.
1307 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1308 const llvm::APSInt &Y) {
1309 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1310 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1311 return ConvertedX == ConvertedY;
1314 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
1315 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1316 Expr *FromExpr, Expr *ToExpr) {
1317 if (FromExpr == ToExpr)
1320 if (!FromExpr || !ToExpr)
1323 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr->IgnoreParens()),
1324 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr->IgnoreParens());
1326 if (FromDRE || ToDRE) {
1327 if (!FromDRE || !ToDRE)
1329 return FromDRE->getDecl() == ToDRE->getDecl();
1332 Expr::EvalResult FromResult, ToResult;
1333 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1334 !ToExpr->EvaluateAsRValue(ToResult, Context)) {
1335 llvm::FoldingSetNodeID FromID, ToID;
1336 FromExpr->Profile(FromID, Context, true);
1337 ToExpr->Profile(ToID, Context, true);
1338 return FromID == ToID;
1341 APValue &FromVal = FromResult.Val;
1342 APValue &ToVal = ToResult.Val;
1344 if (FromVal.getKind() != ToVal.getKind()) return false;
1346 switch (FromVal.getKind()) {
1348 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
1349 case APValue::LValue: {
1350 APValue::LValueBase FromBase = FromVal.getLValueBase();
1351 APValue::LValueBase ToBase = ToVal.getLValueBase();
1352 if (FromBase.isNull() && ToBase.isNull())
1354 if (FromBase.isNull() || ToBase.isNull())
1356 return FromBase.get<const ValueDecl*>() ==
1357 ToBase.get<const ValueDecl*>();
1359 case APValue::MemberPointer:
1360 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1362 llvm_unreachable("Unknown template argument expression.");
1366 // These functions converts the tree representation of the template
1367 // differences into the internal character vector.
1369 /// TreeToString - Converts the Tree object into a character stream which
1370 /// will later be turned into the output string.
1371 void TreeToString(int Indent = 1) {
1374 OS.indent(2 * Indent);
1378 // Handle cases where the difference is not templates with different
1380 switch (Tree.GetKind()) {
1381 case DiffTree::Invalid:
1382 llvm_unreachable("Template diffing failed with bad DiffNode");
1383 case DiffTree::Type: {
1384 QualType FromType, ToType;
1385 Tree.GetNode(FromType, ToType);
1386 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1390 case DiffTree::Expression: {
1391 Expr *FromExpr, *ToExpr;
1392 Tree.GetNode(FromExpr, ToExpr);
1393 PrintExpr(FromExpr, ToExpr, Tree.FromNullPtr(), Tree.ToNullPtr(),
1394 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1397 case DiffTree::TemplateTemplate: {
1398 TemplateDecl *FromTD, *ToTD;
1399 Tree.GetNode(FromTD, ToTD);
1400 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1401 Tree.ToDefault(), Tree.NodeIsSame());
1404 case DiffTree::Integer: {
1405 llvm::APSInt FromInt, ToInt;
1406 Expr *FromExpr, *ToExpr;
1407 bool IsValidFromInt, IsValidToInt;
1408 Tree.GetNode(FromExpr, ToExpr);
1409 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1410 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1411 FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1415 case DiffTree::Declaration: {
1416 ValueDecl *FromValueDecl, *ToValueDecl;
1417 bool FromAddressOf, ToAddressOf;
1418 Tree.GetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
1419 PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf,
1420 Tree.FromNullPtr(), Tree.ToNullPtr(), Tree.FromDefault(),
1421 Tree.ToDefault(), Tree.NodeIsSame());
1424 case DiffTree::Template: {
1425 // Node is root of template. Recurse on children.
1426 TemplateDecl *FromTD, *ToTD;
1427 Tree.GetNode(FromTD, ToTD);
1429 if (!Tree.HasChildren()) {
1430 // If we're dealing with a template specialization with zero
1431 // arguments, there are no children; special-case this.
1432 OS << FromTD->getNameAsString() << "<>";
1436 Qualifiers FromQual, ToQual;
1437 Tree.GetNode(FromQual, ToQual);
1438 PrintQualifiers(FromQual, ToQual);
1440 OS << FromTD->getNameAsString() << '<';
1442 unsigned NumElideArgs = 0;
1445 if (Tree.NodeIsSame()) {
1449 if (NumElideArgs > 0) {
1450 PrintElideArgs(NumElideArgs, Indent);
1455 TreeToString(Indent);
1456 if (Tree.HasNextSibling())
1458 } while (Tree.AdvanceSibling());
1459 if (NumElideArgs > 0)
1460 PrintElideArgs(NumElideArgs, Indent);
1469 // To signal to the text printer that a certain text needs to be bolded,
1470 // a special character is injected into the character stream which the
1471 // text printer will later strip out.
1473 /// Bold - Start bolding text.
1475 assert(!IsBold && "Attempting to bold text that is already bold.");
1478 OS << ToggleHighlight;
1481 /// Unbold - Stop bolding text.
1483 assert(IsBold && "Attempting to remove bold from unbold text.");
1486 OS << ToggleHighlight;
1489 // Functions to print out the arguments and highlighting the difference.
1491 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1492 /// typenames that are the same and attempt to disambiguate them by using
1493 /// canonical typenames.
1494 void PrintTypeNames(QualType FromType, QualType ToType,
1495 bool FromDefault, bool ToDefault, bool Same) {
1496 assert((!FromType.isNull() || !ToType.isNull()) &&
1497 "Only one template argument may be missing.");
1500 OS << FromType.getAsString(Policy);
1504 if (!FromType.isNull() && !ToType.isNull() &&
1505 FromType.getLocalUnqualifiedType() ==
1506 ToType.getLocalUnqualifiedType()) {
1507 Qualifiers FromQual = FromType.getLocalQualifiers(),
1508 ToQual = ToType.getLocalQualifiers();
1509 PrintQualifiers(FromQual, ToQual);
1510 FromType.getLocalUnqualifiedType().print(OS, Policy);
1514 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1515 : FromType.getAsString(Policy);
1516 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1517 : ToType.getAsString(Policy);
1518 // Switch to canonical typename if it is better.
1519 // TODO: merge this with other aka printing above.
1520 if (FromTypeStr == ToTypeStr) {
1521 std::string FromCanTypeStr =
1522 FromType.getCanonicalType().getAsString(Policy);
1523 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString(Policy);
1524 if (FromCanTypeStr != ToCanTypeStr) {
1525 FromTypeStr = FromCanTypeStr;
1526 ToTypeStr = ToCanTypeStr;
1530 if (PrintTree) OS << '[';
1531 OS << (FromDefault ? "(default) " : "");
1536 OS << " != " << (ToDefault ? "(default) " : "");
1545 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1547 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr, bool FromNullPtr,
1548 bool ToNullPtr, bool FromDefault, bool ToDefault, bool Same) {
1549 assert((FromExpr || ToExpr) &&
1550 "Only one template argument may be missing.");
1552 PrintExpr(FromExpr, FromNullPtr);
1553 } else if (!PrintTree) {
1554 OS << (FromDefault ? "(default) " : "");
1556 PrintExpr(FromExpr, FromNullPtr);
1559 OS << (FromDefault ? "[(default) " : "[");
1561 PrintExpr(FromExpr, FromNullPtr);
1563 OS << " != " << (ToDefault ? "(default) " : "");
1565 PrintExpr(ToExpr, ToNullPtr);
1571 /// PrintExpr - Actual formatting and printing of expressions.
1572 void PrintExpr(const Expr *E, bool NullPtr = false) {
1574 E->printPretty(OS, nullptr, Policy);
1581 OS << "(no argument)";
1584 /// PrintTemplateTemplate - Handles printing of template template arguments,
1585 /// highlighting argument differences.
1586 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1587 bool FromDefault, bool ToDefault, bool Same) {
1588 assert((FromTD || ToTD) && "Only one template argument may be missing.");
1590 std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
1591 std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
1592 if (FromTD && ToTD && FromName == ToName) {
1593 FromName = FromTD->getQualifiedNameAsString();
1594 ToName = ToTD->getQualifiedNameAsString();
1598 OS << "template " << FromTD->getNameAsString();
1599 } else if (!PrintTree) {
1600 OS << (FromDefault ? "(default) template " : "template ");
1605 OS << (FromDefault ? "[(default) template " : "[template ");
1609 OS << " != " << (ToDefault ? "(default) template " : "template ");
1617 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1618 /// argument differences.
1619 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1620 bool IsValidFromInt, bool IsValidToInt, Expr *FromExpr,
1621 Expr *ToExpr, bool FromDefault, bool ToDefault, bool Same) {
1622 assert((IsValidFromInt || IsValidToInt) &&
1623 "Only one integral argument may be missing.");
1626 OS << FromInt.toString(10);
1627 } else if (!PrintTree) {
1628 OS << (FromDefault ? "(default) " : "");
1629 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
1631 OS << (FromDefault ? "[(default) " : "[");
1632 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
1633 OS << " != " << (ToDefault ? "(default) " : "");
1634 PrintAPSInt(ToInt, ToExpr, IsValidToInt);
1639 /// PrintAPSInt - If valid, print the APSInt. If the expression is
1640 /// gives more information, print it too.
1641 void PrintAPSInt(llvm::APSInt Val, Expr *E, bool Valid) {
1644 if (HasExtraInfo(E)) {
1650 OS << Val.toString(10);
1654 OS << "(no argument)";
1659 /// HasExtraInfo - Returns true if E is not an integer literal or the
1660 /// negation of an integer literal
1661 bool HasExtraInfo(Expr *E) {
1662 if (!E) return false;
1663 if (isa<IntegerLiteral>(E)) return false;
1665 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
1666 if (UO->getOpcode() == UO_Minus)
1667 if (isa<IntegerLiteral>(UO->getSubExpr()))
1673 void PrintValueDecl(ValueDecl *VD, bool AddressOf, bool NullPtr) {
1677 OS << VD->getName();
1686 OS << "(no argument)";
1689 /// PrintDecl - Handles printing of Decl arguments, highlighting
1690 /// argument differences.
1691 void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
1692 bool FromAddressOf, bool ToAddressOf, bool FromNullPtr,
1693 bool ToNullPtr, bool FromDefault, bool ToDefault,
1695 assert((FromValueDecl || FromNullPtr || ToValueDecl || ToNullPtr) &&
1696 "Only one Decl argument may be NULL");
1699 PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
1700 } else if (!PrintTree) {
1701 OS << (FromDefault ? "(default) " : "");
1703 PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
1706 OS << (FromDefault ? "[(default) " : "[");
1708 PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
1710 OS << " != " << (ToDefault ? "(default) " : "");
1712 PrintValueDecl(ToValueDecl, ToAddressOf, ToNullPtr);
1719 // Prints the appropriate placeholder for elided template arguments.
1720 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1723 for (unsigned i = 0; i < Indent; ++i)
1726 if (NumElideArgs == 0) return;
1727 if (NumElideArgs == 1)
1730 OS << "[" << NumElideArgs << " * ...]";
1733 // Prints and highlights differences in Qualifiers.
1734 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1735 // Both types have no qualifiers
1736 if (FromQual.empty() && ToQual.empty())
1739 // Both types have same qualifiers
1740 if (FromQual == ToQual) {
1741 PrintQualifier(FromQual, /*ApplyBold*/false);
1745 // Find common qualifiers and strip them from FromQual and ToQual.
1746 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1749 // The qualifiers are printed before the template name.
1751 // The common qualifiers are printed. Then, qualifiers only in this type
1752 // are printed and highlighted. Finally, qualifiers only in the other
1753 // type are printed and highlighted inside parentheses after "missing".
1755 // Qualifiers are printed next to each other, inside brackets, and
1756 // separated by "!=". The printing order is:
1757 // common qualifiers, highlighted from qualifiers, "!=",
1758 // common qualifiers, highlighted to qualifiers
1761 if (CommonQual.empty() && FromQual.empty()) {
1763 OS << "(no qualifiers) ";
1766 PrintQualifier(CommonQual, /*ApplyBold*/false);
1767 PrintQualifier(FromQual, /*ApplyBold*/true);
1770 if (CommonQual.empty() && ToQual.empty()) {
1772 OS << "(no qualifiers)";
1775 PrintQualifier(CommonQual, /*ApplyBold*/false,
1776 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1777 PrintQualifier(ToQual, /*ApplyBold*/true,
1778 /*appendSpaceIfNonEmpty*/false);
1782 PrintQualifier(CommonQual, /*ApplyBold*/false);
1783 PrintQualifier(FromQual, /*ApplyBold*/true);
1787 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1788 bool AppendSpaceIfNonEmpty = true) {
1789 if (Q.empty()) return;
1790 if (ApplyBold) Bold();
1791 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1792 if (ApplyBold) Unbold();
1797 TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
1798 QualType ToType, bool PrintTree, bool PrintFromType,
1799 bool ElideType, bool ShowColor)
1801 Policy(Context.getLangOpts()),
1802 ElideType(ElideType),
1803 PrintTree(PrintTree),
1804 ShowColor(ShowColor),
1805 // When printing a single type, the FromType is the one printed.
1806 FromType(PrintFromType ? FromType : ToType),
1807 ToType(PrintFromType ? ToType : FromType),
1812 /// DiffTemplate - Start the template type diffing.
1813 void DiffTemplate() {
1814 Qualifiers FromQual = FromType.getQualifiers(),
1815 ToQual = ToType.getQualifiers();
1817 const TemplateSpecializationType *FromOrigTST =
1818 GetTemplateSpecializationType(Context, FromType);
1819 const TemplateSpecializationType *ToOrigTST =
1820 GetTemplateSpecializationType(Context, ToType);
1822 // Only checking templates.
1823 if (!FromOrigTST || !ToOrigTST)
1826 // Different base templates.
1827 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1831 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1832 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
1833 Tree.SetNode(FromType, ToType);
1834 Tree.SetNode(FromQual, ToQual);
1835 Tree.SetKind(DiffTree::Template);
1837 // Same base template, but different arguments.
1838 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1839 ToOrigTST->getTemplateName().getAsTemplateDecl());
1841 DiffTemplate(FromOrigTST, ToOrigTST);
1844 /// Emit - When the two types given are templated types with the same
1845 /// base template, a string representation of the type difference will be
1846 /// emitted to the stream and return true. Otherwise, return false.
1848 Tree.StartTraverse();
1853 assert(!IsBold && "Bold is applied to end of string.");
1856 }; // end class TemplateDiff
1859 /// FormatTemplateTypeDiff - A helper static function to start the template
1860 /// diff and return the properly formatted string. Returns true if the diff
1862 static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1863 QualType ToType, bool PrintTree,
1864 bool PrintFromType, bool ElideType,
1865 bool ShowColors, raw_ostream &OS) {
1867 PrintFromType = true;
1868 TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
1869 ElideType, ShowColors);