ClangDiagnosticsEmitter.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. //=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
  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. // These tablegen backends emit Clang diagnostics tables.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TableGenBackends.h"
  13. #include "llvm/ADT/DenseSet.h"
  14. #include "llvm/ADT/Optional.h"
  15. #include "llvm/ADT/PointerUnion.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/StringSwitch.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/Support/Casting.h"
  24. #include "llvm/TableGen/Error.h"
  25. #include "llvm/TableGen/Record.h"
  26. #include "llvm/TableGen/StringToOffsetTable.h"
  27. #include "llvm/TableGen/TableGenBackend.h"
  28. #include <algorithm>
  29. #include <cctype>
  30. #include <functional>
  31. #include <map>
  32. #include <set>
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Diagnostic category computation code.
  36. //===----------------------------------------------------------------------===//
  37. namespace {
  38. class DiagGroupParentMap {
  39. RecordKeeper &Records;
  40. std::map<const Record*, std::vector<Record*> > Mapping;
  41. public:
  42. DiagGroupParentMap(RecordKeeper &records) : Records(records) {
  43. std::vector<Record*> DiagGroups
  44. = Records.getAllDerivedDefinitions("DiagGroup");
  45. for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
  46. std::vector<Record*> SubGroups =
  47. DiagGroups[i]->getValueAsListOfDefs("SubGroups");
  48. for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
  49. Mapping[SubGroups[j]].push_back(DiagGroups[i]);
  50. }
  51. }
  52. const std::vector<Record*> &getParents(const Record *Group) {
  53. return Mapping[Group];
  54. }
  55. };
  56. } // end anonymous namespace.
  57. static std::string
  58. getCategoryFromDiagGroup(const Record *Group,
  59. DiagGroupParentMap &DiagGroupParents) {
  60. // If the DiagGroup has a category, return it.
  61. std::string CatName = std::string(Group->getValueAsString("CategoryName"));
  62. if (!CatName.empty()) return CatName;
  63. // The diag group may the subgroup of one or more other diagnostic groups,
  64. // check these for a category as well.
  65. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  66. for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
  67. CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
  68. if (!CatName.empty()) return CatName;
  69. }
  70. return "";
  71. }
  72. /// getDiagnosticCategory - Return the category that the specified diagnostic
  73. /// lives in.
  74. static std::string getDiagnosticCategory(const Record *R,
  75. DiagGroupParentMap &DiagGroupParents) {
  76. // If the diagnostic is in a group, and that group has a category, use it.
  77. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
  78. // Check the diagnostic's diag group for a category.
  79. std::string CatName = getCategoryFromDiagGroup(Group->getDef(),
  80. DiagGroupParents);
  81. if (!CatName.empty()) return CatName;
  82. }
  83. // If the diagnostic itself has a category, get it.
  84. return std::string(R->getValueAsString("CategoryName"));
  85. }
  86. namespace {
  87. class DiagCategoryIDMap {
  88. RecordKeeper &Records;
  89. StringMap<unsigned> CategoryIDs;
  90. std::vector<std::string> CategoryStrings;
  91. public:
  92. DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
  93. DiagGroupParentMap ParentInfo(Records);
  94. // The zero'th category is "".
  95. CategoryStrings.push_back("");
  96. CategoryIDs[""] = 0;
  97. std::vector<Record*> Diags =
  98. Records.getAllDerivedDefinitions("Diagnostic");
  99. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  100. std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
  101. if (Category.empty()) continue; // Skip diags with no category.
  102. unsigned &ID = CategoryIDs[Category];
  103. if (ID != 0) continue; // Already seen.
  104. ID = CategoryStrings.size();
  105. CategoryStrings.push_back(Category);
  106. }
  107. }
  108. unsigned getID(StringRef CategoryString) {
  109. return CategoryIDs[CategoryString];
  110. }
  111. typedef std::vector<std::string>::const_iterator const_iterator;
  112. const_iterator begin() const { return CategoryStrings.begin(); }
  113. const_iterator end() const { return CategoryStrings.end(); }
  114. };
  115. struct GroupInfo {
  116. llvm::StringRef GroupName;
  117. std::vector<const Record*> DiagsInGroup;
  118. std::vector<std::string> SubGroups;
  119. unsigned IDNo;
  120. llvm::SmallVector<const Record *, 1> Defs;
  121. GroupInfo() : IDNo(0) {}
  122. };
  123. } // end anonymous namespace.
  124. static bool beforeThanCompare(const Record *LHS, const Record *RHS) {
  125. assert(!LHS->getLoc().empty() && !RHS->getLoc().empty());
  126. return
  127. LHS->getLoc().front().getPointer() < RHS->getLoc().front().getPointer();
  128. }
  129. static bool diagGroupBeforeByName(const Record *LHS, const Record *RHS) {
  130. return LHS->getValueAsString("GroupName") <
  131. RHS->getValueAsString("GroupName");
  132. }
  133. /// Invert the 1-[0/1] mapping of diags to group into a one to many
  134. /// mapping of groups to diags in the group.
  135. static void groupDiagnostics(const std::vector<Record*> &Diags,
  136. const std::vector<Record*> &DiagGroups,
  137. std::map<std::string, GroupInfo> &DiagsInGroup) {
  138. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  139. const Record *R = Diags[i];
  140. DefInit *DI = dyn_cast<DefInit>(R->getValueInit("Group"));
  141. if (!DI)
  142. continue;
  143. assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&
  144. "Note can't be in a DiagGroup");
  145. std::string GroupName =
  146. std::string(DI->getDef()->getValueAsString("GroupName"));
  147. DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
  148. }
  149. // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
  150. // groups (these are warnings that GCC supports that clang never produces).
  151. for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
  152. Record *Group = DiagGroups[i];
  153. GroupInfo &GI =
  154. DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];
  155. GI.GroupName = Group->getName();
  156. GI.Defs.push_back(Group);
  157. std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
  158. for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
  159. GI.SubGroups.push_back(
  160. std::string(SubGroups[j]->getValueAsString("GroupName")));
  161. }
  162. // Assign unique ID numbers to the groups.
  163. unsigned IDNo = 0;
  164. for (std::map<std::string, GroupInfo>::iterator
  165. I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
  166. I->second.IDNo = IDNo;
  167. // Warn if the same group is defined more than once (including implicitly).
  168. for (auto &Group : DiagsInGroup) {
  169. if (Group.second.Defs.size() == 1 &&
  170. (!Group.second.Defs.front()->isAnonymous() ||
  171. Group.second.DiagsInGroup.size() <= 1))
  172. continue;
  173. bool First = true;
  174. for (const Record *Def : Group.second.Defs) {
  175. // Skip implicit definitions from diagnostics; we'll report those
  176. // separately below.
  177. bool IsImplicit = false;
  178. for (const Record *Diag : Group.second.DiagsInGroup) {
  179. if (cast<DefInit>(Diag->getValueInit("Group"))->getDef() == Def) {
  180. IsImplicit = true;
  181. break;
  182. }
  183. }
  184. if (IsImplicit)
  185. continue;
  186. llvm::SMLoc Loc = Def->getLoc().front();
  187. if (First) {
  188. SrcMgr.PrintMessage(Loc, SourceMgr::DK_Error,
  189. Twine("group '") + Group.first +
  190. "' is defined more than once");
  191. First = false;
  192. } else {
  193. SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note, "also defined here");
  194. }
  195. }
  196. for (const Record *Diag : Group.second.DiagsInGroup) {
  197. if (!cast<DefInit>(Diag->getValueInit("Group"))->getDef()->isAnonymous())
  198. continue;
  199. llvm::SMLoc Loc = Diag->getLoc().front();
  200. if (First) {
  201. SrcMgr.PrintMessage(Loc, SourceMgr::DK_Error,
  202. Twine("group '") + Group.first +
  203. "' is implicitly defined more than once");
  204. First = false;
  205. } else {
  206. SrcMgr.PrintMessage(Loc, SourceMgr::DK_Note,
  207. "also implicitly defined here");
  208. }
  209. }
  210. }
  211. }
  212. //===----------------------------------------------------------------------===//
  213. // Infer members of -Wpedantic.
  214. //===----------------------------------------------------------------------===//
  215. typedef std::vector<const Record *> RecordVec;
  216. typedef llvm::DenseSet<const Record *> RecordSet;
  217. typedef llvm::PointerUnion<RecordVec*, RecordSet*> VecOrSet;
  218. namespace {
  219. class InferPedantic {
  220. typedef llvm::DenseMap<const Record*,
  221. std::pair<unsigned, Optional<unsigned> > > GMap;
  222. DiagGroupParentMap &DiagGroupParents;
  223. const std::vector<Record*> &Diags;
  224. const std::vector<Record*> DiagGroups;
  225. std::map<std::string, GroupInfo> &DiagsInGroup;
  226. llvm::DenseSet<const Record*> DiagsSet;
  227. GMap GroupCount;
  228. public:
  229. InferPedantic(DiagGroupParentMap &DiagGroupParents,
  230. const std::vector<Record*> &Diags,
  231. const std::vector<Record*> &DiagGroups,
  232. std::map<std::string, GroupInfo> &DiagsInGroup)
  233. : DiagGroupParents(DiagGroupParents),
  234. Diags(Diags),
  235. DiagGroups(DiagGroups),
  236. DiagsInGroup(DiagsInGroup) {}
  237. /// Compute the set of diagnostics and groups that are immediately
  238. /// in -Wpedantic.
  239. void compute(VecOrSet DiagsInPedantic,
  240. VecOrSet GroupsInPedantic);
  241. private:
  242. /// Determine whether a group is a subgroup of another group.
  243. bool isSubGroupOfGroup(const Record *Group,
  244. llvm::StringRef RootGroupName);
  245. /// Determine if the diagnostic is an extension.
  246. bool isExtension(const Record *Diag);
  247. /// Determine if the diagnostic is off by default.
  248. bool isOffByDefault(const Record *Diag);
  249. /// Increment the count for a group, and transitively marked
  250. /// parent groups when appropriate.
  251. void markGroup(const Record *Group);
  252. /// Return true if the diagnostic is in a pedantic group.
  253. bool groupInPedantic(const Record *Group, bool increment = false);
  254. };
  255. } // end anonymous namespace
  256. bool InferPedantic::isSubGroupOfGroup(const Record *Group,
  257. llvm::StringRef GName) {
  258. const std::string &GroupName =
  259. std::string(Group->getValueAsString("GroupName"));
  260. if (GName == GroupName)
  261. return true;
  262. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  263. for (unsigned i = 0, e = Parents.size(); i != e; ++i)
  264. if (isSubGroupOfGroup(Parents[i], GName))
  265. return true;
  266. return false;
  267. }
  268. /// Determine if the diagnostic is an extension.
  269. bool InferPedantic::isExtension(const Record *Diag) {
  270. const std::string &ClsName =
  271. std::string(Diag->getValueAsDef("Class")->getName());
  272. return ClsName == "CLASS_EXTENSION";
  273. }
  274. bool InferPedantic::isOffByDefault(const Record *Diag) {
  275. const std::string &DefSeverity = std::string(
  276. Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));
  277. return DefSeverity == "Ignored";
  278. }
  279. bool InferPedantic::groupInPedantic(const Record *Group, bool increment) {
  280. GMap::mapped_type &V = GroupCount[Group];
  281. // Lazily compute the threshold value for the group count.
  282. if (!V.second.hasValue()) {
  283. const GroupInfo &GI =
  284. DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];
  285. V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();
  286. }
  287. if (increment)
  288. ++V.first;
  289. // Consider a group in -Wpendatic IFF if has at least one diagnostic
  290. // or subgroup AND all of those diagnostics and subgroups are covered
  291. // by -Wpedantic via our computation.
  292. return V.first != 0 && V.first == V.second.getValue();
  293. }
  294. void InferPedantic::markGroup(const Record *Group) {
  295. // If all the diagnostics and subgroups have been marked as being
  296. // covered by -Wpedantic, increment the count of parent groups. Once the
  297. // group's count is equal to the number of subgroups and diagnostics in
  298. // that group, we can safely add this group to -Wpedantic.
  299. if (groupInPedantic(Group, /* increment */ true)) {
  300. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  301. for (unsigned i = 0, e = Parents.size(); i != e; ++i)
  302. markGroup(Parents[i]);
  303. }
  304. }
  305. void InferPedantic::compute(VecOrSet DiagsInPedantic,
  306. VecOrSet GroupsInPedantic) {
  307. // All extensions that are not on by default are implicitly in the
  308. // "pedantic" group. For those that aren't explicitly included in -Wpedantic,
  309. // mark them for consideration to be included in -Wpedantic directly.
  310. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  311. Record *R = Diags[i];
  312. if (isExtension(R) && isOffByDefault(R)) {
  313. DiagsSet.insert(R);
  314. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
  315. const Record *GroupRec = Group->getDef();
  316. if (!isSubGroupOfGroup(GroupRec, "pedantic")) {
  317. markGroup(GroupRec);
  318. }
  319. }
  320. }
  321. }
  322. // Compute the set of diagnostics that are directly in -Wpedantic. We
  323. // march through Diags a second time to ensure the results are emitted
  324. // in deterministic order.
  325. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  326. Record *R = Diags[i];
  327. if (!DiagsSet.count(R))
  328. continue;
  329. // Check if the group is implicitly in -Wpedantic. If so,
  330. // the diagnostic should not be directly included in the -Wpedantic
  331. // diagnostic group.
  332. if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group")))
  333. if (groupInPedantic(Group->getDef()))
  334. continue;
  335. // The diagnostic is not included in a group that is (transitively) in
  336. // -Wpedantic. Include it in -Wpedantic directly.
  337. if (RecordVec *V = DiagsInPedantic.dyn_cast<RecordVec*>())
  338. V->push_back(R);
  339. else {
  340. DiagsInPedantic.get<RecordSet*>()->insert(R);
  341. }
  342. }
  343. if (!GroupsInPedantic)
  344. return;
  345. // Compute the set of groups that are directly in -Wpedantic. We
  346. // march through the groups to ensure the results are emitted
  347. /// in a deterministc order.
  348. for (unsigned i = 0, ei = DiagGroups.size(); i != ei; ++i) {
  349. Record *Group = DiagGroups[i];
  350. if (!groupInPedantic(Group))
  351. continue;
  352. unsigned ParentsInPedantic = 0;
  353. const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
  354. for (unsigned j = 0, ej = Parents.size(); j != ej; ++j) {
  355. if (groupInPedantic(Parents[j]))
  356. ++ParentsInPedantic;
  357. }
  358. // If all the parents are in -Wpedantic, this means that this diagnostic
  359. // group will be indirectly included by -Wpedantic already. In that
  360. // case, do not add it directly to -Wpedantic. If the group has no
  361. // parents, obviously it should go into -Wpedantic.
  362. if (Parents.size() > 0 && ParentsInPedantic == Parents.size())
  363. continue;
  364. if (RecordVec *V = GroupsInPedantic.dyn_cast<RecordVec*>())
  365. V->push_back(Group);
  366. else {
  367. GroupsInPedantic.get<RecordSet*>()->insert(Group);
  368. }
  369. }
  370. }
  371. namespace {
  372. enum PieceKind {
  373. MultiPieceClass,
  374. TextPieceClass,
  375. PlaceholderPieceClass,
  376. SelectPieceClass,
  377. PluralPieceClass,
  378. DiffPieceClass,
  379. SubstitutionPieceClass,
  380. };
  381. enum ModifierType {
  382. MT_Unknown,
  383. MT_Placeholder,
  384. MT_Select,
  385. MT_Sub,
  386. MT_Plural,
  387. MT_Diff,
  388. MT_Ordinal,
  389. MT_S,
  390. MT_Q,
  391. MT_ObjCClass,
  392. MT_ObjCInstance,
  393. };
  394. static StringRef getModifierName(ModifierType MT) {
  395. switch (MT) {
  396. case MT_Select:
  397. return "select";
  398. case MT_Sub:
  399. return "sub";
  400. case MT_Diff:
  401. return "diff";
  402. case MT_Plural:
  403. return "plural";
  404. case MT_Ordinal:
  405. return "ordinal";
  406. case MT_S:
  407. return "s";
  408. case MT_Q:
  409. return "q";
  410. case MT_Placeholder:
  411. return "";
  412. case MT_ObjCClass:
  413. return "objcclass";
  414. case MT_ObjCInstance:
  415. return "objcinstance";
  416. case MT_Unknown:
  417. llvm_unreachable("invalid modifier type");
  418. }
  419. // Unhandled case
  420. llvm_unreachable("invalid modifier type");
  421. }
  422. struct Piece {
  423. // This type and its derived classes are move-only.
  424. Piece(PieceKind Kind) : ClassKind(Kind) {}
  425. Piece(Piece const &O) = delete;
  426. Piece &operator=(Piece const &) = delete;
  427. virtual ~Piece() {}
  428. PieceKind getPieceClass() const { return ClassKind; }
  429. static bool classof(const Piece *) { return true; }
  430. private:
  431. PieceKind ClassKind;
  432. };
  433. struct MultiPiece : Piece {
  434. MultiPiece() : Piece(MultiPieceClass) {}
  435. MultiPiece(std::vector<Piece *> Pieces)
  436. : Piece(MultiPieceClass), Pieces(std::move(Pieces)) {}
  437. std::vector<Piece *> Pieces;
  438. static bool classof(const Piece *P) {
  439. return P->getPieceClass() == MultiPieceClass;
  440. }
  441. };
  442. struct TextPiece : Piece {
  443. StringRef Role;
  444. std::string Text;
  445. TextPiece(StringRef Text, StringRef Role = "")
  446. : Piece(TextPieceClass), Role(Role), Text(Text.str()) {}
  447. static bool classof(const Piece *P) {
  448. return P->getPieceClass() == TextPieceClass;
  449. }
  450. };
  451. struct PlaceholderPiece : Piece {
  452. ModifierType Kind;
  453. int Index;
  454. PlaceholderPiece(ModifierType Kind, int Index)
  455. : Piece(PlaceholderPieceClass), Kind(Kind), Index(Index) {}
  456. static bool classof(const Piece *P) {
  457. return P->getPieceClass() == PlaceholderPieceClass;
  458. }
  459. };
  460. struct SelectPiece : Piece {
  461. protected:
  462. SelectPiece(PieceKind Kind, ModifierType ModKind)
  463. : Piece(Kind), ModKind(ModKind) {}
  464. public:
  465. SelectPiece(ModifierType ModKind) : SelectPiece(SelectPieceClass, ModKind) {}
  466. ModifierType ModKind;
  467. std::vector<Piece *> Options;
  468. int Index = 0;
  469. static bool classof(const Piece *P) {
  470. return P->getPieceClass() == SelectPieceClass ||
  471. P->getPieceClass() == PluralPieceClass;
  472. }
  473. };
  474. struct PluralPiece : SelectPiece {
  475. PluralPiece() : SelectPiece(PluralPieceClass, MT_Plural) {}
  476. std::vector<Piece *> OptionPrefixes;
  477. int Index = 0;
  478. static bool classof(const Piece *P) {
  479. return P->getPieceClass() == PluralPieceClass;
  480. }
  481. };
  482. struct DiffPiece : Piece {
  483. DiffPiece() : Piece(DiffPieceClass) {}
  484. Piece *Parts[4] = {};
  485. int Indexes[2] = {};
  486. static bool classof(const Piece *P) {
  487. return P->getPieceClass() == DiffPieceClass;
  488. }
  489. };
  490. struct SubstitutionPiece : Piece {
  491. SubstitutionPiece() : Piece(SubstitutionPieceClass) {}
  492. std::string Name;
  493. std::vector<int> Modifiers;
  494. static bool classof(const Piece *P) {
  495. return P->getPieceClass() == SubstitutionPieceClass;
  496. }
  497. };
  498. /// Diagnostic text, parsed into pieces.
  499. struct DiagnosticTextBuilder {
  500. DiagnosticTextBuilder(DiagnosticTextBuilder const &) = delete;
  501. DiagnosticTextBuilder &operator=(DiagnosticTextBuilder const &) = delete;
  502. DiagnosticTextBuilder(RecordKeeper &Records) {
  503. // Build up the list of substitution records.
  504. for (auto *S : Records.getAllDerivedDefinitions("TextSubstitution")) {
  505. EvaluatingRecordGuard Guard(&EvaluatingRecord, S);
  506. Substitutions.try_emplace(
  507. S->getName(), DiagText(*this, S->getValueAsString("Substitution")));
  508. }
  509. // Check that no diagnostic definitions have the same name as a
  510. // substitution.
  511. for (Record *Diag : Records.getAllDerivedDefinitions("Diagnostic")) {
  512. StringRef Name = Diag->getName();
  513. if (Substitutions.count(Name))
  514. llvm::PrintFatalError(
  515. Diag->getLoc(),
  516. "Diagnostic '" + Name +
  517. "' has same name as TextSubstitution definition");
  518. }
  519. }
  520. std::vector<std::string> buildForDocumentation(StringRef Role,
  521. const Record *R);
  522. std::string buildForDefinition(const Record *R);
  523. Piece *getSubstitution(SubstitutionPiece *S) const {
  524. auto It = Substitutions.find(S->Name);
  525. if (It == Substitutions.end())
  526. PrintFatalError("Failed to find substitution with name: " + S->Name);
  527. return It->second.Root;
  528. }
  529. [[noreturn]] void PrintFatalError(llvm::Twine const &Msg) const {
  530. assert(EvaluatingRecord && "not evaluating a record?");
  531. llvm::PrintFatalError(EvaluatingRecord->getLoc(), Msg);
  532. }
  533. private:
  534. struct DiagText {
  535. DiagnosticTextBuilder &Builder;
  536. std::vector<Piece *> AllocatedPieces;
  537. Piece *Root = nullptr;
  538. template <class T, class... Args> T *New(Args &&... args) {
  539. static_assert(std::is_base_of<Piece, T>::value, "must be piece");
  540. T *Mem = new T(std::forward<Args>(args)...);
  541. AllocatedPieces.push_back(Mem);
  542. return Mem;
  543. }
  544. DiagText(DiagnosticTextBuilder &Builder, StringRef Text)
  545. : Builder(Builder), Root(parseDiagText(Text, StopAt::End)) {}
  546. enum class StopAt {
  547. // Parse until the end of the string.
  548. End,
  549. // Additionally stop if we hit a non-nested '|' or '}'.
  550. PipeOrCloseBrace,
  551. // Additionally stop if we hit a non-nested '$'.
  552. Dollar,
  553. };
  554. Piece *parseDiagText(StringRef &Text, StopAt Stop);
  555. int parseModifier(StringRef &) const;
  556. public:
  557. DiagText(DiagText &&O) noexcept
  558. : Builder(O.Builder), AllocatedPieces(std::move(O.AllocatedPieces)),
  559. Root(O.Root) {
  560. O.Root = nullptr;
  561. }
  562. ~DiagText() {
  563. for (Piece *P : AllocatedPieces)
  564. delete P;
  565. }
  566. };
  567. private:
  568. const Record *EvaluatingRecord = nullptr;
  569. struct EvaluatingRecordGuard {
  570. EvaluatingRecordGuard(const Record **Dest, const Record *New)
  571. : Dest(Dest), Old(*Dest) {
  572. *Dest = New;
  573. }
  574. ~EvaluatingRecordGuard() { *Dest = Old; }
  575. const Record **Dest;
  576. const Record *Old;
  577. };
  578. StringMap<DiagText> Substitutions;
  579. };
  580. template <class Derived> struct DiagTextVisitor {
  581. using ModifierMappingsType = Optional<std::vector<int>>;
  582. private:
  583. Derived &getDerived() { return static_cast<Derived &>(*this); }
  584. public:
  585. std::vector<int>
  586. getSubstitutionMappings(SubstitutionPiece *P,
  587. const ModifierMappingsType &Mappings) const {
  588. std::vector<int> NewMappings;
  589. for (int Idx : P->Modifiers)
  590. NewMappings.push_back(mapIndex(Idx, Mappings));
  591. return NewMappings;
  592. }
  593. struct SubstitutionContext {
  594. SubstitutionContext(DiagTextVisitor &Visitor, SubstitutionPiece *P)
  595. : Visitor(Visitor) {
  596. Substitution = Visitor.Builder.getSubstitution(P);
  597. OldMappings = std::move(Visitor.ModifierMappings);
  598. std::vector<int> NewMappings =
  599. Visitor.getSubstitutionMappings(P, OldMappings);
  600. Visitor.ModifierMappings = std::move(NewMappings);
  601. }
  602. ~SubstitutionContext() {
  603. Visitor.ModifierMappings = std::move(OldMappings);
  604. }
  605. private:
  606. DiagTextVisitor &Visitor;
  607. Optional<std::vector<int>> OldMappings;
  608. public:
  609. Piece *Substitution;
  610. };
  611. public:
  612. DiagTextVisitor(DiagnosticTextBuilder &Builder) : Builder(Builder) {}
  613. void Visit(Piece *P) {
  614. switch (P->getPieceClass()) {
  615. #define CASE(T) \
  616. case T##PieceClass: \
  617. return getDerived().Visit##T(static_cast<T##Piece *>(P))
  618. CASE(Multi);
  619. CASE(Text);
  620. CASE(Placeholder);
  621. CASE(Select);
  622. CASE(Plural);
  623. CASE(Diff);
  624. CASE(Substitution);
  625. #undef CASE
  626. }
  627. }
  628. void VisitSubstitution(SubstitutionPiece *P) {
  629. SubstitutionContext Guard(*this, P);
  630. Visit(Guard.Substitution);
  631. }
  632. int mapIndex(int Idx,
  633. ModifierMappingsType const &ModifierMappings) const {
  634. if (!ModifierMappings)
  635. return Idx;
  636. if (ModifierMappings->size() <= static_cast<unsigned>(Idx))
  637. Builder.PrintFatalError("Modifier value '" + std::to_string(Idx) +
  638. "' is not valid for this mapping (has " +
  639. std::to_string(ModifierMappings->size()) +
  640. " mappings)");
  641. return (*ModifierMappings)[Idx];
  642. }
  643. int mapIndex(int Idx) const {
  644. return mapIndex(Idx, ModifierMappings);
  645. }
  646. protected:
  647. DiagnosticTextBuilder &Builder;
  648. ModifierMappingsType ModifierMappings;
  649. };
  650. void escapeRST(StringRef Str, std::string &Out) {
  651. for (auto K : Str) {
  652. if (StringRef("`*|_[]\\").count(K))
  653. Out.push_back('\\');
  654. Out.push_back(K);
  655. }
  656. }
  657. template <typename It> void padToSameLength(It Begin, It End) {
  658. size_t Width = 0;
  659. for (It I = Begin; I != End; ++I)
  660. Width = std::max(Width, I->size());
  661. for (It I = Begin; I != End; ++I)
  662. (*I) += std::string(Width - I->size(), ' ');
  663. }
  664. template <typename It> void makeTableRows(It Begin, It End) {
  665. if (Begin == End)
  666. return;
  667. padToSameLength(Begin, End);
  668. for (It I = Begin; I != End; ++I)
  669. *I = "|" + *I + "|";
  670. }
  671. void makeRowSeparator(std::string &Str) {
  672. for (char &K : Str)
  673. K = (K == '|' ? '+' : '-');
  674. }
  675. struct DiagTextDocPrinter : DiagTextVisitor<DiagTextDocPrinter> {
  676. using BaseTy = DiagTextVisitor<DiagTextDocPrinter>;
  677. DiagTextDocPrinter(DiagnosticTextBuilder &Builder,
  678. std::vector<std::string> &RST)
  679. : BaseTy(Builder), RST(RST) {}
  680. void gatherNodes(
  681. Piece *OrigP, const ModifierMappingsType &CurrentMappings,
  682. std::vector<std::pair<Piece *, ModifierMappingsType>> &Pieces) const {
  683. if (auto *Sub = dyn_cast<SubstitutionPiece>(OrigP)) {
  684. ModifierMappingsType NewMappings =
  685. getSubstitutionMappings(Sub, CurrentMappings);
  686. return gatherNodes(Builder.getSubstitution(Sub), NewMappings, Pieces);
  687. }
  688. if (auto *MD = dyn_cast<MultiPiece>(OrigP)) {
  689. for (Piece *Node : MD->Pieces)
  690. gatherNodes(Node, CurrentMappings, Pieces);
  691. return;
  692. }
  693. Pieces.push_back(std::make_pair(OrigP, CurrentMappings));
  694. }
  695. void VisitMulti(MultiPiece *P) {
  696. if (P->Pieces.empty()) {
  697. RST.push_back("");
  698. return;
  699. }
  700. if (P->Pieces.size() == 1)
  701. return Visit(P->Pieces[0]);
  702. // Flatten the list of nodes, replacing any substitution pieces with the
  703. // recursively flattened substituted node.
  704. std::vector<std::pair<Piece *, ModifierMappingsType>> Pieces;
  705. gatherNodes(P, ModifierMappings, Pieces);
  706. std::string EmptyLinePrefix;
  707. size_t Start = RST.size();
  708. bool HasMultipleLines = true;
  709. for (const std::pair<Piece *, ModifierMappingsType> &NodePair : Pieces) {
  710. std::vector<std::string> Lines;
  711. DiagTextDocPrinter Visitor{Builder, Lines};
  712. Visitor.ModifierMappings = NodePair.second;
  713. Visitor.Visit(NodePair.first);
  714. if (Lines.empty())
  715. continue;
  716. // We need a vertical separator if either this or the previous piece is a
  717. // multi-line piece, or this is the last piece.
  718. const char *Separator = (Lines.size() > 1 || HasMultipleLines) ? "|" : "";
  719. HasMultipleLines = Lines.size() > 1;
  720. if (Start + Lines.size() > RST.size())
  721. RST.resize(Start + Lines.size(), EmptyLinePrefix);
  722. padToSameLength(Lines.begin(), Lines.end());
  723. for (size_t I = 0; I != Lines.size(); ++I)
  724. RST[Start + I] += Separator + Lines[I];
  725. std::string Empty(Lines[0].size(), ' ');
  726. for (size_t I = Start + Lines.size(); I != RST.size(); ++I)
  727. RST[I] += Separator + Empty;
  728. EmptyLinePrefix += Separator + Empty;
  729. }
  730. for (size_t I = Start; I != RST.size(); ++I)
  731. RST[I] += "|";
  732. EmptyLinePrefix += "|";
  733. makeRowSeparator(EmptyLinePrefix);
  734. RST.insert(RST.begin() + Start, EmptyLinePrefix);
  735. RST.insert(RST.end(), EmptyLinePrefix);
  736. }
  737. void VisitText(TextPiece *P) {
  738. RST.push_back("");
  739. auto &S = RST.back();
  740. StringRef T = P->Text;
  741. while (!T.empty() && T.front() == ' ') {
  742. RST.back() += " |nbsp| ";
  743. T = T.drop_front();
  744. }
  745. std::string Suffix;
  746. while (!T.empty() && T.back() == ' ') {
  747. Suffix += " |nbsp| ";
  748. T = T.drop_back();
  749. }
  750. if (!T.empty()) {
  751. S += ':';
  752. S += P->Role;
  753. S += ":`";
  754. escapeRST(T, S);
  755. S += '`';
  756. }
  757. S += Suffix;
  758. }
  759. void VisitPlaceholder(PlaceholderPiece *P) {
  760. RST.push_back(std::string(":placeholder:`") +
  761. char('A' + mapIndex(P->Index)) + "`");
  762. }
  763. void VisitSelect(SelectPiece *P) {
  764. std::vector<size_t> SeparatorIndexes;
  765. SeparatorIndexes.push_back(RST.size());
  766. RST.emplace_back();
  767. for (auto *O : P->Options) {
  768. Visit(O);
  769. SeparatorIndexes.push_back(RST.size());
  770. RST.emplace_back();
  771. }
  772. makeTableRows(RST.begin() + SeparatorIndexes.front(),
  773. RST.begin() + SeparatorIndexes.back() + 1);
  774. for (size_t I : SeparatorIndexes)
  775. makeRowSeparator(RST[I]);
  776. }
  777. void VisitPlural(PluralPiece *P) { VisitSelect(P); }
  778. void VisitDiff(DiffPiece *P) {
  779. // Render %diff{a $ b $ c|d}e,f as %select{a %e b %f c|d}.
  780. PlaceholderPiece E(MT_Placeholder, P->Indexes[0]);
  781. PlaceholderPiece F(MT_Placeholder, P->Indexes[1]);
  782. MultiPiece FirstOption;
  783. FirstOption.Pieces.push_back(P->Parts[0]);
  784. FirstOption.Pieces.push_back(&E);
  785. FirstOption.Pieces.push_back(P->Parts[1]);
  786. FirstOption.Pieces.push_back(&F);
  787. FirstOption.Pieces.push_back(P->Parts[2]);
  788. SelectPiece Select(MT_Diff);
  789. Select.Options.push_back(&FirstOption);
  790. Select.Options.push_back(P->Parts[3]);
  791. VisitSelect(&Select);
  792. }
  793. std::vector<std::string> &RST;
  794. };
  795. struct DiagTextPrinter : DiagTextVisitor<DiagTextPrinter> {
  796. public:
  797. using BaseTy = DiagTextVisitor<DiagTextPrinter>;
  798. DiagTextPrinter(DiagnosticTextBuilder &Builder, std::string &Result)
  799. : BaseTy(Builder), Result(Result) {}
  800. void VisitMulti(MultiPiece *P) {
  801. for (auto *Child : P->Pieces)
  802. Visit(Child);
  803. }
  804. void VisitText(TextPiece *P) { Result += P->Text; }
  805. void VisitPlaceholder(PlaceholderPiece *P) {
  806. Result += "%";
  807. Result += getModifierName(P->Kind);
  808. addInt(mapIndex(P->Index));
  809. }
  810. void VisitSelect(SelectPiece *P) {
  811. Result += "%";
  812. Result += getModifierName(P->ModKind);
  813. if (P->ModKind == MT_Select) {
  814. Result += "{";
  815. for (auto *D : P->Options) {
  816. Visit(D);
  817. Result += '|';
  818. }
  819. if (!P->Options.empty())
  820. Result.pop_back();
  821. Result += '}';
  822. }
  823. addInt(mapIndex(P->Index));
  824. }
  825. void VisitPlural(PluralPiece *P) {
  826. Result += "%plural{";
  827. assert(P->Options.size() == P->OptionPrefixes.size());
  828. for (unsigned I = 0, End = P->Options.size(); I < End; ++I) {
  829. if (P->OptionPrefixes[I])
  830. Visit(P->OptionPrefixes[I]);
  831. Visit(P->Options[I]);
  832. Result += "|";
  833. }
  834. if (!P->Options.empty())
  835. Result.pop_back();
  836. Result += '}';
  837. addInt(mapIndex(P->Index));
  838. }
  839. void VisitDiff(DiffPiece *P) {
  840. Result += "%diff{";
  841. Visit(P->Parts[0]);
  842. Result += "$";
  843. Visit(P->Parts[1]);
  844. Result += "$";
  845. Visit(P->Parts[2]);
  846. Result += "|";
  847. Visit(P->Parts[3]);
  848. Result += "}";
  849. addInt(mapIndex(P->Indexes[0]));
  850. Result += ",";
  851. addInt(mapIndex(P->Indexes[1]));
  852. }
  853. void addInt(int Val) { Result += std::to_string(Val); }
  854. std::string &Result;
  855. };
  856. int DiagnosticTextBuilder::DiagText::parseModifier(StringRef &Text) const {
  857. if (Text.empty() || !isdigit(Text[0]))
  858. Builder.PrintFatalError("expected modifier in diagnostic");
  859. int Val = 0;
  860. do {
  861. Val *= 10;
  862. Val += Text[0] - '0';
  863. Text = Text.drop_front();
  864. } while (!Text.empty() && isdigit(Text[0]));
  865. return Val;
  866. }
  867. Piece *DiagnosticTextBuilder::DiagText::parseDiagText(StringRef &Text,
  868. StopAt Stop) {
  869. std::vector<Piece *> Parsed;
  870. constexpr llvm::StringLiteral StopSets[] = {"%", "%|}", "%|}$"};
  871. llvm::StringRef StopSet = StopSets[static_cast<int>(Stop)];
  872. while (!Text.empty()) {
  873. size_t End = (size_t)-2;
  874. do
  875. End = Text.find_first_of(StopSet, End + 2);
  876. while (
  877. End < Text.size() - 1 && Text[End] == '%' &&
  878. (Text[End + 1] == '%' || Text[End + 1] == '|' || Text[End + 1] == '$'));
  879. if (End) {
  880. Parsed.push_back(New<TextPiece>(Text.slice(0, End), "diagtext"));
  881. Text = Text.slice(End, StringRef::npos);
  882. if (Text.empty())
  883. break;
  884. }
  885. if (Text[0] == '|' || Text[0] == '}' || Text[0] == '$')
  886. break;
  887. // Drop the '%'.
  888. Text = Text.drop_front();
  889. // Extract the (optional) modifier.
  890. size_t ModLength = Text.find_first_of("0123456789{");
  891. StringRef Modifier = Text.slice(0, ModLength);
  892. Text = Text.slice(ModLength, StringRef::npos);
  893. ModifierType ModType = llvm::StringSwitch<ModifierType>{Modifier}
  894. .Case("select", MT_Select)
  895. .Case("sub", MT_Sub)
  896. .Case("diff", MT_Diff)
  897. .Case("plural", MT_Plural)
  898. .Case("s", MT_S)
  899. .Case("ordinal", MT_Ordinal)
  900. .Case("q", MT_Q)
  901. .Case("objcclass", MT_ObjCClass)
  902. .Case("objcinstance", MT_ObjCInstance)
  903. .Case("", MT_Placeholder)
  904. .Default(MT_Unknown);
  905. auto ExpectAndConsume = [&](StringRef Prefix) {
  906. if (!Text.consume_front(Prefix))
  907. Builder.PrintFatalError("expected '" + Prefix + "' while parsing %" +
  908. Modifier);
  909. };
  910. switch (ModType) {
  911. case MT_Unknown:
  912. Builder.PrintFatalError("Unknown modifier type: " + Modifier);
  913. case MT_Select: {
  914. SelectPiece *Select = New<SelectPiece>(MT_Select);
  915. do {
  916. Text = Text.drop_front(); // '{' or '|'
  917. Select->Options.push_back(
  918. parseDiagText(Text, StopAt::PipeOrCloseBrace));
  919. assert(!Text.empty() && "malformed %select");
  920. } while (Text.front() == '|');
  921. ExpectAndConsume("}");
  922. Select->Index = parseModifier(Text);
  923. Parsed.push_back(Select);
  924. continue;
  925. }
  926. case MT_Plural: {
  927. PluralPiece *Plural = New<PluralPiece>();
  928. do {
  929. Text = Text.drop_front(); // '{' or '|'
  930. size_t End = Text.find_first_of(":");
  931. if (End == StringRef::npos)
  932. Builder.PrintFatalError("expected ':' while parsing %plural");
  933. ++End;
  934. assert(!Text.empty());
  935. Plural->OptionPrefixes.push_back(
  936. New<TextPiece>(Text.slice(0, End), "diagtext"));
  937. Text = Text.slice(End, StringRef::npos);
  938. Plural->Options.push_back(
  939. parseDiagText(Text, StopAt::PipeOrCloseBrace));
  940. assert(!Text.empty() && "malformed %plural");
  941. } while (Text.front() == '|');
  942. ExpectAndConsume("}");
  943. Plural->Index = parseModifier(Text);
  944. Parsed.push_back(Plural);
  945. continue;
  946. }
  947. case MT_Sub: {
  948. SubstitutionPiece *Sub = New<SubstitutionPiece>();
  949. ExpectAndConsume("{");
  950. size_t NameSize = Text.find_first_of('}');
  951. assert(NameSize != size_t(-1) && "failed to find the end of the name");
  952. assert(NameSize != 0 && "empty name?");
  953. Sub->Name = Text.substr(0, NameSize).str();
  954. Text = Text.drop_front(NameSize);
  955. ExpectAndConsume("}");
  956. if (!Text.empty()) {
  957. while (true) {
  958. if (!isdigit(Text[0]))
  959. break;
  960. Sub->Modifiers.push_back(parseModifier(Text));
  961. if (Text.empty() || Text[0] != ',')
  962. break;
  963. Text = Text.drop_front(); // ','
  964. assert(!Text.empty() && isdigit(Text[0]) &&
  965. "expected another modifier");
  966. }
  967. }
  968. Parsed.push_back(Sub);
  969. continue;
  970. }
  971. case MT_Diff: {
  972. DiffPiece *Diff = New<DiffPiece>();
  973. ExpectAndConsume("{");
  974. Diff->Parts[0] = parseDiagText(Text, StopAt::Dollar);
  975. ExpectAndConsume("$");
  976. Diff->Parts[1] = parseDiagText(Text, StopAt::Dollar);
  977. ExpectAndConsume("$");
  978. Diff->Parts[2] = parseDiagText(Text, StopAt::PipeOrCloseBrace);
  979. ExpectAndConsume("|");
  980. Diff->Parts[3] = parseDiagText(Text, StopAt::PipeOrCloseBrace);
  981. ExpectAndConsume("}");
  982. Diff->Indexes[0] = parseModifier(Text);
  983. ExpectAndConsume(",");
  984. Diff->Indexes[1] = parseModifier(Text);
  985. Parsed.push_back(Diff);
  986. continue;
  987. }
  988. case MT_S: {
  989. SelectPiece *Select = New<SelectPiece>(ModType);
  990. Select->Options.push_back(New<TextPiece>(""));
  991. Select->Options.push_back(New<TextPiece>("s", "diagtext"));
  992. Select->Index = parseModifier(Text);
  993. Parsed.push_back(Select);
  994. continue;
  995. }
  996. case MT_Q:
  997. case MT_Placeholder:
  998. case MT_ObjCClass:
  999. case MT_ObjCInstance:
  1000. case MT_Ordinal: {
  1001. Parsed.push_back(New<PlaceholderPiece>(ModType, parseModifier(Text)));
  1002. continue;
  1003. }
  1004. }
  1005. }
  1006. return New<MultiPiece>(Parsed);
  1007. }
  1008. std::vector<std::string>
  1009. DiagnosticTextBuilder::buildForDocumentation(StringRef Severity,
  1010. const Record *R) {
  1011. EvaluatingRecordGuard Guard(&EvaluatingRecord, R);
  1012. StringRef Text = R->getValueAsString("Text");
  1013. DiagText D(*this, Text);
  1014. TextPiece *Prefix = D.New<TextPiece>(Severity, Severity);
  1015. Prefix->Text += ": ";
  1016. auto *MP = dyn_cast<MultiPiece>(D.Root);
  1017. if (!MP) {
  1018. MP = D.New<MultiPiece>();
  1019. MP->Pieces.push_back(D.Root);
  1020. D.Root = MP;
  1021. }
  1022. MP->Pieces.insert(MP->Pieces.begin(), Prefix);
  1023. std::vector<std::string> Result;
  1024. DiagTextDocPrinter{*this, Result}.Visit(D.Root);
  1025. return Result;
  1026. }
  1027. std::string DiagnosticTextBuilder::buildForDefinition(const Record *R) {
  1028. EvaluatingRecordGuard Guard(&EvaluatingRecord, R);
  1029. StringRef Text = R->getValueAsString("Text");
  1030. DiagText D(*this, Text);
  1031. std::string Result;
  1032. DiagTextPrinter{*this, Result}.Visit(D.Root);
  1033. return Result;
  1034. }
  1035. } // namespace
  1036. //===----------------------------------------------------------------------===//
  1037. // Warning Tables (.inc file) generation.
  1038. //===----------------------------------------------------------------------===//
  1039. static bool isError(const Record &Diag) {
  1040. const std::string &ClsName =
  1041. std::string(Diag.getValueAsDef("Class")->getName());
  1042. return ClsName == "CLASS_ERROR";
  1043. }
  1044. static bool isRemark(const Record &Diag) {
  1045. const std::string &ClsName =
  1046. std::string(Diag.getValueAsDef("Class")->getName());
  1047. return ClsName == "CLASS_REMARK";
  1048. }
  1049. /// ClangDiagsDefsEmitter - The top-level class emits .def files containing
  1050. /// declarations of Clang diagnostics.
  1051. void clang::EmitClangDiagsDefs(RecordKeeper &Records, raw_ostream &OS,
  1052. const std::string &Component) {
  1053. // Write the #if guard
  1054. if (!Component.empty()) {
  1055. std::string ComponentName = StringRef(Component).upper();
  1056. OS << "#ifdef " << ComponentName << "START\n";
  1057. OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
  1058. << ",\n";
  1059. OS << "#undef " << ComponentName << "START\n";
  1060. OS << "#endif\n\n";
  1061. }
  1062. DiagnosticTextBuilder DiagTextBuilder(Records);
  1063. std::vector<Record *> Diags = Records.getAllDerivedDefinitions("Diagnostic");
  1064. std::vector<Record*> DiagGroups
  1065. = Records.getAllDerivedDefinitions("DiagGroup");
  1066. std::map<std::string, GroupInfo> DiagsInGroup;
  1067. groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  1068. DiagCategoryIDMap CategoryIDs(Records);
  1069. DiagGroupParentMap DGParentMap(Records);
  1070. // Compute the set of diagnostics that are in -Wpedantic.
  1071. RecordSet DiagsInPedantic;
  1072. InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
  1073. inferPedantic.compute(&DiagsInPedantic, (RecordVec*)nullptr);
  1074. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  1075. const Record &R = *Diags[i];
  1076. // Check if this is an error that is accidentally in a warning
  1077. // group.
  1078. if (isError(R)) {
  1079. if (DefInit *Group = dyn_cast<DefInit>(R.getValueInit("Group"))) {
  1080. const Record *GroupRec = Group->getDef();
  1081. const std::string &GroupName =
  1082. std::string(GroupRec->getValueAsString("GroupName"));
  1083. PrintFatalError(R.getLoc(), "Error " + R.getName() +
  1084. " cannot be in a warning group [" + GroupName + "]");
  1085. }
  1086. }
  1087. // Check that all remarks have an associated diagnostic group.
  1088. if (isRemark(R)) {
  1089. if (!isa<DefInit>(R.getValueInit("Group"))) {
  1090. PrintFatalError(R.getLoc(), "Error " + R.getName() +
  1091. " not in any diagnostic group");
  1092. }
  1093. }
  1094. // Filter by component.
  1095. if (!Component.empty() && Component != R.getValueAsString("Component"))
  1096. continue;
  1097. OS << "DIAG(" << R.getName() << ", ";
  1098. OS << R.getValueAsDef("Class")->getName();
  1099. OS << ", (unsigned)diag::Severity::"
  1100. << R.getValueAsDef("DefaultSeverity")->getValueAsString("Name");
  1101. // Description string.
  1102. OS << ", \"";
  1103. OS.write_escaped(DiagTextBuilder.buildForDefinition(&R)) << '"';
  1104. // Warning group associated with the diagnostic. This is stored as an index
  1105. // into the alphabetically sorted warning group table.
  1106. if (DefInit *DI = dyn_cast<DefInit>(R.getValueInit("Group"))) {
  1107. std::map<std::string, GroupInfo>::iterator I = DiagsInGroup.find(
  1108. std::string(DI->getDef()->getValueAsString("GroupName")));
  1109. assert(I != DiagsInGroup.end());
  1110. OS << ", " << I->second.IDNo;
  1111. } else if (DiagsInPedantic.count(&R)) {
  1112. std::map<std::string, GroupInfo>::iterator I =
  1113. DiagsInGroup.find("pedantic");
  1114. assert(I != DiagsInGroup.end() && "pedantic group not defined");
  1115. OS << ", " << I->second.IDNo;
  1116. } else {
  1117. OS << ", 0";
  1118. }
  1119. // SFINAE response.
  1120. OS << ", " << R.getValueAsDef("SFINAE")->getName();
  1121. // Default warning has no Werror bit.
  1122. if (R.getValueAsBit("WarningNoWerror"))
  1123. OS << ", true";
  1124. else
  1125. OS << ", false";
  1126. if (R.getValueAsBit("ShowInSystemHeader"))
  1127. OS << ", true";
  1128. else
  1129. OS << ", false";
  1130. if (R.getValueAsBit("ShowInSystemMacro"))
  1131. OS << ", true";
  1132. else
  1133. OS << ", false";
  1134. if (R.getValueAsBit("Deferrable"))
  1135. OS << ", true";
  1136. else
  1137. OS << ", false";
  1138. // Category number.
  1139. OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));
  1140. OS << ")\n";
  1141. }
  1142. }
  1143. //===----------------------------------------------------------------------===//
  1144. // Warning Group Tables generation
  1145. //===----------------------------------------------------------------------===//
  1146. static std::string getDiagCategoryEnum(llvm::StringRef name) {
  1147. if (name.empty())
  1148. return "DiagCat_None";
  1149. SmallString<256> enumName = llvm::StringRef("DiagCat_");
  1150. for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
  1151. enumName += isalnum(*I) ? *I : '_';
  1152. return std::string(enumName.str());
  1153. }
  1154. /// Emit the array of diagnostic subgroups.
  1155. ///
  1156. /// The array of diagnostic subgroups contains for each group a list of its
  1157. /// subgroups. The individual lists are separated by '-1'. Groups with no
  1158. /// subgroups are skipped.
  1159. ///
  1160. /// \code
  1161. /// static const int16_t DiagSubGroups[] = {
  1162. /// /* Empty */ -1,
  1163. /// /* DiagSubGroup0 */ 142, -1,
  1164. /// /* DiagSubGroup13 */ 265, 322, 399, -1
  1165. /// }
  1166. /// \endcode
  1167. ///
  1168. static void emitDiagSubGroups(std::map<std::string, GroupInfo> &DiagsInGroup,
  1169. RecordVec &GroupsInPedantic, raw_ostream &OS) {
  1170. OS << "static const int16_t DiagSubGroups[] = {\n"
  1171. << " /* Empty */ -1,\n";
  1172. for (auto const &I : DiagsInGroup) {
  1173. const bool IsPedantic = I.first == "pedantic";
  1174. const std::vector<std::string> &SubGroups = I.second.SubGroups;
  1175. if (!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty())) {
  1176. OS << " /* DiagSubGroup" << I.second.IDNo << " */ ";
  1177. for (auto const &SubGroup : SubGroups) {
  1178. std::map<std::string, GroupInfo>::const_iterator RI =
  1179. DiagsInGroup.find(SubGroup);
  1180. assert(RI != DiagsInGroup.end() && "Referenced without existing?");
  1181. OS << RI->second.IDNo << ", ";
  1182. }
  1183. // Emit the groups implicitly in "pedantic".
  1184. if (IsPedantic) {
  1185. for (auto const &Group : GroupsInPedantic) {
  1186. const std::string &GroupName =
  1187. std::string(Group->getValueAsString("GroupName"));
  1188. std::map<std::string, GroupInfo>::const_iterator RI =
  1189. DiagsInGroup.find(GroupName);
  1190. assert(RI != DiagsInGroup.end() && "Referenced without existing?");
  1191. OS << RI->second.IDNo << ", ";
  1192. }
  1193. }
  1194. OS << "-1,\n";
  1195. }
  1196. }
  1197. OS << "};\n\n";
  1198. }
  1199. /// Emit the list of diagnostic arrays.
  1200. ///
  1201. /// This data structure is a large array that contains itself arrays of varying
  1202. /// size. Each array represents a list of diagnostics. The different arrays are
  1203. /// separated by the value '-1'.
  1204. ///
  1205. /// \code
  1206. /// static const int16_t DiagArrays[] = {
  1207. /// /* Empty */ -1,
  1208. /// /* DiagArray1 */ diag::warn_pragma_message,
  1209. /// -1,
  1210. /// /* DiagArray2 */ diag::warn_abs_too_small,
  1211. /// diag::warn_unsigned_abs,
  1212. /// diag::warn_wrong_absolute_value_type,
  1213. /// -1
  1214. /// };
  1215. /// \endcode
  1216. ///
  1217. static void emitDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,
  1218. RecordVec &DiagsInPedantic, raw_ostream &OS) {
  1219. OS << "static const int16_t DiagArrays[] = {\n"
  1220. << " /* Empty */ -1,\n";
  1221. for (auto const &I : DiagsInGroup) {
  1222. const bool IsPedantic = I.first == "pedantic";
  1223. const std::vector<const Record *> &V = I.second.DiagsInGroup;
  1224. if (!V.empty() || (IsPedantic && !DiagsInPedantic.empty())) {
  1225. OS << " /* DiagArray" << I.second.IDNo << " */ ";
  1226. for (auto *Record : V)
  1227. OS << "diag::" << Record->getName() << ", ";
  1228. // Emit the diagnostics implicitly in "pedantic".
  1229. if (IsPedantic) {
  1230. for (auto const &Diag : DiagsInPedantic)
  1231. OS << "diag::" << Diag->getName() << ", ";
  1232. }
  1233. OS << "-1,\n";
  1234. }
  1235. }
  1236. OS << "};\n\n";
  1237. }
  1238. /// Emit a list of group names.
  1239. ///
  1240. /// This creates a long string which by itself contains a list of pascal style
  1241. /// strings, which consist of a length byte directly followed by the string.
  1242. ///
  1243. /// \code
  1244. /// static const char DiagGroupNames[] = {
  1245. /// \000\020#pragma-messages\t#warnings\020CFString-literal"
  1246. /// };
  1247. /// \endcode
  1248. static void emitDiagGroupNames(StringToOffsetTable &GroupNames,
  1249. raw_ostream &OS) {
  1250. OS << "static const char DiagGroupNames[] = {\n";
  1251. GroupNames.EmitString(OS);
  1252. OS << "};\n\n";
  1253. }
  1254. /// Emit diagnostic arrays and related data structures.
  1255. ///
  1256. /// This creates the actual diagnostic array, an array of diagnostic subgroups
  1257. /// and an array of subgroup names.
  1258. ///
  1259. /// \code
  1260. /// #ifdef GET_DIAG_ARRAYS
  1261. /// static const int16_t DiagArrays[];
  1262. /// static const int16_t DiagSubGroups[];
  1263. /// static const char DiagGroupNames[];
  1264. /// #endif
  1265. /// \endcode
  1266. static void emitAllDiagArrays(std::map<std::string, GroupInfo> &DiagsInGroup,
  1267. RecordVec &DiagsInPedantic,
  1268. RecordVec &GroupsInPedantic,
  1269. StringToOffsetTable &GroupNames,
  1270. raw_ostream &OS) {
  1271. OS << "\n#ifdef GET_DIAG_ARRAYS\n";
  1272. emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);
  1273. emitDiagSubGroups(DiagsInGroup, GroupsInPedantic, OS);
  1274. emitDiagGroupNames(GroupNames, OS);
  1275. OS << "#endif // GET_DIAG_ARRAYS\n\n";
  1276. }
  1277. /// Emit diagnostic table.
  1278. ///
  1279. /// The table is sorted by the name of the diagnostic group. Each element
  1280. /// consists of the name of the diagnostic group (given as offset in the
  1281. /// group name table), a reference to a list of diagnostics (optional) and a
  1282. /// reference to a set of subgroups (optional).
  1283. ///
  1284. /// \code
  1285. /// #ifdef GET_DIAG_TABLE
  1286. /// {/* abi */ 159, /* DiagArray11 */ 19, /* Empty */ 0},
  1287. /// {/* aggregate-return */ 180, /* Empty */ 0, /* Empty */ 0},
  1288. /// {/* all */ 197, /* Empty */ 0, /* DiagSubGroup13 */ 3},
  1289. /// {/* deprecated */ 1981,/* DiagArray1 */ 348, /* DiagSubGroup3 */ 9},
  1290. /// #endif
  1291. /// \endcode
  1292. static void emitDiagTable(std::map<std::string, GroupInfo> &DiagsInGroup,
  1293. RecordVec &DiagsInPedantic,
  1294. RecordVec &GroupsInPedantic,
  1295. StringToOffsetTable &GroupNames, raw_ostream &OS) {
  1296. unsigned MaxLen = 0;
  1297. for (auto const &I: DiagsInGroup)
  1298. MaxLen = std::max(MaxLen, (unsigned)I.first.size());
  1299. OS << "\n#ifdef DIAG_ENTRY\n";
  1300. unsigned SubGroupIndex = 1, DiagArrayIndex = 1;
  1301. for (auto const &I: DiagsInGroup) {
  1302. // Group option string.
  1303. OS << "DIAG_ENTRY(";
  1304. OS << I.second.GroupName << " /* ";
  1305. if (I.first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
  1306. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1307. "0123456789!@#$%^*-+=:?") !=
  1308. std::string::npos)
  1309. PrintFatalError("Invalid character in diagnostic group '" + I.first +
  1310. "'");
  1311. OS << I.first << " */, ";
  1312. // Store a pascal-style length byte at the beginning of the string.
  1313. std::string Name = char(I.first.size()) + I.first;
  1314. OS << GroupNames.GetOrAddStringOffset(Name, false) << ", ";
  1315. // Special handling for 'pedantic'.
  1316. const bool IsPedantic = I.first == "pedantic";
  1317. // Diagnostics in the group.
  1318. const std::vector<const Record *> &V = I.second.DiagsInGroup;
  1319. const bool hasDiags =
  1320. !V.empty() || (IsPedantic && !DiagsInPedantic.empty());
  1321. if (hasDiags) {
  1322. OS << "/* DiagArray" << I.second.IDNo << " */ " << DiagArrayIndex
  1323. << ", ";
  1324. if (IsPedantic)
  1325. DiagArrayIndex += DiagsInPedantic.size();
  1326. DiagArrayIndex += V.size() + 1;
  1327. } else {
  1328. OS << "0, ";
  1329. }
  1330. // Subgroups.
  1331. const std::vector<std::string> &SubGroups = I.second.SubGroups;
  1332. const bool hasSubGroups =
  1333. !SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty());
  1334. if (hasSubGroups) {
  1335. OS << "/* DiagSubGroup" << I.second.IDNo << " */ " << SubGroupIndex;
  1336. if (IsPedantic)
  1337. SubGroupIndex += GroupsInPedantic.size();
  1338. SubGroupIndex += SubGroups.size() + 1;
  1339. } else {
  1340. OS << "0";
  1341. }
  1342. OS << ")\n";
  1343. }
  1344. OS << "#endif // DIAG_ENTRY\n\n";
  1345. }
  1346. /// Emit the table of diagnostic categories.
  1347. ///
  1348. /// The table has the form of macro calls that have two parameters. The
  1349. /// category's name as well as an enum that represents the category. The
  1350. /// table can be used by defining the macro 'CATEGORY' and including this
  1351. /// table right after.
  1352. ///
  1353. /// \code
  1354. /// #ifdef GET_CATEGORY_TABLE
  1355. /// CATEGORY("Semantic Issue", DiagCat_Semantic_Issue)
  1356. /// CATEGORY("Lambda Issue", DiagCat_Lambda_Issue)
  1357. /// #endif
  1358. /// \endcode
  1359. static void emitCategoryTable(RecordKeeper &Records, raw_ostream &OS) {
  1360. DiagCategoryIDMap CategoriesByID(Records);
  1361. OS << "\n#ifdef GET_CATEGORY_TABLE\n";
  1362. for (auto const &C : CategoriesByID)
  1363. OS << "CATEGORY(\"" << C << "\", " << getDiagCategoryEnum(C) << ")\n";
  1364. OS << "#endif // GET_CATEGORY_TABLE\n\n";
  1365. }
  1366. void clang::EmitClangDiagGroups(RecordKeeper &Records, raw_ostream &OS) {
  1367. // Compute a mapping from a DiagGroup to all of its parents.
  1368. DiagGroupParentMap DGParentMap(Records);
  1369. std::vector<Record *> Diags = Records.getAllDerivedDefinitions("Diagnostic");
  1370. std::vector<Record *> DiagGroups =
  1371. Records.getAllDerivedDefinitions("DiagGroup");
  1372. std::map<std::string, GroupInfo> DiagsInGroup;
  1373. groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  1374. // All extensions are implicitly in the "pedantic" group. Record the
  1375. // implicit set of groups in the "pedantic" group, and use this information
  1376. // later when emitting the group information for Pedantic.
  1377. RecordVec DiagsInPedantic;
  1378. RecordVec GroupsInPedantic;
  1379. InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
  1380. inferPedantic.compute(&DiagsInPedantic, &GroupsInPedantic);
  1381. StringToOffsetTable GroupNames;
  1382. for (std::map<std::string, GroupInfo>::const_iterator
  1383. I = DiagsInGroup.begin(),
  1384. E = DiagsInGroup.end();
  1385. I != E; ++I) {
  1386. // Store a pascal-style length byte at the beginning of the string.
  1387. std::string Name = char(I->first.size()) + I->first;
  1388. GroupNames.GetOrAddStringOffset(Name, false);
  1389. }
  1390. emitAllDiagArrays(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
  1391. OS);
  1392. emitDiagTable(DiagsInGroup, DiagsInPedantic, GroupsInPedantic, GroupNames,
  1393. OS);
  1394. emitCategoryTable(Records, OS);
  1395. }
  1396. //===----------------------------------------------------------------------===//
  1397. // Diagnostic name index generation
  1398. //===----------------------------------------------------------------------===//
  1399. namespace {
  1400. struct RecordIndexElement
  1401. {
  1402. RecordIndexElement() {}
  1403. explicit RecordIndexElement(Record const &R)
  1404. : Name(std::string(R.getName())) {}
  1405. std::string Name;
  1406. };
  1407. } // end anonymous namespace.
  1408. void clang::EmitClangDiagsIndexName(RecordKeeper &Records, raw_ostream &OS) {
  1409. const std::vector<Record*> &Diags =
  1410. Records.getAllDerivedDefinitions("Diagnostic");
  1411. std::vector<RecordIndexElement> Index;
  1412. Index.reserve(Diags.size());
  1413. for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
  1414. const Record &R = *(Diags[i]);
  1415. Index.push_back(RecordIndexElement(R));
  1416. }
  1417. llvm::sort(Index,
  1418. [](const RecordIndexElement &Lhs, const RecordIndexElement &Rhs) {
  1419. return Lhs.Name < Rhs.Name;
  1420. });
  1421. for (unsigned i = 0, e = Index.size(); i != e; ++i) {
  1422. const RecordIndexElement &R = Index[i];
  1423. OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";
  1424. }
  1425. }
  1426. //===----------------------------------------------------------------------===//
  1427. // Diagnostic documentation generation
  1428. //===----------------------------------------------------------------------===//
  1429. namespace docs {
  1430. namespace {
  1431. bool isRemarkGroup(const Record *DiagGroup,
  1432. const std::map<std::string, GroupInfo> &DiagsInGroup) {
  1433. bool AnyRemarks = false, AnyNonRemarks = false;
  1434. std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
  1435. auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;
  1436. for (const Record *Diag : GroupInfo.DiagsInGroup)
  1437. (isRemark(*Diag) ? AnyRemarks : AnyNonRemarks) = true;
  1438. for (const auto &Name : GroupInfo.SubGroups)
  1439. Visit(Name);
  1440. };
  1441. Visit(DiagGroup->getValueAsString("GroupName"));
  1442. if (AnyRemarks && AnyNonRemarks)
  1443. PrintFatalError(
  1444. DiagGroup->getLoc(),
  1445. "Diagnostic group contains both remark and non-remark diagnostics");
  1446. return AnyRemarks;
  1447. }
  1448. std::string getDefaultSeverity(const Record *Diag) {
  1449. return std::string(
  1450. Diag->getValueAsDef("DefaultSeverity")->getValueAsString("Name"));
  1451. }
  1452. std::set<std::string>
  1453. getDefaultSeverities(const Record *DiagGroup,
  1454. const std::map<std::string, GroupInfo> &DiagsInGroup) {
  1455. std::set<std::string> States;
  1456. std::function<void(StringRef)> Visit = [&](StringRef GroupName) {
  1457. auto &GroupInfo = DiagsInGroup.find(std::string(GroupName))->second;
  1458. for (const Record *Diag : GroupInfo.DiagsInGroup)
  1459. States.insert(getDefaultSeverity(Diag));
  1460. for (const auto &Name : GroupInfo.SubGroups)
  1461. Visit(Name);
  1462. };
  1463. Visit(DiagGroup->getValueAsString("GroupName"));
  1464. return States;
  1465. }
  1466. void writeHeader(StringRef Str, raw_ostream &OS, char Kind = '-') {
  1467. OS << Str << "\n" << std::string(Str.size(), Kind) << "\n";
  1468. }
  1469. void writeDiagnosticText(DiagnosticTextBuilder &Builder, const Record *R,
  1470. StringRef Role, raw_ostream &OS) {
  1471. StringRef Text = R->getValueAsString("Text");
  1472. if (Text == "%0")
  1473. OS << "The text of this diagnostic is not controlled by Clang.\n\n";
  1474. else {
  1475. std::vector<std::string> Out = Builder.buildForDocumentation(Role, R);
  1476. for (auto &Line : Out)
  1477. OS << Line << "\n";
  1478. OS << "\n";
  1479. }
  1480. }
  1481. } // namespace
  1482. } // namespace docs
  1483. void clang::EmitClangDiagDocs(RecordKeeper &Records, raw_ostream &OS) {
  1484. using namespace docs;
  1485. // Get the documentation introduction paragraph.
  1486. const Record *Documentation = Records.getDef("GlobalDocumentation");
  1487. if (!Documentation) {
  1488. PrintFatalError("The Documentation top-level definition is missing, "
  1489. "no documentation will be generated.");
  1490. return;
  1491. }
  1492. OS << Documentation->getValueAsString("Intro") << "\n";
  1493. DiagnosticTextBuilder Builder(Records);
  1494. std::vector<Record*> Diags =
  1495. Records.getAllDerivedDefinitions("Diagnostic");
  1496. std::vector<Record*> DiagGroups =
  1497. Records.getAllDerivedDefinitions("DiagGroup");
  1498. llvm::sort(DiagGroups, diagGroupBeforeByName);
  1499. DiagGroupParentMap DGParentMap(Records);
  1500. std::map<std::string, GroupInfo> DiagsInGroup;
  1501. groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  1502. // Compute the set of diagnostics that are in -Wpedantic.
  1503. {
  1504. RecordSet DiagsInPedanticSet;
  1505. RecordSet GroupsInPedanticSet;
  1506. InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
  1507. inferPedantic.compute(&DiagsInPedanticSet, &GroupsInPedanticSet);
  1508. auto &PedDiags = DiagsInGroup["pedantic"];
  1509. // Put the diagnostics into a deterministic order.
  1510. RecordVec DiagsInPedantic(DiagsInPedanticSet.begin(),
  1511. DiagsInPedanticSet.end());
  1512. RecordVec GroupsInPedantic(GroupsInPedanticSet.begin(),
  1513. GroupsInPedanticSet.end());
  1514. llvm::sort(DiagsInPedantic, beforeThanCompare);
  1515. llvm::sort(GroupsInPedantic, beforeThanCompare);
  1516. PedDiags.DiagsInGroup.insert(PedDiags.DiagsInGroup.end(),
  1517. DiagsInPedantic.begin(),
  1518. DiagsInPedantic.end());
  1519. for (auto *Group : GroupsInPedantic)
  1520. PedDiags.SubGroups.push_back(
  1521. std::string(Group->getValueAsString("GroupName")));
  1522. }
  1523. // FIXME: Write diagnostic categories and link to diagnostic groups in each.
  1524. // Write out the diagnostic groups.
  1525. for (const Record *G : DiagGroups) {
  1526. bool IsRemarkGroup = isRemarkGroup(G, DiagsInGroup);
  1527. auto &GroupInfo =
  1528. DiagsInGroup[std::string(G->getValueAsString("GroupName"))];
  1529. bool IsSynonym = GroupInfo.DiagsInGroup.empty() &&
  1530. GroupInfo.SubGroups.size() == 1;
  1531. writeHeader(((IsRemarkGroup ? "-R" : "-W") +
  1532. G->getValueAsString("GroupName")).str(),
  1533. OS);
  1534. if (!IsSynonym) {
  1535. // FIXME: Ideally, all the diagnostics in a group should have the same
  1536. // default state, but that is not currently the case.
  1537. auto DefaultSeverities = getDefaultSeverities(G, DiagsInGroup);
  1538. if (!DefaultSeverities.empty() && !DefaultSeverities.count("Ignored")) {
  1539. bool AnyNonErrors = DefaultSeverities.count("Warning") ||
  1540. DefaultSeverities.count("Remark");
  1541. if (!AnyNonErrors)
  1542. OS << "This diagnostic is an error by default, but the flag ``-Wno-"
  1543. << G->getValueAsString("GroupName") << "`` can be used to disable "
  1544. << "the error.\n\n";
  1545. else
  1546. OS << "This diagnostic is enabled by default.\n\n";
  1547. } else if (DefaultSeverities.size() > 1) {
  1548. OS << "Some of the diagnostics controlled by this flag are enabled "
  1549. << "by default.\n\n";
  1550. }
  1551. }
  1552. if (!GroupInfo.SubGroups.empty()) {
  1553. if (IsSynonym)
  1554. OS << "Synonym for ";
  1555. else if (GroupInfo.DiagsInGroup.empty())
  1556. OS << "Controls ";
  1557. else
  1558. OS << "Also controls ";
  1559. bool First = true;
  1560. llvm::sort(GroupInfo.SubGroups);
  1561. for (const auto &Name : GroupInfo.SubGroups) {
  1562. if (!First) OS << ", ";
  1563. OS << "`" << (IsRemarkGroup ? "-R" : "-W") << Name << "`_";
  1564. First = false;
  1565. }
  1566. OS << ".\n\n";
  1567. }
  1568. if (!GroupInfo.DiagsInGroup.empty()) {
  1569. OS << "**Diagnostic text:**\n\n";
  1570. for (const Record *D : GroupInfo.DiagsInGroup) {
  1571. auto Severity = getDefaultSeverity(D);
  1572. Severity[0] = tolower(Severity[0]);
  1573. if (Severity == "ignored")
  1574. Severity = IsRemarkGroup ? "remark" : "warning";
  1575. writeDiagnosticText(Builder, D, Severity, OS);
  1576. }
  1577. }
  1578. auto Doc = G->getValueAsString("Documentation");
  1579. if (!Doc.empty())
  1580. OS << Doc;
  1581. else if (GroupInfo.SubGroups.empty() && GroupInfo.DiagsInGroup.empty())
  1582. OS << "This diagnostic flag exists for GCC compatibility, and has no "
  1583. "effect in Clang.\n";
  1584. OS << "\n";
  1585. }
  1586. }