ASTDiagnostic.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. //===--- 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. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/TemplateBase.h"
  21. #include "clang/AST/Type.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. // //
  25. ///////////////////////////////////////////////////////////////////////////////
  26. using namespace clang;
  27. // Returns a desugared version of the QualType, and marks ShouldAKA as true
  28. // whenever we remove significant sugar from the type.
  29. static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA) {
  30. QualifierCollector QC;
  31. while (true) {
  32. const Type *Ty = QC.strip(QT);
  33. // Don't aka just because we saw an elaborated type...
  34. if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Ty)) {
  35. QT = ET->desugar();
  36. continue;
  37. }
  38. // ... or a paren type ...
  39. if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
  40. QT = PT->desugar();
  41. continue;
  42. }
  43. // ...or a substituted template type parameter ...
  44. if (const SubstTemplateTypeParmType *ST =
  45. dyn_cast<SubstTemplateTypeParmType>(Ty)) {
  46. QT = ST->desugar();
  47. continue;
  48. }
  49. // ...or an attributed type...
  50. if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
  51. QT = AT->desugar();
  52. continue;
  53. }
  54. // ...or an adjusted type...
  55. if (const AdjustedType *AT = dyn_cast<AdjustedType>(Ty)) {
  56. QT = AT->desugar();
  57. continue;
  58. }
  59. // ... or an auto type.
  60. if (const AutoType *AT = dyn_cast<AutoType>(Ty)) {
  61. if (!AT->isSugared())
  62. break;
  63. QT = AT->desugar();
  64. continue;
  65. }
  66. // Don't desugar template specializations, unless it's an alias template.
  67. if (const TemplateSpecializationType *TST
  68. = dyn_cast<TemplateSpecializationType>(Ty))
  69. if (!TST->isTypeAlias())
  70. break;
  71. // Don't desugar magic Objective-C types.
  72. if (QualType(Ty,0) == Context.getObjCIdType() ||
  73. QualType(Ty,0) == Context.getObjCClassType() ||
  74. QualType(Ty,0) == Context.getObjCSelType() ||
  75. QualType(Ty,0) == Context.getObjCProtoType())
  76. break;
  77. // Don't desugar va_list.
  78. if (QualType(Ty,0) == Context.getBuiltinVaListType())
  79. break;
  80. // HLSL Change: don't desugar typedefs that were injected into AST.
  81. if (Ty->getTypeClass() == Type::TypeClass::Typedef) {
  82. const TypedefType* tt = cast<TypedefType>(Ty);
  83. if (tt->getDecl()->getLocation() == SourceLocation()) {
  84. break;
  85. }
  86. }
  87. // Otherwise, do a single-step desugar.
  88. QualType Underlying;
  89. bool IsSugar = false;
  90. switch (Ty->getTypeClass()) {
  91. #define ABSTRACT_TYPE(Class, Base)
  92. #define TYPE(Class, Base) \
  93. case Type::Class: { \
  94. const Class##Type *CTy = cast<Class##Type>(Ty); \
  95. if (CTy->isSugared()) { \
  96. IsSugar = true; \
  97. Underlying = CTy->desugar(); \
  98. } \
  99. break; \
  100. }
  101. #include "clang/AST/TypeNodes.def"
  102. }
  103. // If it wasn't sugared, we're done.
  104. if (!IsSugar)
  105. break;
  106. // If the desugared type is a vector type, we don't want to expand
  107. // it, it will turn into an attribute mess. People want their "vec4".
  108. if (isa<VectorType>(Underlying))
  109. break;
  110. // Don't desugar through the primary typedef of an anonymous type.
  111. if (const TagType *UTT = Underlying->getAs<TagType>())
  112. if (const TypedefType *QTT = dyn_cast<TypedefType>(QT))
  113. if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl())
  114. break;
  115. // Record that we actually looked through an opaque type here.
  116. ShouldAKA = true;
  117. QT = Underlying;
  118. }
  119. // If we have a pointer-like type, desugar the pointee as well.
  120. // FIXME: Handle other pointer-like types.
  121. if (const PointerType *Ty = QT->getAs<PointerType>()) {
  122. QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(),
  123. ShouldAKA));
  124. } else if (const auto *Ty = QT->getAs<ObjCObjectPointerType>()) {
  125. QT = Context.getObjCObjectPointerType(Desugar(Context, Ty->getPointeeType(),
  126. ShouldAKA));
  127. } else if (const LValueReferenceType *Ty = QT->getAs<LValueReferenceType>()) {
  128. QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(),
  129. ShouldAKA));
  130. } else if (const RValueReferenceType *Ty = QT->getAs<RValueReferenceType>()) {
  131. QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(),
  132. ShouldAKA));
  133. } else if (const auto *Ty = QT->getAs<ObjCObjectType>()) {
  134. if (Ty->getBaseType().getTypePtr() != Ty && !ShouldAKA) {
  135. QualType BaseType = Desugar(Context, Ty->getBaseType(), ShouldAKA);
  136. QT = Context.getObjCObjectType(BaseType, Ty->getTypeArgsAsWritten(),
  137. llvm::makeArrayRef(Ty->qual_begin(),
  138. Ty->getNumProtocols()),
  139. Ty->isKindOfTypeAsWritten());
  140. }
  141. }
  142. return QC.apply(Context, QT);
  143. }
  144. /// \brief Convert the given type to a string suitable for printing as part of
  145. /// a diagnostic.
  146. ///
  147. /// There are four main criteria when determining whether we should have an
  148. /// a.k.a. clause when pretty-printing a type:
  149. ///
  150. /// 1) Some types provide very minimal sugar that doesn't impede the
  151. /// user's understanding --- for example, elaborated type
  152. /// specifiers. If this is all the sugar we see, we don't want an
  153. /// a.k.a. clause.
  154. /// 2) Some types are technically sugared but are much more familiar
  155. /// when seen in their sugared form --- for example, va_list,
  156. /// vector types, and the magic Objective C types. We don't
  157. /// want to desugar these, even if we do produce an a.k.a. clause.
  158. /// 3) Some types may have already been desugared previously in this diagnostic.
  159. /// if this is the case, doing another "aka" would just be clutter.
  160. /// 4) Two different types within the same diagnostic have the same output
  161. /// string. In this case, force an a.k.a with the desugared type when
  162. /// doing so will provide additional information.
  163. ///
  164. /// \param Context the context in which the type was allocated
  165. /// \param Ty the type to print
  166. /// \param QualTypeVals pointer values to QualTypes which are used in the
  167. /// diagnostic message
  168. static std::string
  169. ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
  170. ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
  171. ArrayRef<intptr_t> QualTypeVals) {
  172. // FIXME: Playing with std::string is really slow.
  173. bool ForceAKA = false;
  174. QualType CanTy = Ty.getCanonicalType();
  175. std::string S = Ty.getAsString(Context.getPrintingPolicy());
  176. std::string CanS = CanTy.getAsString(Context.getPrintingPolicy());
  177. for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) {
  178. QualType CompareTy =
  179. QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]));
  180. if (CompareTy.isNull())
  181. continue;
  182. if (CompareTy == Ty)
  183. continue; // Same types
  184. QualType CompareCanTy = CompareTy.getCanonicalType();
  185. if (CompareCanTy == CanTy)
  186. continue; // Same canonical types
  187. std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy());
  188. bool ShouldAKA = false;
  189. QualType CompareDesugar = Desugar(Context, CompareTy, ShouldAKA);
  190. std::string CompareDesugarStr =
  191. CompareDesugar.getAsString(Context.getPrintingPolicy());
  192. if (CompareS != S && CompareDesugarStr != S)
  193. continue; // The type string is different than the comparison string
  194. // and the desugared comparison string.
  195. std::string CompareCanS =
  196. CompareCanTy.getAsString(Context.getPrintingPolicy());
  197. if (CompareCanS == CanS)
  198. continue; // No new info from canonical type
  199. ForceAKA = true;
  200. break;
  201. }
  202. // Check to see if we already desugared this type in this
  203. // diagnostic. If so, don't do it again.
  204. bool Repeated = false;
  205. for (unsigned i = 0, e = PrevArgs.size(); i != e; ++i) {
  206. // TODO: Handle ak_declcontext case.
  207. if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) {
  208. void *Ptr = (void*)PrevArgs[i].second;
  209. QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
  210. if (PrevTy == Ty) {
  211. Repeated = true;
  212. break;
  213. }
  214. }
  215. }
  216. // Consider producing an a.k.a. clause if removing all the direct
  217. // sugar gives us something "significantly different".
  218. if (!Repeated) {
  219. bool ShouldAKA = false;
  220. QualType DesugaredTy = Desugar(Context, Ty, ShouldAKA);
  221. if (ShouldAKA || ForceAKA) {
  222. if (DesugaredTy == Ty) {
  223. DesugaredTy = Ty.getCanonicalType();
  224. }
  225. std::string akaStr = DesugaredTy.getAsString(Context.getPrintingPolicy());
  226. if (akaStr != S) {
  227. S = "'" + S + "' (aka '" + akaStr + "')";
  228. return S;
  229. }
  230. }
  231. // Give some additional info on vector types. These are either not desugared
  232. // or displaying complex __attribute__ expressions so add details of the
  233. // type and element count.
  234. if (Ty->isVectorType()) {
  235. const VectorType *VTy = Ty->getAs<VectorType>();
  236. std::string DecoratedString;
  237. llvm::raw_string_ostream OS(DecoratedString);
  238. const char *Values = VTy->getNumElements() > 1 ? "values" : "value";
  239. OS << "'" << S << "' (vector of " << VTy->getNumElements() << " '"
  240. << VTy->getElementType().getAsString(Context.getPrintingPolicy())
  241. << "' " << Values << ")";
  242. return OS.str();
  243. }
  244. }
  245. S = "'" + S + "'";
  246. return S;
  247. }
  248. static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
  249. QualType ToType, bool PrintTree,
  250. bool PrintFromType, bool ElideType,
  251. bool ShowColors, raw_ostream &OS);
  252. void clang::FormatASTNodeDiagnosticArgument(
  253. DiagnosticsEngine::ArgumentKind Kind,
  254. intptr_t Val,
  255. StringRef Modifier,
  256. StringRef Argument,
  257. ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
  258. SmallVectorImpl<char> &Output,
  259. void *Cookie,
  260. ArrayRef<intptr_t> QualTypeVals) {
  261. ASTContext &Context = *static_cast<ASTContext*>(Cookie);
  262. size_t OldEnd = Output.size();
  263. llvm::raw_svector_ostream OS(Output);
  264. bool NeedQuotes = true;
  265. switch (Kind) {
  266. default: llvm_unreachable("unknown ArgumentKind");
  267. case DiagnosticsEngine::ak_qualtype_pair: {
  268. TemplateDiffTypes &TDT = *reinterpret_cast<TemplateDiffTypes*>(Val);
  269. QualType FromType =
  270. QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.FromType));
  271. QualType ToType =
  272. QualType::getFromOpaquePtr(reinterpret_cast<void*>(TDT.ToType));
  273. if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree,
  274. TDT.PrintFromType, TDT.ElideType,
  275. TDT.ShowColors, OS)) {
  276. NeedQuotes = !TDT.PrintTree;
  277. TDT.TemplateDiffUsed = true;
  278. break;
  279. }
  280. // Don't fall-back during tree printing. The caller will handle
  281. // this case.
  282. if (TDT.PrintTree)
  283. return;
  284. // Attempting to do a template diff on non-templates. Set the variables
  285. // and continue with regular type printing of the appropriate type.
  286. Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
  287. Modifier = StringRef();
  288. Argument = StringRef();
  289. // Fall through
  290. }
  291. case DiagnosticsEngine::ak_qualtype: {
  292. assert(Modifier.empty() && Argument.empty() &&
  293. "Invalid modifier for QualType argument");
  294. QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
  295. OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals);
  296. NeedQuotes = false;
  297. break;
  298. }
  299. case DiagnosticsEngine::ak_declarationname: {
  300. if (Modifier == "objcclass" && Argument.empty())
  301. OS << '+';
  302. else if (Modifier == "objcinstance" && Argument.empty())
  303. OS << '-';
  304. else
  305. assert(Modifier.empty() && Argument.empty() &&
  306. "Invalid modifier for DeclarationName argument");
  307. OS << DeclarationName::getFromOpaqueInteger(Val);
  308. break;
  309. }
  310. case DiagnosticsEngine::ak_nameddecl: {
  311. bool Qualified;
  312. if (Modifier == "q" && Argument.empty())
  313. Qualified = true;
  314. else {
  315. assert(Modifier.empty() && Argument.empty() &&
  316. "Invalid modifier for NamedDecl* argument");
  317. Qualified = false;
  318. }
  319. const NamedDecl *ND = reinterpret_cast<const NamedDecl*>(Val);
  320. ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified);
  321. break;
  322. }
  323. case DiagnosticsEngine::ak_nestednamespec: {
  324. NestedNameSpecifier *NNS = reinterpret_cast<NestedNameSpecifier*>(Val);
  325. NNS->print(OS, Context.getPrintingPolicy());
  326. NeedQuotes = false;
  327. break;
  328. }
  329. case DiagnosticsEngine::ak_declcontext: {
  330. DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
  331. assert(DC && "Should never have a null declaration context");
  332. NeedQuotes = false;
  333. // FIXME: Get the strings for DeclContext from some localized place
  334. if (DC->isTranslationUnit()) {
  335. if (Context.getLangOpts().CPlusPlus)
  336. OS << "the global namespace";
  337. else
  338. OS << "the global scope";
  339. } else if (DC->isClosure()) {
  340. OS << "block literal";
  341. } else if (isLambdaCallOperator(DC)) {
  342. OS << "lambda expression";
  343. } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
  344. OS << ConvertTypeToDiagnosticString(Context,
  345. Context.getTypeDeclType(Type),
  346. PrevArgs, QualTypeVals);
  347. } else {
  348. assert(isa<NamedDecl>(DC) && "Expected a NamedDecl");
  349. NamedDecl *ND = cast<NamedDecl>(DC);
  350. if (isa<NamespaceDecl>(ND))
  351. OS << "namespace ";
  352. else if (isa<ObjCMethodDecl>(ND))
  353. OS << "method ";
  354. else if (isa<FunctionDecl>(ND))
  355. OS << "function ";
  356. OS << '\'';
  357. ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
  358. OS << '\'';
  359. }
  360. break;
  361. }
  362. case DiagnosticsEngine::ak_attr: {
  363. const Attr *At = reinterpret_cast<Attr *>(Val);
  364. assert(At && "Received null Attr object!");
  365. OS << '\'' << At->getSpelling() << '\'';
  366. NeedQuotes = false;
  367. break;
  368. }
  369. }
  370. OS.flush();
  371. if (NeedQuotes) {
  372. Output.insert(Output.begin()+OldEnd, '\'');
  373. Output.push_back('\'');
  374. }
  375. }
  376. /// TemplateDiff - A class that constructs a pretty string for a pair of
  377. /// QualTypes. For the pair of types, a diff tree will be created containing
  378. /// all the information about the templates and template arguments. Afterwards,
  379. /// the tree is transformed to a string according to the options passed in.
  380. namespace {
  381. class TemplateDiff {
  382. /// Context - The ASTContext which is used for comparing template arguments.
  383. ASTContext &Context;
  384. /// Policy - Used during expression printing.
  385. PrintingPolicy Policy;
  386. /// ElideType - Option to elide identical types.
  387. bool ElideType;
  388. /// PrintTree - Format output string as a tree.
  389. bool PrintTree;
  390. /// ShowColor - Diagnostics support color, so bolding will be used.
  391. bool ShowColor;
  392. /// FromType - When single type printing is selected, this is the type to be
  393. /// be printed. When tree printing is selected, this type will show up first
  394. /// in the tree.
  395. QualType FromType;
  396. /// ToType - The type that FromType is compared to. Only in tree printing
  397. /// will this type be outputed.
  398. QualType ToType;
  399. /// OS - The stream used to construct the output strings.
  400. raw_ostream &OS;
  401. /// IsBold - Keeps track of the bold formatting for the output string.
  402. bool IsBold;
  403. /// DiffTree - A tree representation the differences between two types.
  404. class DiffTree {
  405. public:
  406. /// DiffKind - The difference in a DiffNode and which fields are used.
  407. enum DiffKind {
  408. /// Incomplete or invalid node.
  409. Invalid,
  410. /// Another level of templates, uses TemplateDecl and Qualifiers
  411. Template,
  412. /// Type difference, uses QualType
  413. Type,
  414. /// Expression difference, uses Expr
  415. Expression,
  416. /// Template argument difference, uses TemplateDecl
  417. TemplateTemplate,
  418. /// Integer difference, uses APSInt and Expr
  419. Integer,
  420. /// Declaration difference, uses ValueDecl
  421. Declaration
  422. };
  423. private:
  424. /// DiffNode - The root node stores the original type. Each child node
  425. /// stores template arguments of their parents. For templated types, the
  426. /// template decl is also stored.
  427. struct DiffNode {
  428. DiffKind Kind;
  429. /// NextNode - The index of the next sibling node or 0.
  430. unsigned NextNode;
  431. /// ChildNode - The index of the first child node or 0.
  432. unsigned ChildNode;
  433. /// ParentNode - The index of the parent node.
  434. unsigned ParentNode;
  435. /// FromType, ToType - The type arguments.
  436. QualType FromType, ToType;
  437. /// FromExpr, ToExpr - The expression arguments.
  438. Expr *FromExpr, *ToExpr;
  439. /// FromNullPtr, ToNullPtr - If the template argument is a nullptr
  440. bool FromNullPtr, ToNullPtr;
  441. /// FromTD, ToTD - The template decl for template template
  442. /// arguments or the type arguments that are templates.
  443. TemplateDecl *FromTD, *ToTD;
  444. /// FromQual, ToQual - Qualifiers for template types.
  445. Qualifiers FromQual, ToQual;
  446. /// FromInt, ToInt - APSInt's for integral arguments.
  447. llvm::APSInt FromInt, ToInt;
  448. /// IsValidFromInt, IsValidToInt - Whether the APSInt's are valid.
  449. bool IsValidFromInt, IsValidToInt;
  450. /// FromValueDecl, ToValueDecl - Whether the argument is a decl.
  451. ValueDecl *FromValueDecl, *ToValueDecl;
  452. /// FromAddressOf, ToAddressOf - Whether the ValueDecl needs an address of
  453. /// operator before it.
  454. bool FromAddressOf, ToAddressOf;
  455. /// FromDefault, ToDefault - Whether the argument is a default argument.
  456. bool FromDefault, ToDefault;
  457. /// Same - Whether the two arguments evaluate to the same value.
  458. bool Same;
  459. DiffNode(unsigned ParentNode = 0)
  460. : Kind(Invalid), NextNode(0), ChildNode(0), ParentNode(ParentNode),
  461. FromType(), ToType(), FromExpr(nullptr), ToExpr(nullptr),
  462. FromNullPtr(false), ToNullPtr(false),
  463. FromTD(nullptr), ToTD(nullptr), IsValidFromInt(false),
  464. IsValidToInt(false), FromValueDecl(nullptr), ToValueDecl(nullptr),
  465. FromAddressOf(false), ToAddressOf(false), FromDefault(false),
  466. ToDefault(false), Same(false) {}
  467. };
  468. /// FlatTree - A flattened tree used to store the DiffNodes.
  469. SmallVector<DiffNode, 16> FlatTree;
  470. /// CurrentNode - The index of the current node being used.
  471. unsigned CurrentNode;
  472. /// NextFreeNode - The index of the next unused node. Used when creating
  473. /// child nodes.
  474. unsigned NextFreeNode;
  475. /// ReadNode - The index of the current node being read.
  476. unsigned ReadNode;
  477. public:
  478. DiffTree() :
  479. CurrentNode(0), NextFreeNode(1) {
  480. FlatTree.push_back(DiffNode());
  481. }
  482. // Node writing functions.
  483. /// SetNode - Sets FromTD and ToTD of the current node.
  484. void SetNode(TemplateDecl *FromTD, TemplateDecl *ToTD) {
  485. FlatTree[CurrentNode].FromTD = FromTD;
  486. FlatTree[CurrentNode].ToTD = ToTD;
  487. }
  488. /// SetNode - Sets FromType and ToType of the current node.
  489. void SetNode(QualType FromType, QualType ToType) {
  490. FlatTree[CurrentNode].FromType = FromType;
  491. FlatTree[CurrentNode].ToType = ToType;
  492. }
  493. /// SetNode - Set FromExpr and ToExpr of the current node.
  494. void SetNode(Expr *FromExpr, Expr *ToExpr) {
  495. FlatTree[CurrentNode].FromExpr = FromExpr;
  496. FlatTree[CurrentNode].ToExpr = ToExpr;
  497. }
  498. /// SetNode - Set FromInt and ToInt of the current node.
  499. void SetNode(llvm::APSInt FromInt, llvm::APSInt ToInt,
  500. bool IsValidFromInt, bool IsValidToInt) {
  501. FlatTree[CurrentNode].FromInt = FromInt;
  502. FlatTree[CurrentNode].ToInt = ToInt;
  503. FlatTree[CurrentNode].IsValidFromInt = IsValidFromInt;
  504. FlatTree[CurrentNode].IsValidToInt = IsValidToInt;
  505. }
  506. /// SetNode - Set FromQual and ToQual of the current node.
  507. void SetNode(Qualifiers FromQual, Qualifiers ToQual) {
  508. FlatTree[CurrentNode].FromQual = FromQual;
  509. FlatTree[CurrentNode].ToQual = ToQual;
  510. }
  511. /// SetNode - Set FromValueDecl and ToValueDecl of the current node.
  512. void SetNode(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
  513. bool FromAddressOf, bool ToAddressOf) {
  514. FlatTree[CurrentNode].FromValueDecl = FromValueDecl;
  515. FlatTree[CurrentNode].ToValueDecl = ToValueDecl;
  516. FlatTree[CurrentNode].FromAddressOf = FromAddressOf;
  517. FlatTree[CurrentNode].ToAddressOf = ToAddressOf;
  518. }
  519. /// SetSame - Sets the same flag of the current node.
  520. void SetSame(bool Same) {
  521. FlatTree[CurrentNode].Same = Same;
  522. }
  523. /// SetNullPtr - Sets the NullPtr flags of the current node.
  524. void SetNullPtr(bool FromNullPtr, bool ToNullPtr) {
  525. FlatTree[CurrentNode].FromNullPtr = FromNullPtr;
  526. FlatTree[CurrentNode].ToNullPtr = ToNullPtr;
  527. }
  528. /// SetDefault - Sets FromDefault and ToDefault flags of the current node.
  529. void SetDefault(bool FromDefault, bool ToDefault) {
  530. FlatTree[CurrentNode].FromDefault = FromDefault;
  531. FlatTree[CurrentNode].ToDefault = ToDefault;
  532. }
  533. /// SetKind - Sets the current node's type.
  534. void SetKind(DiffKind Kind) {
  535. FlatTree[CurrentNode].Kind = Kind;
  536. }
  537. /// Up - Changes the node to the parent of the current node.
  538. void Up() {
  539. CurrentNode = FlatTree[CurrentNode].ParentNode;
  540. }
  541. /// AddNode - Adds a child node to the current node, then sets that node
  542. /// node as the current node.
  543. void AddNode() {
  544. FlatTree.push_back(DiffNode(CurrentNode));
  545. DiffNode &Node = FlatTree[CurrentNode];
  546. if (Node.ChildNode == 0) {
  547. // If a child node doesn't exist, add one.
  548. Node.ChildNode = NextFreeNode;
  549. } else {
  550. // If a child node exists, find the last child node and add a
  551. // next node to it.
  552. unsigned i;
  553. for (i = Node.ChildNode; FlatTree[i].NextNode != 0;
  554. i = FlatTree[i].NextNode) {
  555. }
  556. FlatTree[i].NextNode = NextFreeNode;
  557. }
  558. CurrentNode = NextFreeNode;
  559. ++NextFreeNode;
  560. }
  561. // Node reading functions.
  562. /// StartTraverse - Prepares the tree for recursive traversal.
  563. void StartTraverse() {
  564. ReadNode = 0;
  565. CurrentNode = NextFreeNode;
  566. NextFreeNode = 0;
  567. }
  568. /// Parent - Move the current read node to its parent.
  569. void Parent() {
  570. ReadNode = FlatTree[ReadNode].ParentNode;
  571. }
  572. /// GetNode - Gets the FromType and ToType.
  573. void GetNode(QualType &FromType, QualType &ToType) {
  574. FromType = FlatTree[ReadNode].FromType;
  575. ToType = FlatTree[ReadNode].ToType;
  576. }
  577. /// GetNode - Gets the FromExpr and ToExpr.
  578. void GetNode(Expr *&FromExpr, Expr *&ToExpr) {
  579. FromExpr = FlatTree[ReadNode].FromExpr;
  580. ToExpr = FlatTree[ReadNode].ToExpr;
  581. }
  582. /// GetNode - Gets the FromTD and ToTD.
  583. void GetNode(TemplateDecl *&FromTD, TemplateDecl *&ToTD) {
  584. FromTD = FlatTree[ReadNode].FromTD;
  585. ToTD = FlatTree[ReadNode].ToTD;
  586. }
  587. /// GetNode - Gets the FromInt and ToInt.
  588. void GetNode(llvm::APSInt &FromInt, llvm::APSInt &ToInt,
  589. bool &IsValidFromInt, bool &IsValidToInt) {
  590. FromInt = FlatTree[ReadNode].FromInt;
  591. ToInt = FlatTree[ReadNode].ToInt;
  592. IsValidFromInt = FlatTree[ReadNode].IsValidFromInt;
  593. IsValidToInt = FlatTree[ReadNode].IsValidToInt;
  594. }
  595. /// GetNode - Gets the FromQual and ToQual.
  596. void GetNode(Qualifiers &FromQual, Qualifiers &ToQual) {
  597. FromQual = FlatTree[ReadNode].FromQual;
  598. ToQual = FlatTree[ReadNode].ToQual;
  599. }
  600. /// GetNode - Gets the FromValueDecl and ToValueDecl.
  601. void GetNode(ValueDecl *&FromValueDecl, ValueDecl *&ToValueDecl,
  602. bool &FromAddressOf, bool &ToAddressOf) {
  603. FromValueDecl = FlatTree[ReadNode].FromValueDecl;
  604. ToValueDecl = FlatTree[ReadNode].ToValueDecl;
  605. FromAddressOf = FlatTree[ReadNode].FromAddressOf;
  606. ToAddressOf = FlatTree[ReadNode].ToAddressOf;
  607. }
  608. /// NodeIsSame - Returns true the arguments are the same.
  609. bool NodeIsSame() {
  610. return FlatTree[ReadNode].Same;
  611. }
  612. /// HasChildrend - Returns true if the node has children.
  613. bool HasChildren() {
  614. return FlatTree[ReadNode].ChildNode != 0;
  615. }
  616. /// MoveToChild - Moves from the current node to its child.
  617. void MoveToChild() {
  618. ReadNode = FlatTree[ReadNode].ChildNode;
  619. }
  620. /// AdvanceSibling - If there is a next sibling, advance to it and return
  621. /// true. Otherwise, return false.
  622. bool AdvanceSibling() {
  623. if (FlatTree[ReadNode].NextNode == 0)
  624. return false;
  625. ReadNode = FlatTree[ReadNode].NextNode;
  626. return true;
  627. }
  628. /// HasNextSibling - Return true if the node has a next sibling.
  629. bool HasNextSibling() {
  630. return FlatTree[ReadNode].NextNode != 0;
  631. }
  632. /// FromNullPtr - Returns true if the from argument is null.
  633. bool FromNullPtr() {
  634. return FlatTree[ReadNode].FromNullPtr;
  635. }
  636. /// ToNullPtr - Returns true if the to argument is null.
  637. bool ToNullPtr() {
  638. return FlatTree[ReadNode].ToNullPtr;
  639. }
  640. /// FromDefault - Return true if the from argument is the default.
  641. bool FromDefault() {
  642. return FlatTree[ReadNode].FromDefault;
  643. }
  644. /// ToDefault - Return true if the to argument is the default.
  645. bool ToDefault() {
  646. return FlatTree[ReadNode].ToDefault;
  647. }
  648. /// Empty - Returns true if the tree has no information.
  649. bool Empty() {
  650. return GetKind() == Invalid;
  651. }
  652. /// GetKind - Returns the current node's type.
  653. DiffKind GetKind() {
  654. return FlatTree[ReadNode].Kind;
  655. }
  656. };
  657. DiffTree Tree;
  658. /// TSTiterator - an iterator that is used to enter a
  659. /// TemplateSpecializationType and read TemplateArguments inside template
  660. /// parameter packs in order with the rest of the TemplateArguments.
  661. struct TSTiterator {
  662. typedef const TemplateArgument& reference;
  663. typedef const TemplateArgument* pointer;
  664. /// TST - the template specialization whose arguments this iterator
  665. /// traverse over.
  666. const TemplateSpecializationType *TST;
  667. /// DesugarTST - desugared template specialization used to extract
  668. /// default argument information
  669. const TemplateSpecializationType *DesugarTST;
  670. /// Index - the index of the template argument in TST.
  671. unsigned Index;
  672. /// CurrentTA - if CurrentTA is not the same as EndTA, then CurrentTA
  673. /// points to a TemplateArgument within a parameter pack.
  674. TemplateArgument::pack_iterator CurrentTA;
  675. /// EndTA - the end iterator of a parameter pack
  676. TemplateArgument::pack_iterator EndTA;
  677. /// TSTiterator - Constructs an iterator and sets it to the first template
  678. /// argument.
  679. TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST)
  680. : TST(TST),
  681. DesugarTST(GetTemplateSpecializationType(Context, TST->desugar())),
  682. Index(0), CurrentTA(nullptr), EndTA(nullptr) {
  683. if (isEnd()) return;
  684. // Set to first template argument. If not a parameter pack, done.
  685. TemplateArgument TA = TST->getArg(0);
  686. if (TA.getKind() != TemplateArgument::Pack) return;
  687. // Start looking into the parameter pack.
  688. CurrentTA = TA.pack_begin();
  689. EndTA = TA.pack_end();
  690. // Found a valid template argument.
  691. if (CurrentTA != EndTA) return;
  692. // Parameter pack is empty, use the increment to get to a valid
  693. // template argument.
  694. ++(*this);
  695. }
  696. /// isEnd - Returns true if the iterator is one past the end.
  697. bool isEnd() const {
  698. return Index >= TST->getNumArgs();
  699. }
  700. /// &operator++ - Increment the iterator to the next template argument.
  701. TSTiterator &operator++() {
  702. // After the end, Index should be the default argument position in
  703. // DesugarTST, if it exists.
  704. if (isEnd()) {
  705. ++Index;
  706. return *this;
  707. }
  708. // If in a parameter pack, advance in the parameter pack.
  709. if (CurrentTA != EndTA) {
  710. ++CurrentTA;
  711. if (CurrentTA != EndTA)
  712. return *this;
  713. }
  714. // Loop until a template argument is found, or the end is reached.
  715. while (true) {
  716. // Advance to the next template argument. Break if reached the end.
  717. if (++Index == TST->getNumArgs()) break;
  718. // If the TemplateArgument is not a parameter pack, done.
  719. TemplateArgument TA = TST->getArg(Index);
  720. if (TA.getKind() != TemplateArgument::Pack) break;
  721. // Handle parameter packs.
  722. CurrentTA = TA.pack_begin();
  723. EndTA = TA.pack_end();
  724. // If the parameter pack is empty, try to advance again.
  725. if (CurrentTA != EndTA) break;
  726. }
  727. return *this;
  728. }
  729. /// operator* - Returns the appropriate TemplateArgument.
  730. reference operator*() const {
  731. assert(!isEnd() && "Index exceeds number of arguments.");
  732. if (CurrentTA == EndTA)
  733. return TST->getArg(Index);
  734. else
  735. return *CurrentTA;
  736. }
  737. /// operator-> - Allow access to the underlying TemplateArgument.
  738. pointer operator->() const {
  739. return &operator*();
  740. }
  741. /// getDesugar - Returns the deduced template argument from DesguarTST
  742. reference getDesugar() const {
  743. return DesugarTST->getArg(Index);
  744. }
  745. };
  746. // These functions build up the template diff tree, including functions to
  747. // retrieve and compare template arguments.
  748. static const TemplateSpecializationType * GetTemplateSpecializationType(
  749. ASTContext &Context, QualType Ty) {
  750. if (const TemplateSpecializationType *TST =
  751. Ty->getAs<TemplateSpecializationType>())
  752. return TST;
  753. const RecordType *RT = Ty->getAs<RecordType>();
  754. if (!RT)
  755. return nullptr;
  756. const ClassTemplateSpecializationDecl *CTSD =
  757. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  758. if (!CTSD)
  759. return nullptr;
  760. Ty = Context.getTemplateSpecializationType(
  761. TemplateName(CTSD->getSpecializedTemplate()),
  762. CTSD->getTemplateArgs().data(),
  763. CTSD->getTemplateArgs().size(),
  764. Ty.getLocalUnqualifiedType().getCanonicalType());
  765. return Ty->getAs<TemplateSpecializationType>();
  766. }
  767. /// DiffTypes - Fills a DiffNode with information about a type difference.
  768. void DiffTypes(const TSTiterator &FromIter, const TSTiterator &ToIter,
  769. TemplateTypeParmDecl *FromDefaultTypeDecl,
  770. TemplateTypeParmDecl *ToDefaultTypeDecl) {
  771. QualType FromType = GetType(FromIter, FromDefaultTypeDecl);
  772. QualType ToType = GetType(ToIter, ToDefaultTypeDecl);
  773. Tree.SetNode(FromType, ToType);
  774. Tree.SetDefault(FromIter.isEnd() && !FromType.isNull(),
  775. ToIter.isEnd() && !ToType.isNull());
  776. Tree.SetKind(DiffTree::Type);
  777. if (FromType.isNull() || ToType.isNull())
  778. return;
  779. if (Context.hasSameType(FromType, ToType)) {
  780. Tree.SetSame(true);
  781. return;
  782. }
  783. const TemplateSpecializationType *FromArgTST =
  784. GetTemplateSpecializationType(Context, FromType);
  785. if (!FromArgTST)
  786. return;
  787. const TemplateSpecializationType *ToArgTST =
  788. GetTemplateSpecializationType(Context, ToType);
  789. if (!ToArgTST)
  790. return;
  791. if (!hasSameTemplate(FromArgTST, ToArgTST))
  792. return;
  793. Qualifiers FromQual = FromType.getQualifiers(),
  794. ToQual = ToType.getQualifiers();
  795. FromQual -= QualType(FromArgTST, 0).getQualifiers();
  796. ToQual -= QualType(ToArgTST, 0).getQualifiers();
  797. Tree.SetNode(FromArgTST->getTemplateName().getAsTemplateDecl(),
  798. ToArgTST->getTemplateName().getAsTemplateDecl());
  799. Tree.SetNode(FromQual, ToQual);
  800. Tree.SetKind(DiffTree::Template);
  801. DiffTemplate(FromArgTST, ToArgTST);
  802. }
  803. /// DiffTemplateTemplates - Fills a DiffNode with information about a
  804. /// template template difference.
  805. void DiffTemplateTemplates(const TSTiterator &FromIter,
  806. const TSTiterator &ToIter,
  807. TemplateTemplateParmDecl *FromDefaultTemplateDecl,
  808. TemplateTemplateParmDecl *ToDefaultTemplateDecl) {
  809. TemplateDecl *FromDecl = GetTemplateDecl(FromIter, FromDefaultTemplateDecl);
  810. TemplateDecl *ToDecl = GetTemplateDecl(ToIter, ToDefaultTemplateDecl);
  811. Tree.SetNode(FromDecl, ToDecl);
  812. Tree.SetSame(FromDecl && ToDecl &&
  813. FromDecl->getCanonicalDecl() == ToDecl->getCanonicalDecl());
  814. Tree.SetDefault(FromIter.isEnd() && FromDecl, ToIter.isEnd() && ToDecl);
  815. Tree.SetKind(DiffTree::TemplateTemplate);
  816. }
  817. /// InitializeNonTypeDiffVariables - Helper function for DiffNonTypes
  818. static void InitializeNonTypeDiffVariables(
  819. ASTContext &Context, const TSTiterator &Iter,
  820. NonTypeTemplateParmDecl *Default, bool &HasInt, bool &HasValueDecl,
  821. bool &IsNullPtr, Expr *&E, llvm::APSInt &Value, ValueDecl *&VD) {
  822. HasInt = !Iter.isEnd() && Iter->getKind() == TemplateArgument::Integral;
  823. HasValueDecl =
  824. !Iter.isEnd() && Iter->getKind() == TemplateArgument::Declaration;
  825. IsNullPtr = !Iter.isEnd() && Iter->getKind() == TemplateArgument::NullPtr;
  826. if (HasInt)
  827. Value = Iter->getAsIntegral();
  828. else if (HasValueDecl)
  829. VD = Iter->getAsDecl();
  830. else if (!IsNullPtr)
  831. E = GetExpr(Iter, Default);
  832. if (E && Default->getType()->isPointerType())
  833. IsNullPtr = CheckForNullPtr(Context, E);
  834. }
  835. /// NeedsAddressOf - Helper function for DiffNonTypes. Returns true if the
  836. /// ValueDecl needs a '&' when printed.
  837. static bool NeedsAddressOf(ValueDecl *VD, Expr *E,
  838. NonTypeTemplateParmDecl *Default) {
  839. if (!VD)
  840. return false;
  841. if (E) {
  842. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
  843. if (UO->getOpcode() == UO_AddrOf) {
  844. return true;
  845. }
  846. }
  847. return false;
  848. }
  849. if (!Default->getType()->isReferenceType()) {
  850. return true;
  851. }
  852. return false;
  853. }
  854. /// DiffNonTypes - Handles any template parameters not handled by DiffTypes
  855. /// of DiffTemplatesTemplates, such as integer and declaration parameters.
  856. void DiffNonTypes(const TSTiterator &FromIter, const TSTiterator &ToIter,
  857. NonTypeTemplateParmDecl *FromDefaultNonTypeDecl,
  858. NonTypeTemplateParmDecl *ToDefaultNonTypeDecl) {
  859. Expr *FromExpr = nullptr, *ToExpr = nullptr;
  860. llvm::APSInt FromInt, ToInt;
  861. ValueDecl *FromValueDecl = nullptr, *ToValueDecl = nullptr;
  862. bool HasFromInt = false, HasToInt = false, HasFromValueDecl = false,
  863. HasToValueDecl = false, FromNullPtr = false, ToNullPtr = false;
  864. InitializeNonTypeDiffVariables(Context, FromIter, FromDefaultNonTypeDecl,
  865. HasFromInt, HasFromValueDecl, FromNullPtr,
  866. FromExpr, FromInt, FromValueDecl);
  867. InitializeNonTypeDiffVariables(Context, ToIter, ToDefaultNonTypeDecl,
  868. HasToInt, HasToValueDecl, ToNullPtr,
  869. ToExpr, ToInt, ToValueDecl);
  870. assert(((!HasFromInt && !HasToInt) ||
  871. (!HasFromValueDecl && !HasToValueDecl)) &&
  872. "Template argument cannot be both integer and declaration");
  873. if (!HasFromInt && !HasToInt && !HasFromValueDecl && !HasToValueDecl) {
  874. Tree.SetNode(FromExpr, ToExpr);
  875. Tree.SetDefault(FromIter.isEnd() && FromExpr, ToIter.isEnd() && ToExpr);
  876. if (FromDefaultNonTypeDecl->getType()->isIntegralOrEnumerationType()) {
  877. if (FromExpr)
  878. HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt,
  879. FromDefaultNonTypeDecl->getType());
  880. if (ToExpr)
  881. HasToInt = GetInt(Context, ToIter, ToExpr, ToInt,
  882. ToDefaultNonTypeDecl->getType());
  883. }
  884. if (HasFromInt && HasToInt) {
  885. Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
  886. Tree.SetSame(FromInt == ToInt);
  887. Tree.SetKind(DiffTree::Integer);
  888. } else if (HasFromInt || HasToInt) {
  889. Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
  890. Tree.SetSame(false);
  891. Tree.SetKind(DiffTree::Integer);
  892. } else {
  893. Tree.SetSame(IsEqualExpr(Context, FromExpr, ToExpr) ||
  894. (FromNullPtr && ToNullPtr));
  895. Tree.SetNullPtr(FromNullPtr, ToNullPtr);
  896. Tree.SetKind(DiffTree::Expression);
  897. }
  898. return;
  899. }
  900. if (HasFromInt || HasToInt) {
  901. if (!HasFromInt && FromExpr)
  902. HasFromInt = GetInt(Context, FromIter, FromExpr, FromInt,
  903. FromDefaultNonTypeDecl->getType());
  904. if (!HasToInt && ToExpr)
  905. HasToInt = GetInt(Context, ToIter, ToExpr, ToInt,
  906. ToDefaultNonTypeDecl->getType());
  907. Tree.SetNode(FromInt, ToInt, HasFromInt, HasToInt);
  908. if (HasFromInt && HasToInt) {
  909. Tree.SetSame(FromInt == ToInt);
  910. } else {
  911. Tree.SetSame(false);
  912. }
  913. Tree.SetDefault(FromIter.isEnd() && HasFromInt,
  914. ToIter.isEnd() && HasToInt);
  915. Tree.SetKind(DiffTree::Integer);
  916. return;
  917. }
  918. if (!HasFromValueDecl && FromExpr)
  919. FromValueDecl = GetValueDecl(FromIter, FromExpr);
  920. if (!HasToValueDecl && ToExpr)
  921. ToValueDecl = GetValueDecl(ToIter, ToExpr);
  922. bool FromAddressOf =
  923. NeedsAddressOf(FromValueDecl, FromExpr, FromDefaultNonTypeDecl);
  924. bool ToAddressOf =
  925. NeedsAddressOf(ToValueDecl, ToExpr, ToDefaultNonTypeDecl);
  926. Tree.SetNullPtr(FromNullPtr, ToNullPtr);
  927. Tree.SetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
  928. Tree.SetSame(FromValueDecl && ToValueDecl &&
  929. FromValueDecl->getCanonicalDecl() ==
  930. ToValueDecl->getCanonicalDecl());
  931. Tree.SetDefault(FromIter.isEnd() && FromValueDecl,
  932. ToIter.isEnd() && ToValueDecl);
  933. Tree.SetKind(DiffTree::Declaration);
  934. }
  935. /// DiffTemplate - recursively visits template arguments and stores the
  936. /// argument info into a tree.
  937. void DiffTemplate(const TemplateSpecializationType *FromTST,
  938. const TemplateSpecializationType *ToTST) {
  939. // Begin descent into diffing template tree.
  940. TemplateParameterList *ParamsFrom =
  941. FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
  942. TemplateParameterList *ParamsTo =
  943. ToTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters();
  944. unsigned TotalArgs = 0;
  945. for (TSTiterator FromIter(Context, FromTST), ToIter(Context, ToTST);
  946. !FromIter.isEnd() || !ToIter.isEnd(); ++TotalArgs) {
  947. Tree.AddNode();
  948. // Get the parameter at index TotalArgs. If index is larger
  949. // than the total number of parameters, then there is an
  950. // argument pack, so re-use the last parameter.
  951. unsigned FromParamIndex = std::min(TotalArgs, ParamsFrom->size() - 1);
  952. unsigned ToParamIndex = std::min(TotalArgs, ParamsTo->size() - 1);
  953. NamedDecl *FromParamND = ParamsFrom->getParam(FromParamIndex);
  954. NamedDecl *ToParamND = ParamsTo->getParam(ToParamIndex);
  955. TemplateTypeParmDecl *FromDefaultTypeDecl =
  956. dyn_cast<TemplateTypeParmDecl>(FromParamND);
  957. TemplateTypeParmDecl *ToDefaultTypeDecl =
  958. dyn_cast<TemplateTypeParmDecl>(ToParamND);
  959. if (FromDefaultTypeDecl && ToDefaultTypeDecl)
  960. DiffTypes(FromIter, ToIter, FromDefaultTypeDecl, ToDefaultTypeDecl);
  961. TemplateTemplateParmDecl *FromDefaultTemplateDecl =
  962. dyn_cast<TemplateTemplateParmDecl>(FromParamND);
  963. TemplateTemplateParmDecl *ToDefaultTemplateDecl =
  964. dyn_cast<TemplateTemplateParmDecl>(ToParamND);
  965. if (FromDefaultTemplateDecl && ToDefaultTemplateDecl)
  966. DiffTemplateTemplates(FromIter, ToIter, FromDefaultTemplateDecl,
  967. ToDefaultTemplateDecl);
  968. NonTypeTemplateParmDecl *FromDefaultNonTypeDecl =
  969. dyn_cast<NonTypeTemplateParmDecl>(FromParamND);
  970. NonTypeTemplateParmDecl *ToDefaultNonTypeDecl =
  971. dyn_cast<NonTypeTemplateParmDecl>(ToParamND);
  972. if (FromDefaultNonTypeDecl && ToDefaultNonTypeDecl)
  973. DiffNonTypes(FromIter, ToIter, FromDefaultNonTypeDecl,
  974. ToDefaultNonTypeDecl);
  975. ++FromIter;
  976. ++ToIter;
  977. Tree.Up();
  978. }
  979. }
  980. /// makeTemplateList - Dump every template alias into the vector.
  981. static void makeTemplateList(
  982. SmallVectorImpl<const TemplateSpecializationType *> &TemplateList,
  983. const TemplateSpecializationType *TST) {
  984. while (TST) {
  985. TemplateList.push_back(TST);
  986. if (!TST->isTypeAlias())
  987. return;
  988. TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
  989. }
  990. }
  991. /// hasSameBaseTemplate - Returns true when the base templates are the same,
  992. /// even if the template arguments are not.
  993. static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST,
  994. const TemplateSpecializationType *ToTST) {
  995. return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() ==
  996. ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl();
  997. }
  998. /// hasSameTemplate - Returns true if both types are specialized from the
  999. /// same template declaration. If they come from different template aliases,
  1000. /// do a parallel ascension search to determine the highest template alias in
  1001. /// common and set the arguments to them.
  1002. static bool hasSameTemplate(const TemplateSpecializationType *&FromTST,
  1003. const TemplateSpecializationType *&ToTST) {
  1004. // Check the top templates if they are the same.
  1005. if (hasSameBaseTemplate(FromTST, ToTST))
  1006. return true;
  1007. // Create vectors of template aliases.
  1008. SmallVector<const TemplateSpecializationType*, 1> FromTemplateList,
  1009. ToTemplateList;
  1010. makeTemplateList(FromTemplateList, FromTST);
  1011. makeTemplateList(ToTemplateList, ToTST);
  1012. SmallVectorImpl<const TemplateSpecializationType *>::reverse_iterator
  1013. FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(),
  1014. ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend();
  1015. // Check if the lowest template types are the same. If not, return.
  1016. if (!hasSameBaseTemplate(*FromIter, *ToIter))
  1017. return false;
  1018. // Begin searching up the template aliases. The bottom most template
  1019. // matches so move up until one pair does not match. Use the template
  1020. // right before that one.
  1021. for (; FromIter != FromEnd && ToIter != ToEnd; ++FromIter, ++ToIter) {
  1022. if (!hasSameBaseTemplate(*FromIter, *ToIter))
  1023. break;
  1024. }
  1025. FromTST = FromIter[-1];
  1026. ToTST = ToIter[-1];
  1027. return true;
  1028. }
  1029. /// GetType - Retrieves the template type arguments, including default
  1030. /// arguments.
  1031. static QualType GetType(const TSTiterator &Iter,
  1032. TemplateTypeParmDecl *DefaultTTPD) {
  1033. bool isVariadic = DefaultTTPD->isParameterPack();
  1034. if (!Iter.isEnd())
  1035. return Iter->getAsType();
  1036. if (isVariadic)
  1037. return QualType();
  1038. QualType ArgType = DefaultTTPD->getDefaultArgument();
  1039. if (ArgType->isDependentType())
  1040. return Iter.getDesugar().getAsType();
  1041. return ArgType;
  1042. }
  1043. /// GetExpr - Retrieves the template expression argument, including default
  1044. /// arguments.
  1045. static Expr *GetExpr(const TSTiterator &Iter,
  1046. NonTypeTemplateParmDecl *DefaultNTTPD) {
  1047. Expr *ArgExpr = nullptr;
  1048. bool isVariadic = DefaultNTTPD->isParameterPack();
  1049. if (!Iter.isEnd())
  1050. ArgExpr = Iter->getAsExpr();
  1051. else if (!isVariadic)
  1052. ArgExpr = DefaultNTTPD->getDefaultArgument();
  1053. if (ArgExpr)
  1054. while (SubstNonTypeTemplateParmExpr *SNTTPE =
  1055. dyn_cast<SubstNonTypeTemplateParmExpr>(ArgExpr))
  1056. ArgExpr = SNTTPE->getReplacement();
  1057. return ArgExpr;
  1058. }
  1059. /// GetInt - Retrieves the template integer argument, including evaluating
  1060. /// default arguments. If the value comes from an expression, extend the
  1061. /// APSInt to size of IntegerType to match the behavior in
  1062. /// Sema::CheckTemplateArgument
  1063. static bool GetInt(ASTContext &Context, const TSTiterator &Iter,
  1064. Expr *ArgExpr, llvm::APSInt &Int, QualType IntegerType) {
  1065. // Default, value-depenedent expressions require fetching
  1066. // from the desugared TemplateArgument, otherwise expression needs to
  1067. // be evaluatable.
  1068. if (Iter.isEnd() && ArgExpr->isValueDependent()) {
  1069. switch (Iter.getDesugar().getKind()) {
  1070. case TemplateArgument::Integral:
  1071. Int = Iter.getDesugar().getAsIntegral();
  1072. return true;
  1073. case TemplateArgument::Expression:
  1074. ArgExpr = Iter.getDesugar().getAsExpr();
  1075. Int = ArgExpr->EvaluateKnownConstInt(Context);
  1076. Int = Int.extOrTrunc(Context.getTypeSize(IntegerType));
  1077. return true;
  1078. default:
  1079. llvm_unreachable("Unexpected template argument kind");
  1080. }
  1081. } else if (ArgExpr->isEvaluatable(Context)) {
  1082. Int = ArgExpr->EvaluateKnownConstInt(Context);
  1083. Int = Int.extOrTrunc(Context.getTypeSize(IntegerType));
  1084. return true;
  1085. }
  1086. return false;
  1087. }
  1088. /// GetValueDecl - Retrieves the template Decl argument, including
  1089. /// default expression argument.
  1090. static ValueDecl *GetValueDecl(const TSTiterator &Iter, Expr *ArgExpr) {
  1091. // Default, value-depenedent expressions require fetching
  1092. // from the desugared TemplateArgument
  1093. if (Iter.isEnd() && ArgExpr->isValueDependent())
  1094. switch (Iter.getDesugar().getKind()) {
  1095. case TemplateArgument::Declaration:
  1096. return Iter.getDesugar().getAsDecl();
  1097. case TemplateArgument::Expression:
  1098. ArgExpr = Iter.getDesugar().getAsExpr();
  1099. return cast<DeclRefExpr>(ArgExpr)->getDecl();
  1100. default:
  1101. llvm_unreachable("Unexpected template argument kind");
  1102. }
  1103. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr);
  1104. if (!DRE) {
  1105. UnaryOperator *UO = dyn_cast<UnaryOperator>(ArgExpr->IgnoreParens());
  1106. if (!UO)
  1107. return nullptr;
  1108. DRE = cast<DeclRefExpr>(UO->getSubExpr());
  1109. }
  1110. return DRE->getDecl();
  1111. }
  1112. /// CheckForNullPtr - returns true if the expression can be evaluated as
  1113. /// a null pointer
  1114. static bool CheckForNullPtr(ASTContext &Context, Expr *E) {
  1115. assert(E && "Expected expression");
  1116. E = E->IgnoreParenCasts();
  1117. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  1118. return true;
  1119. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  1120. if (!DRE)
  1121. return false;
  1122. VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
  1123. if (!VD || !VD->hasInit())
  1124. return false;
  1125. return VD->getInit()->IgnoreParenCasts()->isNullPointerConstant(
  1126. Context, Expr::NPC_ValueDependentIsNull);
  1127. }
  1128. /// GetTemplateDecl - Retrieves the template template arguments, including
  1129. /// default arguments.
  1130. static TemplateDecl *GetTemplateDecl(const TSTiterator &Iter,
  1131. TemplateTemplateParmDecl *DefaultTTPD) {
  1132. bool isVariadic = DefaultTTPD->isParameterPack();
  1133. TemplateArgument TA = DefaultTTPD->getDefaultArgument().getArgument();
  1134. TemplateDecl *DefaultTD = nullptr;
  1135. if (TA.getKind() != TemplateArgument::Null)
  1136. DefaultTD = TA.getAsTemplate().getAsTemplateDecl();
  1137. if (!Iter.isEnd())
  1138. return Iter->getAsTemplate().getAsTemplateDecl();
  1139. if (!isVariadic)
  1140. return DefaultTD;
  1141. return nullptr;
  1142. }
  1143. /// IsEqualExpr - Returns true if the expressions evaluate to the same value.
  1144. static bool IsEqualExpr(ASTContext &Context, Expr *FromExpr, Expr *ToExpr) {
  1145. if (FromExpr == ToExpr)
  1146. return true;
  1147. if (!FromExpr || !ToExpr)
  1148. return false;
  1149. DeclRefExpr *FromDRE = dyn_cast<DeclRefExpr>(FromExpr->IgnoreParens()),
  1150. *ToDRE = dyn_cast<DeclRefExpr>(ToExpr->IgnoreParens());
  1151. if (FromDRE || ToDRE) {
  1152. if (!FromDRE || !ToDRE)
  1153. return false;
  1154. return FromDRE->getDecl() == ToDRE->getDecl();
  1155. }
  1156. Expr::EvalResult FromResult, ToResult;
  1157. if (!FromExpr->EvaluateAsRValue(FromResult, Context) ||
  1158. !ToExpr->EvaluateAsRValue(ToResult, Context)) {
  1159. llvm::FoldingSetNodeID FromID, ToID;
  1160. FromExpr->Profile(FromID, Context, true);
  1161. ToExpr->Profile(ToID, Context, true);
  1162. return FromID == ToID;
  1163. }
  1164. APValue &FromVal = FromResult.Val;
  1165. APValue &ToVal = ToResult.Val;
  1166. if (FromVal.getKind() != ToVal.getKind()) return false;
  1167. switch (FromVal.getKind()) {
  1168. case APValue::Int:
  1169. return FromVal.getInt() == ToVal.getInt();
  1170. case APValue::LValue: {
  1171. APValue::LValueBase FromBase = FromVal.getLValueBase();
  1172. APValue::LValueBase ToBase = ToVal.getLValueBase();
  1173. if (FromBase.isNull() && ToBase.isNull())
  1174. return true;
  1175. if (FromBase.isNull() || ToBase.isNull())
  1176. return false;
  1177. return FromBase.get<const ValueDecl*>() ==
  1178. ToBase.get<const ValueDecl*>();
  1179. }
  1180. case APValue::MemberPointer:
  1181. return FromVal.getMemberPointerDecl() == ToVal.getMemberPointerDecl();
  1182. default:
  1183. llvm_unreachable("Unknown template argument expression.");
  1184. }
  1185. }
  1186. // These functions converts the tree representation of the template
  1187. // differences into the internal character vector.
  1188. /// TreeToString - Converts the Tree object into a character stream which
  1189. /// will later be turned into the output string.
  1190. void TreeToString(int Indent = 1) {
  1191. if (PrintTree) {
  1192. OS << '\n';
  1193. OS.indent(2 * Indent);
  1194. ++Indent;
  1195. }
  1196. // Handle cases where the difference is not templates with different
  1197. // arguments.
  1198. switch (Tree.GetKind()) {
  1199. case DiffTree::Invalid:
  1200. llvm_unreachable("Template diffing failed with bad DiffNode");
  1201. case DiffTree::Type: {
  1202. QualType FromType, ToType;
  1203. Tree.GetNode(FromType, ToType);
  1204. PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(),
  1205. Tree.NodeIsSame());
  1206. return;
  1207. }
  1208. case DiffTree::Expression: {
  1209. Expr *FromExpr, *ToExpr;
  1210. Tree.GetNode(FromExpr, ToExpr);
  1211. PrintExpr(FromExpr, ToExpr, Tree.FromNullPtr(), Tree.ToNullPtr(),
  1212. Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame());
  1213. return;
  1214. }
  1215. case DiffTree::TemplateTemplate: {
  1216. TemplateDecl *FromTD, *ToTD;
  1217. Tree.GetNode(FromTD, ToTD);
  1218. PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(),
  1219. Tree.ToDefault(), Tree.NodeIsSame());
  1220. return;
  1221. }
  1222. case DiffTree::Integer: {
  1223. llvm::APSInt FromInt, ToInt;
  1224. Expr *FromExpr, *ToExpr;
  1225. bool IsValidFromInt, IsValidToInt;
  1226. Tree.GetNode(FromExpr, ToExpr);
  1227. Tree.GetNode(FromInt, ToInt, IsValidFromInt, IsValidToInt);
  1228. PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt,
  1229. FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(),
  1230. Tree.NodeIsSame());
  1231. return;
  1232. }
  1233. case DiffTree::Declaration: {
  1234. ValueDecl *FromValueDecl, *ToValueDecl;
  1235. bool FromAddressOf, ToAddressOf;
  1236. Tree.GetNode(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf);
  1237. PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf,
  1238. Tree.FromNullPtr(), Tree.ToNullPtr(), Tree.FromDefault(),
  1239. Tree.ToDefault(), Tree.NodeIsSame());
  1240. return;
  1241. }
  1242. case DiffTree::Template: {
  1243. // Node is root of template. Recurse on children.
  1244. TemplateDecl *FromTD, *ToTD;
  1245. Tree.GetNode(FromTD, ToTD);
  1246. if (!Tree.HasChildren()) {
  1247. // If we're dealing with a template specialization with zero
  1248. // arguments, there are no children; special-case this.
  1249. OS << FromTD->getNameAsString() << "<>";
  1250. return;
  1251. }
  1252. Qualifiers FromQual, ToQual;
  1253. Tree.GetNode(FromQual, ToQual);
  1254. PrintQualifiers(FromQual, ToQual);
  1255. OS << FromTD->getNameAsString() << '<';
  1256. Tree.MoveToChild();
  1257. unsigned NumElideArgs = 0;
  1258. do {
  1259. if (ElideType) {
  1260. if (Tree.NodeIsSame()) {
  1261. ++NumElideArgs;
  1262. continue;
  1263. }
  1264. if (NumElideArgs > 0) {
  1265. PrintElideArgs(NumElideArgs, Indent);
  1266. NumElideArgs = 0;
  1267. OS << ", ";
  1268. }
  1269. }
  1270. TreeToString(Indent);
  1271. if (Tree.HasNextSibling())
  1272. OS << ", ";
  1273. } while (Tree.AdvanceSibling());
  1274. if (NumElideArgs > 0)
  1275. PrintElideArgs(NumElideArgs, Indent);
  1276. Tree.Parent();
  1277. OS << ">";
  1278. return;
  1279. }
  1280. }
  1281. }
  1282. // To signal to the text printer that a certain text needs to be bolded,
  1283. // a special character is injected into the character stream which the
  1284. // text printer will later strip out.
  1285. /// Bold - Start bolding text.
  1286. void Bold() {
  1287. assert(!IsBold && "Attempting to bold text that is already bold.");
  1288. IsBold = true;
  1289. if (ShowColor)
  1290. OS << ToggleHighlight;
  1291. }
  1292. /// Unbold - Stop bolding text.
  1293. void Unbold() {
  1294. assert(IsBold && "Attempting to remove bold from unbold text.");
  1295. IsBold = false;
  1296. if (ShowColor)
  1297. OS << ToggleHighlight;
  1298. }
  1299. // Functions to print out the arguments and highlighting the difference.
  1300. /// PrintTypeNames - prints the typenames, bolding differences. Will detect
  1301. /// typenames that are the same and attempt to disambiguate them by using
  1302. /// canonical typenames.
  1303. void PrintTypeNames(QualType FromType, QualType ToType,
  1304. bool FromDefault, bool ToDefault, bool Same) {
  1305. assert((!FromType.isNull() || !ToType.isNull()) &&
  1306. "Only one template argument may be missing.");
  1307. if (Same) {
  1308. OS << FromType.getAsString(Policy);
  1309. return;
  1310. }
  1311. if (!FromType.isNull() && !ToType.isNull() &&
  1312. FromType.getLocalUnqualifiedType() ==
  1313. ToType.getLocalUnqualifiedType()) {
  1314. Qualifiers FromQual = FromType.getLocalQualifiers(),
  1315. ToQual = ToType.getLocalQualifiers();
  1316. PrintQualifiers(FromQual, ToQual);
  1317. FromType.getLocalUnqualifiedType().print(OS, Policy);
  1318. return;
  1319. }
  1320. std::string FromTypeStr = FromType.isNull() ? "(no argument)"
  1321. : FromType.getAsString(Policy);
  1322. std::string ToTypeStr = ToType.isNull() ? "(no argument)"
  1323. : ToType.getAsString(Policy);
  1324. // Switch to canonical typename if it is better.
  1325. // TODO: merge this with other aka printing above.
  1326. if (FromTypeStr == ToTypeStr) {
  1327. std::string FromCanTypeStr =
  1328. FromType.getCanonicalType().getAsString(Policy);
  1329. std::string ToCanTypeStr = ToType.getCanonicalType().getAsString(Policy);
  1330. if (FromCanTypeStr != ToCanTypeStr) {
  1331. FromTypeStr = FromCanTypeStr;
  1332. ToTypeStr = ToCanTypeStr;
  1333. }
  1334. }
  1335. if (PrintTree) OS << '[';
  1336. OS << (FromDefault ? "(default) " : "");
  1337. Bold();
  1338. OS << FromTypeStr;
  1339. Unbold();
  1340. if (PrintTree) {
  1341. OS << " != " << (ToDefault ? "(default) " : "");
  1342. Bold();
  1343. OS << ToTypeStr;
  1344. Unbold();
  1345. OS << "]";
  1346. }
  1347. return;
  1348. }
  1349. /// PrintExpr - Prints out the expr template arguments, highlighting argument
  1350. /// differences.
  1351. void PrintExpr(const Expr *FromExpr, const Expr *ToExpr, bool FromNullPtr,
  1352. bool ToNullPtr, bool FromDefault, bool ToDefault, bool Same) {
  1353. assert((FromExpr || ToExpr) &&
  1354. "Only one template argument may be missing.");
  1355. if (Same) {
  1356. PrintExpr(FromExpr, FromNullPtr);
  1357. } else if (!PrintTree) {
  1358. OS << (FromDefault ? "(default) " : "");
  1359. Bold();
  1360. PrintExpr(FromExpr, FromNullPtr);
  1361. Unbold();
  1362. } else {
  1363. OS << (FromDefault ? "[(default) " : "[");
  1364. Bold();
  1365. PrintExpr(FromExpr, FromNullPtr);
  1366. Unbold();
  1367. OS << " != " << (ToDefault ? "(default) " : "");
  1368. Bold();
  1369. PrintExpr(ToExpr, ToNullPtr);
  1370. Unbold();
  1371. OS << ']';
  1372. }
  1373. }
  1374. /// PrintExpr - Actual formatting and printing of expressions.
  1375. void PrintExpr(const Expr *E, bool NullPtr = false) {
  1376. if (E) {
  1377. E->printPretty(OS, nullptr, Policy);
  1378. return;
  1379. }
  1380. if (NullPtr) {
  1381. OS << "nullptr";
  1382. return;
  1383. }
  1384. OS << "(no argument)";
  1385. }
  1386. /// PrintTemplateTemplate - Handles printing of template template arguments,
  1387. /// highlighting argument differences.
  1388. void PrintTemplateTemplate(TemplateDecl *FromTD, TemplateDecl *ToTD,
  1389. bool FromDefault, bool ToDefault, bool Same) {
  1390. assert((FromTD || ToTD) && "Only one template argument may be missing.");
  1391. std::string FromName = FromTD ? FromTD->getName() : "(no argument)";
  1392. std::string ToName = ToTD ? ToTD->getName() : "(no argument)";
  1393. if (FromTD && ToTD && FromName == ToName) {
  1394. FromName = FromTD->getQualifiedNameAsString();
  1395. ToName = ToTD->getQualifiedNameAsString();
  1396. }
  1397. if (Same) {
  1398. OS << "template " << FromTD->getNameAsString();
  1399. } else if (!PrintTree) {
  1400. OS << (FromDefault ? "(default) template " : "template ");
  1401. Bold();
  1402. OS << FromName;
  1403. Unbold();
  1404. } else {
  1405. OS << (FromDefault ? "[(default) template " : "[template ");
  1406. Bold();
  1407. OS << FromName;
  1408. Unbold();
  1409. OS << " != " << (ToDefault ? "(default) template " : "template ");
  1410. Bold();
  1411. OS << ToName;
  1412. Unbold();
  1413. OS << ']';
  1414. }
  1415. }
  1416. /// PrintAPSInt - Handles printing of integral arguments, highlighting
  1417. /// argument differences.
  1418. void PrintAPSInt(llvm::APSInt FromInt, llvm::APSInt ToInt,
  1419. bool IsValidFromInt, bool IsValidToInt, Expr *FromExpr,
  1420. Expr *ToExpr, bool FromDefault, bool ToDefault, bool Same) {
  1421. assert((IsValidFromInt || IsValidToInt) &&
  1422. "Only one integral argument may be missing.");
  1423. if (Same) {
  1424. OS << FromInt.toString(10);
  1425. } else if (!PrintTree) {
  1426. OS << (FromDefault ? "(default) " : "");
  1427. PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
  1428. } else {
  1429. OS << (FromDefault ? "[(default) " : "[");
  1430. PrintAPSInt(FromInt, FromExpr, IsValidFromInt);
  1431. OS << " != " << (ToDefault ? "(default) " : "");
  1432. PrintAPSInt(ToInt, ToExpr, IsValidToInt);
  1433. OS << ']';
  1434. }
  1435. }
  1436. /// PrintAPSInt - If valid, print the APSInt. If the expression is
  1437. /// gives more information, print it too.
  1438. void PrintAPSInt(llvm::APSInt Val, Expr *E, bool Valid) {
  1439. Bold();
  1440. if (Valid) {
  1441. if (HasExtraInfo(E)) {
  1442. PrintExpr(E);
  1443. Unbold();
  1444. OS << " aka ";
  1445. Bold();
  1446. }
  1447. OS << Val.toString(10);
  1448. } else if (E) {
  1449. PrintExpr(E);
  1450. } else {
  1451. OS << "(no argument)";
  1452. }
  1453. Unbold();
  1454. }
  1455. /// HasExtraInfo - Returns true if E is not an integer literal or the
  1456. /// negation of an integer literal
  1457. bool HasExtraInfo(Expr *E) {
  1458. if (!E) return false;
  1459. E = E->IgnoreImpCasts();
  1460. if (isa<IntegerLiteral>(E)) return false;
  1461. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
  1462. if (UO->getOpcode() == UO_Minus)
  1463. if (isa<IntegerLiteral>(UO->getSubExpr()))
  1464. return false;
  1465. return true;
  1466. }
  1467. void PrintValueDecl(ValueDecl *VD, bool AddressOf, bool NullPtr) {
  1468. if (VD) {
  1469. if (AddressOf)
  1470. OS << "&";
  1471. OS << VD->getName();
  1472. return;
  1473. }
  1474. if (NullPtr) {
  1475. OS << "nullptr";
  1476. return;
  1477. }
  1478. OS << "(no argument)";
  1479. }
  1480. /// PrintDecl - Handles printing of Decl arguments, highlighting
  1481. /// argument differences.
  1482. void PrintValueDecl(ValueDecl *FromValueDecl, ValueDecl *ToValueDecl,
  1483. bool FromAddressOf, bool ToAddressOf, bool FromNullPtr,
  1484. bool ToNullPtr, bool FromDefault, bool ToDefault,
  1485. bool Same) {
  1486. assert((FromValueDecl || FromNullPtr || ToValueDecl || ToNullPtr) &&
  1487. "Only one Decl argument may be NULL");
  1488. if (Same) {
  1489. PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
  1490. } else if (!PrintTree) {
  1491. OS << (FromDefault ? "(default) " : "");
  1492. Bold();
  1493. PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
  1494. Unbold();
  1495. } else {
  1496. OS << (FromDefault ? "[(default) " : "[");
  1497. Bold();
  1498. PrintValueDecl(FromValueDecl, FromAddressOf, FromNullPtr);
  1499. Unbold();
  1500. OS << " != " << (ToDefault ? "(default) " : "");
  1501. Bold();
  1502. PrintValueDecl(ToValueDecl, ToAddressOf, ToNullPtr);
  1503. Unbold();
  1504. OS << ']';
  1505. }
  1506. }
  1507. // Prints the appropriate placeholder for elided template arguments.
  1508. void PrintElideArgs(unsigned NumElideArgs, unsigned Indent) {
  1509. if (PrintTree) {
  1510. OS << '\n';
  1511. for (unsigned i = 0; i < Indent; ++i)
  1512. OS << " ";
  1513. }
  1514. if (NumElideArgs == 0) return;
  1515. if (NumElideArgs == 1)
  1516. OS << "[...]";
  1517. else
  1518. OS << "[" << NumElideArgs << " * ...]";
  1519. }
  1520. // Prints and highlights differences in Qualifiers.
  1521. void PrintQualifiers(Qualifiers FromQual, Qualifiers ToQual) {
  1522. // Both types have no qualifiers
  1523. if (FromQual.empty() && ToQual.empty())
  1524. return;
  1525. // Both types have same qualifiers
  1526. if (FromQual == ToQual) {
  1527. PrintQualifier(FromQual, /*ApplyBold*/false);
  1528. return;
  1529. }
  1530. // Find common qualifiers and strip them from FromQual and ToQual.
  1531. Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual,
  1532. ToQual);
  1533. // The qualifiers are printed before the template name.
  1534. // Inline printing:
  1535. // The common qualifiers are printed. Then, qualifiers only in this type
  1536. // are printed and highlighted. Finally, qualifiers only in the other
  1537. // type are printed and highlighted inside parentheses after "missing".
  1538. // Tree printing:
  1539. // Qualifiers are printed next to each other, inside brackets, and
  1540. // separated by "!=". The printing order is:
  1541. // common qualifiers, highlighted from qualifiers, "!=",
  1542. // common qualifiers, highlighted to qualifiers
  1543. if (PrintTree) {
  1544. OS << "[";
  1545. if (CommonQual.empty() && FromQual.empty()) {
  1546. Bold();
  1547. OS << "(no qualifiers) ";
  1548. Unbold();
  1549. } else {
  1550. PrintQualifier(CommonQual, /*ApplyBold*/false);
  1551. PrintQualifier(FromQual, /*ApplyBold*/true);
  1552. }
  1553. OS << "!= ";
  1554. if (CommonQual.empty() && ToQual.empty()) {
  1555. Bold();
  1556. OS << "(no qualifiers)";
  1557. Unbold();
  1558. } else {
  1559. PrintQualifier(CommonQual, /*ApplyBold*/false,
  1560. /*appendSpaceIfNonEmpty*/!ToQual.empty());
  1561. PrintQualifier(ToQual, /*ApplyBold*/true,
  1562. /*appendSpaceIfNonEmpty*/false);
  1563. }
  1564. OS << "] ";
  1565. } else {
  1566. PrintQualifier(CommonQual, /*ApplyBold*/false);
  1567. PrintQualifier(FromQual, /*ApplyBold*/true);
  1568. }
  1569. }
  1570. void PrintQualifier(Qualifiers Q, bool ApplyBold,
  1571. bool AppendSpaceIfNonEmpty = true) {
  1572. if (Q.empty()) return;
  1573. if (ApplyBold) Bold();
  1574. Q.print(OS, Policy, AppendSpaceIfNonEmpty);
  1575. if (ApplyBold) Unbold();
  1576. }
  1577. public:
  1578. TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType,
  1579. QualType ToType, bool PrintTree, bool PrintFromType,
  1580. bool ElideType, bool ShowColor)
  1581. : Context(Context),
  1582. Policy(Context.getLangOpts()),
  1583. ElideType(ElideType),
  1584. PrintTree(PrintTree),
  1585. ShowColor(ShowColor),
  1586. // When printing a single type, the FromType is the one printed.
  1587. FromType(PrintFromType ? FromType : ToType),
  1588. ToType(PrintFromType ? ToType : FromType),
  1589. OS(OS),
  1590. IsBold(false) {
  1591. }
  1592. /// DiffTemplate - Start the template type diffing.
  1593. void DiffTemplate() {
  1594. Qualifiers FromQual = FromType.getQualifiers(),
  1595. ToQual = ToType.getQualifiers();
  1596. const TemplateSpecializationType *FromOrigTST =
  1597. GetTemplateSpecializationType(Context, FromType);
  1598. const TemplateSpecializationType *ToOrigTST =
  1599. GetTemplateSpecializationType(Context, ToType);
  1600. // Only checking templates.
  1601. if (!FromOrigTST || !ToOrigTST)
  1602. return;
  1603. // Different base templates.
  1604. if (!hasSameTemplate(FromOrigTST, ToOrigTST)) {
  1605. return;
  1606. }
  1607. FromQual -= QualType(FromOrigTST, 0).getQualifiers();
  1608. ToQual -= QualType(ToOrigTST, 0).getQualifiers();
  1609. Tree.SetNode(FromType, ToType);
  1610. Tree.SetNode(FromQual, ToQual);
  1611. Tree.SetKind(DiffTree::Template);
  1612. // Same base template, but different arguments.
  1613. Tree.SetNode(FromOrigTST->getTemplateName().getAsTemplateDecl(),
  1614. ToOrigTST->getTemplateName().getAsTemplateDecl());
  1615. DiffTemplate(FromOrigTST, ToOrigTST);
  1616. }
  1617. /// Emit - When the two types given are templated types with the same
  1618. /// base template, a string representation of the type difference will be
  1619. /// emitted to the stream and return true. Otherwise, return false.
  1620. bool Emit() {
  1621. Tree.StartTraverse();
  1622. if (Tree.Empty())
  1623. return false;
  1624. TreeToString();
  1625. assert(!IsBold && "Bold is applied to end of string.");
  1626. return true;
  1627. }
  1628. }; // end class TemplateDiff
  1629. } // end namespace
  1630. /// FormatTemplateTypeDiff - A helper static function to start the template
  1631. /// diff and return the properly formatted string. Returns true if the diff
  1632. /// is successful.
  1633. static bool FormatTemplateTypeDiff(ASTContext &Context, QualType FromType,
  1634. QualType ToType, bool PrintTree,
  1635. bool PrintFromType, bool ElideType,
  1636. bool ShowColors, raw_ostream &OS) {
  1637. if (PrintTree)
  1638. PrintFromType = true;
  1639. TemplateDiff TD(OS, Context, FromType, ToType, PrintTree, PrintFromType,
  1640. ElideType, ShowColors);
  1641. TD.DiffTemplate();
  1642. return TD.Emit();
  1643. }