blob: 3115d00b50224123c222fbc61b6a31e919441bb3 [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"
14
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Richard Trieu91844232012-06-26 18:18:47 +000017#include "clang/AST/TemplateBase.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/DeclTemplate.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 }
Richard Smith30482bc2011-02-20 03:19:35 +000055 // ... or an auto type.
56 if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
57 if (!AT->isSugared())
58 break;
59 QT = AT->desugar();
Douglas Gregor639cccc2010-02-09 22:26:47 +000060 continue;
61 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +000062
Richard Smith3f1b5d02011-05-05 21:57:07 +000063 // Don't desugar template specializations, unless it's an alias template.
64 if (const TemplateSpecializationType *TST
65 = dyn_cast<TemplateSpecializationType>(Ty))
66 if (!TST->isTypeAlias())
67 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000068
Douglas Gregor639cccc2010-02-09 22:26:47 +000069 // Don't desugar magic Objective-C types.
70 if (QualType(Ty,0) == Context.getObjCIdType() ||
71 QualType(Ty,0) == Context.getObjCClassType() ||
72 QualType(Ty,0) == Context.getObjCSelType() ||
73 QualType(Ty,0) == Context.getObjCProtoType())
74 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000075
Douglas Gregor639cccc2010-02-09 22:26:47 +000076 // Don't desugar va_list.
77 if (QualType(Ty,0) == Context.getBuiltinVaListType())
78 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +000079
Douglas Gregor639cccc2010-02-09 22:26:47 +000080 // Otherwise, do a single-step desugar.
81 QualType Underlying;
82 bool IsSugar = false;
83 switch (Ty->getTypeClass()) {
84#define ABSTRACT_TYPE(Class, Base)
85#define TYPE(Class, Base) \
86case Type::Class: { \
87const Class##Type *CTy = cast<Class##Type>(Ty); \
88if (CTy->isSugared()) { \
89IsSugar = true; \
90Underlying = CTy->desugar(); \
91} \
92break; \
93}
94#include "clang/AST/TypeNodes.def"
95 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +000096
Douglas Gregor639cccc2010-02-09 22:26:47 +000097 // If it wasn't sugared, we're done.
98 if (!IsSugar)
99 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000100
Douglas Gregor639cccc2010-02-09 22:26:47 +0000101 // If the desugared type is a vector type, we don't want to expand
102 // it, it will turn into an attribute mess. People want their "vec4".
103 if (isa<VectorType>(Underlying))
104 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000105
Douglas Gregor639cccc2010-02-09 22:26:47 +0000106 // Don't desugar through the primary typedef of an anonymous type.
Chris Lattneredbdff62010-09-04 23:16:01 +0000107 if (const TagType *UTT = Underlying->getAs<TagType>())
108 if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
Richard Smithdda56e42011-04-15 14:24:37 +0000109 if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
Chris Lattneredbdff62010-09-04 23:16:01 +0000110 break;
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000111
112 // Record that we actually looked through an opaque type here.
113 ShouldAKA = true;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000114 QT = Underlying;
Douglas Gregor639cccc2010-02-09 22:26:47 +0000115 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000116
117 // If we have a pointer-like type, desugar the pointee as well.
118 // FIXME: Handle other pointer-like types.
119 if (const PointerType *Ty = QT->getAs<PointerType>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000120 QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
121 ShouldAKA));
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000122 } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
Chris Lattneredbdff62010-09-04 23:16:01 +0000123 QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
124 ShouldAKA));
Douglas Gregor7a2a1162011-01-20 16:08:06 +0000125 } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
126 QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
127 ShouldAKA));
Douglas Gregor639cccc2010-02-09 22:26:47 +0000128 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000129
John McCall717d9b02010-12-10 11:01:00 +0000130 return QC.apply(Context, QT);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000131}
132
133/// \brief Convert the given type to a string suitable for printing as part of
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000134/// a diagnostic.
135///
Chandler Carruthd5173952011-07-11 17:49:21 +0000136/// There are four main criteria when determining whether we should have an
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000137/// a.k.a. clause when pretty-printing a type:
138///
139/// 1) Some types provide very minimal sugar that doesn't impede the
140/// user's understanding --- for example, elaborated type
141/// specifiers. If this is all the sugar we see, we don't want an
142/// a.k.a. clause.
143/// 2) Some types are technically sugared but are much more familiar
144/// when seen in their sugared form --- for example, va_list,
145/// vector types, and the magic Objective C types. We don't
146/// want to desugar these, even if we do produce an a.k.a. clause.
147/// 3) Some types may have already been desugared previously in this diagnostic.
148/// if this is the case, doing another "aka" would just be clutter.
Chandler Carruthd5173952011-07-11 17:49:21 +0000149/// 4) Two different types within the same diagnostic have the same output
150/// string. In this case, force an a.k.a with the desugared type when
151/// doing so will provide additional information.
Douglas Gregor639cccc2010-02-09 22:26:47 +0000152///
153/// \param Context the context in which the type was allocated
154/// \param Ty the type to print
Chandler Carruthd5173952011-07-11 17:49:21 +0000155/// \param QualTypeVals pointer values to QualTypes which are used in the
156/// diagnostic message
Douglas Gregor639cccc2010-02-09 22:26:47 +0000157static std::string
158ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
David Blaikie9c902b52011-09-25 23:23:43 +0000159 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000160 unsigned NumPrevArgs,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000161 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000162 // FIXME: Playing with std::string is really slow.
Chandler Carruthd5173952011-07-11 17:49:21 +0000163 bool ForceAKA = false;
164 QualType CanTy = Ty.getCanonicalType();
Douglas Gregorc0b07282011-09-27 22:38:19 +0000165 std::string S = Ty.getAsString(Context.getPrintingPolicy());
166 std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000167
Bill Wendling8eb771d2012-02-22 09:51:33 +0000168 for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
Chandler Carruthd5173952011-07-11 17:49:21 +0000169 QualType CompareTy =
Bill Wendling8eb771d2012-02-22 09:51:33 +0000170 QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
Richard Smithbcc22fc2012-03-09 08:00:36 +0000171 if (CompareTy.isNull())
172 continue;
Chandler Carruthd5173952011-07-11 17:49:21 +0000173 if (CompareTy == Ty)
174 continue; // Same types
175 QualType CompareCanTy = CompareTy.getCanonicalType();
176 if (CompareCanTy == CanTy)
177 continue; // Same canonical types
Douglas Gregorc0b07282011-09-27 22:38:19 +0000178 std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
Richard Trieu5d1aff02011-11-14 19:39:25 +0000179 bool aka;
180 QualType CompareDesugar = Desugar(Context, CompareTy, aka);
181 std::string CompareDesugarStr =
182 CompareDesugar.getAsString(Context.getPrintingPolicy());
183 if (CompareS != S && CompareDesugarStr != S)
184 continue; // The type string is different than the comparison string
185 // and the desugared comparison string.
186 std::string CompareCanS =
187 CompareCanTy.getAsString(Context.getPrintingPolicy());
188
Chandler Carruthd5173952011-07-11 17:49:21 +0000189 if (CompareCanS == CanS)
190 continue; // No new info from canonical type
191
192 ForceAKA = true;
193 break;
194 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000195
196 // Check to see if we already desugared this type in this
197 // diagnostic. If so, don't do it again.
198 bool Repeated = false;
199 for (unsigned i = 0; i != NumPrevArgs; ++i) {
200 // TODO: Handle ak_declcontext case.
David Blaikie9c902b52011-09-25 23:23:43 +0000201 if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000202 void *Ptr = (void*)PrevArgs[i].second;
203 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
204 if (PrevTy == Ty) {
205 Repeated = true;
206 break;
207 }
208 }
209 }
210
Douglas Gregor639cccc2010-02-09 22:26:47 +0000211 // Consider producing an a.k.a. clause if removing all the direct
212 // sugar gives us something "significantly different".
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000213 if (!Repeated) {
214 bool ShouldAKA = false;
215 QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
Chandler Carruthd5173952011-07-11 17:49:21 +0000216 if (ShouldAKA || ForceAKA) {
217 if (DesugaredTy == Ty) {
218 DesugaredTy = Ty.getCanonicalType();
219 }
Douglas Gregorc0b07282011-09-27 22:38:19 +0000220 std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
Chandler Carruthd5173952011-07-11 17:49:21 +0000221 if (akaStr != S) {
222 S = "'" + S + "' (aka '" + akaStr + "')";
223 return S;
224 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000225 }
Douglas Gregor639cccc2010-02-09 22:26:47 +0000226 }
Chandler Carruthd102f2d2010-05-13 11:37:24 +0000227
Douglas Gregor639cccc2010-02-09 22:26:47 +0000228 S = "'" + S + "'";
229 return S;
230}
231
Richard Trieu91844232012-06-26 18:18:47 +0000232static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
233 QualType ToType, bool PrintTree,
234 bool PrintFromType, bool ElideType,
235 bool ShowColors, std::string &S);
236
Chandler Carruthd5173952011-07-11 17:49:21 +0000237void clang::FormatASTNodeDiagnosticArgument(
David Blaikie9c902b52011-09-25 23:23:43 +0000238 DiagnosticsEngine::ArgumentKind Kind,
Chandler Carruthd5173952011-07-11 17:49:21 +0000239 intptr_t Val,
240 const char *Modifier,
241 unsigned ModLen,
242 const char *Argument,
243 unsigned ArgLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000244 const DiagnosticsEngine::ArgumentValue *PrevArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000245 unsigned NumPrevArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000246 SmallVectorImpl<char> &Output,
Chandler Carruthd5173952011-07-11 17:49:21 +0000247 void *Cookie,
Bill Wendling8eb771d2012-02-22 09:51:33 +0000248 ArrayRef<intptr_t> QualTypeVals) {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000249 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
250
251 std::string S;
252 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,
265 TDT.ShowColors, S)) {
266 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
276 // Attempting to do a templete diff on non-templates. Set the variables
277 // and continue with regular type printing of the appropriate type.
278 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
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)));
Chandler Carruthd5173952011-07-11 17:49:21 +0000288 S = 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 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
295 S = N.getAsString();
296
297 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
298 S = '+' + S;
299 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
300 && ArgLen==0)
301 S = '-' + S;
302 else
303 assert(ModLen == 0 && ArgLen == 0 &&
304 "Invalid modifier for DeclarationName argument");
305 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);
Douglas Gregorc0b07282011-09-27 22:38:19 +0000317 ND->getNameForDiagnostic(S, 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: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000321 llvm::raw_string_ostream OS(S);
322 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
Douglas Gregorc0b07282011-09-27 22:38:19 +0000323 Context.getPrintingPolicy());
Douglas Gregor639cccc2010-02-09 22:26:47 +0000324 NeedQuotes = false;
325 break;
326 }
David Blaikie9c902b52011-09-25 23:23:43 +0000327 case DiagnosticsEngine::ak_declcontext: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000328 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
329 assert(DC && "Should never have a null declaration context");
330
331 if (DC->isTranslationUnit()) {
332 // FIXME: Get these strings from some localized place
David Blaikiebbafb8a2012-03-11 07:00:24 +0000333 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor639cccc2010-02-09 22:26:47 +0000334 S = "the global namespace";
335 else
336 S = "the global scope";
337 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
338 S = ConvertTypeToDiagnosticString(Context,
339 Context.getTypeDeclType(Type),
Chandler Carruthd5173952011-07-11 17:49:21 +0000340 PrevArgs, NumPrevArgs, 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))
345 S += "namespace ";
346 else if (isa<ObjCMethodDecl>(ND))
347 S += "method ";
348 else if (isa<FunctionDecl>(ND))
349 S += "function ";
350
351 S += "'";
Douglas Gregorc0b07282011-09-27 22:38:19 +0000352 ND->getNameForDiagnostic(S, Context.getPrintingPolicy(), true);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000353 S += "'";
354 }
355 NeedQuotes = false;
356 break;
357 }
358 }
359
360 if (NeedQuotes)
361 Output.push_back('\'');
362
363 Output.append(S.begin(), S.end());
364
365 if (NeedQuotes)
366 Output.push_back('\'');
367}
Richard Trieu91844232012-06-26 18:18:47 +0000368
369/// TemplateDiff - A class that constructs a pretty string for a pair of
370/// QualTypes. For the pair of types, a diff tree will be created containing
371/// all the information about the templates and template arguments. Afterwards,
372/// the tree is transformed to a string according to the options passed in.
373namespace {
374class TemplateDiff {
375 /// Context - The ASTContext which is used for comparing template arguments.
376 ASTContext &Context;
377
378 /// Policy - Used during expression printing.
379 PrintingPolicy Policy;
380
381 /// ElideType - Option to elide identical types.
382 bool ElideType;
383
384 /// PrintTree - Format output string as a tree.
385 bool PrintTree;
386
387 /// ShowColor - Diagnostics support color, so bolding will be used.
388 bool ShowColor;
389
390 /// FromType - When single type printing is selected, this is the type to be
391 /// be printed. When tree printing is selected, this type will show up first
392 /// in the tree.
393 QualType FromType;
394
395 /// ToType - The type that FromType is compared to. Only in tree printing
396 /// will this type be outputed.
397 QualType ToType;
398
399 /// Str - Storage for the output stream.
400 llvm::SmallString<128> Str;
401
402 /// OS - The stream used to construct the output strings.
403 llvm::raw_svector_ostream OS;
404
405 /// IsBold - Keeps track of the bold formatting for the output string.
406 bool IsBold;
407
408 /// DiffTree - A tree representation the differences between two types.
409 class DiffTree {
410 /// DiffNode - The root node stores the original type. Each child node
411 /// stores template arguments of their parents. For templated types, the
412 /// template decl is also stored.
413 struct DiffNode {
414 /// NextNode - The index of the next sibling node or 0.
415 unsigned NextNode;
416
417 /// ChildNode - The index of the first child node or 0.
418 unsigned ChildNode;
419
420 /// ParentNode - The index of the parent node.
421 unsigned ParentNode;
422
423 /// FromType, ToType - The type arguments.
424 QualType FromType, ToType;
425
426 /// FromExpr, ToExpr - The expression arguments.
427 Expr *FromExpr, *ToExpr;
428
429 /// FromTD, ToTD - The template decl for template template
430 /// arguments or the type arguments that are templates.
431 TemplateDecl *FromTD, *ToTD;
432
Richard Trieub7243852012-09-28 20:32:51 +0000433 /// FromQual, ToQual - Qualifiers for template types.
434 Qualifiers FromQual, ToQual;
435
Richard Trieu6df89452012-11-01 21:29:28 +0000436 /// FromInt, ToInt - APSInt's for integral arguments.
437 llvm::APSInt FromInt, ToInt;
438
439 /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
440 bool IsValidFromInt, IsValidToInt;
441
Richard Trieu91844232012-06-26 18:18:47 +0000442 /// FromDefault, ToDefault - Whether the argument is a default argument.
443 bool FromDefault, ToDefault;
444
445 /// Same - Whether the two arguments evaluate to the same value.
446 bool Same;
447
448 DiffNode(unsigned ParentNode = 0)
449 : NextNode(0), ChildNode(0), ParentNode(ParentNode),
450 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
451 FromDefault(false), ToDefault(false), Same(false) { }
452 };
453
454 /// FlatTree - A flattened tree used to store the DiffNodes.
455 llvm::SmallVector<DiffNode, 16> FlatTree;
456
457 /// CurrentNode - The index of the current node being used.
458 unsigned CurrentNode;
459
460 /// NextFreeNode - The index of the next unused node. Used when creating
461 /// child nodes.
462 unsigned NextFreeNode;
463
464 /// ReadNode - The index of the current node being read.
465 unsigned ReadNode;
466
467 public:
468 DiffTree() :
469 CurrentNode(0), NextFreeNode(1) {
470 FlatTree.push_back(DiffNode());
471 }
472
473 // Node writing functions.
474 /// SetNode - Sets FromTD and ToTD of the current node.
475 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
476 FlatTree[CurrentNode].FromTD = FromTD;
477 FlatTree[CurrentNode].ToTD = ToTD;
478 }
479
480 /// SetNode - Sets FromType and ToType of the current node.
481 void SetNode(QualType FromType, QualType ToType) {
482 FlatTree[CurrentNode].FromType = FromType;
483 FlatTree[CurrentNode].ToType = ToType;
484 }
485
486 /// SetNode - Set FromExpr and ToExpr of the current node.
487 void SetNode(Expr *FromExpr, Expr *ToExpr) {
488 FlatTree[CurrentNode].FromExpr = FromExpr;
489 FlatTree[CurrentNode].ToExpr = ToExpr;
490 }
491
Richard Trieu6df89452012-11-01 21:29:28 +0000492 /// SetNode - Set FromInt and ToInt of the current node.
493 void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
494 bool IsValidFromInt, bool IsValidToInt) {
495 FlatTree[CurrentNode].FromInt = FromInt;
496 FlatTree[CurrentNode].ToInt = ToInt;
497 FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
498 FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
499 }
500
Richard Trieub7243852012-09-28 20:32:51 +0000501 /// SetNode - Set FromQual and ToQual of the current node.
502 void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
503 FlatTree[CurrentNode].FromQual = FromQual;
504 FlatTree[CurrentNode].ToQual = ToQual;
505 }
506
Richard Trieu91844232012-06-26 18:18:47 +0000507 /// SetSame - Sets the same flag of the current node.
508 void SetSame(bool Same) {
509 FlatTree[CurrentNode].Same = Same;
510 }
511
512 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
513 void SetDefault(bool FromDefault, bool ToDefault) {
514 FlatTree[CurrentNode].FromDefault = FromDefault;
515 FlatTree[CurrentNode].ToDefault = ToDefault;
516 }
517
518 /// Up - Changes the node to the parent of the current node.
519 void Up() {
520 CurrentNode = FlatTree[CurrentNode].ParentNode;
521 }
522
523 /// AddNode - Adds a child node to the current node, then sets that node
524 /// node as the current node.
525 void AddNode() {
526 FlatTree.push_back(DiffNode(CurrentNode));
527 DiffNode &Node = FlatTree[CurrentNode];
528 if (Node.ChildNode == 0) {
529 // If a child node doesn't exist, add one.
530 Node.ChildNode = NextFreeNode;
531 } else {
532 // If a child node exists, find the last child node and add a
533 // next node to it.
534 unsigned i;
535 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
536 i = FlatTree[i].NextNode) {
537 }
538 FlatTree[i].NextNode = NextFreeNode;
539 }
540 CurrentNode = NextFreeNode;
541 ++NextFreeNode;
542 }
543
544 // Node reading functions.
545 /// StartTraverse - Prepares the tree for recursive traversal.
546 void StartTraverse() {
547 ReadNode = 0;
548 CurrentNode = NextFreeNode;
549 NextFreeNode = 0;
550 }
551
552 /// Parent - Move the current read node to its parent.
553 void Parent() {
554 ReadNode = FlatTree[ReadNode].ParentNode;
555 }
556
557 /// NodeIsTemplate - Returns true if a template decl is set, and types are
558 /// set.
559 bool NodeIsTemplate() {
560 return (FlatTree[ReadNode].FromTD &&
561 !FlatTree[ReadNode].ToType.isNull()) ||
562 (FlatTree[ReadNode].ToTD && !FlatTree[ReadNode].ToType.isNull());
563 }
564
565 /// NodeIsQualType - Returns true if a Qualtype is set.
566 bool NodeIsQualType() {
567 return !FlatTree[ReadNode].FromType.isNull() ||
568 !FlatTree[ReadNode].ToType.isNull();
569 }
570
571 /// NodeIsExpr - Returns true if an expr is set.
572 bool NodeIsExpr() {
573 return FlatTree[ReadNode].FromExpr || FlatTree[ReadNode].ToExpr;
574 }
575
576 /// NodeIsTemplateTemplate - Returns true if the argument is a template
577 /// template type.
578 bool NodeIsTemplateTemplate() {
579 return FlatTree[ReadNode].FromType.isNull() &&
580 FlatTree[ReadNode].ToType.isNull() &&
581 (FlatTree[ReadNode].FromTD || FlatTree[ReadNode].ToTD);
582 }
583
Richard Trieu6df89452012-11-01 21:29:28 +0000584 /// NodeIsAPSInt - Returns true if the arugments are stored in APSInt's.
585 bool NodeIsAPSInt() {
586 return FlatTree[ReadNode].IsValidFromInt ||
587 FlatTree[ReadNode].IsValidToInt;
588 }
589
Richard Trieu91844232012-06-26 18:18:47 +0000590 /// GetNode - Gets the FromType and ToType.
591 void GetNode(QualType &FromType, QualType &ToType) {
592 FromType = FlatTree[ReadNode].FromType;
593 ToType = FlatTree[ReadNode].ToType;
594 }
595
596 /// GetNode - Gets the FromExpr and ToExpr.
597 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
598 FromExpr = FlatTree[ReadNode].FromExpr;
599 ToExpr = FlatTree[ReadNode].ToExpr;
600 }
601
602 /// GetNode - Gets the FromTD and ToTD.
603 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
604 FromTD = FlatTree[ReadNode].FromTD;
605 ToTD = FlatTree[ReadNode].ToTD;
606 }
607
Richard Trieu6df89452012-11-01 21:29:28 +0000608 /// GetNode - Gets the FromInt and ToInt.
609 void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
610 bool &IsValidFromInt, bool &IsValidToInt) {
611 FromInt = FlatTree[ReadNode].FromInt;
612 ToInt = FlatTree[ReadNode].ToInt;
613 IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
614 IsValidToInt = FlatTree[ReadNode].IsValidToInt;
615 }
616
Richard Trieub7243852012-09-28 20:32:51 +0000617 /// GetNode - Gets the FromQual and ToQual.
618 void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
619 FromQual = FlatTree[ReadNode].FromQual;
620 ToQual = FlatTree[ReadNode].ToQual;
621 }
622
Richard Trieu91844232012-06-26 18:18:47 +0000623 /// NodeIsSame - Returns true the arguments are the same.
624 bool NodeIsSame() {
625 return FlatTree[ReadNode].Same;
626 }
627
628 /// HasChildrend - Returns true if the node has children.
629 bool HasChildren() {
630 return FlatTree[ReadNode].ChildNode != 0;
631 }
632
633 /// MoveToChild - Moves from the current node to its child.
634 void MoveToChild() {
635 ReadNode = FlatTree[ReadNode].ChildNode;
636 }
637
638 /// AdvanceSibling - If there is a next sibling, advance to it and return
639 /// true. Otherwise, return false.
640 bool AdvanceSibling() {
641 if (FlatTree[ReadNode].NextNode == 0)
642 return false;
643
644 ReadNode = FlatTree[ReadNode].NextNode;
645 return true;
646 }
647
648 /// HasNextSibling - Return true if the node has a next sibling.
649 bool HasNextSibling() {
650 return FlatTree[ReadNode].NextNode != 0;
651 }
652
653 /// FromDefault - Return true if the from argument is the default.
654 bool FromDefault() {
655 return FlatTree[ReadNode].FromDefault;
656 }
657
658 /// ToDefault - Return true if the to argument is the default.
659 bool ToDefault() {
660 return FlatTree[ReadNode].ToDefault;
661 }
662
663 /// Empty - Returns true if the tree has no information.
664 bool Empty() {
665 return !FlatTree[0].FromTD && !FlatTree[0].ToTD &&
666 !FlatTree[0].FromExpr && !FlatTree[0].ToExpr &&
667 FlatTree[0].FromType.isNull() && FlatTree[0].ToType.isNull();
668 }
669 };
670
671 DiffTree Tree;
672
673 /// TSTiterator - an iterator that is used to enter a
674 /// TemplateSpecializationType and read TemplateArguments inside template
675 /// parameter packs in order with the rest of the TemplateArguments.
676 struct TSTiterator {
677 typedef const TemplateArgument& reference;
678 typedef const TemplateArgument* pointer;
679
680 /// TST - the template specialization whose arguments this iterator
681 /// traverse over.
682 const TemplateSpecializationType *TST;
683
684 /// Index - the index of the template argument in TST.
685 unsigned Index;
686
687 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
688 /// points to a TemplateArgument within a parameter pack.
689 TemplateArgument::pack_iterator CurrentTA;
690
691 /// EndTA - the end iterator of a parameter pack
692 TemplateArgument::pack_iterator EndTA;
693
694 /// TSTiterator - Constructs an iterator and sets it to the first template
695 /// argument.
696 TSTiterator(const TemplateSpecializationType *TST)
697 : TST(TST), Index(0), CurrentTA(0), EndTA(0) {
698 if (isEnd()) return;
699
700 // Set to first template argument. If not a parameter pack, done.
701 TemplateArgument TA = TST->getArg(0);
702 if (TA.getKind() != TemplateArgument::Pack) return;
703
704 // Start looking into the parameter pack.
705 CurrentTA = TA.pack_begin();
706 EndTA = TA.pack_end();
707
708 // Found a valid template argument.
709 if (CurrentTA != EndTA) return;
710
711 // Parameter pack is empty, use the increment to get to a valid
712 // template argument.
713 ++(*this);
714 }
715
716 /// isEnd - Returns true if the iterator is one past the end.
717 bool isEnd() const {
718 return Index == TST->getNumArgs();
719 }
720
721 /// &operator++ - Increment the iterator to the next template argument.
722 TSTiterator &operator++() {
723 assert(!isEnd() && "Iterator incremented past end of arguments.");
724
725 // If in a parameter pack, advance in the parameter pack.
726 if (CurrentTA != EndTA) {
727 ++CurrentTA;
728 if (CurrentTA != EndTA)
729 return *this;
730 }
731
732 // Loop until a template argument is found, or the end is reached.
733 while (true) {
734 // Advance to the next template argument. Break if reached the end.
735 if (++Index == TST->getNumArgs()) break;
736
737 // If the TemplateArgument is not a parameter pack, done.
738 TemplateArgument TA = TST->getArg(Index);
739 if (TA.getKind() != TemplateArgument::Pack) break;
740
741 // Handle parameter packs.
742 CurrentTA = TA.pack_begin();
743 EndTA = TA.pack_end();
744
745 // If the parameter pack is empty, try to advance again.
746 if (CurrentTA != EndTA) break;
747 }
748 return *this;
749 }
750
751 /// operator* - Returns the appropriate TemplateArgument.
752 reference operator*() const {
753 assert(!isEnd() && "Index exceeds number of arguments.");
754 if (CurrentTA == EndTA)
755 return TST->getArg(Index);
756 else
757 return *CurrentTA;
758 }
759
760 /// operator-> - Allow access to the underlying TemplateArgument.
761 pointer operator->() const {
762 return &operator*();
763 }
764 };
765
766 // These functions build up the template diff tree, including functions to
767 // retrieve and compare template arguments.
768
769 static const TemplateSpecializationType * GetTemplateSpecializationType(
770 ASTContext &Context, QualType Ty) {
771 if (const TemplateSpecializationType *TST =
772 Ty->getAs<TemplateSpecializationType>())
773 return TST;
774
775 const RecordType *RT = Ty->getAs<RecordType>();
776
777 if (!RT)
778 return 0;
779
780 const ClassTemplateSpecializationDecl *CTSD =
781 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
782
783 if (!CTSD)
784 return 0;
785
786 Ty = Context.getTemplateSpecializationType(
787 TemplateName(CTSD->getSpecializedTemplate()),
788 CTSD->getTemplateArgs().data(),
789 CTSD->getTemplateArgs().size(),
790 Ty.getCanonicalType());
791
792 return Ty->getAs<TemplateSpecializationType>();
793 }
794
795 /// DiffTemplate - recursively visits template arguments and stores the
796 /// argument info into a tree.
797 void DiffTemplate(const TemplateSpecializationType *FromTST,
798 const TemplateSpecializationType *ToTST) {
799 // Begin descent into diffing template tree.
800 TemplateParameterList *Params =
801 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
802 unsigned TotalArgs = 0;
803 for (TSTiterator FromIter(FromTST), ToIter(ToTST);
804 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
805 Tree.AddNode();
806
807 // Get the parameter at index TotalArgs. If index is larger
808 // than the total number of parameters, then there is an
809 // argument pack, so re-use the last parameter.
810 NamedDecl *ParamND = Params->getParam(
811 (TotalArgs < Params->size()) ? TotalArgs
812 : Params->size() - 1);
813 // Handle Types
814 if (TemplateTypeParmDecl *DefaultTTPD =
815 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
816 QualType FromType, ToType;
817 GetType(FromIter, DefaultTTPD, FromType);
818 GetType(ToIter, DefaultTTPD, ToType);
819 Tree.SetNode(FromType, ToType);
820 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
821 ToIter.isEnd() && !ToType.isNull());
822 if (!FromType.isNull() && !ToType.isNull()) {
823 if (Context.hasSameType(FromType, ToType)) {
824 Tree.SetSame(true);
825 } else {
Richard Trieub7243852012-09-28 20:32:51 +0000826 Qualifiers FromQual = FromType.getQualifiers(),
827 ToQual = ToType.getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +0000828 const TemplateSpecializationType *FromArgTST =
829 GetTemplateSpecializationType(Context, FromType);
830 const TemplateSpecializationType *ToArgTST =
831 GetTemplateSpecializationType(Context, ToType);
832
Richard Trieu8e14cac2012-09-28 19:51:57 +0000833 if (FromArgTST && ToArgTST &&
834 hasSameTemplate(FromArgTST, ToArgTST)) {
Richard Trieub7243852012-09-28 20:32:51 +0000835 FromQual -= QualType(FromArgTST, 0).getQualifiers();
836 ToQual -= QualType(ToArgTST, 0).getQualifiers();
Richard Trieu8e14cac2012-09-28 19:51:57 +0000837 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
838 ToArgTST->getTemplateName().getAsTemplateDecl());
Richard Trieub7243852012-09-28 20:32:51 +0000839 Tree.SetNode(FromQual, ToQual);
Richard Trieu8e14cac2012-09-28 19:51:57 +0000840 DiffTemplate(FromArgTST, ToArgTST);
Richard Trieu91844232012-06-26 18:18:47 +0000841 }
842 }
843 }
844 }
845
846 // Handle Expressions
847 if (NonTypeTemplateParmDecl *DefaultNTTPD =
848 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
849 Expr *FromExpr, *ToExpr;
Richard Trieu6df89452012-11-01 21:29:28 +0000850 llvm::APSInt FromInt, ToInt;
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000851 unsigned ParamWidth = 0;
852 if (DefaultNTTPD->getType()->isIntegralOrEnumerationType())
853 ParamWidth = Context.getIntWidth(DefaultNTTPD->getType());
Richard Trieu6df89452012-11-01 21:29:28 +0000854 bool HasFromInt = !FromIter.isEnd() &&
855 FromIter->getKind() == TemplateArgument::Integral;
856 bool HasToInt = !ToIter.isEnd() &&
857 ToIter->getKind() == TemplateArgument::Integral;
858 //bool IsValidFromInt = false, IsValidToInt = false;
859 if (HasFromInt)
860 FromInt = FromIter->getAsIntegral();
861 else
862 GetExpr(FromIter, DefaultNTTPD, FromExpr);
863
864 if (HasToInt)
865 ToInt = ToIter->getAsIntegral();
866 else
867 GetExpr(ToIter, DefaultNTTPD, ToExpr);
868
869 if (!HasFromInt && !HasToInt) {
870 Tree.SetNode(FromExpr, ToExpr);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000871 Tree.SetSame(IsEqualExpr(Context, ParamWidth, FromExpr, ToExpr));
Richard Trieu6df89452012-11-01 21:29:28 +0000872 Tree.SetDefault(FromIter.isEnd() && FromExpr,
873 ToIter.isEnd() && ToExpr);
874 } else {
875 if (!HasFromInt && FromExpr) {
876 FromInt = FromExpr->EvaluateKnownConstInt(Context);
877 HasFromInt = true;
878 }
879 if (!HasToInt && ToExpr) {
880 ToInt = ToExpr->EvaluateKnownConstInt(Context);
881 HasToInt = true;
882 }
883 Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
Eli Friedmanc2c982c2012-11-14 23:57:08 +0000884 Tree.SetSame(IsSameConvertedInt(ParamWidth, FromInt, ToInt));
Richard Trieu6df89452012-11-01 21:29:28 +0000885 Tree.SetDefault(FromIter.isEnd() && HasFromInt,
886 ToIter.isEnd() && HasToInt);
887 }
Richard Trieu91844232012-06-26 18:18:47 +0000888 }
889
890 // Handle Templates
891 if (TemplateTemplateParmDecl *DefaultTTPD =
892 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
893 TemplateDecl *FromDecl, *ToDecl;
894 GetTemplateDecl(FromIter, DefaultTTPD, FromDecl);
895 GetTemplateDecl(ToIter, DefaultTTPD, ToDecl);
896 Tree.SetNode(FromDecl, ToDecl);
897 Tree.SetSame(FromDecl && ToDecl &&
898 FromDecl->getIdentifier() == ToDecl->getIdentifier());
899 }
900
901 if (!FromIter.isEnd()) ++FromIter;
902 if (!ToIter.isEnd()) ++ToIter;
903 Tree.Up();
904 }
905 }
906
Richard Trieu8e14cac2012-09-28 19:51:57 +0000907 /// makeTemplateList - Dump every template alias into the vector.
908 static void makeTemplateList(
909 SmallVector<const TemplateSpecializationType*, 1> &TemplateList,
910 const TemplateSpecializationType *TST) {
911 while (TST) {
912 TemplateList.push_back(TST);
913 if (!TST->isTypeAlias())
914 return;
915 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
916 }
917 }
918
919 /// hasSameBaseTemplate - Returns true when the base templates are the same,
920 /// even if the template arguments are not.
921 static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
922 const TemplateSpecializationType *ToTST) {
923 return FromTST->getTemplateName().getAsTemplateDecl()->getIdentifier() ==
924 ToTST->getTemplateName().getAsTemplateDecl()->getIdentifier();
925 }
926
Richard Trieu91844232012-06-26 18:18:47 +0000927 /// hasSameTemplate - Returns true if both types are specialized from the
928 /// same template declaration. If they come from different template aliases,
929 /// do a parallel ascension search to determine the highest template alias in
930 /// common and set the arguments to them.
931 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
932 const TemplateSpecializationType *&ToTST) {
933 // Check the top templates if they are the same.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000934 if (hasSameBaseTemplate(FromTST, ToTST))
Richard Trieu91844232012-06-26 18:18:47 +0000935 return true;
936
937 // Create vectors of template aliases.
938 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
939 ToTemplateList;
940
Richard Trieu8e14cac2012-09-28 19:51:57 +0000941 makeTemplateList(FromTemplateList, FromTST);
942 makeTemplateList(ToTemplateList, ToTST);
Richard Trieu91844232012-06-26 18:18:47 +0000943
944 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
945 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
946 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
947
948 // Check if the lowest template types are the same. If not, return.
Richard Trieu8e14cac2012-09-28 19:51:57 +0000949 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +0000950 return false;
951
952 // Begin searching up the template aliases. The bottom most template
953 // matches so move up until one pair does not match. Use the template
954 // right before that one.
955 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
Richard Trieu8e14cac2012-09-28 19:51:57 +0000956 if (!hasSameBaseTemplate(*FromIter, *ToIter))
Richard Trieu91844232012-06-26 18:18:47 +0000957 break;
958 }
959
960 FromTST = FromIter[-1];
961 ToTST = ToIter[-1];
962
963 return true;
964 }
965
966 /// GetType - Retrieves the template type arguments, including default
967 /// arguments.
968 void GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD,
969 QualType &ArgType) {
970 ArgType = QualType();
971 bool isVariadic = DefaultTTPD->isParameterPack();
972
973 if (!Iter.isEnd())
974 ArgType = Iter->getAsType();
975 else if (!isVariadic)
976 ArgType = DefaultTTPD->getDefaultArgument();
David Blaikie47e45182012-06-26 18:52:09 +0000977 }
Richard Trieu91844232012-06-26 18:18:47 +0000978
979 /// GetExpr - Retrieves the template expression argument, including default
980 /// arguments.
981 void GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD,
982 Expr *&ArgExpr) {
983 ArgExpr = 0;
984 bool isVariadic = DefaultNTTPD->isParameterPack();
985
986 if (!Iter.isEnd())
987 ArgExpr = Iter->getAsExpr();
988 else if (!isVariadic)
989 ArgExpr = DefaultNTTPD->getDefaultArgument();
990
991 if (ArgExpr)
992 while (SubstNonTypeTemplateParmExpr *SNTTPE =
993 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
994 ArgExpr = SNTTPE->getReplacement();
995 }
996
997 /// GetTemplateDecl - Retrieves the template template arguments, including
998 /// default arguments.
999 void GetTemplateDecl(const TSTiterator &Iter,
1000 TemplateTemplateParmDecl *DefaultTTPD,
1001 TemplateDecl *&ArgDecl) {
1002 ArgDecl = 0;
1003 bool isVariadic = DefaultTTPD->isParameterPack();
1004
1005 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
Eli Friedmanb826a002012-09-26 02:36:12 +00001006 TemplateDecl *DefaultTD = 0;
1007 if (TA.getKind() != TemplateArgument::Null)
1008 DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
Richard Trieu91844232012-06-26 18:18:47 +00001009
1010 if (!Iter.isEnd())
1011 ArgDecl = Iter->getAsTemplate().getAsTemplateDecl();
1012 else if (!isVariadic)
1013 ArgDecl = DefaultTD;
1014 }
1015
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001016 /// IsSameConvertedInt - Returns true if both integers are equal when
1017 /// converted to an integer type with the given width.
1018 static bool IsSameConvertedInt(unsigned Width, const llvm::APSInt &X,
1019 const llvm::APSInt &Y) {
1020 llvm::APInt ConvertedX = X.extOrTrunc(Width);
1021 llvm::APInt ConvertedY = Y.extOrTrunc(Width);
1022 return ConvertedX == ConvertedY;
1023 }
1024
Richard Trieu91844232012-06-26 18:18:47 +00001025 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001026 static bool IsEqualExpr(ASTContext &Context, unsigned ParamWidth,
1027 Expr *FromExpr, Expr *ToExpr) {
Richard Trieu91844232012-06-26 18:18:47 +00001028 if (FromExpr == ToExpr)
1029 return true;
1030
1031 if (!FromExpr || !ToExpr)
1032 return false;
1033
1034 FromExpr = FromExpr->IgnoreParens();
1035 ToExpr = ToExpr->IgnoreParens();
1036
1037 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
1038 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
1039
1040 if (FromDRE || ToDRE) {
1041 if (!FromDRE || !ToDRE)
1042 return false;
1043 return FromDRE->getDecl() == ToDRE->getDecl();
1044 }
1045
1046 Expr::EvalResult FromResult, ToResult;
1047 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
1048 !ToExpr->EvaluateAsRValue(ToResult, Context))
1049 assert(0 && "Template arguments must be known at compile time.");
1050
1051 APValue &FromVal = FromResult.Val;
1052 APValue &ToVal = ToResult.Val;
1053
1054 if (FromVal.getKind() != ToVal.getKind()) return false;
1055
1056 switch (FromVal.getKind()) {
1057 case APValue::Int:
Eli Friedmanc2c982c2012-11-14 23:57:08 +00001058 return IsSameConvertedInt(ParamWidth, FromVal.getInt(), ToVal.getInt());
Richard Trieu91844232012-06-26 18:18:47 +00001059 case APValue::LValue: {
1060 APValue::LValueBase FromBase = FromVal.getLValueBase();
1061 APValue::LValueBase ToBase = ToVal.getLValueBase();
1062 if (FromBase.isNull() && ToBase.isNull())
1063 return true;
1064 if (FromBase.isNull() || ToBase.isNull())
1065 return false;
1066 return FromBase.get<const ValueDecl*>() ==
1067 ToBase.get<const ValueDecl*>();
1068 }
1069 case APValue::MemberPointer:
1070 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
1071 default:
1072 llvm_unreachable("Unknown template argument expression.");
1073 }
1074 }
1075
1076 // These functions converts the tree representation of the template
1077 // differences into the internal character vector.
1078
1079 /// TreeToString - Converts the Tree object into a character stream which
1080 /// will later be turned into the output string.
1081 void TreeToString(int Indent = 1) {
1082 if (PrintTree) {
1083 OS << '\n';
1084 for (int i = 0; i < Indent; ++i)
1085 OS << " ";
1086 ++Indent;
1087 }
1088
1089 // Handle cases where the difference is not templates with different
1090 // arguments.
1091 if (!Tree.NodeIsTemplate()) {
1092 if (Tree.NodeIsQualType()) {
1093 QualType FromType, ToType;
1094 Tree.GetNode(FromType, ToType);
1095 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1096 Tree.NodeIsSame());
1097 return;
1098 }
1099 if (Tree.NodeIsExpr()) {
1100 Expr *FromExpr, *ToExpr;
1101 Tree.GetNode(FromExpr, ToExpr);
1102 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1103 Tree.NodeIsSame());
1104 return;
1105 }
1106 if (Tree.NodeIsTemplateTemplate()) {
1107 TemplateDecl *FromTD, *ToTD;
1108 Tree.GetNode(FromTD, ToTD);
1109 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1110 Tree.ToDefault(), Tree.NodeIsSame());
1111 return;
1112 }
Richard Trieu6df89452012-11-01 21:29:28 +00001113
1114 if (Tree.NodeIsAPSInt()) {
1115 llvm::APSInt FromInt, ToInt;
1116 bool IsValidFromInt, IsValidToInt;
1117 Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
1118 PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
1119 Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
1120 return;
1121 }
Richard Trieu91844232012-06-26 18:18:47 +00001122 llvm_unreachable("Unable to deduce template difference.");
1123 }
1124
1125 // Node is root of template. Recurse on children.
1126 TemplateDecl *FromTD, *ToTD;
1127 Tree.GetNode(FromTD, ToTD);
1128
1129 assert(Tree.HasChildren() && "Template difference not found in diff tree.");
1130
Richard Trieub7243852012-09-28 20:32:51 +00001131 Qualifiers FromQual, ToQual;
1132 Tree.GetNode(FromQual, ToQual);
1133 PrintQualifiers(FromQual, ToQual);
1134
Richard Trieu91844232012-06-26 18:18:47 +00001135 OS << FromTD->getNameAsString() << '<';
1136 Tree.MoveToChild();
1137 unsigned NumElideArgs = 0;
1138 do {
1139 if (ElideType) {
1140 if (Tree.NodeIsSame()) {
1141 ++NumElideArgs;
1142 continue;
1143 }
1144 if (NumElideArgs > 0) {
1145 PrintElideArgs(NumElideArgs, Indent);
1146 NumElideArgs = 0;
1147 OS << ", ";
1148 }
1149 }
1150 TreeToString(Indent);
1151 if (Tree.HasNextSibling())
1152 OS << ", ";
1153 } while (Tree.AdvanceSibling());
1154 if (NumElideArgs > 0)
1155 PrintElideArgs(NumElideArgs, Indent);
1156
1157 Tree.Parent();
1158 OS << ">";
1159 }
1160
1161 // To signal to the text printer that a certain text needs to be bolded,
1162 // a special character is injected into the character stream which the
1163 // text printer will later strip out.
1164
1165 /// Bold - Start bolding text.
1166 void Bold() {
1167 assert(!IsBold && "Attempting to bold text that is already bold.");
1168 IsBold = true;
1169 if (ShowColor)
1170 OS << ToggleHighlight;
1171 }
1172
1173 /// Unbold - Stop bolding text.
1174 void Unbold() {
1175 assert(IsBold && "Attempting to remove bold from unbold text.");
1176 IsBold = false;
1177 if (ShowColor)
1178 OS << ToggleHighlight;
1179 }
1180
1181 // Functions to print out the arguments and highlighting the difference.
1182
1183 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1184 /// typenames that are the same and attempt to disambiguate them by using
1185 /// canonical typenames.
1186 void PrintTypeNames(QualType FromType, QualType ToType,
1187 bool FromDefault, bool ToDefault, bool Same) {
1188 assert((!FromType.isNull() || !ToType.isNull()) &&
1189 "Only one template argument may be missing.");
1190
1191 if (Same) {
1192 OS << FromType.getAsString();
1193 return;
1194 }
1195
Richard Trieub7243852012-09-28 20:32:51 +00001196 if (!FromType.isNull() && !ToType.isNull() &&
1197 FromType.getLocalUnqualifiedType() ==
1198 ToType.getLocalUnqualifiedType()) {
1199 Qualifiers FromQual = FromType.getLocalQualifiers(),
1200 ToQual = ToType.getLocalQualifiers(),
1201 CommonQual;
1202 PrintQualifiers(FromQual, ToQual);
1203 FromType.getLocalUnqualifiedType().print(OS, Policy);
1204 return;
1205 }
1206
Richard Trieu91844232012-06-26 18:18:47 +00001207 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1208 : FromType.getAsString();
1209 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1210 : ToType.getAsString();
1211 // Switch to canonical typename if it is better.
1212 // TODO: merge this with other aka printing above.
1213 if (FromTypeStr == ToTypeStr) {
1214 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1215 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1216 if (FromCanTypeStr != ToCanTypeStr) {
1217 FromTypeStr = FromCanTypeStr;
1218 ToTypeStr = ToCanTypeStr;
1219 }
1220 }
1221
1222 if (PrintTree) OS << '[';
1223 OS << (FromDefault ? "(default) " : "");
1224 Bold();
1225 OS << FromTypeStr;
1226 Unbold();
1227 if (PrintTree) {
1228 OS << " != " << (ToDefault ? "(default) " : "");
1229 Bold();
1230 OS << ToTypeStr;
1231 Unbold();
1232 OS << "]";
1233 }
1234 return;
1235 }
1236
1237 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1238 /// differences.
1239 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1240 bool FromDefault, bool ToDefault, bool Same) {
1241 assert((FromExpr || ToExpr) &&
1242 "Only one template argument may be missing.");
1243 if (Same) {
1244 PrintExpr(FromExpr);
1245 } else if (!PrintTree) {
1246 OS << (FromDefault ? "(default) " : "");
1247 Bold();
1248 PrintExpr(FromExpr);
1249 Unbold();
1250 } else {
1251 OS << (FromDefault ? "[(default) " : "[");
1252 Bold();
1253 PrintExpr(FromExpr);
1254 Unbold();
1255 OS << " != " << (ToDefault ? "(default) " : "");
1256 Bold();
1257 PrintExpr(ToExpr);
1258 Unbold();
1259 OS << ']';
1260 }
1261 }
1262
1263 /// PrintExpr - Actual formatting and printing of expressions.
1264 void PrintExpr(const Expr *E) {
1265 if (!E)
1266 OS << "(no argument)";
1267 else
Richard Smith235341b2012-08-16 03:56:14 +00001268 E->printPretty(OS, 0, Policy); return;
Richard Trieu91844232012-06-26 18:18:47 +00001269 }
1270
1271 /// PrintTemplateTemplate - Handles printing of template template arguments,
1272 /// highlighting argument differences.
1273 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1274 bool FromDefault, bool ToDefault, bool Same) {
1275 assert((FromTD || ToTD) && "Only one template argument may be missing.");
1276 if (Same) {
1277 OS << "template " << FromTD->getNameAsString();
1278 } else if (!PrintTree) {
1279 OS << (FromDefault ? "(default) template " : "template ");
1280 Bold();
1281 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1282 Unbold();
1283 } else {
1284 OS << (FromDefault ? "[(default) template " : "[template ");
1285 Bold();
1286 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1287 Unbold();
1288 OS << " != " << (ToDefault ? "(default) template " : "template ");
1289 Bold();
1290 OS << (ToTD ? ToTD->getNameAsString() : "(no argument)");
1291 Unbold();
1292 OS << ']';
1293 }
1294 }
1295
Richard Trieu6df89452012-11-01 21:29:28 +00001296 /// PrintAPSInt - Handles printing of integral arguments, highlighting
1297 /// argument differences.
1298 void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
1299 bool IsValidFromInt, bool IsValidToInt, bool FromDefault,
1300 bool ToDefault, bool Same) {
1301 assert((IsValidFromInt || IsValidToInt) &&
1302 "Only one integral argument may be missing.");
1303
1304 if (Same) {
1305 OS << FromInt.toString(10);
1306 } else if (!PrintTree) {
1307 OS << (FromDefault ? "(default) " : "");
1308 Bold();
1309 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1310 Unbold();
1311 } else {
1312 OS << (FromDefault ? "[(default) " : "[");
1313 Bold();
1314 OS << (IsValidFromInt ? FromInt.toString(10) : "(no argument)");
1315 Unbold();
1316 OS << " != " << (ToDefault ? "(default) " : "");
1317 Bold();
1318 OS << (IsValidToInt ? ToInt.toString(10) : "(no argument)");
1319 Unbold();
1320 OS << ']';
1321 }
1322 }
1323
Richard Trieu91844232012-06-26 18:18:47 +00001324 // Prints the appropriate placeholder for elided template arguments.
1325 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1326 if (PrintTree) {
1327 OS << '\n';
1328 for (unsigned i = 0; i < Indent; ++i)
1329 OS << " ";
1330 }
1331 if (NumElideArgs == 0) return;
1332 if (NumElideArgs == 1)
1333 OS << "[...]";
1334 else
1335 OS << "[" << NumElideArgs << " * ...]";
1336 }
1337
Richard Trieub7243852012-09-28 20:32:51 +00001338 // Prints and highlights differences in Qualifiers.
1339 void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
1340 // Both types have no qualifiers
1341 if (FromQual.empty() && ToQual.empty())
1342 return;
1343
1344 // Both types have same qualifiers
1345 if (FromQual == ToQual) {
1346 PrintQualifier(FromQual, /*ApplyBold*/false);
1347 return;
1348 }
1349
1350 // Find common qualifiers and strip them from FromQual and ToQual.
1351 Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
1352 ToQual);
1353
1354 // The qualifiers are printed before the template name.
1355 // Inline printing:
1356 // The common qualifiers are printed. Then, qualifiers only in this type
1357 // are printed and highlighted. Finally, qualifiers only in the other
1358 // type are printed and highlighted inside parentheses after "missing".
1359 // Tree printing:
1360 // Qualifiers are printed next to each other, inside brackets, and
1361 // separated by "!=". The printing order is:
1362 // common qualifiers, highlighted from qualifiers, "!=",
1363 // common qualifiers, highlighted to qualifiers
1364 if (PrintTree) {
1365 OS << "[";
1366 if (CommonQual.empty() && FromQual.empty()) {
1367 Bold();
1368 OS << "(no qualifiers) ";
1369 Unbold();
1370 } else {
1371 PrintQualifier(CommonQual, /*ApplyBold*/false);
1372 PrintQualifier(FromQual, /*ApplyBold*/true);
1373 }
1374 OS << "!= ";
1375 if (CommonQual.empty() && ToQual.empty()) {
1376 Bold();
1377 OS << "(no qualifiers)";
1378 Unbold();
1379 } else {
1380 PrintQualifier(CommonQual, /*ApplyBold*/false,
1381 /*appendSpaceIfNonEmpty*/!ToQual.empty());
1382 PrintQualifier(ToQual, /*ApplyBold*/true,
1383 /*appendSpaceIfNonEmpty*/false);
1384 }
1385 OS << "] ";
1386 } else {
1387 PrintQualifier(CommonQual, /*ApplyBold*/false);
1388 PrintQualifier(FromQual, /*ApplyBold*/true);
1389 }
1390 }
1391
1392 void PrintQualifier(Qualifiers Q, bool ApplyBold,
1393 bool AppendSpaceIfNonEmpty = true) {
1394 if (Q.empty()) return;
1395 if (ApplyBold) Bold();
1396 Q.print(OS, Policy, AppendSpaceIfNonEmpty);
1397 if (ApplyBold) Unbold();
1398 }
1399
Richard Trieu91844232012-06-26 18:18:47 +00001400public:
1401
1402 TemplateDiff(ASTContext &Context, QualType FromType, QualType ToType,
1403 bool PrintTree, bool PrintFromType, bool ElideType,
1404 bool ShowColor)
1405 : Context(Context),
1406 Policy(Context.getLangOpts()),
1407 ElideType(ElideType),
1408 PrintTree(PrintTree),
1409 ShowColor(ShowColor),
1410 // When printing a single type, the FromType is the one printed.
1411 FromType(PrintFromType ? FromType : ToType),
1412 ToType(PrintFromType ? ToType : FromType),
1413 OS(Str),
1414 IsBold(false) {
1415 }
1416
1417 /// DiffTemplate - Start the template type diffing.
1418 void DiffTemplate() {
Richard Trieub7243852012-09-28 20:32:51 +00001419 Qualifiers FromQual = FromType.getQualifiers(),
1420 ToQual = ToType.getQualifiers();
1421
Richard Trieu91844232012-06-26 18:18:47 +00001422 const TemplateSpecializationType *FromOrigTST =
1423 GetTemplateSpecializationType(Context, FromType);
1424 const TemplateSpecializationType *ToOrigTST =
1425 GetTemplateSpecializationType(Context, ToType);
1426
1427 // Only checking templates.
1428 if (!FromOrigTST || !ToOrigTST)
1429 return;
1430
1431 // Different base templates.
1432 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1433 return;
1434 }
1435
Richard Trieub7243852012-09-28 20:32:51 +00001436 FromQual -= QualType(FromOrigTST, 0).getQualifiers();
1437 ToQual -= QualType(ToOrigTST, 0).getQualifiers();
Richard Trieu91844232012-06-26 18:18:47 +00001438 Tree.SetNode(FromType, ToType);
Richard Trieub7243852012-09-28 20:32:51 +00001439 Tree.SetNode(FromQual, ToQual);
Richard Trieu91844232012-06-26 18:18:47 +00001440
1441 // Same base template, but different arguments.
1442 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1443 ToOrigTST->getTemplateName().getAsTemplateDecl());
1444
1445 DiffTemplate(FromOrigTST, ToOrigTST);
David Blaikie47e45182012-06-26 18:52:09 +00001446 }
Richard Trieu91844232012-06-26 18:18:47 +00001447
1448 /// MakeString - When the two types given are templated types with the same
1449 /// base template, a string representation of the type difference will be
1450 /// loaded into S and return true. Otherwise, return false.
1451 bool MakeString(std::string &S) {
1452 Tree.StartTraverse();
1453 if (Tree.Empty())
1454 return false;
1455
1456 TreeToString();
1457 assert(!IsBold && "Bold is applied to end of string.");
1458 S = OS.str();
1459 return true;
1460 }
1461}; // end class TemplateDiff
1462} // end namespace
1463
1464/// FormatTemplateTypeDiff - A helper static function to start the template
1465/// diff and return the properly formatted string. Returns true if the diff
1466/// is successful.
1467static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1468 QualType ToType, bool PrintTree,
1469 bool PrintFromType, bool ElideType,
1470 bool ShowColors, std::string &S) {
1471 if (PrintTree)
1472 PrintFromType = true;
1473 TemplateDiff TD(Context, FromType, ToType, PrintTree, PrintFromType,
1474 ElideType, ShowColors);
1475 TD.DiffTemplate();
1476 return TD.MakeString(S);
1477}