blob: d67423ed3d29dfe20998485fa76254e7f688bb70 [file] [log] [blame]
Douglas Gregor639cccc2010-02-09 22:26:47 +00001//===--- ASTDiagnostic.cpp - Diagnostic Printing Hooks for AST Nodes ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a diagnostic formatting hook for AST elements.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
Richard Trieu91844232012-06-26 18:18:47 +000016#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/ExprCXX.h"
18#include "clang/AST/TemplateBase.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000019#include "clang/AST/Type.h"
Richard Trieu91844232012-06-26 18:18:47 +000020#include "llvm/ADT/SmallString.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000021#include "llvm/Support/raw_ostream.h"
22
23using namespace clang;
24
Chandler Carruthd102f2d2010-05-13 11:37:24 +000025// Returns a desugared version of the QualType, and marks ShouldAKA as true
26// whenever we remove significant sugar from the type.
27static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
28 QualifierCollector QC;
29
Douglas Gregor639cccc2010-02-09 22:26:47 +000030 while (true) {
Chandler Carruthd102f2d2010-05-13 11:37:24 +000031 const Type *Ty = QC.strip(QT);
32
Douglas Gregor639cccc2010-02-09 22:26:47 +000033 // Don't aka just because we saw an elaborated type...
Richard Smith30482bc2011-02-20 03:19:35 +000034 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
35 QT = ET->desugar();
Douglas Gregor639cccc2010-02-09 22:26:47 +000036 continue;
37 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +000038 // ... or a paren type ...
Richard Smith30482bc2011-02-20 03:19:35 +000039 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
40 QT = PT->desugar();
Abramo Bagnara924a8f32010-12-10 16:29:40 +000041 continue;
42 }
Richard Smith30482bc2011-02-20 03:19:35 +000043 // ...or a substituted template type parameter ...
44 if (const SubstTemplateTypeParmType *ST =
45 dyn_cast<SubstTemplateTypeParmType>(Ty)) {
46 QT = ST->desugar();
47 continue;
48 }
John McCall4223a9e2011-03-04 04:00:19 +000049 // ...or an attributed type...
50 if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
51 QT = AT->desugar();
52 continue;
53 }
Richard Smith30482bc2011-02-20 03:19:35 +000054 // ... or an auto type.
55 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
56 if (!AT->isSugared())
57 break;
58 QT = AT->desugar();
Douglas Gregor639cccc2010-02-09 22:26:47 +000059 continue;
60 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +000061
Richard Smith3f1b5d02011-05-05 21:57:07 +000062 // 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())
66 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000067
Douglas Gregor639cccc2010-02-09 22:26:47 +000068 // 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())
73 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000074
Douglas Gregor639cccc2010-02-09 22:26:47 +000075 // Don't desugar va_list.
76 if (QualType(Ty,0) == Context.getBuiltinVaListType())
77 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000078
Douglas Gregor639cccc2010-02-09 22:26:47 +000079 // Otherwise, do a single-step desugar.
80 QualType Underlying;
81 bool IsSugar = false;
82 switch (Ty->getTypeClass()) {
83#define ABSTRACT_TYPE(Class, Base)
84#define TYPE(Class, Base) \
85case Type::Class: { \
86const Class##Type *CTy = cast<Class##Type>(Ty); \
87if (CTy->isSugared()) { \
88IsSugar = true; \
89Underlying = CTy->desugar(); \
90} \
91break; \
92}
93#include "clang/AST/TypeNodes.def"
94 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +000095
Douglas Gregor639cccc2010-02-09 22:26:47 +000096 // If it wasn't sugared, we're done.
97 if (!IsSugar)
98 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000099
Douglas Gregor639cccc2010-02-09 22:26:47 +0000100 // 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))
103 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000104
Douglas Gregor639cccc2010-02-09 22:26:47 +0000105 // Don't desugar through the primary typedef of an anonymous type.
Chris Lattneredbdff62010-09-04 23:16:01 +0000106 if (const TagType *UTT = Underlying->getAs<TagType>())
107 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
Richard Smithdda56e42011-04-15 14:24:37 +0000108 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
Chris Lattneredbdff62010-09-04 23:16:01 +0000109 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000110
111 // Record that we actually looked through an opaque type here.
112 ShouldAKA = true;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000113 QT = Underlying;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000114 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000115
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>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000119 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
120 ShouldAKA));
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000121 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000122 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
123 ShouldAKA));
Douglas Gregor7a2a1162011-01-20 16:08:06 +0000124 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
125 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
126 ShouldAKA));
Douglas Gregor639cccc2010-02-09 22:26:47 +0000127 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000128
John McCall717d9b02010-12-10 11:01:00 +0000129 return QC.apply(Context, QT);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000130}
131
132/// \brief Convert the given type to a string suitable for printing as part of
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000133/// a diagnostic.
134///
Chandler Carruthd5173952011-07-11 17:49:21 +0000135/// There are four main criteria when determining whether we should have an
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000136/// a.k.a. clause when pretty-printing a type:
137///
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
141/// a.k.a. clause.
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.
Chandler Carruthd5173952011-07-11 17:49:21 +0000148/// 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.
Douglas Gregor639cccc2010-02-09 22:26:47 +0000151///
152/// \param Context the context in which the type was allocated
153/// \param Ty the type to print
Chandler Carruthd5173952011-07-11 17:49:21 +0000154/// \param QualTypeVals pointer values to QualTypes which are used in the
155/// diagnostic message
Douglas Gregor639cccc2010-02-09 22:26:47 +0000156static std::string
157ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
David Blaikie9c902b52011-09-25 23:23:43 +0000158 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000159 unsigned NumPrevArgs,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000160 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000161 // FIXME: Playing with std::string is really slow.
Chandler Carruthd5173952011-07-11 17:49:21 +0000162 bool ForceAKA = false;
163 QualType CanTy = Ty.getCanonicalType();
Douglas Gregorc0b07282011-09-27 22:38:19 +0000164 std::string S = Ty.getAsString(Context.getPrintingPolicy());
165 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000166
Bill Wendling8eb771d2012-02-22 09:51:33 +0000167 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
Chandler Carruthd5173952011-07-11 17:49:21 +0000168 QualType CompareTy =
Bill Wendling8eb771d2012-02-22 09:51:33 +0000169 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
Richard Smithbcc22fc2012-03-09 08:00:36 +0000170 if (CompareTy.isNull())
171 continue;
Chandler Carruthd5173952011-07-11 17:49:21 +0000172 if (CompareTy == Ty)
173 continue; // Same types
174 QualType CompareCanTy = CompareTy.getCanonicalType();
175 if (CompareCanTy == CanTy)
176 continue; // Same canonical types
Douglas Gregorc0b07282011-09-27 22:38:19 +0000177 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
Richard Trieu5d1aff02011-11-14 19:39:25 +0000178 bool aka;
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());
187
Chandler Carruthd5173952011-07-11 17:49:21 +0000188 if (CompareCanS == CanS)
189 continue; // No new info from canonical type
190
191 ForceAKA = true;
192 break;
193 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000194
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.
David Blaikie9c902b52011-09-25 23:23:43 +0000200 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000201 void *Ptr = (void*)PrevArgs[i].second;
202 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
203 if (PrevTy == Ty) {
204 Repeated = true;
205 break;
206 }
207 }
208 }
209
Douglas Gregor639cccc2010-02-09 22:26:47 +0000210 // Consider producing an a.k.a. clause if removing all the direct
211 // sugar gives us something "significantly different".
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000212 if (!Repeated) {
213 bool ShouldAKA = false;
214 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
Chandler Carruthd5173952011-07-11 17:49:21 +0000215 if (ShouldAKA || ForceAKA) {
216 if (DesugaredTy == Ty) {
217 DesugaredTy = Ty.getCanonicalType();
218 }
Douglas Gregorc0b07282011-09-27 22:38:19 +0000219 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000220 if (akaStr != S) {
221 S = "'" + S + "' (aka '" + akaStr + "')";
222 return S;
223 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000224 }
Douglas Gregor639cccc2010-02-09 22:26:47 +0000225 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000226
Douglas Gregor639cccc2010-02-09 22:26:47 +0000227 S = "'" + S + "'";
228 return S;
229}
230
Richard Trieu91844232012-06-26 18:18:47 +0000231static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
232 QualType ToType, bool PrintTree,
233 bool PrintFromType, bool ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +0000234 bool ShowColors, raw_ostream &OS);
Richard Trieu91844232012-06-26 18:18:47 +0000235
Chandler Carruthd5173952011-07-11 17:49:21 +0000236void clang::FormatASTNodeDiagnosticArgument(
David Blaikie9c902b52011-09-25 23:23:43 +0000237 DiagnosticsEngine::ArgumentKind Kind,
Chandler Carruthd5173952011-07-11 17:49:21 +0000238 intptr_t Val,
239 const char *Modifier,
240 unsigned ModLen,
241 const char *Argument,
242 unsigned ArgLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000243 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000244 unsigned NumPrevArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000245 SmallVectorImpl<char> &Output,
Chandler Carruthd5173952011-07-11 17:49:21 +0000246 void *Cookie,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000247 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000248 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
249
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000250 size_t OldEnd = Output.size();
251 llvm::raw_svector_ostream OS(Output);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000252 bool NeedQuotes = true;
253
254 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000255 default: llvm_unreachable("unknown ArgumentKind");
Richard Trieu91844232012-06-26 18:18:47 +0000256 case DiagnosticsEngine::ak_qualtype_pair: {
Richard Trieu50f5f462012-07-10 01:46:04 +0000257 TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
Richard Trieu91844232012-06-26 18:18:47 +0000258 QualType FromType =
259 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
260 QualType ToType =
261 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
262
263 if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
264 TDT.PrintFromType, TDT.ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +0000265 TDT.ShowColors, OS)) {
Richard Trieu91844232012-06-26 18:18:47 +0000266 NeedQuotes = !TDT.PrintTree;
Richard Trieu50f5f462012-07-10 01:46:04 +0000267 TDT.TemplateDiffUsed = true;
Richard Trieu91844232012-06-26 18:18:47 +0000268 break;
269 }
270
271 // Don't fall-back during tree printing. The caller will handle
272 // this case.
273 if (TDT.PrintTree)
274 return;
275
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000276 // Attempting to do a template diff on non-templates. Set the variables
Richard Trieu91844232012-06-26 18:18:47 +0000277 // and continue with regular type printing of the appropriate type.
278 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
279 ModLen = 0;
280 ArgLen = 0;
281 // Fall through
282 }
David Blaikie9c902b52011-09-25 23:23:43 +0000283 case DiagnosticsEngine::ak_qualtype: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000284 assert(ModLen == 0 && ArgLen == 0 &&
285 "Invalid modifier for QualType argument");
286
287 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000288 OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs,
289 QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000290 NeedQuotes = false;
291 break;
292 }
David Blaikie9c902b52011-09-25 23:23:43 +0000293 case DiagnosticsEngine::ak_declarationname: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000294 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000295 OS << '+';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000296 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
297 && ArgLen==0)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000298 OS << '-';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000299 else
300 assert(ModLen == 0 && ArgLen == 0 &&
301 "Invalid modifier for DeclarationName argument");
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000302
303 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
304 N.printName(OS);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000305 break;
306 }
David Blaikie9c902b52011-09-25 23:23:43 +0000307 case DiagnosticsEngine::ak_nameddecl: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000308 bool Qualified;
309 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
310 Qualified = true;
311 else {
312 assert(ModLen == 0 && ArgLen == 0 &&
313 "Invalid modifier for NamedDecl* argument");
314 Qualified = false;
315 }
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000316 const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000317 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000318 break;
319 }
David Blaikie9c902b52011-09-25 23:23:43 +0000320 case DiagnosticsEngine::ak_nestednamespec: {
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000321 NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
322 NNS->print(OS, Context.getPrintingPolicy());
Douglas Gregor639cccc2010-02-09 22:26:47 +0000323 NeedQuotes = false;
324 break;
325 }
David Blaikie9c902b52011-09-25 23:23:43 +0000326 case DiagnosticsEngine::ak_declcontext: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000327 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
328 assert(DC && "Should never have a null declaration context");
329
330 if (DC->isTranslationUnit()) {
331 // FIXME: Get these strings from some localized place
David Blaikiebbafb8a2012-03-11 07:00:24 +0000332 if (Context.getLangOpts().CPlusPlus)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000333 OS << "the global namespace";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000334 else
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000335 OS << "the global scope";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000336 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000337 OS << ConvertTypeToDiagnosticString(Context,
338 Context.getTypeDeclType(Type),
339 PrevArgs, NumPrevArgs,
340 QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000341 } else {
342 // FIXME: Get these strings from some localized place
343 NamedDecl *ND = cast<NamedDecl>(DC);
344 if (isa<NamespaceDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000345 OS << "namespace ";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000346 else if (isa<ObjCMethodDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000347 OS << "method ";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000348 else if (isa<FunctionDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000349 OS << "function ";
350
351 OS << '\'';
352 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
353 OS << '\'';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000354 }
355 NeedQuotes = false;
356 break;
357 }
358 }
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000359
360 OS.flush();
361
362 if (NeedQuotes) {
363 Output.insert(Output.begin()+OldEnd, '\'');
Douglas Gregor639cccc2010-02-09 22:26:47 +0000364 Output.push_back('\'');
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000365 }
Douglas Gregor639cccc2010-02-09 22:26:47 +0000366}
Richard Trieu91844232012-06-26 18:18:47 +0000367
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.
372namespace {
373class TemplateDiff {
374 /// Context - The ASTContext which is used for comparing template arguments.
375 ASTContext &Context;
376
377 /// Policy - Used during expression printing.
378 PrintingPolicy Policy;
379
380 /// ElideType - Option to elide identical types.
381 bool ElideType;
382
383 /// PrintTree - Format output string as a tree.
384 bool PrintTree;
385
386 /// ShowColor - Diagnostics support color, so bolding will be used.
387 bool ShowColor;
388
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
391 /// in the tree.
392 QualType FromType;
393
394 /// ToType - The type that FromType is compared to. Only in tree printing
395 /// will this type be outputed.
396 QualType ToType;
397
Richard Trieu91844232012-06-26 18:18:47 +0000398 /// OS - The stream used to construct the output strings.
Benjamin Kramer8de90462013-02-22 16:08:12 +0000399 raw_ostream &OS;
Richard Trieu91844232012-06-26 18:18:47 +0000400
401 /// IsBold - Keeps track of the bold formatting for the output string.
402 bool IsBold;
403
404 /// DiffTree - A tree representation the differences between two types.
405 class DiffTree {
406 /// DiffNode - The root node stores the original type. Each child node
407 /// stores template arguments of their parents. For templated types, the
408 /// template decl is also stored.
409 struct DiffNode {
410 /// NextNode - The index of the next sibling node or 0.
411 unsigned NextNode;
412
413 /// ChildNode - The index of the first child node or 0.
414 unsigned ChildNode;
415
416 /// ParentNode - The index of the parent node.
417 unsigned ParentNode;
418
419 /// FromType, ToType - The type arguments.
420 QualType FromType, ToType;
421
422 /// FromExpr, ToExpr - The expression arguments.
423 Expr *FromExpr, *ToExpr;
424
425 /// FromTD, ToTD - The template decl for template template
426 /// arguments or the type arguments that are templates.
427 TemplateDecl *FromTD, *ToTD;
428
Richard Trieub7243852012-09-28 20:32:51 +0000429 /// FromQual, ToQual - Qualifiers for template types.
430 Qualifiers FromQual, ToQual;
431
Richard Trieu6df89452012-11-01 21:29:28 +0000432 /// FromInt, ToInt - APSInt's for integral arguments.
433 llvm::APSInt FromInt, ToInt;
434
435 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
436 bool IsValidFromInt, IsValidToInt;
437
Richard Trieu954aaaf2013-02-27 01:41:53 +0000438 /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
439 ValueDecl *FromValueDecl, *ToValueDecl;
440
Richard Trieu91844232012-06-26 18:18:47 +0000441 /// FromDefault, ToDefault - Whether the argument is a default argument.
442 bool FromDefault, ToDefault;
443
444 /// Same - Whether the two arguments evaluate to the same value.
445 bool Same;
446
447 DiffNode(unsigned ParentNode = 0)
448 : NextNode(0), ChildNode(0), ParentNode(ParentNode),
449 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
Richard Trieu954aaaf2013-02-27 01:41:53 +0000450 IsValidFromInt(false), IsValidToInt(false), FromValueDecl(0),
451 ToValueDecl(0), FromDefault(false), ToDefault(false), Same(false) { }
Richard Trieu91844232012-06-26 18:18:47 +0000452 };
453
454 /// FlatTree - A flattened tree used to store the DiffNodes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000455 SmallVector<DiffNode, 16> FlatTree;
Richard Trieu91844232012-06-26 18:18:47 +0000456
457 /// CurrentNode - The index of the current node being used.
458 unsigned CurrentNode;
459
460 /// NextFreeNode - The index of the next unused node. Used when creating
461 /// child nodes.
462 unsigned NextFreeNode;
463
464 /// ReadNode - The index of the current node being read.
465 unsigned ReadNode;
466
467 public:
468 DiffTree() :
469 CurrentNode(0), NextFreeNode(1) {
470 FlatTree.push_back(DiffNode());
471 }
472
473 // Node writing functions.
474 /// SetNode - Sets FromTD and ToTD of the current node.
475 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
476 FlatTree[CurrentNode].FromTD = FromTD;
477 FlatTree[CurrentNode].ToTD = ToTD;
478 }
479
480 /// SetNode - Sets FromType and ToType of the current node.
481 void SetNode(QualType FromType, QualType ToType) {
482 FlatTree[CurrentNode].FromType = FromType;
483 FlatTree[CurrentNode].ToType = ToType;
484 }
485
486 /// SetNode - Set FromExpr and ToExpr of the current node.
487 void SetNode(Expr *FromExpr, Expr *ToExpr) {
488 FlatTree[CurrentNode].FromExpr = FromExpr;
489 FlatTree[CurrentNode].ToExpr = ToExpr;
490 }
491
Richard Trieu6df89452012-11-01 21:29:28 +0000492 /// SetNode - Set FromInt and ToInt of the current node.
493 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
494 bool IsValidFromInt, bool IsValidToInt) {
495 FlatTree[CurrentNode].FromInt = FromInt;
496 FlatTree[CurrentNode].ToInt = ToInt;
497 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
498 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
499 }
500
Richard Trieub7243852012-09-28 20:32:51 +0000501 /// SetNode - Set FromQual and ToQual of the current node.
502 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
503 FlatTree[CurrentNode].FromQual = FromQual;
504 FlatTree[CurrentNode].ToQual = ToQual;
505 }
506
Richard Trieu954aaaf2013-02-27 01:41:53 +0000507 /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
508 void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl) {
509 FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
510 FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
511 }
512
Richard Trieu91844232012-06-26 18:18:47 +0000513 /// SetSame - Sets the same flag of the current node.
514 void SetSame(bool Same) {
515 FlatTree[CurrentNode].Same = Same;
516 }
517
518 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
519 void SetDefault(bool FromDefault, bool ToDefault) {
520 FlatTree[CurrentNode].FromDefault = FromDefault;
521 FlatTree[CurrentNode].ToDefault = ToDefault;
522 }
523
524 /// Up - Changes the node to the parent of the current node.
525 void Up() {
526 CurrentNode = FlatTree[CurrentNode].ParentNode;
527 }
528
529 /// AddNode - Adds a child node to the current node, then sets that node
530 /// node as the current node.
531 void AddNode() {
532 FlatTree.push_back(DiffNode(CurrentNode));
533 DiffNode &Node = FlatTree[CurrentNode];
534 if (Node.ChildNode == 0) {
535 // If a child node doesn't exist, add one.
536 Node.ChildNode = NextFreeNode;
537 } else {
538 // If a child node exists, find the last child node and add a
539 // next node to it.
540 unsigned i;
541 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
542 i = FlatTree[i].NextNode) {
543 }
544 FlatTree[i].NextNode = NextFreeNode;
545 }
546 CurrentNode = NextFreeNode;
547 ++NextFreeNode;
548 }
549
550 // Node reading functions.
551 /// StartTraverse - Prepares the tree for recursive traversal.
552 void StartTraverse() {
553 ReadNode = 0;
554 CurrentNode = NextFreeNode;
555 NextFreeNode = 0;
556 }
557
558 /// Parent - Move the current read node to its parent.
559 void Parent() {
560 ReadNode = FlatTree[ReadNode].ParentNode;
561 }
562
563 /// NodeIsTemplate - Returns true if a template decl is set, and types are
564 /// set.
565 bool NodeIsTemplate() {
566 return (FlatTree[ReadNode].FromTD &&
567 !FlatTree[ReadNode].ToType.isNull()) ||
568 (FlatTree[ReadNode].ToTD && !FlatTree[ReadNode].ToType.isNull());
569 }
570
571 /// NodeIsQualType - Returns true if a Qualtype is set.
572 bool NodeIsQualType() {
573 return !FlatTree[ReadNode].FromType.isNull() ||
574 !FlatTree[ReadNode].ToType.isNull();
575 }
576
577 /// NodeIsExpr - Returns true if an expr is set.
578 bool NodeIsExpr() {
579 return FlatTree[ReadNode].FromExpr || FlatTree[ReadNode].ToExpr;
580 }
581
582 /// NodeIsTemplateTemplate - Returns true if the argument is a template
583 /// template type.
584 bool NodeIsTemplateTemplate() {
585 return FlatTree[ReadNode].FromType.isNull() &&
586 FlatTree[ReadNode].ToType.isNull() &&
587 (FlatTree[ReadNode].FromTD || FlatTree[ReadNode].ToTD);
588 }
589
Richard Trieu6df89452012-11-01 21:29:28 +0000590 /// NodeIsAPSInt - Returns true if the arugments are stored in APSInt's.
591 bool NodeIsAPSInt() {
592 return FlatTree[ReadNode].IsValidFromInt ||
593 FlatTree[ReadNode].IsValidToInt;
594 }
595
Richard Trieu954aaaf2013-02-27 01:41:53 +0000596 /// NodeIsDecl - Returns true if the arguments are stored as Decl's.
597 bool NodeIsValueDecl() {
598 return FlatTree[ReadNode].FromValueDecl || FlatTree[ReadNode].ToValueDecl;
599 }
600
Richard Trieu91844232012-06-26 18:18:47 +0000601 /// GetNode - Gets the FromType and ToType.
602 void GetNode(QualType &FromType, QualType &ToType) {
603 FromType = FlatTree[ReadNode].FromType;
604 ToType = FlatTree[ReadNode].ToType;
605 }
606
607 /// GetNode - Gets the FromExpr and ToExpr.
608 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
609 FromExpr = FlatTree[ReadNode].FromExpr;
610 ToExpr = FlatTree[ReadNode].ToExpr;
611 }
612
613 /// GetNode - Gets the FromTD and ToTD.
614 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
615 FromTD = FlatTree[ReadNode].FromTD;
616 ToTD = FlatTree[ReadNode].ToTD;
617 }
618
Richard Trieu6df89452012-11-01 21:29:28 +0000619 /// GetNode - Gets the FromInt and ToInt.
620 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
621 bool &IsValidFromInt, bool &IsValidToInt) {
622 FromInt = FlatTree[ReadNode].FromInt;
623 ToInt = FlatTree[ReadNode].ToInt;
624 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
625 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
626 }
627
Richard Trieub7243852012-09-28 20:32:51 +0000628 /// GetNode - Gets the FromQual and ToQual.
629 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
630 FromQual = FlatTree[ReadNode].FromQual;
631 ToQual = FlatTree[ReadNode].ToQual;
632 }
633
Richard Trieu954aaaf2013-02-27 01:41:53 +0000634 /// GetNode - Gets the FromValueDecl and ToValueDecl.
635 void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl) {
636 FromValueDecl = FlatTree[ReadNode].FromValueDecl;
637 ToValueDecl = FlatTree[ReadNode].ToValueDecl;
638 }
639
Richard Trieu91844232012-06-26 18:18:47 +0000640 /// NodeIsSame - Returns true the arguments are the same.
641 bool NodeIsSame() {
642 return FlatTree[ReadNode].Same;
643 }
644
645 /// HasChildrend - Returns true if the node has children.
646 bool HasChildren() {
647 return FlatTree[ReadNode].ChildNode != 0;
648 }
649
650 /// MoveToChild - Moves from the current node to its child.
651 void MoveToChild() {
652 ReadNode = FlatTree[ReadNode].ChildNode;
653 }
654
655 /// AdvanceSibling - If there is a next sibling, advance to it and return
656 /// true. Otherwise, return false.
657 bool AdvanceSibling() {
658 if (FlatTree[ReadNode].NextNode == 0)
659 return false;
660
661 ReadNode = FlatTree[ReadNode].NextNode;
662 return true;
663 }
664
665 /// HasNextSibling - Return true if the node has a next sibling.
666 bool HasNextSibling() {
667 return FlatTree[ReadNode].NextNode != 0;
668 }
669
670 /// FromDefault - Return true if the from argument is the default.
671 bool FromDefault() {
672 return FlatTree[ReadNode].FromDefault;
673 }
674
675 /// ToDefault - Return true if the to argument is the default.
676 bool ToDefault() {
677 return FlatTree[ReadNode].ToDefault;
678 }
679
680 /// Empty - Returns true if the tree has no information.
681 bool Empty() {
682 return !FlatTree[0].FromTD && !FlatTree[0].ToTD &&
683 !FlatTree[0].FromExpr && !FlatTree[0].ToExpr &&
684 FlatTree[0].FromType.isNull() && FlatTree[0].ToType.isNull();
685 }
686 };
687
688 DiffTree Tree;
689
690 /// TSTiterator - an iterator that is used to enter a
691 /// TemplateSpecializationType and read TemplateArguments inside template
692 /// parameter packs in order with the rest of the TemplateArguments.
693 struct TSTiterator {
694 typedef const TemplateArgument& reference;
695 typedef const TemplateArgument* pointer;
696
697 /// TST - the template specialization whose arguments this iterator
698 /// traverse over.
699 const TemplateSpecializationType *TST;
700
701 /// Index - the index of the template argument in TST.
702 unsigned Index;
703
704 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
705 /// points to a TemplateArgument within a parameter pack.
706 TemplateArgument::pack_iterator CurrentTA;
707
708 /// EndTA - the end iterator of a parameter pack
709 TemplateArgument::pack_iterator EndTA;
710
711 /// TSTiterator - Constructs an iterator and sets it to the first template
712 /// argument.
713 TSTiterator(const TemplateSpecializationType *TST)
714 : TST(TST), Index(0), CurrentTA(0), EndTA(0) {
715 if (isEnd()) return;
716
717 // Set to first template argument. If not a parameter pack, done.
718 TemplateArgument TA = TST->getArg(0);
719 if (TA.getKind() != TemplateArgument::Pack) return;
720
721 // Start looking into the parameter pack.
722 CurrentTA = TA.pack_begin();
723 EndTA = TA.pack_end();
724
725 // Found a valid template argument.
726 if (CurrentTA != EndTA) return;
727
728 // Parameter pack is empty, use the increment to get to a valid
729 // template argument.
730 ++(*this);
731 }
732
733 /// isEnd - Returns true if the iterator is one past the end.
734 bool isEnd() const {
735 return Index == TST->getNumArgs();
736 }
737
738 /// &operator++ - Increment the iterator to the next template argument.
739 TSTiterator &operator++() {
740 assert(!isEnd() && "Iterator incremented past end of arguments.");
741
742 // If in a parameter pack, advance in the parameter pack.
743 if (CurrentTA != EndTA) {
744 ++CurrentTA;
745 if (CurrentTA != EndTA)
746 return *this;
747 }
748
749 // Loop until a template argument is found, or the end is reached.
750 while (true) {
751 // Advance to the next template argument. Break if reached the end.
752 if (++Index == TST->getNumArgs()) break;
753
754 // If the TemplateArgument is not a parameter pack, done.
755 TemplateArgument TA = TST->getArg(Index);
756 if (TA.getKind() != TemplateArgument::Pack) break;
757
758 // Handle parameter packs.
759 CurrentTA = TA.pack_begin();
760 EndTA = TA.pack_end();
761
762 // If the parameter pack is empty, try to advance again.
763 if (CurrentTA != EndTA) break;
764 }
765 return *this;
766 }
767
768 /// operator* - Returns the appropriate TemplateArgument.
769 reference operator*() const {
770 assert(!isEnd() && "Index exceeds number of arguments.");
771 if (CurrentTA == EndTA)
772 return TST->getArg(Index);
773 else
774 return *CurrentTA;
775 }
776
777 /// operator-> - Allow access to the underlying TemplateArgument.
778 pointer operator->() const {
779 return &operator*();
780 }
781 };
782
783 // These functions build up the template diff tree, including functions to
784 // retrieve and compare template arguments.
785
786 static const TemplateSpecializationType * GetTemplateSpecializationType(
787 ASTContext &Context, QualType Ty) {
788 if (const TemplateSpecializationType *TST =
789 Ty->getAs<TemplateSpecializationType>())
790 return TST;
791
792 const RecordType *RT = Ty->getAs<RecordType>();
793
794 if (!RT)
795 return 0;
796
797 const ClassTemplateSpecializationDecl *CTSD =
798 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
799
800 if (!CTSD)
801 return 0;
802
803 Ty = Context.getTemplateSpecializationType(
804 TemplateName(CTSD->getSpecializedTemplate()),
805 CTSD->getTemplateArgs().data(),
806 CTSD->getTemplateArgs().size(),
807 Ty.getCanonicalType());
808
809 return Ty->getAs<TemplateSpecializationType>();
810 }
811
812 /// DiffTemplate - recursively visits template arguments and stores the
813 /// argument info into a tree.
814 void DiffTemplate(const TemplateSpecializationType *FromTST,
815 const TemplateSpecializationType *ToTST) {
816 // Begin descent into diffing template tree.
817 TemplateParameterList *Params =
818 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
819 unsigned TotalArgs = 0;
820 for (TSTiterator FromIter(FromTST), ToIter(ToTST);
821 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
822 Tree.AddNode();
823
824 // Get the parameter at index TotalArgs. If index is larger
825 // than the total number of parameters, then there is an
826 // argument pack, so re-use the last parameter.
827 NamedDecl *ParamND = Params->getParam(
828 (TotalArgs < Params->size()) ? TotalArgs
829 : Params->size() - 1);
830 // Handle Types
831 if (TemplateTypeParmDecl *DefaultTTPD =
832 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
833 QualType FromType, ToType;
834 GetType(FromIter, DefaultTTPD, FromType);
835 GetType(ToIter, DefaultTTPD, ToType);
836 Tree.SetNode(FromType, ToType);
837 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
838 ToIter.isEnd() && !ToType.isNull());
839 if (!FromType.isNull() && !ToType.isNull()) {
840 if (Context.hasSameType(FromType, ToType)) {
841 Tree.SetSame(true);
842 } else {
Richard Trieub7243852012-09-28 20:32:51 +0000843 Qualifiers FromQual = FromType.getQualifiers(),
844 ToQual = ToType.getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +0000845 const TemplateSpecializationType *FromArgTST =
846 GetTemplateSpecializationType(Context, FromType);
847 const TemplateSpecializationType *ToArgTST =
848 GetTemplateSpecializationType(Context, ToType);
849
Richard Trieu8e14cac2012-09-28 19:51:57 +0000850 if (FromArgTST && ToArgTST &&
851 hasSameTemplate(FromArgTST, ToArgTST)) {
Richard Trieub7243852012-09-28 20:32:51 +0000852 FromQual -= QualType(FromArgTST, 0).getQualifiers();
853 ToQual -= QualType(ToArgTST, 0).getQualifiers();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000854 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
855 ToArgTST->getTemplateName().getAsTemplateDecl());
Richard Trieub7243852012-09-28 20:32:51 +0000856 Tree.SetNode(FromQual, ToQual);
Richard Trieu8e14cac2012-09-28 19:51:57 +0000857 DiffTemplate(FromArgTST, ToArgTST);
Richard Trieu91844232012-06-26 18:18:47 +0000858 }
859 }
860 }
861 }
862
863 // Handle Expressions
864 if (NonTypeTemplateParmDecl *DefaultNTTPD =
865 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
866 Expr *FromExpr, *ToExpr;
Richard Trieu6df89452012-11-01 21:29:28 +0000867 llvm::APSInt FromInt, ToInt;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000868 ValueDecl *FromValueDecl = 0, *ToValueDecl = 0;
Douglas Gregor2d5a5612012-12-21 23:03:27 +0000869 unsigned ParamWidth = 128; // Safe default
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000870 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType())
871 ParamWidth = Context.getIntWidth(DefaultNTTPD->getType());
Richard Trieu6df89452012-11-01 21:29:28 +0000872 bool HasFromInt = !FromIter.isEnd() &&
873 FromIter->getKind() == TemplateArgument::Integral;
874 bool HasToInt = !ToIter.isEnd() &&
875 ToIter->getKind() == TemplateArgument::Integral;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000876 bool HasFromValueDecl =
877 !FromIter.isEnd() &&
878 FromIter->getKind() == TemplateArgument::Declaration;
879 bool HasToValueDecl =
880 !ToIter.isEnd() &&
881 ToIter->getKind() == TemplateArgument::Declaration;
882
883 assert(((!HasFromInt && !HasToInt) ||
884 (!HasFromValueDecl && !HasToValueDecl)) &&
885 "Template argument cannot be both integer and declaration");
Richard Trieu515dc0f2013-02-21 00:50:43 +0000886
Richard Trieu6df89452012-11-01 21:29:28 +0000887 if (HasFromInt)
888 FromInt = FromIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000889 else if (HasFromValueDecl)
890 FromValueDecl = FromIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000891 else
892 GetExpr(FromIter, DefaultNTTPD, FromExpr);
893
894 if (HasToInt)
895 ToInt = ToIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000896 else if (HasToValueDecl)
897 ToValueDecl = ToIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000898 else
899 GetExpr(ToIter, DefaultNTTPD, ToExpr);
900
Richard Trieu954aaaf2013-02-27 01:41:53 +0000901 if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
Richard Trieu6df89452012-11-01 21:29:28 +0000902 Tree.SetNode(FromExpr, ToExpr);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000903 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr));
Richard Trieu6df89452012-11-01 21:29:28 +0000904 Tree.SetDefault(FromIter.isEnd() && FromExpr,
905 ToIter.isEnd() && ToExpr);
Richard Trieu954aaaf2013-02-27 01:41:53 +0000906 } else if (HasFromInt || HasToInt) {
Richard Trieu6df89452012-11-01 21:29:28 +0000907 if (!HasFromInt && FromExpr) {
908 FromInt = FromExpr->EvaluateKnownConstInt(Context);
909 HasFromInt = true;
910 }
911 if (!HasToInt && ToExpr) {
912 ToInt = ToExpr->EvaluateKnownConstInt(Context);
913 HasToInt = true;
914 }
915 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000916 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
Richard Trieu6df89452012-11-01 21:29:28 +0000917 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
918 ToIter.isEnd() && HasToInt);
Richard Trieu954aaaf2013-02-27 01:41:53 +0000919 } else {
920 if (!HasFromValueDecl && FromExpr) {
921 DeclRefExpr *DRE = cast<DeclRefExpr>(FromExpr);
922 FromValueDecl = cast<ValueDecl>(DRE->getDecl());
923 }
924 if (!HasToValueDecl && ToExpr) {
925 DeclRefExpr *DRE = cast<DeclRefExpr>(ToExpr);
926 ToValueDecl = cast<ValueDecl>(DRE->getDecl());
927 }
928 Tree.SetNode(FromValueDecl, ToValueDecl);
929 Tree.SetSame(FromValueDecl->getCanonicalDecl() ==
930 ToValueDecl->getCanonicalDecl());
931 Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
932 ToIter.isEnd() && ToValueDecl);
Richard Trieu6df89452012-11-01 21:29:28 +0000933 }
Richard Trieu91844232012-06-26 18:18:47 +0000934 }
935
936 // Handle Templates
937 if (TemplateTemplateParmDecl *DefaultTTPD =
938 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
939 TemplateDecl *FromDecl, *ToDecl;
940 GetTemplateDecl(FromIter, DefaultTTPD, FromDecl);
941 GetTemplateDecl(ToIter, DefaultTTPD, ToDecl);
942 Tree.SetNode(FromDecl, ToDecl);
Richard Trieue673d71a2013-01-31 02:47:46 +0000943 Tree.SetSame(
944 FromDecl && ToDecl &&
945 FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
Richard Trieu91844232012-06-26 18:18:47 +0000946 }
947
948 if (!FromIter.isEnd()) ++FromIter;
949 if (!ToIter.isEnd()) ++ToIter;
950 Tree.Up();
951 }
952 }
953
Richard Trieu8e14cac2012-09-28 19:51:57 +0000954 /// makeTemplateList - Dump every template alias into the vector.
955 static void makeTemplateList(
956 SmallVector<const TemplateSpecializationType*, 1> &TemplateList,
957 const TemplateSpecializationType *TST) {
958 while (TST) {
959 TemplateList.push_back(TST);
960 if (!TST->isTypeAlias())
961 return;
962 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
963 }
964 }
965
966 /// hasSameBaseTemplate - Returns true when the base templates are the same,
967 /// even if the template arguments are not.
968 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
969 const TemplateSpecializationType *ToTST) {
Douglas Gregor8e9f55f2013-01-31 01:08:35 +0000970 return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
971 ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000972 }
973
Richard Trieu91844232012-06-26 18:18:47 +0000974 /// hasSameTemplate - Returns true if both types are specialized from the
975 /// same template declaration. If they come from different template aliases,
976 /// do a parallel ascension search to determine the highest template alias in
977 /// common and set the arguments to them.
978 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
979 const TemplateSpecializationType *&ToTST) {
980 // Check the top templates if they are the same.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000981 if (hasSameBaseTemplate(FromTST, ToTST))
Richard Trieu91844232012-06-26 18:18:47 +0000982 return true;
983
984 // Create vectors of template aliases.
985 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
986 ToTemplateList;
987
Richard Trieu8e14cac2012-09-28 19:51:57 +0000988 makeTemplateList(FromTemplateList, FromTST);
989 makeTemplateList(ToTemplateList, ToTST);
Richard Trieu91844232012-06-26 18:18:47 +0000990
991 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
992 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
993 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
994
995 // Check if the lowest template types are the same. If not, return.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000996 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +0000997 return false;
998
999 // Begin searching up the template aliases. The bottom most template
1000 // matches so move up until one pair does not match. Use the template
1001 // right before that one.
1002 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
Richard Trieu8e14cac2012-09-28 19:51:57 +00001003 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +00001004 break;
1005 }
1006
1007 FromTST = FromIter[-1];
1008 ToTST = ToIter[-1];
1009
1010 return true;
1011 }
1012
1013 /// GetType - Retrieves the template type arguments, including default
1014 /// arguments.
1015 void GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD,
1016 QualType &ArgType) {
1017 ArgType = QualType();
1018 bool isVariadic = DefaultTTPD->isParameterPack();
1019
1020 if (!Iter.isEnd())
1021 ArgType = Iter->getAsType();
1022 else if (!isVariadic)
1023 ArgType = DefaultTTPD->getDefaultArgument();
David Blaikie47e45182012-06-26 18:52:09 +00001024 }
Richard Trieu91844232012-06-26 18:18:47 +00001025
1026 /// GetExpr - Retrieves the template expression argument, including default
1027 /// arguments.
1028 void GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD,
1029 Expr *&ArgExpr) {
1030 ArgExpr = 0;
1031 bool isVariadic = DefaultNTTPD->isParameterPack();
1032
1033 if (!Iter.isEnd())
1034 ArgExpr = Iter->getAsExpr();
1035 else if (!isVariadic)
1036 ArgExpr = DefaultNTTPD->getDefaultArgument();
1037
1038 if (ArgExpr)
1039 while (SubstNonTypeTemplateParmExpr *SNTTPE =
1040 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
1041 ArgExpr = SNTTPE->getReplacement();
1042 }
1043
1044 /// GetTemplateDecl - Retrieves the template template arguments, including
1045 /// default arguments.
1046 void GetTemplateDecl(const TSTiterator &Iter,
1047 TemplateTemplateParmDecl *DefaultTTPD,
1048 TemplateDecl *&ArgDecl) {
1049 ArgDecl = 0;
1050 bool isVariadic = DefaultTTPD->isParameterPack();
1051
1052 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
Eli Friedmanb826a002012-09-26 02:36:12 +00001053 TemplateDecl *DefaultTD = 0;
1054 if (TA.getKind() != TemplateArgument::Null)
1055 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
Richard Trieu91844232012-06-26 18:18:47 +00001056
1057 if (!Iter.isEnd())
1058 ArgDecl = Iter->getAsTemplate().getAsTemplateDecl();
1059 else if (!isVariadic)
1060 ArgDecl = DefaultTD;
1061 }
1062
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001063 /// IsSameConvertedInt - Returns true if both integers are equal when
1064 /// converted to an integer type with the given width.
1065 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1066 const llvm::APSInt &Y) {
1067 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1068 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1069 return ConvertedX == ConvertedY;
1070 }
1071
Richard Trieu91844232012-06-26 18:18:47 +00001072 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001073 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1074 Expr *FromExpr, Expr *ToExpr) {
Richard Trieu91844232012-06-26 18:18:47 +00001075 if (FromExpr == ToExpr)
1076 return true;
1077
1078 if (!FromExpr || !ToExpr)
1079 return false;
1080
1081 FromExpr = FromExpr->IgnoreParens();
1082 ToExpr = ToExpr->IgnoreParens();
1083
1084 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1085 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1086
1087 if (FromDRE || ToDRE) {
1088 if (!FromDRE || !ToDRE)
1089 return false;
1090 return FromDRE->getDecl() == ToDRE->getDecl();
1091 }
1092
1093 Expr::EvalResult FromResult, ToResult;
1094 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1095 !ToExpr->EvaluateAsRValue(ToResult, Context))
1096 assert(0 && "Template arguments must be known at compile time.");
1097
1098 APValue &FromVal = FromResult.Val;
1099 APValue &ToVal = ToResult.Val;
1100
1101 if (FromVal.getKind() != ToVal.getKind()) return false;
1102
1103 switch (FromVal.getKind()) {
1104 case APValue::Int:
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001105 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
Richard Trieu91844232012-06-26 18:18:47 +00001106 case APValue::LValue: {
1107 APValue::LValueBase FromBase = FromVal.getLValueBase();
1108 APValue::LValueBase ToBase = ToVal.getLValueBase();
1109 if (FromBase.isNull() && ToBase.isNull())
1110 return true;
1111 if (FromBase.isNull() || ToBase.isNull())
1112 return false;
1113 return FromBase.get<const ValueDecl*>() ==
1114 ToBase.get<const ValueDecl*>();
1115 }
1116 case APValue::MemberPointer:
1117 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1118 default:
1119 llvm_unreachable("Unknown template argument expression.");
1120 }
1121 }
1122
1123 // These functions converts the tree representation of the template
1124 // differences into the internal character vector.
1125
1126 /// TreeToString - Converts the Tree object into a character stream which
1127 /// will later be turned into the output string.
1128 void TreeToString(int Indent = 1) {
1129 if (PrintTree) {
1130 OS << '\n';
Benjamin Kramer6582c362013-02-22 16:13:34 +00001131 OS.indent(2 * Indent);
Richard Trieu91844232012-06-26 18:18:47 +00001132 ++Indent;
1133 }
1134
1135 // Handle cases where the difference is not templates with different
1136 // arguments.
1137 if (!Tree.NodeIsTemplate()) {
1138 if (Tree.NodeIsQualType()) {
1139 QualType FromType, ToType;
1140 Tree.GetNode(FromType, ToType);
1141 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1142 Tree.NodeIsSame());
1143 return;
1144 }
1145 if (Tree.NodeIsExpr()) {
1146 Expr *FromExpr, *ToExpr;
1147 Tree.GetNode(FromExpr, ToExpr);
1148 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1149 Tree.NodeIsSame());
1150 return;
1151 }
1152 if (Tree.NodeIsTemplateTemplate()) {
1153 TemplateDecl *FromTD, *ToTD;
1154 Tree.GetNode(FromTD, ToTD);
1155 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1156 Tree.ToDefault(), Tree.NodeIsSame());
1157 return;
1158 }
Richard Trieu6df89452012-11-01 21:29:28 +00001159
1160 if (Tree.NodeIsAPSInt()) {
1161 llvm::APSInt FromInt, ToInt;
1162 bool IsValidFromInt, IsValidToInt;
1163 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1164 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1165 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1166 return;
1167 }
Richard Trieu954aaaf2013-02-27 01:41:53 +00001168
1169 if (Tree.NodeIsValueDecl()) {
1170 ValueDecl *FromValueDecl, *ToValueDecl;
1171 Tree.GetNode(FromValueDecl, ToValueDecl);
1172 PrintValueDecl(FromValueDecl, ToValueDecl, Tree.FromDefault(),
1173 Tree.ToDefault(), Tree.NodeIsSame());
1174 return;
1175 }
1176
Richard Trieu91844232012-06-26 18:18:47 +00001177 llvm_unreachable("Unable to deduce template difference.");
1178 }
1179
1180 // Node is root of template. Recurse on children.
1181 TemplateDecl *FromTD, *ToTD;
1182 Tree.GetNode(FromTD, ToTD);
1183
Eli Friedman40ea2642012-12-18 23:32:47 +00001184 if (!Tree.HasChildren()) {
1185 // If we're dealing with a template specialization with zero
1186 // arguments, there are no children; special-case this.
1187 OS << FromTD->getNameAsString() << "<>";
1188 return;
1189 }
Richard Trieu91844232012-06-26 18:18:47 +00001190
Richard Trieub7243852012-09-28 20:32:51 +00001191 Qualifiers FromQual, ToQual;
1192 Tree.GetNode(FromQual, ToQual);
1193 PrintQualifiers(FromQual, ToQual);
1194
Richard Trieu91844232012-06-26 18:18:47 +00001195 OS << FromTD->getNameAsString() << '<';
1196 Tree.MoveToChild();
1197 unsigned NumElideArgs = 0;
1198 do {
1199 if (ElideType) {
1200 if (Tree.NodeIsSame()) {
1201 ++NumElideArgs;
1202 continue;
1203 }
1204 if (NumElideArgs > 0) {
1205 PrintElideArgs(NumElideArgs, Indent);
1206 NumElideArgs = 0;
1207 OS << ", ";
1208 }
1209 }
1210 TreeToString(Indent);
1211 if (Tree.HasNextSibling())
1212 OS << ", ";
1213 } while (Tree.AdvanceSibling());
1214 if (NumElideArgs > 0)
1215 PrintElideArgs(NumElideArgs, Indent);
1216
1217 Tree.Parent();
1218 OS << ">";
1219 }
1220
1221 // To signal to the text printer that a certain text needs to be bolded,
1222 // a special character is injected into the character stream which the
1223 // text printer will later strip out.
1224
1225 /// Bold - Start bolding text.
1226 void Bold() {
1227 assert(!IsBold && "Attempting to bold text that is already bold.");
1228 IsBold = true;
1229 if (ShowColor)
1230 OS << ToggleHighlight;
1231 }
1232
1233 /// Unbold - Stop bolding text.
1234 void Unbold() {
1235 assert(IsBold && "Attempting to remove bold from unbold text.");
1236 IsBold = false;
1237 if (ShowColor)
1238 OS << ToggleHighlight;
1239 }
1240
1241 // Functions to print out the arguments and highlighting the difference.
1242
1243 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1244 /// typenames that are the same and attempt to disambiguate them by using
1245 /// canonical typenames.
1246 void PrintTypeNames(QualType FromType, QualType ToType,
1247 bool FromDefault, bool ToDefault, bool Same) {
1248 assert((!FromType.isNull() || !ToType.isNull()) &&
1249 "Only one template argument may be missing.");
1250
1251 if (Same) {
1252 OS << FromType.getAsString();
1253 return;
1254 }
1255
Richard Trieub7243852012-09-28 20:32:51 +00001256 if (!FromType.isNull() && !ToType.isNull() &&
1257 FromType.getLocalUnqualifiedType() ==
1258 ToType.getLocalUnqualifiedType()) {
1259 Qualifiers FromQual = FromType.getLocalQualifiers(),
1260 ToQual = ToType.getLocalQualifiers(),
1261 CommonQual;
1262 PrintQualifiers(FromQual, ToQual);
1263 FromType.getLocalUnqualifiedType().print(OS, Policy);
1264 return;
1265 }
1266
Richard Trieu91844232012-06-26 18:18:47 +00001267 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1268 : FromType.getAsString();
1269 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1270 : ToType.getAsString();
1271 // Switch to canonical typename if it is better.
1272 // TODO: merge this with other aka printing above.
1273 if (FromTypeStr == ToTypeStr) {
1274 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1275 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1276 if (FromCanTypeStr != ToCanTypeStr) {
1277 FromTypeStr = FromCanTypeStr;
1278 ToTypeStr = ToCanTypeStr;
1279 }
1280 }
1281
1282 if (PrintTree) OS << '[';
1283 OS << (FromDefault ? "(default) " : "");
1284 Bold();
1285 OS << FromTypeStr;
1286 Unbold();
1287 if (PrintTree) {
1288 OS << " != " << (ToDefault ? "(default) " : "");
1289 Bold();
1290 OS << ToTypeStr;
1291 Unbold();
1292 OS << "]";
1293 }
1294 return;
1295 }
1296
1297 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1298 /// differences.
1299 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1300 bool FromDefault, bool ToDefault, bool Same) {
1301 assert((FromExpr || ToExpr) &&
1302 "Only one template argument may be missing.");
1303 if (Same) {
1304 PrintExpr(FromExpr);
1305 } else if (!PrintTree) {
1306 OS << (FromDefault ? "(default) " : "");
1307 Bold();
1308 PrintExpr(FromExpr);
1309 Unbold();
1310 } else {
1311 OS << (FromDefault ? "[(default) " : "[");
1312 Bold();
1313 PrintExpr(FromExpr);
1314 Unbold();
1315 OS << " != " << (ToDefault ? "(default) " : "");
1316 Bold();
1317 PrintExpr(ToExpr);
1318 Unbold();
1319 OS << ']';
1320 }
1321 }
1322
1323 /// PrintExpr - Actual formatting and printing of expressions.
1324 void PrintExpr(const Expr *E) {
1325 if (!E)
1326 OS << "(no argument)";
1327 else
Richard Smith235341b2012-08-16 03:56:14 +00001328 E->printPretty(OS, 0, Policy); return;
Richard Trieu91844232012-06-26 18:18:47 +00001329 }
1330
1331 /// PrintTemplateTemplate - Handles printing of template template arguments,
1332 /// highlighting argument differences.
1333 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1334 bool FromDefault, bool ToDefault, bool Same) {
1335 assert((FromTD || ToTD) && "Only one template argument may be missing.");
Richard Trieue673d71a2013-01-31 02:47:46 +00001336
1337 std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
1338 std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
1339 if (FromTD && ToTD && FromName == ToName) {
1340 FromName = FromTD->getQualifiedNameAsString();
1341 ToName = ToTD->getQualifiedNameAsString();
1342 }
1343
Richard Trieu91844232012-06-26 18:18:47 +00001344 if (Same) {
1345 OS << "template " << FromTD->getNameAsString();
1346 } else if (!PrintTree) {
1347 OS << (FromDefault ? "(default) template " : "template ");
1348 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001349 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001350 Unbold();
1351 } else {
1352 OS << (FromDefault ? "[(default) template " : "[template ");
1353 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001354 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001355 Unbold();
1356 OS << " != " << (ToDefault ? "(default) template " : "template ");
1357 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001358 OS << ToName;
Richard Trieu91844232012-06-26 18:18:47 +00001359 Unbold();
1360 OS << ']';
1361 }
1362 }
1363
Richard Trieu6df89452012-11-01 21:29:28 +00001364 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1365 /// argument differences.
1366 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1367 bool IsValidFromInt, bool IsValidToInt, bool FromDefault,
1368 bool ToDefault, bool Same) {
1369 assert((IsValidFromInt || IsValidToInt) &&
1370 "Only one integral argument may be missing.");
1371
1372 if (Same) {
1373 OS << FromInt.toString(10);
1374 } else if (!PrintTree) {
1375 OS << (FromDefault ? "(default) " : "");
1376 Bold();
1377 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1378 Unbold();
1379 } else {
1380 OS << (FromDefault ? "[(default) " : "[");
1381 Bold();
1382 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1383 Unbold();
1384 OS << " != " << (ToDefault ? "(default) " : "");
1385 Bold();
1386 OS << (IsValidToInt ? ToInt.toString(10) : "(no argument)");
1387 Unbold();
1388 OS << ']';
1389 }
1390 }
1391
Richard Trieu954aaaf2013-02-27 01:41:53 +00001392
1393 /// PrintDecl - Handles printing of Decl arguments, highlighting
1394 /// argument differences.
1395 void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
1396 bool FromDefault, bool ToDefault, bool Same) {
1397 assert((FromValueDecl || ToValueDecl) &&
1398 "Only one Decl argument may be NULL");
1399
1400 if (Same) {
1401 OS << FromValueDecl->getName();
1402 } else if (!PrintTree) {
1403 OS << (FromDefault ? "(default) " : "");
1404 Bold();
1405 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1406 Unbold();
1407 } else {
1408 OS << (FromDefault ? "[(default) " : "[");
1409 Bold();
1410 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1411 Unbold();
1412 OS << " != " << (ToDefault ? "(default) " : "");
1413 Bold();
1414 OS << (ToValueDecl ? ToValueDecl->getName() : "(no argument)");
1415 Unbold();
1416 OS << ']';
1417 }
1418
1419 }
1420
Richard Trieu91844232012-06-26 18:18:47 +00001421 // Prints the appropriate placeholder for elided template arguments.
1422 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1423 if (PrintTree) {
1424 OS << '\n';
1425 for (unsigned i = 0; i < Indent; ++i)
1426 OS << " ";
1427 }
1428 if (NumElideArgs == 0) return;
1429 if (NumElideArgs == 1)
1430 OS << "[...]";
1431 else
1432 OS << "[" << NumElideArgs << " * ...]";
1433 }
1434
Richard Trieub7243852012-09-28 20:32:51 +00001435 // Prints and highlights differences in Qualifiers.
1436 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1437 // Both types have no qualifiers
1438 if (FromQual.empty() && ToQual.empty())
1439 return;
1440
1441 // Both types have same qualifiers
1442 if (FromQual == ToQual) {
1443 PrintQualifier(FromQual, /*ApplyBold*/false);
1444 return;
1445 }
1446
1447 // Find common qualifiers and strip them from FromQual and ToQual.
1448 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1449 ToQual);
1450
1451 // The qualifiers are printed before the template name.
1452 // Inline printing:
1453 // The common qualifiers are printed. Then, qualifiers only in this type
1454 // are printed and highlighted. Finally, qualifiers only in the other
1455 // type are printed and highlighted inside parentheses after "missing".
1456 // Tree printing:
1457 // Qualifiers are printed next to each other, inside brackets, and
1458 // separated by "!=". The printing order is:
1459 // common qualifiers, highlighted from qualifiers, "!=",
1460 // common qualifiers, highlighted to qualifiers
1461 if (PrintTree) {
1462 OS << "[";
1463 if (CommonQual.empty() && FromQual.empty()) {
1464 Bold();
1465 OS << "(no qualifiers) ";
1466 Unbold();
1467 } else {
1468 PrintQualifier(CommonQual, /*ApplyBold*/false);
1469 PrintQualifier(FromQual, /*ApplyBold*/true);
1470 }
1471 OS << "!= ";
1472 if (CommonQual.empty() && ToQual.empty()) {
1473 Bold();
1474 OS << "(no qualifiers)";
1475 Unbold();
1476 } else {
1477 PrintQualifier(CommonQual, /*ApplyBold*/false,
1478 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1479 PrintQualifier(ToQual, /*ApplyBold*/true,
1480 /*appendSpaceIfNonEmpty*/false);
1481 }
1482 OS << "] ";
1483 } else {
1484 PrintQualifier(CommonQual, /*ApplyBold*/false);
1485 PrintQualifier(FromQual, /*ApplyBold*/true);
1486 }
1487 }
1488
1489 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1490 bool AppendSpaceIfNonEmpty = true) {
1491 if (Q.empty()) return;
1492 if (ApplyBold) Bold();
1493 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1494 if (ApplyBold) Unbold();
1495 }
1496
Richard Trieu91844232012-06-26 18:18:47 +00001497public:
1498
Benjamin Kramer8de90462013-02-22 16:08:12 +00001499 TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
1500 QualType ToType, bool PrintTree, bool PrintFromType,
1501 bool ElideType, bool ShowColor)
Richard Trieu91844232012-06-26 18:18:47 +00001502 : Context(Context),
1503 Policy(Context.getLangOpts()),
1504 ElideType(ElideType),
1505 PrintTree(PrintTree),
1506 ShowColor(ShowColor),
1507 // When printing a single type, the FromType is the one printed.
1508 FromType(PrintFromType ? FromType : ToType),
1509 ToType(PrintFromType ? ToType : FromType),
Benjamin Kramer8de90462013-02-22 16:08:12 +00001510 OS(OS),
Richard Trieu91844232012-06-26 18:18:47 +00001511 IsBold(false) {
1512 }
1513
1514 /// DiffTemplate - Start the template type diffing.
1515 void DiffTemplate() {
Richard Trieub7243852012-09-28 20:32:51 +00001516 Qualifiers FromQual = FromType.getQualifiers(),
1517 ToQual = ToType.getQualifiers();
1518
Richard Trieu91844232012-06-26 18:18:47 +00001519 const TemplateSpecializationType *FromOrigTST =
1520 GetTemplateSpecializationType(Context, FromType);
1521 const TemplateSpecializationType *ToOrigTST =
1522 GetTemplateSpecializationType(Context, ToType);
1523
1524 // Only checking templates.
1525 if (!FromOrigTST || !ToOrigTST)
1526 return;
1527
1528 // Different base templates.
1529 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1530 return;
1531 }
1532
Richard Trieub7243852012-09-28 20:32:51 +00001533 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1534 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +00001535 Tree.SetNode(FromType, ToType);
Richard Trieub7243852012-09-28 20:32:51 +00001536 Tree.SetNode(FromQual, ToQual);
Richard Trieu91844232012-06-26 18:18:47 +00001537
1538 // Same base template, but different arguments.
1539 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1540 ToOrigTST->getTemplateName().getAsTemplateDecl());
1541
1542 DiffTemplate(FromOrigTST, ToOrigTST);
David Blaikie47e45182012-06-26 18:52:09 +00001543 }
Richard Trieu91844232012-06-26 18:18:47 +00001544
Benjamin Kramer6582c362013-02-22 16:13:34 +00001545 /// Emit - When the two types given are templated types with the same
Richard Trieu91844232012-06-26 18:18:47 +00001546 /// base template, a string representation of the type difference will be
Benjamin Kramer6582c362013-02-22 16:13:34 +00001547 /// emitted to the stream and return true. Otherwise, return false.
Benjamin Kramer8de90462013-02-22 16:08:12 +00001548 bool Emit() {
Richard Trieu91844232012-06-26 18:18:47 +00001549 Tree.StartTraverse();
1550 if (Tree.Empty())
1551 return false;
1552
1553 TreeToString();
1554 assert(!IsBold && "Bold is applied to end of string.");
Richard Trieu91844232012-06-26 18:18:47 +00001555 return true;
1556 }
1557}; // end class TemplateDiff
1558} // end namespace
1559
1560/// FormatTemplateTypeDiff - A helper static function to start the template
1561/// diff and return the properly formatted string. Returns true if the diff
1562/// is successful.
1563static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1564 QualType ToType, bool PrintTree,
1565 bool PrintFromType, bool ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +00001566 bool ShowColors, raw_ostream &OS) {
Richard Trieu91844232012-06-26 18:18:47 +00001567 if (PrintTree)
1568 PrintFromType = true;
Benjamin Kramer8de90462013-02-22 16:08:12 +00001569 TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
Richard Trieu91844232012-06-26 18:18:47 +00001570 ElideType, ShowColors);
1571 TD.DiffTemplate();
Benjamin Kramer8de90462013-02-22 16:08:12 +00001572 return TD.Emit();
Richard Trieu91844232012-06-26 18:18:47 +00001573}