ASTDiagnostic.cpp 75 KB

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