blob: a5733237efa8e57e5f86e127455211c62d3eb40c [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: {
257 const TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
258 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;
267 break;
268 }
269
270 // Don't fall-back during tree printing. The caller will handle
271 // this case.
272 if (TDT.PrintTree)
273 return;
274
275 // Attempting to do a templete diff on non-templates. Set the variables
276 // and continue with regular type printing of the appropriate type.
277 Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
278 ModLen = 0;
279 ArgLen = 0;
280 // Fall through
281 }
David Blaikie9c902b52011-09-25 23:23:43 +0000282 case DiagnosticsEngine::ak_qualtype: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000283 assert(ModLen == 0 && ArgLen == 0 &&
284 "Invalid modifier for QualType argument");
285
286 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chandler Carruthd5173952011-07-11 17:49:21 +0000287 S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs,
288 QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000289 NeedQuotes = false;
290 break;
291 }
David Blaikie9c902b52011-09-25 23:23:43 +0000292 case DiagnosticsEngine::ak_declarationname: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000293 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
294 S = N.getAsString();
295
296 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
297 S = '+' + S;
298 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12)
299 && ArgLen==0)
300 S = '-' + S;
301 else
302 assert(ModLen == 0 && ArgLen == 0 &&
303 "Invalid modifier for DeclarationName argument");
304 break;
305 }
David Blaikie9c902b52011-09-25 23:23:43 +0000306 case DiagnosticsEngine::ak_nameddecl: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000307 bool Qualified;
308 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
309 Qualified = true;
310 else {
311 assert(ModLen == 0 && ArgLen == 0 &&
312 "Invalid modifier for NamedDecl* argument");
313 Qualified = false;
314 }
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000315 const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
Douglas Gregorc0b07282011-09-27 22:38:19 +0000316 ND->getNameForDiagnostic(S, Context.getPrintingPolicy(), Qualified);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000317 break;
318 }
David Blaikie9c902b52011-09-25 23:23:43 +0000319 case DiagnosticsEngine::ak_nestednamespec: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000320 llvm::raw_string_ostream OS(S);
321 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
Douglas Gregorc0b07282011-09-27 22:38:19 +0000322 Context.getPrintingPolicy());
Douglas Gregor639cccc2010-02-09 22:26:47 +0000323 NeedQuotes = false;
324 break;
325 }
David Blaikie9c902b52011-09-25 23:23:43 +0000326 case DiagnosticsEngine::ak_declcontext: {
Douglas Gregor639cccc2010-02-09 22:26:47 +0000327 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
328 assert(DC && "Should never have a null declaration context");
329
330 if (DC->isTranslationUnit()) {
331 // FIXME: Get these strings from some localized place
David Blaikiebbafb8a2012-03-11 07:00:24 +0000332 if (Context.getLangOpts().CPlusPlus)
Douglas Gregor639cccc2010-02-09 22:26:47 +0000333 S = "the global namespace";
334 else
335 S = "the global scope";
336 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
337 S = ConvertTypeToDiagnosticString(Context,
338 Context.getTypeDeclType(Type),
Chandler Carruthd5173952011-07-11 17:49:21 +0000339 PrevArgs, NumPrevArgs, QualTypeVals);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000340 } else {
341 // FIXME: Get these strings from some localized place
342 NamedDecl *ND = cast<NamedDecl>(DC);
343 if (isa<NamespaceDecl>(ND))
344 S += "namespace ";
345 else if (isa<ObjCMethodDecl>(ND))
346 S += "method ";
347 else if (isa<FunctionDecl>(ND))
348 S += "function ";
349
350 S += "'";
Douglas Gregorc0b07282011-09-27 22:38:19 +0000351 ND->getNameForDiagnostic(S, Context.getPrintingPolicy(), true);
Douglas Gregor639cccc2010-02-09 22:26:47 +0000352 S += "'";
353 }
354 NeedQuotes = false;
355 break;
356 }
357 }
358
359 if (NeedQuotes)
360 Output.push_back('\'');
361
362 Output.append(S.begin(), S.end());
363
364 if (NeedQuotes)
365 Output.push_back('\'');
366}
Richard Trieu91844232012-06-26 18:18:47 +0000367
368/// TemplateDiff - A class that constructs a pretty string for a pair of
369/// QualTypes. For the pair of types, a diff tree will be created containing
370/// all the information about the templates and template arguments. Afterwards,
371/// the tree is transformed to a string according to the options passed in.
372namespace {
373class TemplateDiff {
374 /// Context - The ASTContext which is used for comparing template arguments.
375 ASTContext &Context;
376
377 /// Policy - Used during expression printing.
378 PrintingPolicy Policy;
379
380 /// ElideType - Option to elide identical types.
381 bool ElideType;
382
383 /// PrintTree - Format output string as a tree.
384 bool PrintTree;
385
386 /// ShowColor - Diagnostics support color, so bolding will be used.
387 bool ShowColor;
388
389 /// FromType - When single type printing is selected, this is the type to be
390 /// be printed. When tree printing is selected, this type will show up first
391 /// in the tree.
392 QualType FromType;
393
394 /// ToType - The type that FromType is compared to. Only in tree printing
395 /// will this type be outputed.
396 QualType ToType;
397
398 /// Str - Storage for the output stream.
399 llvm::SmallString<128> Str;
400
401 /// OS - The stream used to construct the output strings.
402 llvm::raw_svector_ostream OS;
403
404 /// IsBold - Keeps track of the bold formatting for the output string.
405 bool IsBold;
406
407 /// DiffTree - A tree representation the differences between two types.
408 class DiffTree {
409 /// DiffNode - The root node stores the original type. Each child node
410 /// stores template arguments of their parents. For templated types, the
411 /// template decl is also stored.
412 struct DiffNode {
413 /// NextNode - The index of the next sibling node or 0.
414 unsigned NextNode;
415
416 /// ChildNode - The index of the first child node or 0.
417 unsigned ChildNode;
418
419 /// ParentNode - The index of the parent node.
420 unsigned ParentNode;
421
422 /// FromType, ToType - The type arguments.
423 QualType FromType, ToType;
424
425 /// FromExpr, ToExpr - The expression arguments.
426 Expr *FromExpr, *ToExpr;
427
428 /// FromTD, ToTD - The template decl for template template
429 /// arguments or the type arguments that are templates.
430 TemplateDecl *FromTD, *ToTD;
431
432 /// FromDefault, ToDefault - Whether the argument is a default argument.
433 bool FromDefault, ToDefault;
434
435 /// Same - Whether the two arguments evaluate to the same value.
436 bool Same;
437
438 DiffNode(unsigned ParentNode = 0)
439 : NextNode(0), ChildNode(0), ParentNode(ParentNode),
440 FromType(), ToType(), FromExpr(0), ToExpr(0), FromTD(0), ToTD(0),
441 FromDefault(false), ToDefault(false), Same(false) { }
442 };
443
444 /// FlatTree - A flattened tree used to store the DiffNodes.
445 llvm::SmallVector<DiffNode, 16> FlatTree;
446
447 /// CurrentNode - The index of the current node being used.
448 unsigned CurrentNode;
449
450 /// NextFreeNode - The index of the next unused node. Used when creating
451 /// child nodes.
452 unsigned NextFreeNode;
453
454 /// ReadNode - The index of the current node being read.
455 unsigned ReadNode;
456
457 public:
458 DiffTree() :
459 CurrentNode(0), NextFreeNode(1) {
460 FlatTree.push_back(DiffNode());
461 }
462
463 // Node writing functions.
464 /// SetNode - Sets FromTD and ToTD of the current node.
465 void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
466 FlatTree[CurrentNode].FromTD = FromTD;
467 FlatTree[CurrentNode].ToTD = ToTD;
468 }
469
470 /// SetNode - Sets FromType and ToType of the current node.
471 void SetNode(QualType FromType, QualType ToType) {
472 FlatTree[CurrentNode].FromType = FromType;
473 FlatTree[CurrentNode].ToType = ToType;
474 }
475
476 /// SetNode - Set FromExpr and ToExpr of the current node.
477 void SetNode(Expr *FromExpr, Expr *ToExpr) {
478 FlatTree[CurrentNode].FromExpr = FromExpr;
479 FlatTree[CurrentNode].ToExpr = ToExpr;
480 }
481
482 /// SetSame - Sets the same flag of the current node.
483 void SetSame(bool Same) {
484 FlatTree[CurrentNode].Same = Same;
485 }
486
487 /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
488 void SetDefault(bool FromDefault, bool ToDefault) {
489 FlatTree[CurrentNode].FromDefault = FromDefault;
490 FlatTree[CurrentNode].ToDefault = ToDefault;
491 }
492
493 /// Up - Changes the node to the parent of the current node.
494 void Up() {
495 CurrentNode = FlatTree[CurrentNode].ParentNode;
496 }
497
498 /// AddNode - Adds a child node to the current node, then sets that node
499 /// node as the current node.
500 void AddNode() {
501 FlatTree.push_back(DiffNode(CurrentNode));
502 DiffNode &Node = FlatTree[CurrentNode];
503 if (Node.ChildNode == 0) {
504 // If a child node doesn't exist, add one.
505 Node.ChildNode = NextFreeNode;
506 } else {
507 // If a child node exists, find the last child node and add a
508 // next node to it.
509 unsigned i;
510 for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
511 i = FlatTree[i].NextNode) {
512 }
513 FlatTree[i].NextNode = NextFreeNode;
514 }
515 CurrentNode = NextFreeNode;
516 ++NextFreeNode;
517 }
518
519 // Node reading functions.
520 /// StartTraverse - Prepares the tree for recursive traversal.
521 void StartTraverse() {
522 ReadNode = 0;
523 CurrentNode = NextFreeNode;
524 NextFreeNode = 0;
525 }
526
527 /// Parent - Move the current read node to its parent.
528 void Parent() {
529 ReadNode = FlatTree[ReadNode].ParentNode;
530 }
531
532 /// NodeIsTemplate - Returns true if a template decl is set, and types are
533 /// set.
534 bool NodeIsTemplate() {
535 return (FlatTree[ReadNode].FromTD &&
536 !FlatTree[ReadNode].ToType.isNull()) ||
537 (FlatTree[ReadNode].ToTD && !FlatTree[ReadNode].ToType.isNull());
538 }
539
540 /// NodeIsQualType - Returns true if a Qualtype is set.
541 bool NodeIsQualType() {
542 return !FlatTree[ReadNode].FromType.isNull() ||
543 !FlatTree[ReadNode].ToType.isNull();
544 }
545
546 /// NodeIsExpr - Returns true if an expr is set.
547 bool NodeIsExpr() {
548 return FlatTree[ReadNode].FromExpr || FlatTree[ReadNode].ToExpr;
549 }
550
551 /// NodeIsTemplateTemplate - Returns true if the argument is a template
552 /// template type.
553 bool NodeIsTemplateTemplate() {
554 return FlatTree[ReadNode].FromType.isNull() &&
555 FlatTree[ReadNode].ToType.isNull() &&
556 (FlatTree[ReadNode].FromTD || FlatTree[ReadNode].ToTD);
557 }
558
559 /// GetNode - Gets the FromType and ToType.
560 void GetNode(QualType &FromType, QualType &ToType) {
561 FromType = FlatTree[ReadNode].FromType;
562 ToType = FlatTree[ReadNode].ToType;
563 }
564
565 /// GetNode - Gets the FromExpr and ToExpr.
566 void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
567 FromExpr = FlatTree[ReadNode].FromExpr;
568 ToExpr = FlatTree[ReadNode].ToExpr;
569 }
570
571 /// GetNode - Gets the FromTD and ToTD.
572 void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
573 FromTD = FlatTree[ReadNode].FromTD;
574 ToTD = FlatTree[ReadNode].ToTD;
575 }
576
577 /// NodeIsSame - Returns true the arguments are the same.
578 bool NodeIsSame() {
579 return FlatTree[ReadNode].Same;
580 }
581
582 /// HasChildrend - Returns true if the node has children.
583 bool HasChildren() {
584 return FlatTree[ReadNode].ChildNode != 0;
585 }
586
587 /// MoveToChild - Moves from the current node to its child.
588 void MoveToChild() {
589 ReadNode = FlatTree[ReadNode].ChildNode;
590 }
591
592 /// AdvanceSibling - If there is a next sibling, advance to it and return
593 /// true. Otherwise, return false.
594 bool AdvanceSibling() {
595 if (FlatTree[ReadNode].NextNode == 0)
596 return false;
597
598 ReadNode = FlatTree[ReadNode].NextNode;
599 return true;
600 }
601
602 /// HasNextSibling - Return true if the node has a next sibling.
603 bool HasNextSibling() {
604 return FlatTree[ReadNode].NextNode != 0;
605 }
606
607 /// FromDefault - Return true if the from argument is the default.
608 bool FromDefault() {
609 return FlatTree[ReadNode].FromDefault;
610 }
611
612 /// ToDefault - Return true if the to argument is the default.
613 bool ToDefault() {
614 return FlatTree[ReadNode].ToDefault;
615 }
616
617 /// Empty - Returns true if the tree has no information.
618 bool Empty() {
619 return !FlatTree[0].FromTD && !FlatTree[0].ToTD &&
620 !FlatTree[0].FromExpr && !FlatTree[0].ToExpr &&
621 FlatTree[0].FromType.isNull() && FlatTree[0].ToType.isNull();
622 }
623 };
624
625 DiffTree Tree;
626
627 /// TSTiterator - an iterator that is used to enter a
628 /// TemplateSpecializationType and read TemplateArguments inside template
629 /// parameter packs in order with the rest of the TemplateArguments.
630 struct TSTiterator {
631 typedef const TemplateArgument& reference;
632 typedef const TemplateArgument* pointer;
633
634 /// TST - the template specialization whose arguments this iterator
635 /// traverse over.
636 const TemplateSpecializationType *TST;
637
638 /// Index - the index of the template argument in TST.
639 unsigned Index;
640
641 /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
642 /// points to a TemplateArgument within a parameter pack.
643 TemplateArgument::pack_iterator CurrentTA;
644
645 /// EndTA - the end iterator of a parameter pack
646 TemplateArgument::pack_iterator EndTA;
647
648 /// TSTiterator - Constructs an iterator and sets it to the first template
649 /// argument.
650 TSTiterator(const TemplateSpecializationType *TST)
651 : TST(TST), Index(0), CurrentTA(0), EndTA(0) {
652 if (isEnd()) return;
653
654 // Set to first template argument. If not a parameter pack, done.
655 TemplateArgument TA = TST->getArg(0);
656 if (TA.getKind() != TemplateArgument::Pack) return;
657
658 // Start looking into the parameter pack.
659 CurrentTA = TA.pack_begin();
660 EndTA = TA.pack_end();
661
662 // Found a valid template argument.
663 if (CurrentTA != EndTA) return;
664
665 // Parameter pack is empty, use the increment to get to a valid
666 // template argument.
667 ++(*this);
668 }
669
670 /// isEnd - Returns true if the iterator is one past the end.
671 bool isEnd() const {
672 return Index == TST->getNumArgs();
673 }
674
675 /// &operator++ - Increment the iterator to the next template argument.
676 TSTiterator &operator++() {
677 assert(!isEnd() && "Iterator incremented past end of arguments.");
678
679 // If in a parameter pack, advance in the parameter pack.
680 if (CurrentTA != EndTA) {
681 ++CurrentTA;
682 if (CurrentTA != EndTA)
683 return *this;
684 }
685
686 // Loop until a template argument is found, or the end is reached.
687 while (true) {
688 // Advance to the next template argument. Break if reached the end.
689 if (++Index == TST->getNumArgs()) break;
690
691 // If the TemplateArgument is not a parameter pack, done.
692 TemplateArgument TA = TST->getArg(Index);
693 if (TA.getKind() != TemplateArgument::Pack) break;
694
695 // Handle parameter packs.
696 CurrentTA = TA.pack_begin();
697 EndTA = TA.pack_end();
698
699 // If the parameter pack is empty, try to advance again.
700 if (CurrentTA != EndTA) break;
701 }
702 return *this;
703 }
704
705 /// operator* - Returns the appropriate TemplateArgument.
706 reference operator*() const {
707 assert(!isEnd() && "Index exceeds number of arguments.");
708 if (CurrentTA == EndTA)
709 return TST->getArg(Index);
710 else
711 return *CurrentTA;
712 }
713
714 /// operator-> - Allow access to the underlying TemplateArgument.
715 pointer operator->() const {
716 return &operator*();
717 }
718 };
719
720 // These functions build up the template diff tree, including functions to
721 // retrieve and compare template arguments.
722
723 static const TemplateSpecializationType * GetTemplateSpecializationType(
724 ASTContext &Context, QualType Ty) {
725 if (const TemplateSpecializationType *TST =
726 Ty->getAs<TemplateSpecializationType>())
727 return TST;
728
729 const RecordType *RT = Ty->getAs<RecordType>();
730
731 if (!RT)
732 return 0;
733
734 const ClassTemplateSpecializationDecl *CTSD =
735 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
736
737 if (!CTSD)
738 return 0;
739
740 Ty = Context.getTemplateSpecializationType(
741 TemplateName(CTSD->getSpecializedTemplate()),
742 CTSD->getTemplateArgs().data(),
743 CTSD->getTemplateArgs().size(),
744 Ty.getCanonicalType());
745
746 return Ty->getAs<TemplateSpecializationType>();
747 }
748
749 /// DiffTemplate - recursively visits template arguments and stores the
750 /// argument info into a tree.
751 void DiffTemplate(const TemplateSpecializationType *FromTST,
752 const TemplateSpecializationType *ToTST) {
753 // Begin descent into diffing template tree.
754 TemplateParameterList *Params =
755 FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
756 unsigned TotalArgs = 0;
757 for (TSTiterator FromIter(FromTST), ToIter(ToTST);
758 !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
759 Tree.AddNode();
760
761 // Get the parameter at index TotalArgs. If index is larger
762 // than the total number of parameters, then there is an
763 // argument pack, so re-use the last parameter.
764 NamedDecl *ParamND = Params->getParam(
765 (TotalArgs < Params->size()) ? TotalArgs
766 : Params->size() - 1);
767 // Handle Types
768 if (TemplateTypeParmDecl *DefaultTTPD =
769 dyn_cast<TemplateTypeParmDecl>(ParamND)) {
770 QualType FromType, ToType;
771 GetType(FromIter, DefaultTTPD, FromType);
772 GetType(ToIter, DefaultTTPD, ToType);
773 Tree.SetNode(FromType, ToType);
774 Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
775 ToIter.isEnd() && !ToType.isNull());
776 if (!FromType.isNull() && !ToType.isNull()) {
777 if (Context.hasSameType(FromType, ToType)) {
778 Tree.SetSame(true);
779 } else {
780 const TemplateSpecializationType *FromArgTST =
781 GetTemplateSpecializationType(Context, FromType);
782 const TemplateSpecializationType *ToArgTST =
783 GetTemplateSpecializationType(Context, ToType);
784
785 if (FromArgTST && ToArgTST) {
786 bool SameTemplate = hasSameTemplate(FromArgTST, ToArgTST);
787 if (SameTemplate) {
788 Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
789 ToArgTST->getTemplateName().getAsTemplateDecl());
790 DiffTemplate(FromArgTST, ToArgTST);
791 }
792 }
793 }
794 }
795 }
796
797 // Handle Expressions
798 if (NonTypeTemplateParmDecl *DefaultNTTPD =
799 dyn_cast<NonTypeTemplateParmDecl>(ParamND)) {
800 Expr *FromExpr, *ToExpr;
801 GetExpr(FromIter, DefaultNTTPD, FromExpr);
802 GetExpr(ToIter, DefaultNTTPD, ToExpr);
803 Tree.SetNode(FromExpr, ToExpr);
804 Tree.SetSame(IsEqualExpr(Context, FromExpr, ToExpr));
805 Tree.SetDefault(FromIter.isEnd() && FromExpr,
806 ToIter.isEnd() && ToExpr);
807 }
808
809 // Handle Templates
810 if (TemplateTemplateParmDecl *DefaultTTPD =
811 dyn_cast<TemplateTemplateParmDecl>(ParamND)) {
812 TemplateDecl *FromDecl, *ToDecl;
813 GetTemplateDecl(FromIter, DefaultTTPD, FromDecl);
814 GetTemplateDecl(ToIter, DefaultTTPD, ToDecl);
815 Tree.SetNode(FromDecl, ToDecl);
816 Tree.SetSame(FromDecl && ToDecl &&
817 FromDecl->getIdentifier() == ToDecl->getIdentifier());
818 }
819
820 if (!FromIter.isEnd()) ++FromIter;
821 if (!ToIter.isEnd()) ++ToIter;
822 Tree.Up();
823 }
824 }
825
826 /// hasSameTemplate - Returns true if both types are specialized from the
827 /// same template declaration. If they come from different template aliases,
828 /// do a parallel ascension search to determine the highest template alias in
829 /// common and set the arguments to them.
830 static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
831 const TemplateSpecializationType *&ToTST) {
832 // Check the top templates if they are the same.
833 if (FromTST->getTemplateName().getAsTemplateDecl()->getIdentifier() ==
834 ToTST->getTemplateName().getAsTemplateDecl()->getIdentifier())
835 return true;
836
837 // Create vectors of template aliases.
838 SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
839 ToTemplateList;
840
841 const TemplateSpecializationType *TempToTST = ToTST, *TempFromTST = FromTST;
842 FromTemplateList.push_back(FromTST);
843 ToTemplateList.push_back(ToTST);
844
845 // Dump every template alias into the vectors.
846 while (TempFromTST->isTypeAlias()) {
847 TempFromTST =
848 TempFromTST->getAliasedType()->getAs<TemplateSpecializationType>();
849 if (!TempFromTST)
850 break;
851 FromTemplateList.push_back(TempFromTST);
852 }
853 while (TempToTST->isTypeAlias()) {
854 TempToTST =
855 TempToTST->getAliasedType()->getAs<TemplateSpecializationType>();
856 if (!TempToTST)
857 break;
858 ToTemplateList.push_back(TempToTST);
859 }
860
861 SmallVector<const TemplateSpecializationType*, 1>::reverse_iterator
862 FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
863 ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
864
865 // Check if the lowest template types are the same. If not, return.
866 if ((*FromIter)->getTemplateName().getAsTemplateDecl()->getIdentifier() !=
867 (*ToIter)->getTemplateName().getAsTemplateDecl()->getIdentifier())
868 return false;
869
870 // Begin searching up the template aliases. The bottom most template
871 // matches so move up until one pair does not match. Use the template
872 // right before that one.
873 for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
874 if ((*FromIter)->getTemplateName().getAsTemplateDecl()->getIdentifier() !=
875 (*ToIter)->getTemplateName().getAsTemplateDecl()->getIdentifier())
876 break;
877 }
878
879 FromTST = FromIter[-1];
880 ToTST = ToIter[-1];
881
882 return true;
883 }
884
885 /// GetType - Retrieves the template type arguments, including default
886 /// arguments.
887 void GetType(const TSTiterator &Iter, TemplateTypeParmDecl *DefaultTTPD,
888 QualType &ArgType) {
889 ArgType = QualType();
890 bool isVariadic = DefaultTTPD->isParameterPack();
891
892 if (!Iter.isEnd())
893 ArgType = Iter->getAsType();
894 else if (!isVariadic)
895 ArgType = DefaultTTPD->getDefaultArgument();
896 };
897
898 /// GetExpr - Retrieves the template expression argument, including default
899 /// arguments.
900 void GetExpr(const TSTiterator &Iter, NonTypeTemplateParmDecl *DefaultNTTPD,
901 Expr *&ArgExpr) {
902 ArgExpr = 0;
903 bool isVariadic = DefaultNTTPD->isParameterPack();
904
905 if (!Iter.isEnd())
906 ArgExpr = Iter->getAsExpr();
907 else if (!isVariadic)
908 ArgExpr = DefaultNTTPD->getDefaultArgument();
909
910 if (ArgExpr)
911 while (SubstNonTypeTemplateParmExpr *SNTTPE =
912 dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
913 ArgExpr = SNTTPE->getReplacement();
914 }
915
916 /// GetTemplateDecl - Retrieves the template template arguments, including
917 /// default arguments.
918 void GetTemplateDecl(const TSTiterator &Iter,
919 TemplateTemplateParmDecl *DefaultTTPD,
920 TemplateDecl *&ArgDecl) {
921 ArgDecl = 0;
922 bool isVariadic = DefaultTTPD->isParameterPack();
923
924 TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
925 TemplateDecl *DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
926
927 if (!Iter.isEnd())
928 ArgDecl = Iter->getAsTemplate().getAsTemplateDecl();
929 else if (!isVariadic)
930 ArgDecl = DefaultTD;
931 }
932
933 /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
934 static bool IsEqualExpr(ASTContext &Context, Expr *FromExpr, Expr *ToExpr) {
935 if (FromExpr == ToExpr)
936 return true;
937
938 if (!FromExpr || !ToExpr)
939 return false;
940
941 FromExpr = FromExpr->IgnoreParens();
942 ToExpr = ToExpr->IgnoreParens();
943
944 DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr),
945 *ToDRE = dyn_cast<DeclRefExpr>(ToExpr);
946
947 if (FromDRE || ToDRE) {
948 if (!FromDRE || !ToDRE)
949 return false;
950 return FromDRE->getDecl() == ToDRE->getDecl();
951 }
952
953 Expr::EvalResult FromResult, ToResult;
954 if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
955 !ToExpr->EvaluateAsRValue(ToResult, Context))
956 assert(0 && "Template arguments must be known at compile time.");
957
958 APValue &FromVal = FromResult.Val;
959 APValue &ToVal = ToResult.Val;
960
961 if (FromVal.getKind() != ToVal.getKind()) return false;
962
963 switch (FromVal.getKind()) {
964 case APValue::Int:
965 return FromVal.getInt() == ToVal.getInt();
966 case APValue::LValue: {
967 APValue::LValueBase FromBase = FromVal.getLValueBase();
968 APValue::LValueBase ToBase = ToVal.getLValueBase();
969 if (FromBase.isNull() && ToBase.isNull())
970 return true;
971 if (FromBase.isNull() || ToBase.isNull())
972 return false;
973 return FromBase.get<const ValueDecl*>() ==
974 ToBase.get<const ValueDecl*>();
975 }
976 case APValue::MemberPointer:
977 return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
978 default:
979 llvm_unreachable("Unknown template argument expression.");
980 }
981 }
982
983 // These functions converts the tree representation of the template
984 // differences into the internal character vector.
985
986 /// TreeToString - Converts the Tree object into a character stream which
987 /// will later be turned into the output string.
988 void TreeToString(int Indent = 1) {
989 if (PrintTree) {
990 OS << '\n';
991 for (int i = 0; i < Indent; ++i)
992 OS << " ";
993 ++Indent;
994 }
995
996 // Handle cases where the difference is not templates with different
997 // arguments.
998 if (!Tree.NodeIsTemplate()) {
999 if (Tree.NodeIsQualType()) {
1000 QualType FromType, ToType;
1001 Tree.GetNode(FromType, ToType);
1002 PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
1003 Tree.NodeIsSame());
1004 return;
1005 }
1006 if (Tree.NodeIsExpr()) {
1007 Expr *FromExpr, *ToExpr;
1008 Tree.GetNode(FromExpr, ToExpr);
1009 PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
1010 Tree.NodeIsSame());
1011 return;
1012 }
1013 if (Tree.NodeIsTemplateTemplate()) {
1014 TemplateDecl *FromTD, *ToTD;
1015 Tree.GetNode(FromTD, ToTD);
1016 PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
1017 Tree.ToDefault(), Tree.NodeIsSame());
1018 return;
1019 }
1020 llvm_unreachable("Unable to deduce template difference.");
1021 }
1022
1023 // Node is root of template. Recurse on children.
1024 TemplateDecl *FromTD, *ToTD;
1025 Tree.GetNode(FromTD, ToTD);
1026
1027 assert(Tree.HasChildren() && "Template difference not found in diff tree.");
1028
1029 OS << FromTD->getNameAsString() << '<';
1030 Tree.MoveToChild();
1031 unsigned NumElideArgs = 0;
1032 do {
1033 if (ElideType) {
1034 if (Tree.NodeIsSame()) {
1035 ++NumElideArgs;
1036 continue;
1037 }
1038 if (NumElideArgs > 0) {
1039 PrintElideArgs(NumElideArgs, Indent);
1040 NumElideArgs = 0;
1041 OS << ", ";
1042 }
1043 }
1044 TreeToString(Indent);
1045 if (Tree.HasNextSibling())
1046 OS << ", ";
1047 } while (Tree.AdvanceSibling());
1048 if (NumElideArgs > 0)
1049 PrintElideArgs(NumElideArgs, Indent);
1050
1051 Tree.Parent();
1052 OS << ">";
1053 }
1054
1055 // To signal to the text printer that a certain text needs to be bolded,
1056 // a special character is injected into the character stream which the
1057 // text printer will later strip out.
1058
1059 /// Bold - Start bolding text.
1060 void Bold() {
1061 assert(!IsBold && "Attempting to bold text that is already bold.");
1062 IsBold = true;
1063 if (ShowColor)
1064 OS << ToggleHighlight;
1065 }
1066
1067 /// Unbold - Stop bolding text.
1068 void Unbold() {
1069 assert(IsBold && "Attempting to remove bold from unbold text.");
1070 IsBold = false;
1071 if (ShowColor)
1072 OS << ToggleHighlight;
1073 }
1074
1075 // Functions to print out the arguments and highlighting the difference.
1076
1077 /// PrintTypeNames - prints the typenames, bolding differences. Will detect
1078 /// typenames that are the same and attempt to disambiguate them by using
1079 /// canonical typenames.
1080 void PrintTypeNames(QualType FromType, QualType ToType,
1081 bool FromDefault, bool ToDefault, bool Same) {
1082 assert((!FromType.isNull() || !ToType.isNull()) &&
1083 "Only one template argument may be missing.");
1084
1085 if (Same) {
1086 OS << FromType.getAsString();
1087 return;
1088 }
1089
1090 std::string FromTypeStr = FromType.isNull() ? "(no argument)"
1091 : FromType.getAsString();
1092 std::string ToTypeStr = ToType.isNull() ? "(no argument)"
1093 : ToType.getAsString();
1094 // Switch to canonical typename if it is better.
1095 // TODO: merge this with other aka printing above.
1096 if (FromTypeStr == ToTypeStr) {
1097 std::string FromCanTypeStr = FromType.getCanonicalType().getAsString();
1098 std::string ToCanTypeStr = ToType.getCanonicalType().getAsString();
1099 if (FromCanTypeStr != ToCanTypeStr) {
1100 FromTypeStr = FromCanTypeStr;
1101 ToTypeStr = ToCanTypeStr;
1102 }
1103 }
1104
1105 if (PrintTree) OS << '[';
1106 OS << (FromDefault ? "(default) " : "");
1107 Bold();
1108 OS << FromTypeStr;
1109 Unbold();
1110 if (PrintTree) {
1111 OS << " != " << (ToDefault ? "(default) " : "");
1112 Bold();
1113 OS << ToTypeStr;
1114 Unbold();
1115 OS << "]";
1116 }
1117 return;
1118 }
1119
1120 /// PrintExpr - Prints out the expr template arguments, highlighting argument
1121 /// differences.
1122 void PrintExpr(const Expr *FromExpr, const Expr *ToExpr,
1123 bool FromDefault, bool ToDefault, bool Same) {
1124 assert((FromExpr || ToExpr) &&
1125 "Only one template argument may be missing.");
1126 if (Same) {
1127 PrintExpr(FromExpr);
1128 } else if (!PrintTree) {
1129 OS << (FromDefault ? "(default) " : "");
1130 Bold();
1131 PrintExpr(FromExpr);
1132 Unbold();
1133 } else {
1134 OS << (FromDefault ? "[(default) " : "[");
1135 Bold();
1136 PrintExpr(FromExpr);
1137 Unbold();
1138 OS << " != " << (ToDefault ? "(default) " : "");
1139 Bold();
1140 PrintExpr(ToExpr);
1141 Unbold();
1142 OS << ']';
1143 }
1144 }
1145
1146 /// PrintExpr - Actual formatting and printing of expressions.
1147 void PrintExpr(const Expr *E) {
1148 if (!E)
1149 OS << "(no argument)";
1150 else
1151 E->printPretty(OS, Context, 0, Policy); return;
1152 }
1153
1154 /// PrintTemplateTemplate - Handles printing of template template arguments,
1155 /// highlighting argument differences.
1156 void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
1157 bool FromDefault, bool ToDefault, bool Same) {
1158 assert((FromTD || ToTD) && "Only one template argument may be missing.");
1159 if (Same) {
1160 OS << "template " << FromTD->getNameAsString();
1161 } else if (!PrintTree) {
1162 OS << (FromDefault ? "(default) template " : "template ");
1163 Bold();
1164 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1165 Unbold();
1166 } else {
1167 OS << (FromDefault ? "[(default) template " : "[template ");
1168 Bold();
1169 OS << (FromTD ? FromTD->getNameAsString() : "(no argument)");
1170 Unbold();
1171 OS << " != " << (ToDefault ? "(default) template " : "template ");
1172 Bold();
1173 OS << (ToTD ? ToTD->getNameAsString() : "(no argument)");
1174 Unbold();
1175 OS << ']';
1176 }
1177 }
1178
1179 // Prints the appropriate placeholder for elided template arguments.
1180 void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
1181 if (PrintTree) {
1182 OS << '\n';
1183 for (unsigned i = 0; i < Indent; ++i)
1184 OS << " ";
1185 }
1186 if (NumElideArgs == 0) return;
1187 if (NumElideArgs == 1)
1188 OS << "[...]";
1189 else
1190 OS << "[" << NumElideArgs << " * ...]";
1191 }
1192
1193public:
1194
1195 TemplateDiff(ASTContext &Context, QualType FromType, QualType ToType,
1196 bool PrintTree, bool PrintFromType, bool ElideType,
1197 bool ShowColor)
1198 : Context(Context),
1199 Policy(Context.getLangOpts()),
1200 ElideType(ElideType),
1201 PrintTree(PrintTree),
1202 ShowColor(ShowColor),
1203 // When printing a single type, the FromType is the one printed.
1204 FromType(PrintFromType ? FromType : ToType),
1205 ToType(PrintFromType ? ToType : FromType),
1206 OS(Str),
1207 IsBold(false) {
1208 }
1209
1210 /// DiffTemplate - Start the template type diffing.
1211 void DiffTemplate() {
1212 const TemplateSpecializationType *FromOrigTST =
1213 GetTemplateSpecializationType(Context, FromType);
1214 const TemplateSpecializationType *ToOrigTST =
1215 GetTemplateSpecializationType(Context, ToType);
1216
1217 // Only checking templates.
1218 if (!FromOrigTST || !ToOrigTST)
1219 return;
1220
1221 // Different base templates.
1222 if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
1223 return;
1224 }
1225
1226 Tree.SetNode(FromType, ToType);
1227
1228 // Same base template, but different arguments.
1229 Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
1230 ToOrigTST->getTemplateName().getAsTemplateDecl());
1231
1232 DiffTemplate(FromOrigTST, ToOrigTST);
1233 };
1234
1235 /// MakeString - When the two types given are templated types with the same
1236 /// base template, a string representation of the type difference will be
1237 /// loaded into S and return true. Otherwise, return false.
1238 bool MakeString(std::string &S) {
1239 Tree.StartTraverse();
1240 if (Tree.Empty())
1241 return false;
1242
1243 TreeToString();
1244 assert(!IsBold && "Bold is applied to end of string.");
1245 S = OS.str();
1246 return true;
1247 }
1248}; // end class TemplateDiff
1249} // end namespace
1250
1251/// FormatTemplateTypeDiff - A helper static function to start the template
1252/// diff and return the properly formatted string. Returns true if the diff
1253/// is successful.
1254static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
1255 QualType ToType, bool PrintTree,
1256 bool PrintFromType, bool ElideType,
1257 bool ShowColors, std::string &S) {
1258 if (PrintTree)
1259 PrintFromType = true;
1260 TemplateDiff TD(Context, FromType, ToType, PrintTree, PrintFromType,
1261 ElideType, ShowColors);
1262 TD.DiffTemplate();
1263 return TD.MakeString(S);
1264}