ASTDiagnostic.cpp 78 KB

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