blob: bd5c209a9a5e84aa908979273a5f8aac3120eca4 [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"
Aaron Ballman3e424b52013-12-26 18:30:57 +000015#include "clang/AST/Attr.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000016#include "clang/AST/DeclObjC.h"
Richard Trieu91844232012-06-26 18:18:47 +000017#include "clang/AST/DeclTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/ExprCXX.h"
19#include "clang/AST/TemplateBase.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000020#include "clang/AST/Type.h"
Richard Trieu91844232012-06-26 18:18:47 +000021#include "llvm/ADT/SmallString.h"
Douglas Gregor639cccc2010-02-09 22:26:47 +000022#include "llvm/Support/raw_ostream.h"
23
24using namespace clang;
25
Chandler Carruthd102f2d2010-05-13 11:37:24 +000026// Returns a desugared version of the QualType, and marks ShouldAKA as true
27// whenever we remove significant sugar from the type.
28static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
29 QualifierCollector QC;
30
Douglas Gregor639cccc2010-02-09 22:26:47 +000031 while (true) {
Chandler Carruthd102f2d2010-05-13 11:37:24 +000032 const Type *Ty = QC.strip(QT);
33
Douglas Gregor639cccc2010-02-09 22:26:47 +000034 // Don't aka just because we saw an elaborated type...
Richard Smith30482bc2011-02-20 03:19:35 +000035 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
36 QT = ET->desugar();
Douglas Gregor639cccc2010-02-09 22:26:47 +000037 continue;
38 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +000039 // ... or a paren type ...
Richard Smith30482bc2011-02-20 03:19:35 +000040 if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
41 QT = PT->desugar();
Abramo Bagnara924a8f32010-12-10 16:29:40 +000042 continue;
43 }
Richard Smith30482bc2011-02-20 03:19:35 +000044 // ...or a substituted template type parameter ...
45 if (const SubstTemplateTypeParmType *ST =
46 dyn_cast<SubstTemplateTypeParmType>(Ty)) {
47 QT = ST->desugar();
48 continue;
49 }
John McCall4223a9e2011-03-04 04:00:19 +000050 // ...or an attributed type...
51 if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
52 QT = AT->desugar();
53 continue;
54 }
Reid Kleckner0503a872013-12-05 01:23:43 +000055 // ...or an adjusted type...
56 if (const AdjustedType *AT = dyn_cast<AdjustedType>(Ty)) {
57 QT = AT->desugar();
58 continue;
59 }
Richard Smith30482bc2011-02-20 03:19:35 +000060 // ... or an auto type.
61 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
62 if (!AT->isSugared())
63 break;
64 QT = AT->desugar();
Douglas Gregor639cccc2010-02-09 22:26:47 +000065 continue;
66 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +000067
Richard Smith3f1b5d02011-05-05 21:57:07 +000068 // Don't desugar template specializations, unless it's an alias template.
69 if (const TemplateSpecializationType *TST
70 = dyn_cast<TemplateSpecializationType>(Ty))
71 if (!TST->isTypeAlias())
72 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000073
Douglas Gregor639cccc2010-02-09 22:26:47 +000074 // Don't desugar magic Objective-C types.
75 if (QualType(Ty,0) == Context.getObjCIdType() ||
76 QualType(Ty,0) == Context.getObjCClassType() ||
77 QualType(Ty,0) == Context.getObjCSelType() ||
78 QualType(Ty,0) == Context.getObjCProtoType())
79 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000080
Douglas Gregor639cccc2010-02-09 22:26:47 +000081 // Don't desugar va_list.
82 if (QualType(Ty,0) == Context.getBuiltinVaListType())
83 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000084
Douglas Gregor639cccc2010-02-09 22:26:47 +000085 // Otherwise, do a single-step desugar.
86 QualType Underlying;
87 bool IsSugar = false;
88 switch (Ty->getTypeClass()) {
89#define ABSTRACT_TYPE(Class, Base)
90#define TYPE(Class, Base) \
91case Type::Class: { \
92const Class##Type *CTy = cast<Class##Type>(Ty); \
93if (CTy->isSugared()) { \
94IsSugar = true; \
95Underlying = CTy->desugar(); \
96} \
97break; \
98}
99#include "clang/AST/TypeNodes.def"
100 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000101
Douglas Gregor639cccc2010-02-09 22:26:47 +0000102 // If it wasn't sugared, we're done.
103 if (!IsSugar)
104 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000105
Douglas Gregor639cccc2010-02-09 22:26:47 +0000106 // If the desugared type is a vector type, we don't want to expand
107 // it, it will turn into an attribute mess. People want their "vec4".
108 if (isa<VectorType>(Underlying))
109 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000110
Douglas Gregor639cccc2010-02-09 22:26:47 +0000111 // Don't desugar through the primary typedef of an anonymous type.
Chris Lattneredbdff62010-09-04 23:16:01 +0000112 if (const TagType *UTT = Underlying->getAs<TagType>())
113 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
Richard Smithdda56e42011-04-15 14:24:37 +0000114 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
Chris Lattneredbdff62010-09-04 23:16:01 +0000115 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000116
117 // Record that we actually looked through an opaque type here.
118 ShouldAKA = true;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000119 QT = Underlying;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000120 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000121
122 // If we have a pointer-like type, desugar the pointee as well.
123 // FIXME: Handle other pointer-like types.
124 if (const PointerType *Ty = QT->getAs<PointerType>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000125 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
126 ShouldAKA));
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000127 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000128 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
129 ShouldAKA));
Douglas Gregor7a2a1162011-01-20 16:08:06 +0000130 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
131 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
132 ShouldAKA));
Douglas Gregor639cccc2010-02-09 22:26:47 +0000133 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000134
John McCall717d9b02010-12-10 11:01:00 +0000135 return QC.apply(Context, QT);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000136}
137
138/// \brief Convert the given type to a string suitable for printing as part of
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000139/// a diagnostic.
140///
Chandler Carruthd5173952011-07-11 17:49:21 +0000141/// There are four main criteria when determining whether we should have an
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000142/// a.k.a. clause when pretty-printing a type:
143///
144/// 1) Some types provide very minimal sugar that doesn't impede the
145/// user's understanding --- for example, elaborated type
146/// specifiers. If this is all the sugar we see, we don't want an
147/// a.k.a. clause.
148/// 2) Some types are technically sugared but are much more familiar
149/// when seen in their sugared form --- for example, va_list,
150/// vector types, and the magic Objective C types. We don't
151/// want to desugar these, even if we do produce an a.k.a. clause.
152/// 3) Some types may have already been desugared previously in this diagnostic.
153/// if this is the case, doing another "aka" would just be clutter.
Chandler Carruthd5173952011-07-11 17:49:21 +0000154/// 4) Two different types within the same diagnostic have the same output
155/// string. In this case, force an a.k.a with the desugared type when
156/// doing so will provide additional information.
Douglas Gregor639cccc2010-02-09 22:26:47 +0000157///
158/// \param Context the context in which the type was allocated
159/// \param Ty the type to print
Chandler Carruthd5173952011-07-11 17:49:21 +0000160/// \param QualTypeVals pointer values to QualTypes which are used in the
161/// diagnostic message
Douglas Gregor639cccc2010-02-09 22:26:47 +0000162static std::string
163ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
David Blaikie9c902b52011-09-25 23:23:43 +0000164 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000165 unsigned NumPrevArgs,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000166 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000167 // FIXME: Playing with std::string is really slow.
Chandler Carruthd5173952011-07-11 17:49:21 +0000168 bool ForceAKA = false;
169 QualType CanTy = Ty.getCanonicalType();
Douglas Gregorc0b07282011-09-27 22:38:19 +0000170 std::string S = Ty.getAsString(Context.getPrintingPolicy());
171 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000172
Bill Wendling8eb771d2012-02-22 09:51:33 +0000173 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
Chandler Carruthd5173952011-07-11 17:49:21 +0000174 QualType CompareTy =
Bill Wendling8eb771d2012-02-22 09:51:33 +0000175 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
Richard Smithbcc22fc2012-03-09 08:00:36 +0000176 if (CompareTy.isNull())
177 continue;
Chandler Carruthd5173952011-07-11 17:49:21 +0000178 if (CompareTy == Ty)
179 continue; // Same types
180 QualType CompareCanTy = CompareTy.getCanonicalType();
181 if (CompareCanTy == CanTy)
182 continue; // Same canonical types
Douglas Gregorc0b07282011-09-27 22:38:19 +0000183 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
Richard Trieu5d1aff02011-11-14 19:39:25 +0000184 bool aka;
185 QualType CompareDesugar = Desugar(Context, CompareTy, aka);
186 std::string CompareDesugarStr =
187 CompareDesugar.getAsString(Context.getPrintingPolicy());
188 if (CompareS != S && CompareDesugarStr != S)
189 continue; // The type string is different than the comparison string
190 // and the desugared comparison string.
191 std::string CompareCanS =
192 CompareCanTy.getAsString(Context.getPrintingPolicy());
193
Chandler Carruthd5173952011-07-11 17:49:21 +0000194 if (CompareCanS == CanS)
195 continue; // No new info from canonical type
196
197 ForceAKA = true;
198 break;
199 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000200
201 // Check to see if we already desugared this type in this
202 // diagnostic. If so, don't do it again.
203 bool Repeated = false;
204 for (unsigned i = 0; i != NumPrevArgs; ++i) {
205 // TODO: Handle ak_declcontext case.
David Blaikie9c902b52011-09-25 23:23:43 +0000206 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000207 void *Ptr = (void*)PrevArgs[i].second;
208 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
209 if (PrevTy == Ty) {
210 Repeated = true;
211 break;
212 }
213 }
214 }
215
Douglas Gregor639cccc2010-02-09 22:26:47 +0000216 // Consider producing an a.k.a. clause if removing all the direct
217 // sugar gives us something "significantly different".
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000218 if (!Repeated) {
219 bool ShouldAKA = false;
220 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
Chandler Carruthd5173952011-07-11 17:49:21 +0000221 if (ShouldAKA || ForceAKA) {
222 if (DesugaredTy == Ty) {
223 DesugaredTy = Ty.getCanonicalType();
224 }
Douglas Gregorc0b07282011-09-27 22:38:19 +0000225 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000226 if (akaStr != S) {
227 S = "'" + S + "' (aka '" + akaStr + "')";
228 return S;
229 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000230 }
Benjamin Kramer1adc8c32014-04-25 20:41:38 +0000231
232 // Give some additional info on vector types. These are either not desugared
233 // or displaying complex __attribute__ expressions so add details of the
234 // type and element count.
235 if (Ty->isVectorType()) {
236 const VectorType *VTy = Ty->getAs<VectorType>();
237 std::string DecoratedString;
238 llvm::raw_string_ostream OS(DecoratedString);
239 const char *Values = VTy->getNumElements() > 1 ? "values" : "value";
240 OS << "'" << S << "' (vector of " << VTy->getNumElements() << " '"
241 << VTy->getElementType().getAsString(Context.getPrintingPolicy())
242 << "' " << Values << ")";
243 return OS.str();
244 }
Douglas Gregor639cccc2010-02-09 22:26:47 +0000245 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000246
Douglas Gregor639cccc2010-02-09 22:26:47 +0000247 S = "'" + S + "'";
248 return S;
249}
250
Richard Trieu91844232012-06-26 18:18:47 +0000251static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
252 QualType ToType, bool PrintTree,
253 bool PrintFromType, bool ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +0000254 bool ShowColors, raw_ostream &OS);
Richard Trieu91844232012-06-26 18:18:47 +0000255
Chandler Carruthd5173952011-07-11 17:49:21 +0000256void clang::FormatASTNodeDiagnosticArgument(
David Blaikie9c902b52011-09-25 23:23:43 +0000257 DiagnosticsEngine::ArgumentKind Kind,
Chandler Carruthd5173952011-07-11 17:49:21 +0000258 intptr_t Val,
259 const char *Modifier,
260 unsigned ModLen,
261 const char *Argument,
262 unsigned ArgLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000263 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000264 unsigned NumPrevArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000265 SmallVectorImpl<char> &Output,
Chandler Carruthd5173952011-07-11 17:49:21 +0000266 void *Cookie,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000267 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000268 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
269
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000270 size_t OldEnd = Output.size();
271 llvm::raw_svector_ostream OS(Output);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000272 bool NeedQuotes = true;
273
274 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000275 default: llvm_unreachable("unknown ArgumentKind");
Richard Trieu91844232012-06-26 18:18:47 +0000276 case DiagnosticsEngine::ak_qualtype_pair: {
Richard Trieu50f5f462012-07-10 01:46:04 +0000277 TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
Richard Trieu91844232012-06-26 18:18:47 +0000278 QualType FromType =
279 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
280 QualType ToType =
281 QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
282
283 if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
284 TDT.PrintFromType, TDT.ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +0000285 TDT.ShowColors, OS)) {
Richard Trieu91844232012-06-26 18:18:47 +0000286 NeedQuotes = !TDT.PrintTree;
Richard Trieu50f5f462012-07-10 01:46:04 +0000287 TDT.TemplateDiffUsed = true;
Richard Trieu91844232012-06-26 18:18:47 +0000288 break;
289 }
290
291 // Don't fall-back during tree printing. The caller will handle
292 // this case.
293 if (TDT.PrintTree)
294 return;
295
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000296 // Attempting to do a template diff on non-templates. Set the variables
Richard Trieu91844232012-06-26 18:18:47 +0000297 // and continue with regular type printing of the appropriate type.
298 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
299 ModLen = 0;
300 ArgLen = 0;
301 // Fall through
302 }
David Blaikie9c902b52011-09-25 23:23:43 +0000303 case DiagnosticsEngine::ak_qualtype: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000304 assert(ModLen == 0 && ArgLen == 0 &&
305 "Invalid modifier for QualType argument");
306
307 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000308 OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs,
309 QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000310 NeedQuotes = false;
311 break;
312 }
David Blaikie9c902b52011-09-25 23:23:43 +0000313 case DiagnosticsEngine::ak_declarationname: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000314 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000315 OS << '+';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000316 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
317 && ArgLen==0)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000318 OS << '-';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000319 else
320 assert(ModLen == 0 && ArgLen == 0 &&
321 "Invalid modifier for DeclarationName argument");
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000322
David Blaikied4da8722013-05-14 21:04:00 +0000323 OS << DeclarationName::getFromOpaqueInteger(Val);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000324 break;
325 }
David Blaikie9c902b52011-09-25 23:23:43 +0000326 case DiagnosticsEngine::ak_nameddecl: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000327 bool Qualified;
328 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
329 Qualified = true;
330 else {
331 assert(ModLen == 0 && ArgLen == 0 &&
332 "Invalid modifier for NamedDecl* argument");
333 Qualified = false;
334 }
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000335 const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000336 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000337 break;
338 }
David Blaikie9c902b52011-09-25 23:23:43 +0000339 case DiagnosticsEngine::ak_nestednamespec: {
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000340 NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
341 NNS->print(OS, Context.getPrintingPolicy());
Douglas Gregor639cccc2010-02-09 22:26:47 +0000342 NeedQuotes = false;
343 break;
344 }
David Blaikie9c902b52011-09-25 23:23:43 +0000345 case DiagnosticsEngine::ak_declcontext: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000346 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
347 assert(DC && "Should never have a null declaration context");
348
349 if (DC->isTranslationUnit()) {
350 // FIXME: Get these strings from some localized place
David Blaikiebbafb8a2012-03-11 07:00:24 +0000351 if (Context.getLangOpts().CPlusPlus)
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000352 OS << "the global namespace";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000353 else
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000354 OS << "the global scope";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000355 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000356 OS << ConvertTypeToDiagnosticString(Context,
357 Context.getTypeDeclType(Type),
358 PrevArgs, NumPrevArgs,
359 QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000360 } else {
361 // FIXME: Get these strings from some localized place
362 NamedDecl *ND = cast<NamedDecl>(DC);
363 if (isa<NamespaceDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000364 OS << "namespace ";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000365 else if (isa<ObjCMethodDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000366 OS << "method ";
Douglas Gregor639cccc2010-02-09 22:26:47 +0000367 else if (isa<FunctionDecl>(ND))
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000368 OS << "function ";
369
370 OS << '\'';
371 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
372 OS << '\'';
Douglas Gregor639cccc2010-02-09 22:26:47 +0000373 }
374 NeedQuotes = false;
375 break;
376 }
David Majnemerb1004102014-03-02 18:46:05 +0000377 case DiagnosticsEngine::ak_attr: {
378 const Attr *At = reinterpret_cast<Attr *>(Val);
379 assert(At && "Received null Attr object!");
380 OS << '\'' << At->getSpelling() << '\'';
381 NeedQuotes = false;
382 break;
383 }
Aaron Ballman3e424b52013-12-26 18:30:57 +0000384
Douglas Gregor639cccc2010-02-09 22:26:47 +0000385 }
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000386
387 OS.flush();
388
389 if (NeedQuotes) {
390 Output.insert(Output.begin()+OldEnd, '\'');
Douglas Gregor639cccc2010-02-09 22:26:47 +0000391 Output.push_back('\'');
Benjamin Kramer7192c9e2013-02-22 15:46:08 +0000392 }
Douglas Gregor639cccc2010-02-09 22:26:47 +0000393}
Richard Trieu91844232012-06-26 18:18:47 +0000394
395/// TemplateDiff - A class that constructs a pretty string for a pair of
396/// QualTypes. For the pair of types, a diff tree will be created containing
397/// all the information about the templates and template arguments. Afterwards,
398/// the tree is transformed to a string according to the options passed in.
399namespace {
400class TemplateDiff {
401 /// Context - The ASTContext which is used for comparing template arguments.
402 ASTContext &Context;
403
404 /// Policy - Used during expression printing.
405 PrintingPolicy Policy;
406
407 /// ElideType - Option to elide identical types.
408 bool ElideType;
409
410 /// PrintTree - Format output string as a tree.
411 bool PrintTree;
412
413 /// ShowColor - Diagnostics support color, so bolding will be used.
414 bool ShowColor;
415
416 /// FromType - When single type printing is selected, this is the type to be
417 /// be printed. When tree printing is selected, this type will show up first
418 /// in the tree.
419 QualType FromType;
420
421 /// ToType - The type that FromType is compared to. Only in tree printing
422 /// will this type be outputed.
423 QualType ToType;
424
Richard Trieu91844232012-06-26 18:18:47 +0000425 /// OS - The stream used to construct the output strings.
Benjamin Kramer8de90462013-02-22 16:08:12 +0000426 raw_ostream &OS;
Richard Trieu91844232012-06-26 18:18:47 +0000427
428 /// IsBold - Keeps track of the bold formatting for the output string.
429 bool IsBold;
430
431 /// DiffTree - A tree representation the differences between two types.
432 class DiffTree {
Richard Trieub4cff112013-03-15 20:35:18 +0000433 public:
434 /// DiffKind - The difference in a DiffNode and which fields are used.
435 enum DiffKind {
436 /// Incomplete or invalid node.
437 Invalid,
438 /// Another level of templates, uses TemplateDecl and Qualifiers
439 Template,
440 /// Type difference, uses QualType
441 Type,
442 /// Expression difference, uses Expr
443 Expression,
444 /// Template argument difference, uses TemplateDecl
445 TemplateTemplate,
446 /// Integer difference, uses APSInt and Expr
447 Integer,
448 /// Declaration difference, uses ValueDecl
449 Declaration
450 };
451 private:
Richard Trieu91844232012-06-26 18:18:47 +0000452 /// DiffNode - The root node stores the original type. Each child node
453 /// stores template arguments of their parents. For templated types, the
454 /// template decl is also stored.
455 struct DiffNode {
Richard Trieub4cff112013-03-15 20:35:18 +0000456 DiffKind Kind;
457
Richard Trieu91844232012-06-26 18:18:47 +0000458 /// NextNode - The index of the next sibling node or 0.
459 unsigned NextNode;
460
461 /// ChildNode - The index of the first child node or 0.
462 unsigned ChildNode;
463
464 /// ParentNode - The index of the parent node.
465 unsigned ParentNode;
466
467 /// FromType, ToType - The type arguments.
468 QualType FromType, ToType;
469
470 /// FromExpr, ToExpr - The expression arguments.
471 Expr *FromExpr, *ToExpr;
472
473 /// FromTD, ToTD - The template decl for template template
474 /// arguments or the type arguments that are templates.
475 TemplateDecl *FromTD, *ToTD;
476
Richard Trieub7243852012-09-28 20:32:51 +0000477 /// FromQual, ToQual - Qualifiers for template types.
478 Qualifiers FromQual, ToQual;
479
Richard Trieu6df89452012-11-01 21:29:28 +0000480 /// FromInt, ToInt - APSInt's for integral arguments.
481 llvm::APSInt FromInt, ToInt;
482
483 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
484 bool IsValidFromInt, IsValidToInt;
485
Richard Trieu954aaaf2013-02-27 01:41:53 +0000486 /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
487 ValueDecl *FromValueDecl, *ToValueDecl;
488
Richard Trieu091872c52013-05-07 21:36:24 +0000489 /// FromAddressOf, ToAddressOf - Whether the ValueDecl needs an address of
490 /// operator before it.
491 bool FromAddressOf, ToAddressOf;
492
Richard Trieu91844232012-06-26 18:18:47 +0000493 /// FromDefault, ToDefault - Whether the argument is a default argument.
494 bool FromDefault, ToDefault;
495
496 /// Same - Whether the two arguments evaluate to the same value.
497 bool Same;
498
499 DiffNode(unsigned ParentNode = 0)
Richard Trieub4cff112013-03-15 20:35:18 +0000500 : Kind(Invalid), NextNode(0), ChildNode(0), ParentNode(ParentNode),
Craig Topper36250ad2014-05-12 05:36:57 +0000501 FromType(), ToType(), FromExpr(nullptr), ToExpr(nullptr),
502 FromTD(nullptr), ToTD(nullptr), IsValidFromInt(false),
503 IsValidToInt(false), FromValueDecl(nullptr), ToValueDecl(nullptr),
504 FromAddressOf(false), ToAddressOf(false), FromDefault(false),
505 ToDefault(false), Same(false) {}
Richard Trieu91844232012-06-26 18:18:47 +0000506 };
507
508 /// FlatTree - A flattened tree used to store the DiffNodes.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000509 SmallVector<DiffNode, 16> FlatTree;
Richard Trieu91844232012-06-26 18:18:47 +0000510
511 /// CurrentNode - The index of the current node being used.
512 unsigned CurrentNode;
513
514 /// NextFreeNode - The index of the next unused node. Used when creating
515 /// child nodes.
516 unsigned NextFreeNode;
517
518 /// ReadNode - The index of the current node being read.
519 unsigned ReadNode;
520
521 public:
522 DiffTree() :
523 CurrentNode(0), NextFreeNode(1) {
524 FlatTree.push_back(DiffNode());
525 }
526
527 // Node writing functions.
528 /// SetNode - Sets FromTD and ToTD of the current node.
529 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
530 FlatTree[CurrentNode].FromTD = FromTD;
531 FlatTree[CurrentNode].ToTD = ToTD;
532 }
533
534 /// SetNode - Sets FromType and ToType of the current node.
535 void SetNode(QualType FromType, QualType ToType) {
536 FlatTree[CurrentNode].FromType = FromType;
537 FlatTree[CurrentNode].ToType = ToType;
538 }
539
540 /// SetNode - Set FromExpr and ToExpr of the current node.
541 void SetNode(Expr *FromExpr, Expr *ToExpr) {
542 FlatTree[CurrentNode].FromExpr = FromExpr;
543 FlatTree[CurrentNode].ToExpr = ToExpr;
544 }
545
Richard Trieu6df89452012-11-01 21:29:28 +0000546 /// SetNode - Set FromInt and ToInt of the current node.
547 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
548 bool IsValidFromInt, bool IsValidToInt) {
549 FlatTree[CurrentNode].FromInt = FromInt;
550 FlatTree[CurrentNode].ToInt = ToInt;
551 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
552 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
553 }
554
Richard Trieub7243852012-09-28 20:32:51 +0000555 /// SetNode - Set FromQual and ToQual of the current node.
556 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
557 FlatTree[CurrentNode].FromQual = FromQual;
558 FlatTree[CurrentNode].ToQual = ToQual;
559 }
560
Richard Trieu954aaaf2013-02-27 01:41:53 +0000561 /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
Richard Trieu091872c52013-05-07 21:36:24 +0000562 void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
563 bool FromAddressOf, bool ToAddressOf) {
Richard Trieu954aaaf2013-02-27 01:41:53 +0000564 FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
565 FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
Richard Trieu091872c52013-05-07 21:36:24 +0000566 FlatTree[CurrentNode].FromAddressOf = FromAddressOf;
567 FlatTree[CurrentNode].ToAddressOf = ToAddressOf;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000568 }
569
Richard Trieu91844232012-06-26 18:18:47 +0000570 /// SetSame - Sets the same flag of the current node.
571 void SetSame(bool Same) {
572 FlatTree[CurrentNode].Same = Same;
573 }
574
575 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
576 void SetDefault(bool FromDefault, bool ToDefault) {
577 FlatTree[CurrentNode].FromDefault = FromDefault;
578 FlatTree[CurrentNode].ToDefault = ToDefault;
579 }
580
Richard Trieub4cff112013-03-15 20:35:18 +0000581 /// SetKind - Sets the current node's type.
582 void SetKind(DiffKind Kind) {
583 FlatTree[CurrentNode].Kind = Kind;
584 }
585
Richard Trieu91844232012-06-26 18:18:47 +0000586 /// Up - Changes the node to the parent of the current node.
587 void Up() {
588 CurrentNode = FlatTree[CurrentNode].ParentNode;
589 }
590
591 /// AddNode - Adds a child node to the current node, then sets that node
592 /// node as the current node.
593 void AddNode() {
594 FlatTree.push_back(DiffNode(CurrentNode));
595 DiffNode &Node = FlatTree[CurrentNode];
596 if (Node.ChildNode == 0) {
597 // If a child node doesn't exist, add one.
598 Node.ChildNode = NextFreeNode;
599 } else {
600 // If a child node exists, find the last child node and add a
601 // next node to it.
602 unsigned i;
603 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
604 i = FlatTree[i].NextNode) {
605 }
606 FlatTree[i].NextNode = NextFreeNode;
607 }
608 CurrentNode = NextFreeNode;
609 ++NextFreeNode;
610 }
611
612 // Node reading functions.
613 /// StartTraverse - Prepares the tree for recursive traversal.
614 void StartTraverse() {
615 ReadNode = 0;
616 CurrentNode = NextFreeNode;
617 NextFreeNode = 0;
618 }
619
620 /// Parent - Move the current read node to its parent.
621 void Parent() {
622 ReadNode = FlatTree[ReadNode].ParentNode;
623 }
624
Richard Trieu91844232012-06-26 18:18:47 +0000625 /// GetNode - Gets the FromType and ToType.
626 void GetNode(QualType &FromType, QualType &ToType) {
627 FromType = FlatTree[ReadNode].FromType;
628 ToType = FlatTree[ReadNode].ToType;
629 }
630
631 /// GetNode - Gets the FromExpr and ToExpr.
632 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
633 FromExpr = FlatTree[ReadNode].FromExpr;
634 ToExpr = FlatTree[ReadNode].ToExpr;
635 }
636
637 /// GetNode - Gets the FromTD and ToTD.
638 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
639 FromTD = FlatTree[ReadNode].FromTD;
640 ToTD = FlatTree[ReadNode].ToTD;
641 }
642
Richard Trieu6df89452012-11-01 21:29:28 +0000643 /// GetNode - Gets the FromInt and ToInt.
644 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
645 bool &IsValidFromInt, bool &IsValidToInt) {
646 FromInt = FlatTree[ReadNode].FromInt;
647 ToInt = FlatTree[ReadNode].ToInt;
648 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
649 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
650 }
651
Richard Trieub7243852012-09-28 20:32:51 +0000652 /// GetNode - Gets the FromQual and ToQual.
653 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
654 FromQual = FlatTree[ReadNode].FromQual;
655 ToQual = FlatTree[ReadNode].ToQual;
656 }
657
Richard Trieu954aaaf2013-02-27 01:41:53 +0000658 /// GetNode - Gets the FromValueDecl and ToValueDecl.
Richard Trieu091872c52013-05-07 21:36:24 +0000659 void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl,
660 bool &FromAddressOf, bool &ToAddressOf) {
Richard Trieu954aaaf2013-02-27 01:41:53 +0000661 FromValueDecl = FlatTree[ReadNode].FromValueDecl;
662 ToValueDecl = FlatTree[ReadNode].ToValueDecl;
Richard Trieu091872c52013-05-07 21:36:24 +0000663 FromAddressOf = FlatTree[ReadNode].FromAddressOf;
664 ToAddressOf = FlatTree[ReadNode].ToAddressOf;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000665 }
666
Richard Trieu91844232012-06-26 18:18:47 +0000667 /// NodeIsSame - Returns true the arguments are the same.
668 bool NodeIsSame() {
669 return FlatTree[ReadNode].Same;
670 }
671
672 /// HasChildrend - Returns true if the node has children.
673 bool HasChildren() {
674 return FlatTree[ReadNode].ChildNode != 0;
675 }
676
677 /// MoveToChild - Moves from the current node to its child.
678 void MoveToChild() {
679 ReadNode = FlatTree[ReadNode].ChildNode;
680 }
681
682 /// AdvanceSibling - If there is a next sibling, advance to it and return
683 /// true. Otherwise, return false.
684 bool AdvanceSibling() {
685 if (FlatTree[ReadNode].NextNode == 0)
686 return false;
687
688 ReadNode = FlatTree[ReadNode].NextNode;
689 return true;
690 }
691
692 /// HasNextSibling - Return true if the node has a next sibling.
693 bool HasNextSibling() {
694 return FlatTree[ReadNode].NextNode != 0;
695 }
696
697 /// FromDefault - Return true if the from argument is the default.
698 bool FromDefault() {
699 return FlatTree[ReadNode].FromDefault;
700 }
701
702 /// ToDefault - Return true if the to argument is the default.
703 bool ToDefault() {
704 return FlatTree[ReadNode].ToDefault;
705 }
706
707 /// Empty - Returns true if the tree has no information.
708 bool Empty() {
Richard Trieub4cff112013-03-15 20:35:18 +0000709 return GetKind() == Invalid;
710 }
711
712 /// GetKind - Returns the current node's type.
713 DiffKind GetKind() {
714 return FlatTree[ReadNode].Kind;
Richard Trieu91844232012-06-26 18:18:47 +0000715 }
716 };
717
718 DiffTree Tree;
719
720 /// TSTiterator - an iterator that is used to enter a
721 /// TemplateSpecializationType and read TemplateArguments inside template
722 /// parameter packs in order with the rest of the TemplateArguments.
723 struct TSTiterator {
724 typedef const TemplateArgument& reference;
725 typedef const TemplateArgument* pointer;
726
727 /// TST - the template specialization whose arguments this iterator
728 /// traverse over.
729 const TemplateSpecializationType *TST;
730
Richard Trieu64ab30392013-03-15 23:55:09 +0000731 /// DesugarTST - desugared template specialization used to extract
732 /// default argument information
733 const TemplateSpecializationType *DesugarTST;
734
Richard Trieu91844232012-06-26 18:18:47 +0000735 /// Index - the index of the template argument in TST.
736 unsigned Index;
737
738 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
739 /// points to a TemplateArgument within a parameter pack.
740 TemplateArgument::pack_iterator CurrentTA;
741
742 /// EndTA - the end iterator of a parameter pack
743 TemplateArgument::pack_iterator EndTA;
744
745 /// TSTiterator - Constructs an iterator and sets it to the first template
746 /// argument.
Richard Trieu64ab30392013-03-15 23:55:09 +0000747 TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST)
748 : TST(TST),
749 DesugarTST(GetTemplateSpecializationType(Context, TST->desugar())),
Craig Topper36250ad2014-05-12 05:36:57 +0000750 Index(0), CurrentTA(nullptr), EndTA(nullptr) {
Richard Trieu91844232012-06-26 18:18:47 +0000751 if (isEnd()) return;
752
753 // Set to first template argument. If not a parameter pack, done.
754 TemplateArgument TA = TST->getArg(0);
755 if (TA.getKind() != TemplateArgument::Pack) return;
756
757 // Start looking into the parameter pack.
758 CurrentTA = TA.pack_begin();
759 EndTA = TA.pack_end();
760
761 // Found a valid template argument.
762 if (CurrentTA != EndTA) return;
763
764 // Parameter pack is empty, use the increment to get to a valid
765 // template argument.
766 ++(*this);
767 }
768
769 /// isEnd - Returns true if the iterator is one past the end.
770 bool isEnd() const {
Richard Trieu64ab30392013-03-15 23:55:09 +0000771 return Index >= TST->getNumArgs();
Richard Trieu91844232012-06-26 18:18:47 +0000772 }
773
774 /// &operator++ - Increment the iterator to the next template argument.
775 TSTiterator &operator++() {
Richard Trieu64ab30392013-03-15 23:55:09 +0000776 // After the end, Index should be the default argument position in
777 // DesugarTST, if it exists.
778 if (isEnd()) {
779 ++Index;
780 return *this;
781 }
Richard Trieu91844232012-06-26 18:18:47 +0000782
783 // If in a parameter pack, advance in the parameter pack.
784 if (CurrentTA != EndTA) {
785 ++CurrentTA;
786 if (CurrentTA != EndTA)
787 return *this;
788 }
789
790 // Loop until a template argument is found, or the end is reached.
791 while (true) {
792 // Advance to the next template argument. Break if reached the end.
793 if (++Index == TST->getNumArgs()) break;
794
795 // If the TemplateArgument is not a parameter pack, done.
796 TemplateArgument TA = TST->getArg(Index);
797 if (TA.getKind() != TemplateArgument::Pack) break;
798
799 // Handle parameter packs.
800 CurrentTA = TA.pack_begin();
801 EndTA = TA.pack_end();
802
803 // If the parameter pack is empty, try to advance again.
804 if (CurrentTA != EndTA) break;
805 }
806 return *this;
807 }
808
809 /// operator* - Returns the appropriate TemplateArgument.
810 reference operator*() const {
811 assert(!isEnd() && "Index exceeds number of arguments.");
812 if (CurrentTA == EndTA)
813 return TST->getArg(Index);
814 else
815 return *CurrentTA;
816 }
817
818 /// operator-> - Allow access to the underlying TemplateArgument.
819 pointer operator->() const {
820 return &operator*();
821 }
Richard Trieu64ab30392013-03-15 23:55:09 +0000822
823 /// getDesugar - Returns the deduced template argument from DesguarTST
824 reference getDesugar() const {
825 return DesugarTST->getArg(Index);
826 }
Richard Trieu91844232012-06-26 18:18:47 +0000827 };
828
829 // These functions build up the template diff tree, including functions to
830 // retrieve and compare template arguments.
831
832 static const TemplateSpecializationType * GetTemplateSpecializationType(
833 ASTContext &Context, QualType Ty) {
834 if (const TemplateSpecializationType *TST =
835 Ty->getAs<TemplateSpecializationType>())
836 return TST;
837
838 const RecordType *RT = Ty->getAs<RecordType>();
839
840 if (!RT)
Craig Topper36250ad2014-05-12 05:36:57 +0000841 return nullptr;
Richard Trieu91844232012-06-26 18:18:47 +0000842
843 const ClassTemplateSpecializationDecl *CTSD =
844 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
845
846 if (!CTSD)
Craig Topper36250ad2014-05-12 05:36:57 +0000847 return nullptr;
Richard Trieu91844232012-06-26 18:18:47 +0000848
849 Ty = Context.getTemplateSpecializationType(
850 TemplateName(CTSD->getSpecializedTemplate()),
851 CTSD->getTemplateArgs().data(),
852 CTSD->getTemplateArgs().size(),
Richard Trieu3cee4132013-03-23 01:38:36 +0000853 Ty.getLocalUnqualifiedType().getCanonicalType());
Richard Trieu91844232012-06-26 18:18:47 +0000854
855 return Ty->getAs<TemplateSpecializationType>();
856 }
857
858 /// DiffTemplate - recursively visits template arguments and stores the
859 /// argument info into a tree.
860 void DiffTemplate(const TemplateSpecializationType *FromTST,
861 const TemplateSpecializationType *ToTST) {
862 // Begin descent into diffing template tree.
Benjamin Kramer3b05e202013-10-08 16:58:52 +0000863 TemplateParameterList *ParamsFrom =
Richard Trieu91844232012-06-26 18:18:47 +0000864 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
Benjamin Kramer3b05e202013-10-08 16:58:52 +0000865 TemplateParameterList *ParamsTo =
866 ToTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
Richard Trieu91844232012-06-26 18:18:47 +0000867 unsigned TotalArgs = 0;
Richard Trieu64ab30392013-03-15 23:55:09 +0000868 for (TSTiterator FromIter(Context, FromTST), ToIter(Context, ToTST);
Richard Trieu91844232012-06-26 18:18:47 +0000869 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
870 Tree.AddNode();
871
872 // Get the parameter at index TotalArgs. If index is larger
873 // than the total number of parameters, then there is an
874 // argument pack, so re-use the last parameter.
Benjamin Kramer3b05e202013-10-08 16:58:52 +0000875 unsigned ParamIndex = std::min(TotalArgs, ParamsFrom->size() - 1);
876 NamedDecl *ParamND = ParamsFrom->getParam(ParamIndex);
877
Richard Trieu91844232012-06-26 18:18:47 +0000878 // Handle Types
879 if (TemplateTypeParmDecl *DefaultTTPD =
880 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
881 QualType FromType, ToType;
Richard Trieu17f13ec2013-04-03 03:06:48 +0000882 FromType = GetType(FromIter, DefaultTTPD);
Benjamin Kramer3b05e202013-10-08 16:58:52 +0000883 // A forward declaration can have no default arg but the actual class
884 // can, don't mix up iterators and get the original parameter.
885 ToType = GetType(
886 ToIter, cast<TemplateTypeParmDecl>(ParamsTo->getParam(ParamIndex)));
Richard Trieu91844232012-06-26 18:18:47 +0000887 Tree.SetNode(FromType, ToType);
888 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
889 ToIter.isEnd() && !ToType.isNull());
Richard Trieub4cff112013-03-15 20:35:18 +0000890 Tree.SetKind(DiffTree::Type);
Richard Trieu91844232012-06-26 18:18:47 +0000891 if (!FromType.isNull() && !ToType.isNull()) {
892 if (Context.hasSameType(FromType, ToType)) {
893 Tree.SetSame(true);
894 } else {
Richard Trieub7243852012-09-28 20:32:51 +0000895 Qualifiers FromQual = FromType.getQualifiers(),
896 ToQual = ToType.getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +0000897 const TemplateSpecializationType *FromArgTST =
898 GetTemplateSpecializationType(Context, FromType);
899 const TemplateSpecializationType *ToArgTST =
900 GetTemplateSpecializationType(Context, ToType);
901
Richard Trieu8e14cac2012-09-28 19:51:57 +0000902 if (FromArgTST && ToArgTST &&
903 hasSameTemplate(FromArgTST, ToArgTST)) {
Richard Trieub7243852012-09-28 20:32:51 +0000904 FromQual -= QualType(FromArgTST, 0).getQualifiers();
905 ToQual -= QualType(ToArgTST, 0).getQualifiers();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000906 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
907 ToArgTST->getTemplateName().getAsTemplateDecl());
Richard Trieub7243852012-09-28 20:32:51 +0000908 Tree.SetNode(FromQual, ToQual);
Richard Trieub4cff112013-03-15 20:35:18 +0000909 Tree.SetKind(DiffTree::Template);
Richard Trieu8e14cac2012-09-28 19:51:57 +0000910 DiffTemplate(FromArgTST, ToArgTST);
Richard Trieu91844232012-06-26 18:18:47 +0000911 }
912 }
913 }
914 }
915
916 // Handle Expressions
917 if (NonTypeTemplateParmDecl *DefaultNTTPD =
918 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
Craig Topper36250ad2014-05-12 05:36:57 +0000919 Expr *FromExpr = nullptr, *ToExpr = nullptr;
Richard Trieu6df89452012-11-01 21:29:28 +0000920 llvm::APSInt FromInt, ToInt;
Craig Topper36250ad2014-05-12 05:36:57 +0000921 ValueDecl *FromValueDecl = nullptr, *ToValueDecl = nullptr;
Douglas Gregor2d5a5612012-12-21 23:03:27 +0000922 unsigned ParamWidth = 128; // Safe default
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000923 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType())
924 ParamWidth = Context.getIntWidth(DefaultNTTPD->getType());
Richard Trieu6df89452012-11-01 21:29:28 +0000925 bool HasFromInt = !FromIter.isEnd() &&
926 FromIter->getKind() == TemplateArgument::Integral;
927 bool HasToInt = !ToIter.isEnd() &&
928 ToIter->getKind() == TemplateArgument::Integral;
Richard Trieu954aaaf2013-02-27 01:41:53 +0000929 bool HasFromValueDecl =
930 !FromIter.isEnd() &&
931 FromIter->getKind() == TemplateArgument::Declaration;
932 bool HasToValueDecl =
933 !ToIter.isEnd() &&
934 ToIter->getKind() == TemplateArgument::Declaration;
935
936 assert(((!HasFromInt && !HasToInt) ||
937 (!HasFromValueDecl && !HasToValueDecl)) &&
938 "Template argument cannot be both integer and declaration");
Richard Trieu515dc0f2013-02-21 00:50:43 +0000939
Richard Trieu6df89452012-11-01 21:29:28 +0000940 if (HasFromInt)
941 FromInt = FromIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000942 else if (HasFromValueDecl)
943 FromValueDecl = FromIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000944 else
Richard Trieu17f13ec2013-04-03 03:06:48 +0000945 FromExpr = GetExpr(FromIter, DefaultNTTPD);
Richard Trieu6df89452012-11-01 21:29:28 +0000946
947 if (HasToInt)
948 ToInt = ToIter->getAsIntegral();
Richard Trieu954aaaf2013-02-27 01:41:53 +0000949 else if (HasToValueDecl)
950 ToValueDecl = ToIter->getAsDecl();
Richard Trieu6df89452012-11-01 21:29:28 +0000951 else
Richard Trieu17f13ec2013-04-03 03:06:48 +0000952 ToExpr = GetExpr(ToIter, DefaultNTTPD);
Richard Trieu6df89452012-11-01 21:29:28 +0000953
Richard Trieu954aaaf2013-02-27 01:41:53 +0000954 if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
Richard Trieu6df89452012-11-01 21:29:28 +0000955 Tree.SetNode(FromExpr, ToExpr);
Richard Trieu6df89452012-11-01 21:29:28 +0000956 Tree.SetDefault(FromIter.isEnd() && FromExpr,
957 ToIter.isEnd() && ToExpr);
Richard Trieubcd06c02013-04-03 02:31:17 +0000958 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType()) {
Richard Trieu981de5c2013-04-03 02:11:36 +0000959 if (FromExpr)
960 FromInt = GetInt(FromIter, FromExpr);
961 if (ToExpr)
962 ToInt = GetInt(ToIter, ToExpr);
963 Tree.SetNode(FromInt, ToInt, FromExpr, ToExpr);
Richard Trieu64ab30392013-03-15 23:55:09 +0000964 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
965 Tree.SetKind(DiffTree::Integer);
966 } else {
967 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr));
968 Tree.SetKind(DiffTree::Expression);
969 }
Richard Trieu954aaaf2013-02-27 01:41:53 +0000970 } else if (HasFromInt || HasToInt) {
Richard Trieu6df89452012-11-01 21:29:28 +0000971 if (!HasFromInt && FromExpr) {
Richard Trieu981de5c2013-04-03 02:11:36 +0000972 FromInt = GetInt(FromIter, FromExpr);
Richard Trieu6df89452012-11-01 21:29:28 +0000973 HasFromInt = true;
974 }
975 if (!HasToInt && ToExpr) {
Richard Trieu981de5c2013-04-03 02:11:36 +0000976 ToInt = GetInt(ToIter, ToExpr);
Richard Trieu6df89452012-11-01 21:29:28 +0000977 HasToInt = true;
978 }
979 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000980 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
Richard Trieu6df89452012-11-01 21:29:28 +0000981 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
982 ToIter.isEnd() && HasToInt);
Richard Trieub4cff112013-03-15 20:35:18 +0000983 Tree.SetKind(DiffTree::Integer);
Richard Trieu954aaaf2013-02-27 01:41:53 +0000984 } else {
Richard Trieu981de5c2013-04-03 02:11:36 +0000985 if (!HasFromValueDecl && FromExpr)
986 FromValueDecl = GetValueDecl(FromIter, FromExpr);
987 if (!HasToValueDecl && ToExpr)
988 ToValueDecl = GetValueDecl(ToIter, ToExpr);
Richard Trieu091872c52013-05-07 21:36:24 +0000989 QualType ArgumentType = DefaultNTTPD->getType();
990 bool FromAddressOf = FromValueDecl &&
991 !ArgumentType->isReferenceType() &&
992 !FromValueDecl->getType()->isArrayType();
993 bool ToAddressOf = ToValueDecl &&
994 !ArgumentType->isReferenceType() &&
995 !ToValueDecl->getType()->isArrayType();
996 Tree.SetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
Richard Trieuad13f552013-04-03 02:22:12 +0000997 Tree.SetSame(FromValueDecl && ToValueDecl &&
998 FromValueDecl->getCanonicalDecl() ==
Richard Trieu954aaaf2013-02-27 01:41:53 +0000999 ToValueDecl->getCanonicalDecl());
1000 Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
1001 ToIter.isEnd() && ToValueDecl);
Richard Trieub4cff112013-03-15 20:35:18 +00001002 Tree.SetKind(DiffTree::Declaration);
Richard Trieu6df89452012-11-01 21:29:28 +00001003 }
Richard Trieu91844232012-06-26 18:18:47 +00001004 }
1005
1006 // Handle Templates
1007 if (TemplateTemplateParmDecl *DefaultTTPD =
1008 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
1009 TemplateDecl *FromDecl, *ToDecl;
Richard Trieu17f13ec2013-04-03 03:06:48 +00001010 FromDecl = GetTemplateDecl(FromIter, DefaultTTPD);
1011 ToDecl = GetTemplateDecl(ToIter, DefaultTTPD);
Richard Trieu91844232012-06-26 18:18:47 +00001012 Tree.SetNode(FromDecl, ToDecl);
Richard Trieue673d71a2013-01-31 02:47:46 +00001013 Tree.SetSame(
1014 FromDecl && ToDecl &&
1015 FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
Richard Trieub4cff112013-03-15 20:35:18 +00001016 Tree.SetKind(DiffTree::TemplateTemplate);
Richard Trieu91844232012-06-26 18:18:47 +00001017 }
1018
Richard Trieu64ab30392013-03-15 23:55:09 +00001019 ++FromIter;
1020 ++ToIter;
Richard Trieu91844232012-06-26 18:18:47 +00001021 Tree.Up();
1022 }
1023 }
1024
Richard Trieu8e14cac2012-09-28 19:51:57 +00001025 /// makeTemplateList - Dump every template alias into the vector.
1026 static void makeTemplateList(
Craig Topper5603df42013-07-05 19:34:19 +00001027 SmallVectorImpl<const TemplateSpecializationType *> &TemplateList,
Richard Trieu8e14cac2012-09-28 19:51:57 +00001028 const TemplateSpecializationType *TST) {
1029 while (TST) {
1030 TemplateList.push_back(TST);
1031 if (!TST->isTypeAlias())
1032 return;
1033 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1034 }
1035 }
1036
1037 /// hasSameBaseTemplate - Returns true when the base templates are the same,
1038 /// even if the template arguments are not.
1039 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
1040 const TemplateSpecializationType *ToTST) {
Douglas Gregor8e9f55f2013-01-31 01:08:35 +00001041 return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
1042 ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
Richard Trieu8e14cac2012-09-28 19:51:57 +00001043 }
1044
Richard Trieu91844232012-06-26 18:18:47 +00001045 /// hasSameTemplate - Returns true if both types are specialized from the
1046 /// same template declaration. If they come from different template aliases,
1047 /// do a parallel ascension search to determine the highest template alias in
1048 /// common and set the arguments to them.
1049 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
1050 const TemplateSpecializationType *&ToTST) {
1051 // Check the top templates if they are the same.
Richard Trieu8e14cac2012-09-28 19:51:57 +00001052 if (hasSameBaseTemplate(FromTST, ToTST))
Richard Trieu91844232012-06-26 18:18:47 +00001053 return true;
1054
1055 // Create vectors of template aliases.
1056 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
1057 ToTemplateList;
1058
Richard Trieu8e14cac2012-09-28 19:51:57 +00001059 makeTemplateList(FromTemplateList, FromTST);
1060 makeTemplateList(ToTemplateList, ToTST);
Richard Trieu91844232012-06-26 18:18:47 +00001061
Craig Topper61ac9062013-07-08 03:55:09 +00001062 SmallVectorImpl<const TemplateSpecializationType *>::reverse_iterator
Richard Trieu91844232012-06-26 18:18:47 +00001063 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
1064 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
1065
1066 // Check if the lowest template types are the same. If not, return.
Richard Trieu8e14cac2012-09-28 19:51:57 +00001067 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +00001068 return false;
1069
1070 // Begin searching up the template aliases. The bottom most template
1071 // matches so move up until one pair does not match. Use the template
1072 // right before that one.
1073 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
Richard Trieu8e14cac2012-09-28 19:51:57 +00001074 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +00001075 break;
1076 }
1077
1078 FromTST = FromIter[-1];
1079 ToTST = ToIter[-1];
1080
1081 return true;
1082 }
1083
1084 /// GetType - Retrieves the template type arguments, including default
1085 /// arguments.
Richard Trieu17f13ec2013-04-03 03:06:48 +00001086 QualType GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD) {
Richard Trieu91844232012-06-26 18:18:47 +00001087 bool isVariadic = DefaultTTPD->isParameterPack();
1088
1089 if (!Iter.isEnd())
Richard Trieu17f13ec2013-04-03 03:06:48 +00001090 return Iter->getAsType();
Richard Trieu8ed6f2a2013-07-20 03:49:02 +00001091 if (isVariadic)
1092 return QualType();
Richard Trieu17f13ec2013-04-03 03:06:48 +00001093
Richard Trieu8ed6f2a2013-07-20 03:49:02 +00001094 QualType ArgType = DefaultTTPD->getDefaultArgument();
1095 if (ArgType->isDependentType())
1096 return Iter.getDesugar().getAsType();
1097
1098 return ArgType;
David Blaikie47e45182012-06-26 18:52:09 +00001099 }
Richard Trieu91844232012-06-26 18:18:47 +00001100
1101 /// GetExpr - Retrieves the template expression argument, including default
1102 /// arguments.
Richard Trieu17f13ec2013-04-03 03:06:48 +00001103 Expr *GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD) {
Craig Topper36250ad2014-05-12 05:36:57 +00001104 Expr *ArgExpr = nullptr;
Richard Trieu91844232012-06-26 18:18:47 +00001105 bool isVariadic = DefaultNTTPD->isParameterPack();
1106
1107 if (!Iter.isEnd())
1108 ArgExpr = Iter->getAsExpr();
1109 else if (!isVariadic)
1110 ArgExpr = DefaultNTTPD->getDefaultArgument();
1111
1112 if (ArgExpr)
1113 while (SubstNonTypeTemplateParmExpr *SNTTPE =
1114 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
1115 ArgExpr = SNTTPE->getReplacement();
Richard Trieu17f13ec2013-04-03 03:06:48 +00001116
1117 return ArgExpr;
Richard Trieu91844232012-06-26 18:18:47 +00001118 }
1119
Richard Trieu981de5c2013-04-03 02:11:36 +00001120 /// GetInt - Retrieves the template integer argument, including evaluating
1121 /// default arguments.
1122 llvm::APInt GetInt(const TSTiterator &Iter, Expr *ArgExpr) {
1123 // Default, value-depenedent expressions require fetching
1124 // from the desugared TemplateArgument
1125 if (Iter.isEnd() && ArgExpr->isValueDependent())
1126 switch (Iter.getDesugar().getKind()) {
1127 case TemplateArgument::Integral:
1128 return Iter.getDesugar().getAsIntegral();
1129 case TemplateArgument::Expression:
1130 ArgExpr = Iter.getDesugar().getAsExpr();
1131 return ArgExpr->EvaluateKnownConstInt(Context);
1132 default:
1133 assert(0 && "Unexpected template argument kind");
1134 }
1135 return ArgExpr->EvaluateKnownConstInt(Context);
1136 }
1137
Richard Trieu091872c52013-05-07 21:36:24 +00001138 /// GetValueDecl - Retrieves the template Decl argument, including
Richard Trieu981de5c2013-04-03 02:11:36 +00001139 /// default expression argument.
1140 ValueDecl *GetValueDecl(const TSTiterator &Iter, Expr *ArgExpr) {
1141 // Default, value-depenedent expressions require fetching
1142 // from the desugared TemplateArgument
1143 if (Iter.isEnd() && ArgExpr->isValueDependent())
1144 switch (Iter.getDesugar().getKind()) {
1145 case TemplateArgument::Declaration:
1146 return Iter.getDesugar().getAsDecl();
1147 case TemplateArgument::Expression:
1148 ArgExpr = Iter.getDesugar().getAsExpr();
1149 return cast<DeclRefExpr>(ArgExpr)->getDecl();
1150 default:
1151 assert(0 && "Unexpected template argument kind");
1152 }
Richard Trieu091872c52013-05-07 21:36:24 +00001153 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr);
1154 if (!DRE) {
1155 DRE = cast<DeclRefExpr>(cast<UnaryOperator>(ArgExpr)->getSubExpr());
1156 }
1157
1158 return DRE->getDecl();
Richard Trieu981de5c2013-04-03 02:11:36 +00001159 }
1160
Richard Trieu91844232012-06-26 18:18:47 +00001161 /// GetTemplateDecl - Retrieves the template template arguments, including
1162 /// default arguments.
Richard Trieu17f13ec2013-04-03 03:06:48 +00001163 TemplateDecl *GetTemplateDecl(const TSTiterator &Iter,
1164 TemplateTemplateParmDecl *DefaultTTPD) {
Richard Trieu91844232012-06-26 18:18:47 +00001165 bool isVariadic = DefaultTTPD->isParameterPack();
1166
1167 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
Craig Topper36250ad2014-05-12 05:36:57 +00001168 TemplateDecl *DefaultTD = nullptr;
Eli Friedmanb826a002012-09-26 02:36:12 +00001169 if (TA.getKind() != TemplateArgument::Null)
1170 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
Richard Trieu91844232012-06-26 18:18:47 +00001171
1172 if (!Iter.isEnd())
Richard Trieu17f13ec2013-04-03 03:06:48 +00001173 return Iter->getAsTemplate().getAsTemplateDecl();
1174 if (!isVariadic)
1175 return DefaultTD;
1176
Craig Topper36250ad2014-05-12 05:36:57 +00001177 return nullptr;
Richard Trieu91844232012-06-26 18:18:47 +00001178 }
1179
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001180 /// IsSameConvertedInt - Returns true if both integers are equal when
1181 /// converted to an integer type with the given width.
1182 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1183 const llvm::APSInt &Y) {
1184 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1185 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1186 return ConvertedX == ConvertedY;
1187 }
1188
Richard Trieu91844232012-06-26 18:18:47 +00001189 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001190 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1191 Expr *FromExpr, Expr *ToExpr) {
Richard Trieu91844232012-06-26 18:18:47 +00001192 if (FromExpr == ToExpr)
1193 return true;
1194
1195 if (!FromExpr || !ToExpr)
1196 return false;
1197
1198 FromExpr = FromExpr->IgnoreParens();
1199 ToExpr = ToExpr->IgnoreParens();
1200
1201 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1202 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1203
1204 if (FromDRE || ToDRE) {
1205 if (!FromDRE || !ToDRE)
1206 return false;
1207 return FromDRE->getDecl() == ToDRE->getDecl();
1208 }
1209
1210 Expr::EvalResult FromResult, ToResult;
1211 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1212 !ToExpr->EvaluateAsRValue(ToResult, Context))
Douglas Gregor7c5c3782013-03-14 20:44:43 +00001213 return false;
Richard Trieu91844232012-06-26 18:18:47 +00001214
1215 APValue &FromVal = FromResult.Val;
1216 APValue &ToVal = ToResult.Val;
1217
1218 if (FromVal.getKind() != ToVal.getKind()) return false;
1219
1220 switch (FromVal.getKind()) {
1221 case APValue::Int:
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001222 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
Richard Trieu91844232012-06-26 18:18:47 +00001223 case APValue::LValue: {
1224 APValue::LValueBase FromBase = FromVal.getLValueBase();
1225 APValue::LValueBase ToBase = ToVal.getLValueBase();
1226 if (FromBase.isNull() && ToBase.isNull())
1227 return true;
1228 if (FromBase.isNull() || ToBase.isNull())
1229 return false;
1230 return FromBase.get<const ValueDecl*>() ==
1231 ToBase.get<const ValueDecl*>();
1232 }
1233 case APValue::MemberPointer:
1234 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1235 default:
1236 llvm_unreachable("Unknown template argument expression.");
1237 }
1238 }
1239
1240 // These functions converts the tree representation of the template
1241 // differences into the internal character vector.
1242
1243 /// TreeToString - Converts the Tree object into a character stream which
1244 /// will later be turned into the output string.
1245 void TreeToString(int Indent = 1) {
1246 if (PrintTree) {
1247 OS << '\n';
Benjamin Kramer6582c362013-02-22 16:13:34 +00001248 OS.indent(2 * Indent);
Richard Trieu91844232012-06-26 18:18:47 +00001249 ++Indent;
1250 }
1251
1252 // Handle cases where the difference is not templates with different
1253 // arguments.
Richard Trieub4cff112013-03-15 20:35:18 +00001254 switch (Tree.GetKind()) {
Richard Trieub4cff112013-03-15 20:35:18 +00001255 case DiffTree::Invalid:
1256 llvm_unreachable("Template diffing failed with bad DiffNode");
1257 case DiffTree::Type: {
Richard Trieu91844232012-06-26 18:18:47 +00001258 QualType FromType, ToType;
1259 Tree.GetNode(FromType, ToType);
1260 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1261 Tree.NodeIsSame());
1262 return;
1263 }
Richard Trieub4cff112013-03-15 20:35:18 +00001264 case DiffTree::Expression: {
Richard Trieu91844232012-06-26 18:18:47 +00001265 Expr *FromExpr, *ToExpr;
1266 Tree.GetNode(FromExpr, ToExpr);
1267 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1268 Tree.NodeIsSame());
1269 return;
1270 }
Richard Trieub4cff112013-03-15 20:35:18 +00001271 case DiffTree::TemplateTemplate: {
Richard Trieu91844232012-06-26 18:18:47 +00001272 TemplateDecl *FromTD, *ToTD;
1273 Tree.GetNode(FromTD, ToTD);
1274 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1275 Tree.ToDefault(), Tree.NodeIsSame());
1276 return;
1277 }
Richard Trieub4cff112013-03-15 20:35:18 +00001278 case DiffTree::Integer: {
Richard Trieu6df89452012-11-01 21:29:28 +00001279 llvm::APSInt FromInt, ToInt;
Richard Trieu64ab30392013-03-15 23:55:09 +00001280 Expr *FromExpr, *ToExpr;
Richard Trieu6df89452012-11-01 21:29:28 +00001281 bool IsValidFromInt, IsValidToInt;
Richard Trieu64ab30392013-03-15 23:55:09 +00001282 Tree.GetNode(FromExpr, ToExpr);
Richard Trieu6df89452012-11-01 21:29:28 +00001283 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1284 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
Richard Trieu64ab30392013-03-15 23:55:09 +00001285 FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1286 Tree.NodeIsSame());
Richard Trieu6df89452012-11-01 21:29:28 +00001287 return;
1288 }
Richard Trieub4cff112013-03-15 20:35:18 +00001289 case DiffTree::Declaration: {
Richard Trieu954aaaf2013-02-27 01:41:53 +00001290 ValueDecl *FromValueDecl, *ToValueDecl;
Richard Trieu091872c52013-05-07 21:36:24 +00001291 bool FromAddressOf, ToAddressOf;
1292 Tree.GetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
1293 PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf,
1294 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
Richard Trieu954aaaf2013-02-27 01:41:53 +00001295 return;
1296 }
Richard Trieub4cff112013-03-15 20:35:18 +00001297 case DiffTree::Template: {
1298 // Node is root of template. Recurse on children.
1299 TemplateDecl *FromTD, *ToTD;
1300 Tree.GetNode(FromTD, ToTD);
Richard Trieu954aaaf2013-02-27 01:41:53 +00001301
Richard Trieub4cff112013-03-15 20:35:18 +00001302 if (!Tree.HasChildren()) {
1303 // If we're dealing with a template specialization with zero
1304 // arguments, there are no children; special-case this.
1305 OS << FromTD->getNameAsString() << "<>";
1306 return;
Richard Trieu91844232012-06-26 18:18:47 +00001307 }
Richard Trieub4cff112013-03-15 20:35:18 +00001308
1309 Qualifiers FromQual, ToQual;
1310 Tree.GetNode(FromQual, ToQual);
1311 PrintQualifiers(FromQual, ToQual);
1312
1313 OS << FromTD->getNameAsString() << '<';
1314 Tree.MoveToChild();
1315 unsigned NumElideArgs = 0;
1316 do {
1317 if (ElideType) {
1318 if (Tree.NodeIsSame()) {
1319 ++NumElideArgs;
1320 continue;
1321 }
1322 if (NumElideArgs > 0) {
1323 PrintElideArgs(NumElideArgs, Indent);
1324 NumElideArgs = 0;
1325 OS << ", ";
1326 }
1327 }
1328 TreeToString(Indent);
1329 if (Tree.HasNextSibling())
1330 OS << ", ";
1331 } while (Tree.AdvanceSibling());
1332 if (NumElideArgs > 0)
Richard Trieu91844232012-06-26 18:18:47 +00001333 PrintElideArgs(NumElideArgs, Indent);
Richard Trieu91844232012-06-26 18:18:47 +00001334
Richard Trieub4cff112013-03-15 20:35:18 +00001335 Tree.Parent();
1336 OS << ">";
1337 return;
1338 }
1339 }
Richard Trieu91844232012-06-26 18:18:47 +00001340 }
1341
1342 // To signal to the text printer that a certain text needs to be bolded,
1343 // a special character is injected into the character stream which the
1344 // text printer will later strip out.
1345
1346 /// Bold - Start bolding text.
1347 void Bold() {
1348 assert(!IsBold && "Attempting to bold text that is already bold.");
1349 IsBold = true;
1350 if (ShowColor)
1351 OS << ToggleHighlight;
1352 }
1353
1354 /// Unbold - Stop bolding text.
1355 void Unbold() {
1356 assert(IsBold && "Attempting to remove bold from unbold text.");
1357 IsBold = false;
1358 if (ShowColor)
1359 OS << ToggleHighlight;
1360 }
1361
1362 // Functions to print out the arguments and highlighting the difference.
1363
1364 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1365 /// typenames that are the same and attempt to disambiguate them by using
1366 /// canonical typenames.
1367 void PrintTypeNames(QualType FromType, QualType ToType,
1368 bool FromDefault, bool ToDefault, bool Same) {
1369 assert((!FromType.isNull() || !ToType.isNull()) &&
1370 "Only one template argument may be missing.");
1371
1372 if (Same) {
1373 OS << FromType.getAsString();
1374 return;
1375 }
1376
Richard Trieub7243852012-09-28 20:32:51 +00001377 if (!FromType.isNull() && !ToType.isNull() &&
1378 FromType.getLocalUnqualifiedType() ==
1379 ToType.getLocalUnqualifiedType()) {
1380 Qualifiers FromQual = FromType.getLocalQualifiers(),
Alp Tokeraced95a2013-11-26 02:52:41 +00001381 ToQual = ToType.getLocalQualifiers();
Richard Trieub7243852012-09-28 20:32:51 +00001382 PrintQualifiers(FromQual, ToQual);
1383 FromType.getLocalUnqualifiedType().print(OS, Policy);
1384 return;
1385 }
1386
Richard Trieu91844232012-06-26 18:18:47 +00001387 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1388 : FromType.getAsString();
1389 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1390 : ToType.getAsString();
1391 // Switch to canonical typename if it is better.
1392 // TODO: merge this with other aka printing above.
1393 if (FromTypeStr == ToTypeStr) {
1394 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1395 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1396 if (FromCanTypeStr != ToCanTypeStr) {
1397 FromTypeStr = FromCanTypeStr;
1398 ToTypeStr = ToCanTypeStr;
1399 }
1400 }
1401
1402 if (PrintTree) OS << '[';
1403 OS << (FromDefault ? "(default) " : "");
1404 Bold();
1405 OS << FromTypeStr;
1406 Unbold();
1407 if (PrintTree) {
1408 OS << " != " << (ToDefault ? "(default) " : "");
1409 Bold();
1410 OS << ToTypeStr;
1411 Unbold();
1412 OS << "]";
1413 }
1414 return;
1415 }
1416
1417 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1418 /// differences.
1419 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1420 bool FromDefault, bool ToDefault, bool Same) {
1421 assert((FromExpr || ToExpr) &&
1422 "Only one template argument may be missing.");
1423 if (Same) {
1424 PrintExpr(FromExpr);
1425 } else if (!PrintTree) {
1426 OS << (FromDefault ? "(default) " : "");
1427 Bold();
1428 PrintExpr(FromExpr);
1429 Unbold();
1430 } else {
1431 OS << (FromDefault ? "[(default) " : "[");
1432 Bold();
1433 PrintExpr(FromExpr);
1434 Unbold();
1435 OS << " != " << (ToDefault ? "(default) " : "");
1436 Bold();
1437 PrintExpr(ToExpr);
1438 Unbold();
1439 OS << ']';
1440 }
1441 }
1442
1443 /// PrintExpr - Actual formatting and printing of expressions.
1444 void PrintExpr(const Expr *E) {
1445 if (!E)
1446 OS << "(no argument)";
1447 else
Craig Topper36250ad2014-05-12 05:36:57 +00001448 E->printPretty(OS, nullptr, Policy);
Richard Trieu91844232012-06-26 18:18:47 +00001449 }
1450
1451 /// PrintTemplateTemplate - Handles printing of template template arguments,
1452 /// highlighting argument differences.
1453 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1454 bool FromDefault, bool ToDefault, bool Same) {
1455 assert((FromTD || ToTD) && "Only one template argument may be missing.");
Richard Trieue673d71a2013-01-31 02:47:46 +00001456
1457 std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
1458 std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
1459 if (FromTD && ToTD && FromName == ToName) {
1460 FromName = FromTD->getQualifiedNameAsString();
1461 ToName = ToTD->getQualifiedNameAsString();
1462 }
1463
Richard Trieu91844232012-06-26 18:18:47 +00001464 if (Same) {
1465 OS << "template " << FromTD->getNameAsString();
1466 } else if (!PrintTree) {
1467 OS << (FromDefault ? "(default) template " : "template ");
1468 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001469 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001470 Unbold();
1471 } else {
1472 OS << (FromDefault ? "[(default) template " : "[template ");
1473 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001474 OS << FromName;
Richard Trieu91844232012-06-26 18:18:47 +00001475 Unbold();
1476 OS << " != " << (ToDefault ? "(default) template " : "template ");
1477 Bold();
Richard Trieue673d71a2013-01-31 02:47:46 +00001478 OS << ToName;
Richard Trieu91844232012-06-26 18:18:47 +00001479 Unbold();
1480 OS << ']';
1481 }
1482 }
1483
Richard Trieu6df89452012-11-01 21:29:28 +00001484 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1485 /// argument differences.
1486 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
Richard Trieu64ab30392013-03-15 23:55:09 +00001487 bool IsValidFromInt, bool IsValidToInt, Expr *FromExpr,
1488 Expr *ToExpr, bool FromDefault, bool ToDefault, bool Same) {
Richard Trieu6df89452012-11-01 21:29:28 +00001489 assert((IsValidFromInt || IsValidToInt) &&
1490 "Only one integral argument may be missing.");
1491
1492 if (Same) {
1493 OS << FromInt.toString(10);
1494 } else if (!PrintTree) {
1495 OS << (FromDefault ? "(default) " : "");
Richard Trieu64ab30392013-03-15 23:55:09 +00001496 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
Richard Trieu6df89452012-11-01 21:29:28 +00001497 } else {
1498 OS << (FromDefault ? "[(default) " : "[");
Richard Trieu64ab30392013-03-15 23:55:09 +00001499 PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
Richard Trieu6df89452012-11-01 21:29:28 +00001500 OS << " != " << (ToDefault ? "(default) " : "");
Richard Trieu64ab30392013-03-15 23:55:09 +00001501 PrintAPSInt(ToInt, ToExpr, IsValidToInt);
Richard Trieu6df89452012-11-01 21:29:28 +00001502 OS << ']';
1503 }
1504 }
1505
Richard Trieu64ab30392013-03-15 23:55:09 +00001506 /// PrintAPSInt - If valid, print the APSInt. If the expression is
1507 /// gives more information, print it too.
1508 void PrintAPSInt(llvm::APSInt Val, Expr *E, bool Valid) {
1509 Bold();
1510 if (Valid) {
1511 if (HasExtraInfo(E)) {
1512 PrintExpr(E);
1513 Unbold();
1514 OS << " aka ";
1515 Bold();
1516 }
1517 OS << Val.toString(10);
1518 } else {
1519 OS << "(no argument)";
1520 }
1521 Unbold();
1522 }
Richard Trieu954aaaf2013-02-27 01:41:53 +00001523
Richard Trieu64ab30392013-03-15 23:55:09 +00001524 /// HasExtraInfo - Returns true if E is not an integer literal or the
1525 /// negation of an integer literal
1526 bool HasExtraInfo(Expr *E) {
1527 if (!E) return false;
1528 if (isa<IntegerLiteral>(E)) return false;
1529
1530 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
1531 if (UO->getOpcode() == UO_Minus)
1532 if (isa<IntegerLiteral>(UO->getSubExpr()))
1533 return false;
1534
1535 return true;
1536 }
1537
Richard Trieu954aaaf2013-02-27 01:41:53 +00001538 /// PrintDecl - Handles printing of Decl arguments, highlighting
1539 /// argument differences.
1540 void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
Richard Trieu091872c52013-05-07 21:36:24 +00001541 bool FromAddressOf, bool ToAddressOf, bool FromDefault,
1542 bool ToDefault, bool Same) {
Richard Trieu954aaaf2013-02-27 01:41:53 +00001543 assert((FromValueDecl || ToValueDecl) &&
1544 "Only one Decl argument may be NULL");
1545
1546 if (Same) {
1547 OS << FromValueDecl->getName();
1548 } else if (!PrintTree) {
1549 OS << (FromDefault ? "(default) " : "");
1550 Bold();
Richard Trieu091872c52013-05-07 21:36:24 +00001551 if (FromAddressOf)
1552 OS << "&";
Richard Trieu954aaaf2013-02-27 01:41:53 +00001553 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1554 Unbold();
1555 } else {
1556 OS << (FromDefault ? "[(default) " : "[");
1557 Bold();
Richard Trieu091872c52013-05-07 21:36:24 +00001558 if (FromAddressOf)
1559 OS << "&";
Richard Trieu954aaaf2013-02-27 01:41:53 +00001560 OS << (FromValueDecl ? FromValueDecl->getName() : "(no argument)");
1561 Unbold();
1562 OS << " != " << (ToDefault ? "(default) " : "");
1563 Bold();
Richard Trieu091872c52013-05-07 21:36:24 +00001564 if (ToAddressOf)
1565 OS << "&";
Richard Trieu954aaaf2013-02-27 01:41:53 +00001566 OS << (ToValueDecl ? ToValueDecl->getName() : "(no argument)");
1567 Unbold();
1568 OS << ']';
1569 }
1570
1571 }
1572
Richard Trieu91844232012-06-26 18:18:47 +00001573 // Prints the appropriate placeholder for elided template arguments.
1574 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1575 if (PrintTree) {
1576 OS << '\n';
1577 for (unsigned i = 0; i < Indent; ++i)
1578 OS << " ";
1579 }
1580 if (NumElideArgs == 0) return;
1581 if (NumElideArgs == 1)
1582 OS << "[...]";
1583 else
1584 OS << "[" << NumElideArgs << " * ...]";
1585 }
1586
Richard Trieub7243852012-09-28 20:32:51 +00001587 // Prints and highlights differences in Qualifiers.
1588 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1589 // Both types have no qualifiers
1590 if (FromQual.empty() && ToQual.empty())
1591 return;
1592
1593 // Both types have same qualifiers
1594 if (FromQual == ToQual) {
1595 PrintQualifier(FromQual, /*ApplyBold*/false);
1596 return;
1597 }
1598
1599 // Find common qualifiers and strip them from FromQual and ToQual.
1600 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1601 ToQual);
1602
1603 // The qualifiers are printed before the template name.
1604 // Inline printing:
1605 // The common qualifiers are printed. Then, qualifiers only in this type
1606 // are printed and highlighted. Finally, qualifiers only in the other
1607 // type are printed and highlighted inside parentheses after "missing".
1608 // Tree printing:
1609 // Qualifiers are printed next to each other, inside brackets, and
1610 // separated by "!=". The printing order is:
1611 // common qualifiers, highlighted from qualifiers, "!=",
1612 // common qualifiers, highlighted to qualifiers
1613 if (PrintTree) {
1614 OS << "[";
1615 if (CommonQual.empty() && FromQual.empty()) {
1616 Bold();
1617 OS << "(no qualifiers) ";
1618 Unbold();
1619 } else {
1620 PrintQualifier(CommonQual, /*ApplyBold*/false);
1621 PrintQualifier(FromQual, /*ApplyBold*/true);
1622 }
1623 OS << "!= ";
1624 if (CommonQual.empty() && ToQual.empty()) {
1625 Bold();
1626 OS << "(no qualifiers)";
1627 Unbold();
1628 } else {
1629 PrintQualifier(CommonQual, /*ApplyBold*/false,
1630 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1631 PrintQualifier(ToQual, /*ApplyBold*/true,
1632 /*appendSpaceIfNonEmpty*/false);
1633 }
1634 OS << "] ";
1635 } else {
1636 PrintQualifier(CommonQual, /*ApplyBold*/false);
1637 PrintQualifier(FromQual, /*ApplyBold*/true);
1638 }
1639 }
1640
1641 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1642 bool AppendSpaceIfNonEmpty = true) {
1643 if (Q.empty()) return;
1644 if (ApplyBold) Bold();
1645 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1646 if (ApplyBold) Unbold();
1647 }
1648
Richard Trieu91844232012-06-26 18:18:47 +00001649public:
1650
Benjamin Kramer8de90462013-02-22 16:08:12 +00001651 TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
1652 QualType ToType, bool PrintTree, bool PrintFromType,
1653 bool ElideType, bool ShowColor)
Richard Trieu91844232012-06-26 18:18:47 +00001654 : Context(Context),
1655 Policy(Context.getLangOpts()),
1656 ElideType(ElideType),
1657 PrintTree(PrintTree),
1658 ShowColor(ShowColor),
1659 // When printing a single type, the FromType is the one printed.
1660 FromType(PrintFromType ? FromType : ToType),
1661 ToType(PrintFromType ? ToType : FromType),
Benjamin Kramer8de90462013-02-22 16:08:12 +00001662 OS(OS),
Richard Trieu91844232012-06-26 18:18:47 +00001663 IsBold(false) {
1664 }
1665
1666 /// DiffTemplate - Start the template type diffing.
1667 void DiffTemplate() {
Richard Trieub7243852012-09-28 20:32:51 +00001668 Qualifiers FromQual = FromType.getQualifiers(),
1669 ToQual = ToType.getQualifiers();
1670
Richard Trieu91844232012-06-26 18:18:47 +00001671 const TemplateSpecializationType *FromOrigTST =
1672 GetTemplateSpecializationType(Context, FromType);
1673 const TemplateSpecializationType *ToOrigTST =
1674 GetTemplateSpecializationType(Context, ToType);
1675
1676 // Only checking templates.
1677 if (!FromOrigTST || !ToOrigTST)
1678 return;
1679
1680 // Different base templates.
1681 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1682 return;
1683 }
1684
Richard Trieub7243852012-09-28 20:32:51 +00001685 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1686 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +00001687 Tree.SetNode(FromType, ToType);
Richard Trieub7243852012-09-28 20:32:51 +00001688 Tree.SetNode(FromQual, ToQual);
Richard Trieub4cff112013-03-15 20:35:18 +00001689 Tree.SetKind(DiffTree::Template);
Richard Trieu91844232012-06-26 18:18:47 +00001690
1691 // Same base template, but different arguments.
1692 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1693 ToOrigTST->getTemplateName().getAsTemplateDecl());
1694
1695 DiffTemplate(FromOrigTST, ToOrigTST);
David Blaikie47e45182012-06-26 18:52:09 +00001696 }
Richard Trieu91844232012-06-26 18:18:47 +00001697
Benjamin Kramer6582c362013-02-22 16:13:34 +00001698 /// Emit - When the two types given are templated types with the same
Richard Trieu91844232012-06-26 18:18:47 +00001699 /// base template, a string representation of the type difference will be
Benjamin Kramer6582c362013-02-22 16:13:34 +00001700 /// emitted to the stream and return true. Otherwise, return false.
Benjamin Kramer8de90462013-02-22 16:08:12 +00001701 bool Emit() {
Richard Trieu91844232012-06-26 18:18:47 +00001702 Tree.StartTraverse();
1703 if (Tree.Empty())
1704 return false;
1705
1706 TreeToString();
1707 assert(!IsBold && "Bold is applied to end of string.");
Richard Trieu91844232012-06-26 18:18:47 +00001708 return true;
1709 }
1710}; // end class TemplateDiff
1711} // end namespace
1712
1713/// FormatTemplateTypeDiff - A helper static function to start the template
1714/// diff and return the properly formatted string. Returns true if the diff
1715/// is successful.
1716static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1717 QualType ToType, bool PrintTree,
1718 bool PrintFromType, bool ElideType,
Benjamin Kramer8de90462013-02-22 16:08:12 +00001719 bool ShowColors, raw_ostream &OS) {
Richard Trieu91844232012-06-26 18:18:47 +00001720 if (PrintTree)
1721 PrintFromType = true;
Benjamin Kramer8de90462013-02-22 16:08:12 +00001722 TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
Richard Trieu91844232012-06-26 18:18:47 +00001723 ElideType, ShowColors);
1724 TD.DiffTemplate();
Benjamin Kramer8de90462013-02-22 16:08:12 +00001725 return TD.Emit();
Richard Trieu91844232012-06-26 18:18:47 +00001726}