blob: d4c96cf01e05bd617aed72f436001dde4c085a5a [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 {
Richard Trieub4cff112013-03-15 20:35:18 +0000406 public:
407 /// DiffKind - The difference in a DiffNode and which fields are used.
408 enum DiffKind {
409 /// Incomplete or invalid node.
410 Invalid,
411 /// Another level of templates, uses TemplateDecl and Qualifiers
412 Template,
413 /// Type difference, uses QualType
414 Type,
415 /// Expression difference, uses Expr
416 Expression,
417 /// Template argument difference, uses TemplateDecl
418 TemplateTemplate,
419 /// Integer difference, uses APSInt and Expr
420 Integer,
421 /// Declaration difference, uses ValueDecl
422 Declaration
423 };
424 private:
Richard Trieu91844232012-06-26 18:18:47 +0000425 /// DiffNode - The root node stores the original type. Each child node
426 /// stores template arguments of their parents. For templated types, the
427 /// template decl is also stored.
428 struct DiffNode {
Richard Trieub4cff112013-03-15 20:35:18 +0000429 DiffKind Kind;
430
Richard Trieu91844232012-06-26 18:18:47 +0000431 /// NextNode - The index of the next sibling node or 0.
432 unsigned NextNode;
433
434 /// ChildNode - The index of the first child node or 0.
435 unsigned ChildNode;
436
437 /// ParentNode - The index of the parent node.
438 unsigned ParentNode;
439
440 /// FromType, ToType - The type arguments.
441 QualType FromType, ToType;
442
443 /// FromExpr, ToExpr - The expression arguments.
444 Expr *FromExpr, *ToExpr;
445
446 /// FromTD, ToTD - The template decl for template template
447 /// arguments or the type arguments that are templates.
448 TemplateDecl *FromTD, *ToTD;
449
Richard Trieub7243852012-09-28 20:32:51 +0000450 /// FromQual, ToQual - Qualifiers for template types.
451 Qualifiers FromQual, ToQual;
452
Richard Trieu6df89452012-11-01 21:29:28 +0000453 /// FromInt, ToInt - APSInt's for integral arguments.
454 llvm::APSInt FromInt, ToInt;
455
456 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
457 bool IsValidFromInt, IsValidToInt;
458
Richard Trieu954aaaf2013-02-27 01:41:53 +0000459 /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
460 ValueDecl *FromValueDecl, *ToValueDecl;
461
Richard Trieu91844232012-06-26 18:18:47 +0000462 /// FromDefault, ToDefault - Whether the argument is a default argument.
463 bool FromDefault, ToDefault;
464
465 /// Same - Whether the two arguments evaluate to the same value.
466 bool Same;
467
468 DiffNode(unsigned ParentNode = 0)
Richard Trieub4cff112013-03-15 20:35:18 +0000469 : Kind(Invalid), NextNode(0), ChildNode(0), ParentNode(ParentNode),
Richard Trieu91844232012-06-26 18:18:47 +0000470 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
Richard Trieu954aaaf2013-02-27 01:41:53 +0000471 IsValidFromInt(false), IsValidToInt(false), FromValueDecl(0),
472 ToValueDecl(0), FromDefault(false), ToDefault(false), Same(false) { }
Richard Trieu91844232012-06-26 18:18:47 +0000473 };
474
475 /// FlatTree - A flattened tree used to store the DiffNodes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000476 SmallVector<DiffNode, 16> FlatTree;
Richard Trieu91844232012-06-26 18:18:47 +0000477
478 /// CurrentNode - The index of the current node being used.
479 unsigned CurrentNode;
480
481 /// NextFreeNode - The index of the next unused node. Used when creating
482 /// child nodes.
483 unsigned NextFreeNode;
484
485 /// ReadNode - The index of the current node being read.
486 unsigned ReadNode;
487
488 public:
489 DiffTree() :
490 CurrentNode(0), NextFreeNode(1) {
491 FlatTree.push_back(DiffNode());
492 }
493
494 // Node writing functions.
495 /// SetNode - Sets FromTD and ToTD of the current node.
496 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
497 FlatTree[CurrentNode].FromTD = FromTD;
498 FlatTree[CurrentNode].ToTD = ToTD;
499 }
500
501 /// SetNode - Sets FromType and ToType of the current node.
502 void SetNode(QualType FromType, QualType ToType) {
503 FlatTree[CurrentNode].FromType = FromType;
504 FlatTree[CurrentNode].ToType = ToType;
505 }
506
507 /// SetNode - Set FromExpr and ToExpr of the current node.
508 void SetNode(Expr *FromExpr, Expr *ToExpr) {
509 FlatTree[CurrentNode].FromExpr = FromExpr;
510 FlatTree[CurrentNode].ToExpr = ToExpr;
511 }
512
Richard Trieu6df89452012-11-01 21:29:28 +0000513 /// SetNode - Set FromInt and ToInt of the current node.
514 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
515 bool IsValidFromInt, bool IsValidToInt) {
516 FlatTree[CurrentNode].FromInt = FromInt;
517 FlatTree[CurrentNode].ToInt = ToInt;
518 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
519 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
520 }
521
Richard Trieub7243852012-09-28 20:32:51 +0000522 /// SetNode - Set FromQual and ToQual of the current node.
523 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
524 FlatTree[CurrentNode].FromQual = FromQual;
525 FlatTree[CurrentNode].ToQual = ToQual;
526 }
527
Richard Trieu954aaaf2013-02-27 01:41:53 +0000528 /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
529 void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl) {
530 FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
531 FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
532 }
533
Richard Trieu91844232012-06-26 18:18:47 +0000534 /// SetSame - Sets the same flag of the current node.
535 void SetSame(bool Same) {
536 FlatTree[CurrentNode].Same = Same;
537 }
538
539 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
540 void SetDefault(bool FromDefault, bool ToDefault) {
541 FlatTree[CurrentNode].FromDefault = FromDefault;
542 FlatTree[CurrentNode].ToDefault = ToDefault;
543 }
544
Richard Trieub4cff112013-03-15 20:35:18 +0000545 /// SetKind - Sets the current node's type.
546 void SetKind(DiffKind Kind) {
547 FlatTree[CurrentNode].Kind = Kind;
548 }
549
Richard Trieu91844232012-06-26 18:18:47 +0000550 /// Up - Changes the node to the parent of the current node.
551 void Up() {
552 CurrentNode = FlatTree[CurrentNode].ParentNode;
553 }
554
555 /// AddNode - Adds a child node to the current node, then sets that node
556 /// node as the current node.
557 void AddNode() {
558 FlatTree.push_back(DiffNode(CurrentNode));
559 DiffNode &Node = FlatTree[CurrentNode];
560 if (Node.ChildNode == 0) {
561 // If a child node doesn't exist, add one.
562 Node.ChildNode = NextFreeNode;
563 } else {
564 // If a child node exists, find the last child node and add a
565 // next node to it.
566 unsigned i;
567 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
568 i = FlatTree[i].NextNode) {
569 }
570 FlatTree[i].NextNode = NextFreeNode;
571 }
572 CurrentNode = NextFreeNode;
573 ++NextFreeNode;
574 }
575
576 // Node reading functions.
577 /// StartTraverse - Prepares the tree for recursive traversal.
578 void StartTraverse() {
579 ReadNode = 0;
580 CurrentNode = NextFreeNode;
581 NextFreeNode = 0;
582 }
583
584 /// Parent - Move the current read node to its parent.
585 void Parent() {
586 ReadNode = FlatTree[ReadNode].ParentNode;
587 }
588
Richard Trieu91844232012-06-26 18:18:47 +0000589 /// GetNode - Gets the FromType and ToType.
590 void GetNode(QualType &FromType, QualType &ToType) {
591 FromType = FlatTree[ReadNode].FromType;
592 ToType = FlatTree[ReadNode].ToType;
593 }
594
595 /// GetNode - Gets the FromExpr and ToExpr.
596 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
597 FromExpr = FlatTree[ReadNode].FromExpr;
598 ToExpr = FlatTree[ReadNode].ToExpr;
599 }
600
601 /// GetNode - Gets the FromTD and ToTD.
602 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
603 FromTD = FlatTree[ReadNode].FromTD;
604 ToTD = FlatTree[ReadNode].ToTD;
605 }
606
Richard Trieu6df89452012-11-01 21:29:28 +0000607 /// GetNode - Gets the FromInt and ToInt.
608 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
609 bool &IsValidFromInt, bool &IsValidToInt) {
610 FromInt = FlatTree[ReadNode].FromInt;
611 ToInt = FlatTree[ReadNode].ToInt;
612 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
613 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
614 }
615
Richard Trieub7243852012-09-28 20:32:51 +0000616 /// GetNode - Gets the FromQual and ToQual.
617 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
618 FromQual = FlatTree[ReadNode].FromQual;
619 ToQual = FlatTree[ReadNode].ToQual;
620 }
621
Richard Trieu954aaaf2013-02-27 01:41:53 +0000622 /// GetNode - Gets the FromValueDecl and ToValueDecl.
623 void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl) {
624 FromValueDecl = FlatTree[ReadNode].FromValueDecl;
625 ToValueDecl = FlatTree[ReadNode].ToValueDecl;
626 }
627
Richard Trieu91844232012-06-26 18:18:47 +0000628 /// NodeIsSame - Returns true the arguments are the same.
629 bool NodeIsSame() {
630 return FlatTree[ReadNode].Same;
631 }
632
633 /// HasChildrend - Returns true if the node has children.
634 bool HasChildren() {
635 return FlatTree[ReadNode].ChildNode != 0;
636 }
637
638 /// MoveToChild - Moves from the current node to its child.
639 void MoveToChild() {
640 ReadNode = FlatTree[ReadNode].ChildNode;
641 }
642
643 /// AdvanceSibling - If there is a next sibling, advance to it and return
644 /// true. Otherwise, return false.
645 bool AdvanceSibling() {
646 if (FlatTree[ReadNode].NextNode == 0)
647 return false;
648
649 ReadNode = FlatTree[ReadNode].NextNode;
650 return true;
651 }
652
653 /// HasNextSibling - Return true if the node has a next sibling.
654 bool HasNextSibling() {
655 return FlatTree[ReadNode].NextNode != 0;
656 }
657
658 /// FromDefault - Return true if the from argument is the default.
659 bool FromDefault() {
660 return FlatTree[ReadNode].FromDefault;
661 }
662
663 /// ToDefault - Return true if the to argument is the default.
664 bool ToDefault() {
665 return FlatTree[ReadNode].ToDefault;
666 }
667
668 /// Empty - Returns true if the tree has no information.
669 bool Empty() {
Richard Trieub4cff112013-03-15 20:35:18 +0000670 return GetKind() == Invalid;
671 }
672
673 /// GetKind - Returns the current node's type.
674 DiffKind GetKind() {
675 return FlatTree[ReadNode].Kind;
Richard Trieu91844232012-06-26 18:18:47 +0000676 }
677 };
678
679 DiffTree Tree;
680
681 /// TSTiterator - an iterator that is used to enter a
682 /// TemplateSpecializationType and read TemplateArguments inside template
683 /// parameter packs in order with the rest of the TemplateArguments.
684 struct TSTiterator {
685 typedef const TemplateArgument& reference;
686 typedef const TemplateArgument* pointer;
687
688 /// TST - the template specialization whose arguments this iterator
689 /// traverse over.
690 const TemplateSpecializationType *TST;
691
692 /// Index - the index of the template argument in TST.
693 unsigned Index;
694
695 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
696 /// points to a TemplateArgument within a parameter pack.
697 TemplateArgument::pack_iterator CurrentTA;
698
699 /// EndTA - the end iterator of a parameter pack
700 TemplateArgument::pack_iterator EndTA;
701
702 /// TSTiterator - Constructs an iterator and sets it to the first template
703 /// argument.
704 TSTiterator(const TemplateSpecializationType *TST)
705 : TST(TST), Index(0), CurrentTA(0), EndTA(0) {
706 if (isEnd()) return;
707
708 // Set to first template argument. If not a parameter pack, done.
709 TemplateArgument TA = TST->getArg(0);
710 if (TA.getKind() != TemplateArgument::Pack) return;
711
712 // Start looking into the parameter pack.
713 CurrentTA = TA.pack_begin();
714 EndTA = TA.pack_end();
715
716 // Found a valid template argument.
717 if (CurrentTA != EndTA) return;
718
719 // Parameter pack is empty, use the increment to get to a valid
720 // template argument.
721 ++(*this);
722 }
723
724 /// isEnd - Returns true if the iterator is one past the end.
725 bool isEnd() const {
726 return Index == TST->getNumArgs();
727 }
728
729 /// &operator++ - Increment the iterator to the next template argument.
730 TSTiterator &operator++() {
731 assert(!isEnd() && "Iterator incremented past end of arguments.");
732
733 // If in a parameter pack, advance in the parameter pack.
734 if (CurrentTA != EndTA) {
735 ++CurrentTA;
736 if (CurrentTA != EndTA)
737 return *this;
738 }
739
740 // Loop until a template argument is found, or the end is reached.
741 while (true) {
742 // Advance to the next template argument. Break if reached the end.
743 if (++Index == TST->getNumArgs()) break;
744
745 // If the TemplateArgument is not a parameter pack, done.
746 TemplateArgument TA = TST->getArg(Index);
747 if (TA.getKind() != TemplateArgument::Pack) break;
748
749 // Handle parameter packs.
750 CurrentTA = TA.pack_begin();
751 EndTA = TA.pack_end();
752
753 // If the parameter pack is empty, try to advance again.
754 if (CurrentTA != EndTA) break;
755 }
756 return *this;
757 }
758
759 /// operator* - Returns the appropriate TemplateArgument.
760 reference operator*() const {
761 assert(!isEnd() && "Index exceeds number of arguments.");
762 if (CurrentTA == EndTA)
763 return TST->getArg(Index);
764 else
765 return *CurrentTA;
766 }
767
768 /// operator-> - Allow access to the underlying TemplateArgument.
769 pointer operator->() const {
770 return &operator*();
771 }
772 };
773
774 // These functions build up the template diff tree, including functions to
775 // retrieve and compare template arguments.
776
777 static const TemplateSpecializationType * GetTemplateSpecializationType(
778 ASTContext &Context, QualType Ty) {
779 if (const TemplateSpecializationType *TST =
780 Ty->getAs<TemplateSpecializationType>())
781 return TST;
782
783 const RecordType *RT = Ty->getAs<RecordType>();
784
785 if (!RT)
786 return 0;
787
788 const ClassTemplateSpecializationDecl *CTSD =
789 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
790
791 if (!CTSD)
792 return 0;
793
794 Ty = Context.getTemplateSpecializationType(
795 TemplateName(CTSD->getSpecializedTemplate()),
796 CTSD->getTemplateArgs().data(),
797 CTSD->getTemplateArgs().size(),
798 Ty.getCanonicalType());
799
800 return Ty->getAs<TemplateSpecializationType>();
801 }
802
803 /// DiffTemplate - recursively visits template arguments and stores the
804 /// argument info into a tree.
805 void DiffTemplate(const TemplateSpecializationType *FromTST,
806 const TemplateSpecializationType *ToTST) {
807 // Begin descent into diffing template tree.
808 TemplateParameterList *Params =
809 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
810 unsigned TotalArgs = 0;
811 for (TSTiterator FromIter(FromTST), ToIter(ToTST);
812 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
813 Tree.AddNode();
814
815 // Get the parameter at index TotalArgs. If index is larger
816 // than the total number of parameters, then there is an
817 // argument pack, so re-use the last parameter.
818 NamedDecl *ParamND = Params->getParam(
819 (TotalArgs < Params->size()) ? TotalArgs
820 : Params->size() - 1);
821 // Handle Types
822 if (TemplateTypeParmDecl *DefaultTTPD =
823 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
824 QualType FromType, ToType;
825 GetType(FromIter, DefaultTTPD, FromType);
826 GetType(ToIter, DefaultTTPD, ToType);
827 Tree.SetNode(FromType, ToType);
828 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
829 ToIter.isEnd() && !ToType.isNull());
Richard Trieub4cff112013-03-15 20:35:18 +0000830 Tree.SetKind(DiffTree::Type);
Richard Trieu91844232012-06-26 18:18:47 +0000831 if (!FromType.isNull() && !ToType.isNull()) {
832 if (Context.hasSameType(FromType, ToType)) {
833 Tree.SetSame(true);
834 } else {
Richard Trieub7243852012-09-28 20:32:51 +0000835 Qualifiers FromQual = FromType.getQualifiers(),
836 ToQual = ToType.getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +0000837 const TemplateSpecializationType *FromArgTST =
838 GetTemplateSpecializationType(Context, FromType);
839 const TemplateSpecializationType *ToArgTST =
840 GetTemplateSpecializationType(Context, ToType);
841
Richard Trieu8e14cac2012-09-28 19:51:57 +0000842 if (FromArgTST && ToArgTST &&
843 hasSameTemplate(FromArgTST, ToArgTST)) {
Richard Trieub7243852012-09-28 20:32:51 +0000844 FromQual -= QualType(FromArgTST, 0).getQualifiers();
845 ToQual -= QualType(ToArgTST, 0).getQualifiers();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000846 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
847 ToArgTST->getTemplateName().getAsTemplateDecl());
Richard Trieub7243852012-09-28 20:32:51 +0000848 Tree.SetNode(FromQual, ToQual);
Richard Trieub4cff112013-03-15 20:35:18 +0000849 Tree.SetKind(DiffTree::Template);
Richard Trieu8e14cac2012-09-28 19:51:57 +0000850 DiffTemplate(FromArgTST, ToArgTST);
Richard Trieu91844232012-06-26 18:18:47 +0000851 }
852 }
853 }
854 }
855
856 // Handle Expressions
857 if (NonTypeTemplateParmDecl *DefaultNTTPD =
858 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
859 Expr *FromExpr, *ToExpr;
Richard Trieu6df89452012-11-01 21:29:28 +0000860 llvm::APSInt FromInt, ToInt;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000861 ValueDecl *FromValueDecl = 0, *ToValueDecl = 0;
Douglas Gregor2d5a5612012-12-21 23:03:27 +0000862 unsigned ParamWidth = 128; // Safe default
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000863 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType())
864 ParamWidth = Context.getIntWidth(DefaultNTTPD->getType());
Richard Trieu6df89452012-11-01 21:29:28 +0000865 bool HasFromInt = !FromIter.isEnd() &&
866 FromIter->getKind() == TemplateArgument::Integral;
867 bool HasToInt = !ToIter.isEnd() &&
868 ToIter->getKind() == TemplateArgument::Integral;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000869 bool HasFromValueDecl =
870 !FromIter.isEnd() &&
871 FromIter->getKind() == TemplateArgument::Declaration;
872 bool HasToValueDecl =
873 !ToIter.isEnd() &&
874 ToIter->getKind() == TemplateArgument::Declaration;
875
876 assert(((!HasFromInt && !HasToInt) ||
877 (!HasFromValueDecl && !HasToValueDecl)) &&
878 "Template argument cannot be both integer and declaration");
Richard Trieu515dc0f2013-02-21 00:50:43 +0000879
Richard Trieu6df89452012-11-01 21:29:28 +0000880 if (HasFromInt)
881 FromInt = FromIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000882 else if (HasFromValueDecl)
883 FromValueDecl = FromIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000884 else
885 GetExpr(FromIter, DefaultNTTPD, FromExpr);
886
887 if (HasToInt)
888 ToInt = ToIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000889 else if (HasToValueDecl)
890 ToValueDecl = ToIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000891 else
892 GetExpr(ToIter, DefaultNTTPD, ToExpr);
893
Richard Trieu954aaaf2013-02-27 01:41:53 +0000894 if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
Richard Trieu6df89452012-11-01 21:29:28 +0000895 Tree.SetNode(FromExpr, ToExpr);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000896 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr));
Richard Trieu6df89452012-11-01 21:29:28 +0000897 Tree.SetDefault(FromIter.isEnd() && FromExpr,
898 ToIter.isEnd() && ToExpr);
Richard Trieub4cff112013-03-15 20:35:18 +0000899 Tree.SetKind(DiffTree::Expression);
Richard Trieu954aaaf2013-02-27 01:41:53 +0000900 } else if (HasFromInt || HasToInt) {
Richard Trieu6df89452012-11-01 21:29:28 +0000901 if (!HasFromInt && FromExpr) {
902 FromInt = FromExpr->EvaluateKnownConstInt(Context);
903 HasFromInt = true;
904 }
905 if (!HasToInt && ToExpr) {
906 ToInt = ToExpr->EvaluateKnownConstInt(Context);
907 HasToInt = true;
908 }
909 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000910 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
Richard Trieu6df89452012-11-01 21:29:28 +0000911 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
912 ToIter.isEnd() && HasToInt);
Richard Trieub4cff112013-03-15 20:35:18 +0000913 Tree.SetKind(DiffTree::Integer);
Richard Trieu954aaaf2013-02-27 01:41:53 +0000914 } else {
915 if (!HasFromValueDecl && FromExpr) {
916 DeclRefExpr *DRE = cast<DeclRefExpr>(FromExpr);
917 FromValueDecl = cast<ValueDecl>(DRE->getDecl());
918 }
919 if (!HasToValueDecl && ToExpr) {
920 DeclRefExpr *DRE = cast<DeclRefExpr>(ToExpr);
921 ToValueDecl = cast<ValueDecl>(DRE->getDecl());
922 }
923 Tree.SetNode(FromValueDecl, ToValueDecl);
924 Tree.SetSame(FromValueDecl->getCanonicalDecl() ==
925 ToValueDecl->getCanonicalDecl());
926 Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
927 ToIter.isEnd() && ToValueDecl);
Richard Trieub4cff112013-03-15 20:35:18 +0000928 Tree.SetKind(DiffTree::Declaration);
Richard Trieu6df89452012-11-01 21:29:28 +0000929 }
Richard Trieu91844232012-06-26 18:18:47 +0000930 }
931
932 // Handle Templates
933 if (TemplateTemplateParmDecl *DefaultTTPD =
934 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
935 TemplateDecl *FromDecl, *ToDecl;
936 GetTemplateDecl(FromIter, DefaultTTPD, FromDecl);
937 GetTemplateDecl(ToIter, DefaultTTPD, ToDecl);
938 Tree.SetNode(FromDecl, ToDecl);
Richard Trieue673d71a2013-01-31 02:47:46 +0000939 Tree.SetSame(
940 FromDecl && ToDecl &&
941 FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
Richard Trieub4cff112013-03-15 20:35:18 +0000942 Tree.SetKind(DiffTree::TemplateTemplate);
Richard Trieu91844232012-06-26 18:18:47 +0000943 }
944
945 if (!FromIter.isEnd()) ++FromIter;
946 if (!ToIter.isEnd()) ++ToIter;
947 Tree.Up();
948 }
949 }
950
Richard Trieu8e14cac2012-09-28 19:51:57 +0000951 /// makeTemplateList - Dump every template alias into the vector.
952 static void makeTemplateList(
953 SmallVector<const TemplateSpecializationType*, 1> &TemplateList,
954 const TemplateSpecializationType *TST) {
955 while (TST) {
956 TemplateList.push_back(TST);
957 if (!TST->isTypeAlias())
958 return;
959 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
960 }
961 }
962
963 /// hasSameBaseTemplate - Returns true when the base templates are the same,
964 /// even if the template arguments are not.
965 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
966 const TemplateSpecializationType *ToTST) {
Douglas Gregor8e9f55f2013-01-31 01:08:35 +0000967 return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
968 ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000969 }
970
Richard Trieu91844232012-06-26 18:18:47 +0000971 /// hasSameTemplate - Returns true if both types are specialized from the
972 /// same template declaration. If they come from different template aliases,
973 /// do a parallel ascension search to determine the highest template alias in
974 /// common and set the arguments to them.
975 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
976 const TemplateSpecializationType *&ToTST) {
977 // Check the top templates if they are the same.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000978 if (hasSameBaseTemplate(FromTST, ToTST))
Richard Trieu91844232012-06-26 18:18:47 +0000979 return true;
980
981 // Create vectors of template aliases.
982 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
983 ToTemplateList;
984
Richard Trieu8e14cac2012-09-28 19:51:57 +0000985 makeTemplateList(FromTemplateList, FromTST);
986 makeTemplateList(ToTemplateList, ToTST);
Richard Trieu91844232012-06-26 18:18:47 +0000987
988 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
989 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
990 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
991
992 // Check if the lowest template types are the same. If not, return.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000993 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +0000994 return false;
995
996 // Begin searching up the template aliases. The bottom most template
997 // matches so move up until one pair does not match. Use the template
998 // right before that one.
999 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
Richard Trieu8e14cac2012-09-28 19:51:57 +00001000 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +00001001 break;
1002 }
1003
1004 FromTST = FromIter[-1];
1005 ToTST = ToIter[-1];
1006
1007 return true;
1008 }
1009
1010 /// GetType - Retrieves the template type arguments, including default
1011 /// arguments.
1012 void GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD,
1013 QualType &ArgType) {
1014 ArgType = QualType();
1015 bool isVariadic = DefaultTTPD->isParameterPack();
1016
1017 if (!Iter.isEnd())
1018 ArgType = Iter->getAsType();
1019 else if (!isVariadic)
1020 ArgType = DefaultTTPD->getDefaultArgument();
David Blaikie47e45182012-06-26 18:52:09 +00001021 }
Richard Trieu91844232012-06-26 18:18:47 +00001022
1023 /// GetExpr - Retrieves the template expression argument, including default
1024 /// arguments.
1025 void GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD,
1026 Expr *&ArgExpr) {
1027 ArgExpr = 0;
1028 bool isVariadic = DefaultNTTPD->isParameterPack();
1029
1030 if (!Iter.isEnd())
1031 ArgExpr = Iter->getAsExpr();
1032 else if (!isVariadic)
1033 ArgExpr = DefaultNTTPD->getDefaultArgument();
1034
1035 if (ArgExpr)
1036 while (SubstNonTypeTemplateParmExpr *SNTTPE =
1037 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
1038 ArgExpr = SNTTPE->getReplacement();
1039 }
1040
1041 /// GetTemplateDecl - Retrieves the template template arguments, including
1042 /// default arguments.
1043 void GetTemplateDecl(const TSTiterator &Iter,
1044 TemplateTemplateParmDecl *DefaultTTPD,
1045 TemplateDecl *&ArgDecl) {
1046 ArgDecl = 0;
1047 bool isVariadic = DefaultTTPD->isParameterPack();
1048
1049 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
Eli Friedmanb826a002012-09-26 02:36:12 +00001050 TemplateDecl *DefaultTD = 0;
1051 if (TA.getKind() != TemplateArgument::Null)
1052 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
Richard Trieu91844232012-06-26 18:18:47 +00001053
1054 if (!Iter.isEnd())
1055 ArgDecl = Iter->getAsTemplate().getAsTemplateDecl();
1056 else if (!isVariadic)
1057 ArgDecl = DefaultTD;
1058 }
1059
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001060 /// IsSameConvertedInt - Returns true if both integers are equal when
1061 /// converted to an integer type with the given width.
1062 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1063 const llvm::APSInt &Y) {
1064 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1065 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1066 return ConvertedX == ConvertedY;
1067 }
1068
Richard Trieu91844232012-06-26 18:18:47 +00001069 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001070 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1071 Expr *FromExpr, Expr *ToExpr) {
Richard Trieu91844232012-06-26 18:18:47 +00001072 if (FromExpr == ToExpr)
1073 return true;
1074
1075 if (!FromExpr || !ToExpr)
1076 return false;
1077
1078 FromExpr = FromExpr->IgnoreParens();
1079 ToExpr = ToExpr->IgnoreParens();
1080
1081 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1082 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1083
1084 if (FromDRE || ToDRE) {
1085 if (!FromDRE || !ToDRE)
1086 return false;
1087 return FromDRE->getDecl() == ToDRE->getDecl();
1088 }
1089
1090 Expr::EvalResult FromResult, ToResult;
1091 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1092 !ToExpr->EvaluateAsRValue(ToResult, Context))
Douglas Gregor7c5c3782013-03-14 20:44:43 +00001093 return false;
Richard Trieu91844232012-06-26 18:18:47 +00001094
1095 APValue &FromVal = FromResult.Val;
1096 APValue &ToVal = ToResult.Val;
1097
1098 if (FromVal.getKind() != ToVal.getKind()) return false;
1099
1100 switch (FromVal.getKind()) {
1101 case APValue::Int:
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001102 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
Richard Trieu91844232012-06-26 18:18:47 +00001103 case APValue::LValue: {
1104 APValue::LValueBase FromBase = FromVal.getLValueBase();
1105 APValue::LValueBase ToBase = ToVal.getLValueBase();
1106 if (FromBase.isNull() && ToBase.isNull())
1107 return true;
1108 if (FromBase.isNull() || ToBase.isNull())
1109 return false;
1110 return FromBase.get<const ValueDecl*>() ==
1111 ToBase.get<const ValueDecl*>();
1112 }
1113 case APValue::MemberPointer:
1114 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1115 default:
1116 llvm_unreachable("Unknown template argument expression.");
1117 }
1118 }
1119
1120 // These functions converts the tree representation of the template
1121 // differences into the internal character vector.
1122
1123 /// TreeToString - Converts the Tree object into a character stream which
1124 /// will later be turned into the output string.
1125 void TreeToString(int Indent = 1) {
1126 if (PrintTree) {
1127 OS << '\n';
Benjamin Kramer6582c362013-02-22 16:13:34 +00001128 OS.indent(2 * Indent);
Richard Trieu91844232012-06-26 18:18:47 +00001129 ++Indent;
1130 }
1131
1132 // Handle cases where the difference is not templates with different
1133 // arguments.
Richard Trieub4cff112013-03-15 20:35:18 +00001134 switch (Tree.GetKind()) {
Richard Trieub4cff112013-03-15 20:35:18 +00001135 case DiffTree::Invalid:
1136 llvm_unreachable("Template diffing failed with bad DiffNode");
1137 case DiffTree::Type: {
Richard Trieu91844232012-06-26 18:18:47 +00001138 QualType FromType, ToType;
1139 Tree.GetNode(FromType, ToType);
1140 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1141 Tree.NodeIsSame());
1142 return;
1143 }
Richard Trieub4cff112013-03-15 20:35:18 +00001144 case DiffTree::Expression: {
Richard Trieu91844232012-06-26 18:18:47 +00001145 Expr *FromExpr, *ToExpr;
1146 Tree.GetNode(FromExpr, ToExpr);
1147 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1148 Tree.NodeIsSame());
1149 return;
1150 }
Richard Trieub4cff112013-03-15 20:35:18 +00001151 case DiffTree::TemplateTemplate: {
Richard Trieu91844232012-06-26 18:18:47 +00001152 TemplateDecl *FromTD, *ToTD;
1153 Tree.GetNode(FromTD, ToTD);
1154 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1155 Tree.ToDefault(), Tree.NodeIsSame());
1156 return;
1157 }
Richard Trieub4cff112013-03-15 20:35:18 +00001158 case DiffTree::Integer: {
Richard Trieu6df89452012-11-01 21:29:28 +00001159 llvm::APSInt FromInt, ToInt;
1160 bool IsValidFromInt, IsValidToInt;
1161 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1162 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1163 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1164 return;
1165 }
Richard Trieub4cff112013-03-15 20:35:18 +00001166 case DiffTree::Declaration: {
Richard Trieu954aaaf2013-02-27 01:41:53 +00001167 ValueDecl *FromValueDecl, *ToValueDecl;
1168 Tree.GetNode(FromValueDecl, ToValueDecl);
1169 PrintValueDecl(FromValueDecl, ToValueDecl, Tree.FromDefault(),
1170 Tree.ToDefault(), Tree.NodeIsSame());
1171 return;
1172 }
Richard Trieub4cff112013-03-15 20:35:18 +00001173 case DiffTree::Template: {
1174 // Node is root of template. Recurse on children.
1175 TemplateDecl *FromTD, *ToTD;
1176 Tree.GetNode(FromTD, ToTD);
Richard Trieu954aaaf2013-02-27 01:41:53 +00001177
Richard Trieub4cff112013-03-15 20:35:18 +00001178 if (!Tree.HasChildren()) {
1179 // If we're dealing with a template specialization with zero
1180 // arguments, there are no children; special-case this.
1181 OS << FromTD->getNameAsString() << "<>";
1182 return;
Richard Trieu91844232012-06-26 18:18:47 +00001183 }
Richard Trieub4cff112013-03-15 20:35:18 +00001184
1185 Qualifiers FromQual, ToQual;
1186 Tree.GetNode(FromQual, ToQual);
1187 PrintQualifiers(FromQual, ToQual);
1188
1189 OS << FromTD->getNameAsString() << '<';
1190 Tree.MoveToChild();
1191 unsigned NumElideArgs = 0;
1192 do {
1193 if (ElideType) {
1194 if (Tree.NodeIsSame()) {
1195 ++NumElideArgs;
1196 continue;
1197 }
1198 if (NumElideArgs > 0) {
1199 PrintElideArgs(NumElideArgs, Indent);
1200 NumElideArgs = 0;
1201 OS << ", ";
1202 }
1203 }
1204 TreeToString(Indent);
1205 if (Tree.HasNextSibling())
1206 OS << ", ";
1207 } while (Tree.AdvanceSibling());
1208 if (NumElideArgs > 0)
Richard Trieu91844232012-06-26 18:18:47 +00001209 PrintElideArgs(NumElideArgs, Indent);
Richard Trieu91844232012-06-26 18:18:47 +00001210
Richard Trieub4cff112013-03-15 20:35:18 +00001211 Tree.Parent();
1212 OS << ">";
1213 return;
1214 }
1215 }
Richard Trieu91844232012-06-26 18:18:47 +00001216 }
1217
1218 // To signal to the text printer that a certain text needs to be bolded,
1219 // a special character is injected into the character stream which the
1220 // text printer will later strip out.
1221
1222 /// Bold - Start bolding text.
1223 void Bold() {
1224 assert(!IsBold && "Attempting to bold text that is already bold.");
1225 IsBold = true;
1226 if (ShowColor)
1227 OS << ToggleHighlight;
1228 }
1229
1230 /// Unbold - Stop bolding text.
1231 void Unbold() {
1232 assert(IsBold && "Attempting to remove bold from unbold text.");
1233 IsBold = false;
1234 if (ShowColor)
1235 OS << ToggleHighlight;
1236 }
1237
1238 // Functions to print out the arguments and highlighting the difference.
1239
1240 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1241 /// typenames that are the same and attempt to disambiguate them by using
1242 /// canonical typenames.
1243 void PrintTypeNames(QualType FromType, QualType ToType,
1244 bool FromDefault, bool ToDefault, bool Same) {
1245 assert((!FromType.isNull() || !ToType.isNull()) &&
1246 "Only one template argument may be missing.");
1247
1248 if (Same) {
1249 OS << FromType.getAsString();
1250 return;
1251 }
1252
Richard Trieub7243852012-09-28 20:32:51 +00001253 if (!FromType.isNull() && !ToType.isNull() &&
1254 FromType.getLocalUnqualifiedType() ==
1255 ToType.getLocalUnqualifiedType()) {
1256 Qualifiers FromQual = FromType.getLocalQualifiers(),
1257 ToQual = ToType.getLocalQualifiers(),
1258 CommonQual;
1259 PrintQualifiers(FromQual, ToQual);
1260 FromType.getLocalUnqualifiedType().print(OS, Policy);
1261 return;
1262 }
1263
Richard Trieu91844232012-06-26 18:18:47 +00001264 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1265 : FromType.getAsString();
1266 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1267 : ToType.getAsString();
1268 // Switch to canonical typename if it is better.
1269 // TODO: merge this with other aka printing above.
1270 if (FromTypeStr == ToTypeStr) {
1271 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1272 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1273 if (FromCanTypeStr != ToCanTypeStr) {
1274 FromTypeStr = FromCanTypeStr;
1275 ToTypeStr = ToCanTypeStr;
1276 }
1277 }
1278
1279 if (PrintTree) OS << '[';
1280 OS << (FromDefault ? "(default) " : "");
1281 Bold();
1282 OS << FromTypeStr;
1283 Unbold();
1284 if (PrintTree) {
1285 OS << " != " << (ToDefault ? "(default) " : "");
1286 Bold();
1287 OS << ToTypeStr;
1288 Unbold();
1289 OS << "]";
1290 }
1291 return;
1292 }
1293
1294 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1295 /// differences.
1296 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1297 bool FromDefault, bool ToDefault, bool Same) {
1298 assert((FromExpr || ToExpr) &&
1299 "Only one template argument may be missing.");
1300 if (Same) {
1301 PrintExpr(FromExpr);
1302 } else if (!PrintTree) {
1303 OS << (FromDefault ? "(default) " : "");
1304 Bold();
1305 PrintExpr(FromExpr);
1306 Unbold();
1307 } else {
1308 OS << (FromDefault ? "[(default) " : "[");
1309 Bold();
1310 PrintExpr(FromExpr);
1311 Unbold();
1312 OS << " != " << (ToDefault ? "(default) " : "");
1313 Bold();
1314 PrintExpr(ToExpr);
1315 Unbold();
1316 OS << ']';
1317 }
1318 }
1319
1320 /// PrintExpr - Actual formatting and printing of expressions.
1321 void PrintExpr(const Expr *E) {
1322 if (!E)
1323 OS << "(no argument)";
1324 else
Richard Smith235341b2012-08-16 03:56:14 +00001325 E->printPretty(OS, 0, Policy); return;
Richard Trieu91844232012-06-26 18:18:47 +00001326 }
1327
1328 /// PrintTemplateTemplate - Handles printing of template template arguments,
1329 /// highlighting argument differences.
1330 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1331 bool FromDefault, bool ToDefault, bool Same) {
1332 assert((FromTD || ToTD) && "Only one template argument may be missing.");
Richard Trieue673d71a2013-01-31 02:47:46 +00001333
1334 std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
1335 std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
1336 if (FromTD && ToTD && FromName == ToName) {
1337 FromName = FromTD->getQualifiedNameAsString();
1338 ToName = ToTD->getQualifiedNameAsString();
1339 }
1340
Richard Trieu91844232012-06-26 18:18:47 +00001341 if (Same) {
1342 OS << "template " << FromTD->getNameAsString();
1343 } else if (!PrintTree) {
1344 OS << (FromDefault ? "(default) template " : "template ");
1345 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001346 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001347 Unbold();
1348 } else {
1349 OS << (FromDefault ? "[(default) template " : "[template ");
1350 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001351 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001352 Unbold();
1353 OS << " != " << (ToDefault ? "(default) template " : "template ");
1354 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001355 OS << ToName;
Richard Trieu91844232012-06-26 18:18:47 +00001356 Unbold();
1357 OS << ']';
1358 }
1359 }
1360
Richard Trieu6df89452012-11-01 21:29:28 +00001361 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1362 /// argument differences.
1363 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1364 bool IsValidFromInt, bool IsValidToInt, bool FromDefault,
1365 bool ToDefault, bool Same) {
1366 assert((IsValidFromInt || IsValidToInt) &&
1367 "Only one integral argument may be missing.");
1368
1369 if (Same) {
1370 OS << FromInt.toString(10);
1371 } else if (!PrintTree) {
1372 OS << (FromDefault ? "(default) " : "");
1373 Bold();
1374 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1375 Unbold();
1376 } else {
1377 OS << (FromDefault ? "[(default) " : "[");
1378 Bold();
1379 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1380 Unbold();
1381 OS << " != " << (ToDefault ? "(default) " : "");
1382 Bold();
1383 OS << (IsValidToInt ? ToInt.toString(10) : "(no argument)");
1384 Unbold();
1385 OS << ']';
1386 }
1387 }
1388
Richard Trieu954aaaf2013-02-27 01:41:53 +00001389
1390 /// PrintDecl - Handles printing of Decl arguments, highlighting
1391 /// argument differences.
1392 void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
1393 bool FromDefault, bool ToDefault, bool Same) {
1394 assert((FromValueDecl || ToValueDecl) &&
1395 "Only one Decl argument may be NULL");
1396
1397 if (Same) {
1398 OS << FromValueDecl->getName();
1399 } else if (!PrintTree) {
1400 OS << (FromDefault ? "(default) " : "");
1401 Bold();
1402 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1403 Unbold();
1404 } else {
1405 OS << (FromDefault ? "[(default) " : "[");
1406 Bold();
1407 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1408 Unbold();
1409 OS << " != " << (ToDefault ? "(default) " : "");
1410 Bold();
1411 OS << (ToValueDecl ? ToValueDecl->getName() : "(no argument)");
1412 Unbold();
1413 OS << ']';
1414 }
1415
1416 }
1417
Richard Trieu91844232012-06-26 18:18:47 +00001418 // Prints the appropriate placeholder for elided template arguments.
1419 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1420 if (PrintTree) {
1421 OS << '\n';
1422 for (unsigned i = 0; i < Indent; ++i)
1423 OS << " ";
1424 }
1425 if (NumElideArgs == 0) return;
1426 if (NumElideArgs == 1)
1427 OS << "[...]";
1428 else
1429 OS << "[" << NumElideArgs << " * ...]";
1430 }
1431
Richard Trieub7243852012-09-28 20:32:51 +00001432 // Prints and highlights differences in Qualifiers.
1433 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1434 // Both types have no qualifiers
1435 if (FromQual.empty() && ToQual.empty())
1436 return;
1437
1438 // Both types have same qualifiers
1439 if (FromQual == ToQual) {
1440 PrintQualifier(FromQual, /*ApplyBold*/false);
1441 return;
1442 }
1443
1444 // Find common qualifiers and strip them from FromQual and ToQual.
1445 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1446 ToQual);
1447
1448 // The qualifiers are printed before the template name.
1449 // Inline printing:
1450 // The common qualifiers are printed. Then, qualifiers only in this type
1451 // are printed and highlighted. Finally, qualifiers only in the other
1452 // type are printed and highlighted inside parentheses after "missing".
1453 // Tree printing:
1454 // Qualifiers are printed next to each other, inside brackets, and
1455 // separated by "!=". The printing order is:
1456 // common qualifiers, highlighted from qualifiers, "!=",
1457 // common qualifiers, highlighted to qualifiers
1458 if (PrintTree) {
1459 OS << "[";
1460 if (CommonQual.empty() && FromQual.empty()) {
1461 Bold();
1462 OS << "(no qualifiers) ";
1463 Unbold();
1464 } else {
1465 PrintQualifier(CommonQual, /*ApplyBold*/false);
1466 PrintQualifier(FromQual, /*ApplyBold*/true);
1467 }
1468 OS << "!= ";
1469 if (CommonQual.empty() && ToQual.empty()) {
1470 Bold();
1471 OS << "(no qualifiers)";
1472 Unbold();
1473 } else {
1474 PrintQualifier(CommonQual, /*ApplyBold*/false,
1475 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1476 PrintQualifier(ToQual, /*ApplyBold*/true,
1477 /*appendSpaceIfNonEmpty*/false);
1478 }
1479 OS << "] ";
1480 } else {
1481 PrintQualifier(CommonQual, /*ApplyBold*/false);
1482 PrintQualifier(FromQual, /*ApplyBold*/true);
1483 }
1484 }
1485
1486 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1487 bool AppendSpaceIfNonEmpty = true) {
1488 if (Q.empty()) return;
1489 if (ApplyBold) Bold();
1490 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1491 if (ApplyBold) Unbold();
1492 }
1493
Richard Trieu91844232012-06-26 18:18:47 +00001494public:
1495
Benjamin Kramer8de90462013-02-22 16:08:12 +00001496 TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
1497 QualType ToType, bool PrintTree, bool PrintFromType,
1498 bool ElideType, bool ShowColor)
Richard Trieu91844232012-06-26 18:18:47 +00001499 : Context(Context),
1500 Policy(Context.getLangOpts()),
1501 ElideType(ElideType),
1502 PrintTree(PrintTree),
1503 ShowColor(ShowColor),
1504 // When printing a single type, the FromType is the one printed.
1505 FromType(PrintFromType ? FromType : ToType),
1506 ToType(PrintFromType ? ToType : FromType),
Benjamin Kramer8de90462013-02-22 16:08:12 +00001507 OS(OS),
Richard Trieu91844232012-06-26 18:18:47 +00001508 IsBold(false) {
1509 }
1510
1511 /// DiffTemplate - Start the template type diffing.
1512 void DiffTemplate() {
Richard Trieub7243852012-09-28 20:32:51 +00001513 Qualifiers FromQual = FromType.getQualifiers(),
1514 ToQual = ToType.getQualifiers();
1515
Richard Trieu91844232012-06-26 18:18:47 +00001516 const TemplateSpecializationType *FromOrigTST =
1517 GetTemplateSpecializationType(Context, FromType);
1518 const TemplateSpecializationType *ToOrigTST =
1519 GetTemplateSpecializationType(Context, ToType);
1520
1521 // Only checking templates.
1522 if (!FromOrigTST || !ToOrigTST)
1523 return;
1524
1525 // Different base templates.
1526 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1527 return;
1528 }
1529
Richard Trieub7243852012-09-28 20:32:51 +00001530 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1531 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +00001532 Tree.SetNode(FromType, ToType);
Richard Trieub7243852012-09-28 20:32:51 +00001533 Tree.SetNode(FromQual, ToQual);
Richard Trieub4cff112013-03-15 20:35:18 +00001534 Tree.SetKind(DiffTree::Template);
Richard Trieu91844232012-06-26 18:18:47 +00001535
1536 // Same base template, but different arguments.
1537 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1538 ToOrigTST->getTemplateName().getAsTemplateDecl());
1539
1540 DiffTemplate(FromOrigTST, ToOrigTST);
David Blaikie47e45182012-06-26 18:52:09 +00001541 }
Richard Trieu91844232012-06-26 18:18:47 +00001542
Benjamin Kramer6582c362013-02-22 16:13:34 +00001543 /// Emit - When the two types given are templated types with the same
Richard Trieu91844232012-06-26 18:18:47 +00001544 /// base template, a string representation of the type difference will be
Benjamin Kramer6582c362013-02-22 16:13:34 +00001545 /// emitted to the stream and return true. Otherwise, return false.
Benjamin Kramer8de90462013-02-22 16:08:12 +00001546 bool Emit() {
Richard Trieu91844232012-06-26 18:18:47 +00001547 Tree.StartTraverse();
1548 if (Tree.Empty())
1549 return false;
1550
1551 TreeToString();
1552 assert(!IsBold && "Bold is applied to end of string.");
Richard Trieu91844232012-06-26 18:18:47 +00001553 return true;
1554 }
1555}; // end class TemplateDiff
1556} // end namespace
1557
1558/// FormatTemplateTypeDiff - A helper static function to start the template
1559/// diff and return the properly formatted string. Returns true if the diff
1560/// is successful.
1561static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1562 QualType ToType, bool PrintTree,
1563 bool PrintFromType, bool ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +00001564 bool ShowColors, raw_ostream &OS) {
Richard Trieu91844232012-06-26 18:18:47 +00001565 if (PrintTree)
1566 PrintFromType = true;
Benjamin Kramer8de90462013-02-22 16:08:12 +00001567 TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
Richard Trieu91844232012-06-26 18:18:47 +00001568 ElideType, ShowColors);
1569 TD.DiffTemplate();
Benjamin Kramer8de90462013-02-22 16:08:12 +00001570 return TD.Emit();
Richard Trieu91844232012-06-26 18:18:47 +00001571}