DiagnosticIDs.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. //===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===//
  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 the Diagnostic IDs-related interfaces.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/DiagnosticIDs.h"
  13. #include "clang/Basic/AllDiagnostics.h"
  14. #include "clang/Basic/DiagnosticCategories.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/Support/ErrorHandling.h"
  19. #include <map>
  20. #include <optional>
  21. using namespace clang;
  22. //===----------------------------------------------------------------------===//
  23. // Builtin Diagnostic information
  24. //===----------------------------------------------------------------------===//
  25. namespace {
  26. struct StaticDiagInfoRec;
  27. // Store the descriptions in a separate table to avoid pointers that need to
  28. // be relocated, and also decrease the amount of data needed on 64-bit
  29. // platforms. See "How To Write Shared Libraries" by Ulrich Drepper.
  30. struct StaticDiagInfoDescriptionStringTable {
  31. #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
  32. SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
  33. char ENUM##_desc[sizeof(DESC)];
  34. // clang-format off
  35. #include "clang/Basic/DiagnosticCommonKinds.inc"
  36. #include "clang/Basic/DiagnosticDriverKinds.inc"
  37. #include "clang/Basic/DiagnosticFrontendKinds.inc"
  38. #include "clang/Basic/DiagnosticSerializationKinds.inc"
  39. #include "clang/Basic/DiagnosticLexKinds.inc"
  40. #include "clang/Basic/DiagnosticParseKinds.inc"
  41. #include "clang/Basic/DiagnosticASTKinds.inc"
  42. #include "clang/Basic/DiagnosticCommentKinds.inc"
  43. #include "clang/Basic/DiagnosticCrossTUKinds.inc"
  44. #include "clang/Basic/DiagnosticSemaKinds.inc"
  45. #include "clang/Basic/DiagnosticAnalysisKinds.inc"
  46. #include "clang/Basic/DiagnosticRefactoringKinds.inc"
  47. // clang-format on
  48. #undef DIAG
  49. };
  50. const StaticDiagInfoDescriptionStringTable StaticDiagInfoDescriptions = {
  51. #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
  52. SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
  53. DESC,
  54. // clang-format off
  55. #include "clang/Basic/DiagnosticCommonKinds.inc"
  56. #include "clang/Basic/DiagnosticDriverKinds.inc"
  57. #include "clang/Basic/DiagnosticFrontendKinds.inc"
  58. #include "clang/Basic/DiagnosticSerializationKinds.inc"
  59. #include "clang/Basic/DiagnosticLexKinds.inc"
  60. #include "clang/Basic/DiagnosticParseKinds.inc"
  61. #include "clang/Basic/DiagnosticASTKinds.inc"
  62. #include "clang/Basic/DiagnosticCommentKinds.inc"
  63. #include "clang/Basic/DiagnosticCrossTUKinds.inc"
  64. #include "clang/Basic/DiagnosticSemaKinds.inc"
  65. #include "clang/Basic/DiagnosticAnalysisKinds.inc"
  66. #include "clang/Basic/DiagnosticRefactoringKinds.inc"
  67. // clang-format on
  68. #undef DIAG
  69. };
  70. extern const StaticDiagInfoRec StaticDiagInfo[];
  71. // Stored separately from StaticDiagInfoRec to pack better. Otherwise,
  72. // StaticDiagInfoRec would have extra padding on 64-bit platforms.
  73. const uint32_t StaticDiagInfoDescriptionOffsets[] = {
  74. #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
  75. SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
  76. offsetof(StaticDiagInfoDescriptionStringTable, ENUM##_desc),
  77. // clang-format off
  78. #include "clang/Basic/DiagnosticCommonKinds.inc"
  79. #include "clang/Basic/DiagnosticDriverKinds.inc"
  80. #include "clang/Basic/DiagnosticFrontendKinds.inc"
  81. #include "clang/Basic/DiagnosticSerializationKinds.inc"
  82. #include "clang/Basic/DiagnosticLexKinds.inc"
  83. #include "clang/Basic/DiagnosticParseKinds.inc"
  84. #include "clang/Basic/DiagnosticASTKinds.inc"
  85. #include "clang/Basic/DiagnosticCommentKinds.inc"
  86. #include "clang/Basic/DiagnosticCrossTUKinds.inc"
  87. #include "clang/Basic/DiagnosticSemaKinds.inc"
  88. #include "clang/Basic/DiagnosticAnalysisKinds.inc"
  89. #include "clang/Basic/DiagnosticRefactoringKinds.inc"
  90. // clang-format on
  91. #undef DIAG
  92. };
  93. // Diagnostic classes.
  94. enum {
  95. CLASS_NOTE = 0x01,
  96. CLASS_REMARK = 0x02,
  97. CLASS_WARNING = 0x03,
  98. CLASS_EXTENSION = 0x04,
  99. CLASS_ERROR = 0x05
  100. };
  101. struct StaticDiagInfoRec {
  102. uint16_t DiagID;
  103. uint8_t DefaultSeverity : 3;
  104. uint8_t Class : 3;
  105. uint8_t SFINAE : 2;
  106. uint8_t Category : 6;
  107. uint8_t WarnNoWerror : 1;
  108. uint8_t WarnShowInSystemHeader : 1;
  109. uint8_t WarnShowInSystemMacro : 1;
  110. uint16_t OptionGroupIndex : 15;
  111. uint16_t Deferrable : 1;
  112. uint16_t DescriptionLen;
  113. unsigned getOptionGroupIndex() const {
  114. return OptionGroupIndex;
  115. }
  116. StringRef getDescription() const {
  117. size_t MyIndex = this - &StaticDiagInfo[0];
  118. uint32_t StringOffset = StaticDiagInfoDescriptionOffsets[MyIndex];
  119. const char* Table = reinterpret_cast<const char*>(&StaticDiagInfoDescriptions);
  120. return StringRef(&Table[StringOffset], DescriptionLen);
  121. }
  122. diag::Flavor getFlavor() const {
  123. return Class == CLASS_REMARK ? diag::Flavor::Remark
  124. : diag::Flavor::WarningOrError;
  125. }
  126. bool operator<(const StaticDiagInfoRec &RHS) const {
  127. return DiagID < RHS.DiagID;
  128. }
  129. };
  130. #define STRINGIFY_NAME(NAME) #NAME
  131. #define VALIDATE_DIAG_SIZE(NAME) \
  132. static_assert( \
  133. static_cast<unsigned>(diag::NUM_BUILTIN_##NAME##_DIAGNOSTICS) < \
  134. static_cast<unsigned>(diag::DIAG_START_##NAME) + \
  135. static_cast<unsigned>(diag::DIAG_SIZE_##NAME), \
  136. STRINGIFY_NAME( \
  137. DIAG_SIZE_##NAME) " is insufficient to contain all " \
  138. "diagnostics, it may need to be made larger in " \
  139. "DiagnosticIDs.h.");
  140. VALIDATE_DIAG_SIZE(COMMON)
  141. VALIDATE_DIAG_SIZE(DRIVER)
  142. VALIDATE_DIAG_SIZE(FRONTEND)
  143. VALIDATE_DIAG_SIZE(SERIALIZATION)
  144. VALIDATE_DIAG_SIZE(LEX)
  145. VALIDATE_DIAG_SIZE(PARSE)
  146. VALIDATE_DIAG_SIZE(AST)
  147. VALIDATE_DIAG_SIZE(COMMENT)
  148. VALIDATE_DIAG_SIZE(CROSSTU)
  149. VALIDATE_DIAG_SIZE(SEMA)
  150. VALIDATE_DIAG_SIZE(ANALYSIS)
  151. VALIDATE_DIAG_SIZE(REFACTORING)
  152. #undef VALIDATE_DIAG_SIZE
  153. #undef STRINGIFY_NAME
  154. const StaticDiagInfoRec StaticDiagInfo[] = {
  155. // clang-format off
  156. #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
  157. SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
  158. { \
  159. diag::ENUM, \
  160. DEFAULT_SEVERITY, \
  161. CLASS, \
  162. DiagnosticIDs::SFINAE, \
  163. CATEGORY, \
  164. NOWERROR, \
  165. SHOWINSYSHEADER, \
  166. SHOWINSYSMACRO, \
  167. GROUP, \
  168. DEFERRABLE, \
  169. STR_SIZE(DESC, uint16_t)},
  170. #include "clang/Basic/DiagnosticCommonKinds.inc"
  171. #include "clang/Basic/DiagnosticDriverKinds.inc"
  172. #include "clang/Basic/DiagnosticFrontendKinds.inc"
  173. #include "clang/Basic/DiagnosticSerializationKinds.inc"
  174. #include "clang/Basic/DiagnosticLexKinds.inc"
  175. #include "clang/Basic/DiagnosticParseKinds.inc"
  176. #include "clang/Basic/DiagnosticASTKinds.inc"
  177. #include "clang/Basic/DiagnosticCommentKinds.inc"
  178. #include "clang/Basic/DiagnosticCrossTUKinds.inc"
  179. #include "clang/Basic/DiagnosticSemaKinds.inc"
  180. #include "clang/Basic/DiagnosticAnalysisKinds.inc"
  181. #include "clang/Basic/DiagnosticRefactoringKinds.inc"
  182. // clang-format on
  183. #undef DIAG
  184. };
  185. } // namespace
  186. static const unsigned StaticDiagInfoSize = std::size(StaticDiagInfo);
  187. /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
  188. /// or null if the ID is invalid.
  189. static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
  190. // Out of bounds diag. Can't be in the table.
  191. using namespace diag;
  192. if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON)
  193. return nullptr;
  194. // Compute the index of the requested diagnostic in the static table.
  195. // 1. Add the number of diagnostics in each category preceding the
  196. // diagnostic and of the category the diagnostic is in. This gives us
  197. // the offset of the category in the table.
  198. // 2. Subtract the number of IDs in each category from our ID. This gives us
  199. // the offset of the diagnostic in the category.
  200. // This is cheaper than a binary search on the table as it doesn't touch
  201. // memory at all.
  202. unsigned Offset = 0;
  203. unsigned ID = DiagID - DIAG_START_COMMON - 1;
  204. #define CATEGORY(NAME, PREV) \
  205. if (DiagID > DIAG_START_##NAME) { \
  206. Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \
  207. ID -= DIAG_START_##NAME - DIAG_START_##PREV; \
  208. }
  209. CATEGORY(DRIVER, COMMON)
  210. CATEGORY(FRONTEND, DRIVER)
  211. CATEGORY(SERIALIZATION, FRONTEND)
  212. CATEGORY(LEX, SERIALIZATION)
  213. CATEGORY(PARSE, LEX)
  214. CATEGORY(AST, PARSE)
  215. CATEGORY(COMMENT, AST)
  216. CATEGORY(CROSSTU, COMMENT)
  217. CATEGORY(SEMA, CROSSTU)
  218. CATEGORY(ANALYSIS, SEMA)
  219. CATEGORY(REFACTORING, ANALYSIS)
  220. #undef CATEGORY
  221. // Avoid out of bounds reads.
  222. if (ID + Offset >= StaticDiagInfoSize)
  223. return nullptr;
  224. assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize);
  225. const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset];
  226. // If the diag id doesn't match we found a different diag, abort. This can
  227. // happen when this function is called with an ID that points into a hole in
  228. // the diagID space.
  229. if (Found->DiagID != DiagID)
  230. return nullptr;
  231. return Found;
  232. }
  233. static DiagnosticMapping GetDefaultDiagMapping(unsigned DiagID) {
  234. DiagnosticMapping Info = DiagnosticMapping::Make(
  235. diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false);
  236. if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) {
  237. Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity);
  238. if (StaticInfo->WarnNoWerror) {
  239. assert(Info.getSeverity() == diag::Severity::Warning &&
  240. "Unexpected mapping with no-Werror bit!");
  241. Info.setNoWarningAsError(true);
  242. }
  243. }
  244. return Info;
  245. }
  246. /// getCategoryNumberForDiag - Return the category number that a specified
  247. /// DiagID belongs to, or 0 if no category.
  248. unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
  249. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  250. return Info->Category;
  251. return 0;
  252. }
  253. namespace {
  254. // The diagnostic category names.
  255. struct StaticDiagCategoryRec {
  256. const char *NameStr;
  257. uint8_t NameLen;
  258. StringRef getName() const {
  259. return StringRef(NameStr, NameLen);
  260. }
  261. };
  262. }
  263. // Unfortunately, the split between DiagnosticIDs and Diagnostic is not
  264. // particularly clean, but for now we just implement this method here so we can
  265. // access GetDefaultDiagMapping.
  266. DiagnosticMapping &
  267. DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) {
  268. std::pair<iterator, bool> Result =
  269. DiagMap.insert(std::make_pair(Diag, DiagnosticMapping()));
  270. // Initialize the entry if we added it.
  271. if (Result.second)
  272. Result.first->second = GetDefaultDiagMapping(Diag);
  273. return Result.first->second;
  274. }
  275. static const StaticDiagCategoryRec CategoryNameTable[] = {
  276. #define GET_CATEGORY_TABLE
  277. #define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) },
  278. #include "clang/Basic/DiagnosticGroups.inc"
  279. #undef GET_CATEGORY_TABLE
  280. { nullptr, 0 }
  281. };
  282. /// getNumberOfCategories - Return the number of categories
  283. unsigned DiagnosticIDs::getNumberOfCategories() {
  284. return std::size(CategoryNameTable) - 1;
  285. }
  286. /// getCategoryNameFromID - Given a category ID, return the name of the
  287. /// category, an empty string if CategoryID is zero, or null if CategoryID is
  288. /// invalid.
  289. StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) {
  290. if (CategoryID >= getNumberOfCategories())
  291. return StringRef();
  292. return CategoryNameTable[CategoryID].getName();
  293. }
  294. DiagnosticIDs::SFINAEResponse
  295. DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) {
  296. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  297. return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE);
  298. return SFINAE_Report;
  299. }
  300. bool DiagnosticIDs::isDeferrable(unsigned DiagID) {
  301. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  302. return Info->Deferrable;
  303. return false;
  304. }
  305. /// getBuiltinDiagClass - Return the class field of the diagnostic.
  306. ///
  307. static unsigned getBuiltinDiagClass(unsigned DiagID) {
  308. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  309. return Info->Class;
  310. return ~0U;
  311. }
  312. //===----------------------------------------------------------------------===//
  313. // Custom Diagnostic information
  314. //===----------------------------------------------------------------------===//
  315. namespace clang {
  316. namespace diag {
  317. class CustomDiagInfo {
  318. typedef std::pair<DiagnosticIDs::Level, std::string> DiagDesc;
  319. std::vector<DiagDesc> DiagInfo;
  320. std::map<DiagDesc, unsigned> DiagIDs;
  321. public:
  322. /// getDescription - Return the description of the specified custom
  323. /// diagnostic.
  324. StringRef getDescription(unsigned DiagID) const {
  325. assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
  326. "Invalid diagnostic ID");
  327. return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second;
  328. }
  329. /// getLevel - Return the level of the specified custom diagnostic.
  330. DiagnosticIDs::Level getLevel(unsigned DiagID) const {
  331. assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
  332. "Invalid diagnostic ID");
  333. return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
  334. }
  335. unsigned getOrCreateDiagID(DiagnosticIDs::Level L, StringRef Message,
  336. DiagnosticIDs &Diags) {
  337. DiagDesc D(L, std::string(Message));
  338. // Check to see if it already exists.
  339. std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
  340. if (I != DiagIDs.end() && I->first == D)
  341. return I->second;
  342. // If not, assign a new ID.
  343. unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
  344. DiagIDs.insert(std::make_pair(D, ID));
  345. DiagInfo.push_back(D);
  346. return ID;
  347. }
  348. };
  349. } // end diag namespace
  350. } // end clang namespace
  351. //===----------------------------------------------------------------------===//
  352. // Common Diagnostic implementation
  353. //===----------------------------------------------------------------------===//
  354. DiagnosticIDs::DiagnosticIDs() {}
  355. DiagnosticIDs::~DiagnosticIDs() {}
  356. /// getCustomDiagID - Return an ID for a diagnostic with the specified message
  357. /// and level. If this is the first request for this diagnostic, it is
  358. /// registered and created, otherwise the existing ID is returned.
  359. ///
  360. /// \param FormatString A fixed diagnostic format string that will be hashed and
  361. /// mapped to a unique DiagID.
  362. unsigned DiagnosticIDs::getCustomDiagID(Level L, StringRef FormatString) {
  363. if (!CustomDiagInfo)
  364. CustomDiagInfo.reset(new diag::CustomDiagInfo());
  365. return CustomDiagInfo->getOrCreateDiagID(L, FormatString, *this);
  366. }
  367. /// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
  368. /// level of the specified diagnostic ID is a Warning or Extension.
  369. /// This only works on builtin diagnostics, not custom ones, and is not legal to
  370. /// call on NOTEs.
  371. bool DiagnosticIDs::isBuiltinWarningOrExtension(unsigned DiagID) {
  372. return DiagID < diag::DIAG_UPPER_LIMIT &&
  373. getBuiltinDiagClass(DiagID) != CLASS_ERROR;
  374. }
  375. /// Determine whether the given built-in diagnostic ID is a
  376. /// Note.
  377. bool DiagnosticIDs::isBuiltinNote(unsigned DiagID) {
  378. return DiagID < diag::DIAG_UPPER_LIMIT &&
  379. getBuiltinDiagClass(DiagID) == CLASS_NOTE;
  380. }
  381. /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
  382. /// ID is for an extension of some sort. This also returns EnabledByDefault,
  383. /// which is set to indicate whether the diagnostic is ignored by default (in
  384. /// which case -pedantic enables it) or treated as a warning/error by default.
  385. ///
  386. bool DiagnosticIDs::isBuiltinExtensionDiag(unsigned DiagID,
  387. bool &EnabledByDefault) {
  388. if (DiagID >= diag::DIAG_UPPER_LIMIT ||
  389. getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
  390. return false;
  391. EnabledByDefault =
  392. GetDefaultDiagMapping(DiagID).getSeverity() != diag::Severity::Ignored;
  393. return true;
  394. }
  395. bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) {
  396. if (DiagID >= diag::DIAG_UPPER_LIMIT)
  397. return false;
  398. return GetDefaultDiagMapping(DiagID).getSeverity() >= diag::Severity::Error;
  399. }
  400. /// getDescription - Given a diagnostic ID, return a description of the
  401. /// issue.
  402. StringRef DiagnosticIDs::getDescription(unsigned DiagID) const {
  403. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  404. return Info->getDescription();
  405. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  406. return CustomDiagInfo->getDescription(DiagID);
  407. }
  408. static DiagnosticIDs::Level toLevel(diag::Severity SV) {
  409. switch (SV) {
  410. case diag::Severity::Ignored:
  411. return DiagnosticIDs::Ignored;
  412. case diag::Severity::Remark:
  413. return DiagnosticIDs::Remark;
  414. case diag::Severity::Warning:
  415. return DiagnosticIDs::Warning;
  416. case diag::Severity::Error:
  417. return DiagnosticIDs::Error;
  418. case diag::Severity::Fatal:
  419. return DiagnosticIDs::Fatal;
  420. }
  421. llvm_unreachable("unexpected severity");
  422. }
  423. /// getDiagnosticLevel - Based on the way the client configured the
  424. /// DiagnosticsEngine object, classify the specified diagnostic ID into a Level,
  425. /// by consumable the DiagnosticClient.
  426. DiagnosticIDs::Level
  427. DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
  428. const DiagnosticsEngine &Diag) const {
  429. // Handle custom diagnostics, which cannot be mapped.
  430. if (DiagID >= diag::DIAG_UPPER_LIMIT) {
  431. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  432. return CustomDiagInfo->getLevel(DiagID);
  433. }
  434. unsigned DiagClass = getBuiltinDiagClass(DiagID);
  435. if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note;
  436. return toLevel(getDiagnosticSeverity(DiagID, Loc, Diag));
  437. }
  438. /// Based on the way the client configured the Diagnostic
  439. /// object, classify the specified diagnostic ID into a Level, consumable by
  440. /// the DiagnosticClient.
  441. ///
  442. /// \param Loc The source location we are interested in finding out the
  443. /// diagnostic state. Can be null in order to query the latest state.
  444. diag::Severity
  445. DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
  446. const DiagnosticsEngine &Diag) const {
  447. assert(getBuiltinDiagClass(DiagID) != CLASS_NOTE);
  448. // Specific non-error diagnostics may be mapped to various levels from ignored
  449. // to error. Errors can only be mapped to fatal.
  450. diag::Severity Result = diag::Severity::Fatal;
  451. // Get the mapping information, or compute it lazily.
  452. DiagnosticsEngine::DiagState *State = Diag.GetDiagStateForLoc(Loc);
  453. DiagnosticMapping &Mapping = State->getOrAddMapping((diag::kind)DiagID);
  454. // TODO: Can a null severity really get here?
  455. if (Mapping.getSeverity() != diag::Severity())
  456. Result = Mapping.getSeverity();
  457. // Upgrade ignored diagnostics if -Weverything is enabled.
  458. if (State->EnableAllWarnings && Result == diag::Severity::Ignored &&
  459. !Mapping.isUser() && getBuiltinDiagClass(DiagID) != CLASS_REMARK)
  460. Result = diag::Severity::Warning;
  461. // Ignore -pedantic diagnostics inside __extension__ blocks.
  462. // (The diagnostics controlled by -pedantic are the extension diagnostics
  463. // that are not enabled by default.)
  464. bool EnabledByDefault = false;
  465. bool IsExtensionDiag = isBuiltinExtensionDiag(DiagID, EnabledByDefault);
  466. if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
  467. return diag::Severity::Ignored;
  468. // For extension diagnostics that haven't been explicitly mapped, check if we
  469. // should upgrade the diagnostic.
  470. if (IsExtensionDiag && !Mapping.isUser())
  471. Result = std::max(Result, State->ExtBehavior);
  472. // At this point, ignored errors can no longer be upgraded.
  473. if (Result == diag::Severity::Ignored)
  474. return Result;
  475. // Honor -w: this disables all messages which are not Error/Fatal by
  476. // default (disregarding attempts to upgrade severity from Warning to Error),
  477. // as well as disabling all messages which are currently mapped to Warning
  478. // (whether by default or downgraded from Error via e.g. -Wno-error or #pragma
  479. // diagnostic.)
  480. if (State->IgnoreAllWarnings) {
  481. if (Result == diag::Severity::Warning ||
  482. (Result >= diag::Severity::Error &&
  483. !isDefaultMappingAsError((diag::kind)DiagID)))
  484. return diag::Severity::Ignored;
  485. }
  486. // If -Werror is enabled, map warnings to errors unless explicitly disabled.
  487. if (Result == diag::Severity::Warning) {
  488. if (State->WarningsAsErrors && !Mapping.hasNoWarningAsError())
  489. Result = diag::Severity::Error;
  490. }
  491. // If -Wfatal-errors is enabled, map errors to fatal unless explicitly
  492. // disabled.
  493. if (Result == diag::Severity::Error) {
  494. if (State->ErrorsAsFatal && !Mapping.hasNoErrorAsFatal())
  495. Result = diag::Severity::Fatal;
  496. }
  497. // If explicitly requested, map fatal errors to errors.
  498. if (Result == diag::Severity::Fatal &&
  499. Diag.CurDiagID != diag::fatal_too_many_errors && Diag.FatalsAsError)
  500. Result = diag::Severity::Error;
  501. // Custom diagnostics always are emitted in system headers.
  502. bool ShowInSystemHeader =
  503. !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemHeader;
  504. // If we are in a system header, we ignore it. We look at the diagnostic class
  505. // because we also want to ignore extensions and warnings in -Werror and
  506. // -pedantic-errors modes, which *map* warnings/extensions to errors.
  507. if (State->SuppressSystemWarnings && !ShowInSystemHeader && Loc.isValid() &&
  508. Diag.getSourceManager().isInSystemHeader(
  509. Diag.getSourceManager().getExpansionLoc(Loc)))
  510. return diag::Severity::Ignored;
  511. // We also ignore warnings due to system macros
  512. bool ShowInSystemMacro =
  513. !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemMacro;
  514. if (State->SuppressSystemWarnings && !ShowInSystemMacro && Loc.isValid() &&
  515. Diag.getSourceManager().isInSystemMacro(Loc))
  516. return diag::Severity::Ignored;
  517. return Result;
  518. }
  519. #define GET_DIAG_ARRAYS
  520. #include "clang/Basic/DiagnosticGroups.inc"
  521. #undef GET_DIAG_ARRAYS
  522. namespace {
  523. struct WarningOption {
  524. uint16_t NameOffset;
  525. uint16_t Members;
  526. uint16_t SubGroups;
  527. StringRef Documentation;
  528. // String is stored with a pascal-style length byte.
  529. StringRef getName() const {
  530. return StringRef(DiagGroupNames + NameOffset + 1,
  531. DiagGroupNames[NameOffset]);
  532. }
  533. };
  534. }
  535. // Second the table of options, sorted by name for fast binary lookup.
  536. static const WarningOption OptionTable[] = {
  537. #define DIAG_ENTRY(GroupName, FlagNameOffset, Members, SubGroups, Docs) \
  538. {FlagNameOffset, Members, SubGroups, Docs},
  539. #include "clang/Basic/DiagnosticGroups.inc"
  540. #undef DIAG_ENTRY
  541. };
  542. /// Given a diagnostic group ID, return its documentation.
  543. StringRef DiagnosticIDs::getWarningOptionDocumentation(diag::Group Group) {
  544. return OptionTable[static_cast<int>(Group)].Documentation;
  545. }
  546. StringRef DiagnosticIDs::getWarningOptionForGroup(diag::Group Group) {
  547. return OptionTable[static_cast<int>(Group)].getName();
  548. }
  549. std::optional<diag::Group>
  550. DiagnosticIDs::getGroupForWarningOption(StringRef Name) {
  551. const auto *Found = llvm::partition_point(
  552. OptionTable, [=](const WarningOption &O) { return O.getName() < Name; });
  553. if (Found == std::end(OptionTable) || Found->getName() != Name)
  554. return std::nullopt;
  555. return static_cast<diag::Group>(Found - OptionTable);
  556. }
  557. std::optional<diag::Group> DiagnosticIDs::getGroupForDiag(unsigned DiagID) {
  558. if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
  559. return static_cast<diag::Group>(Info->getOptionGroupIndex());
  560. return std::nullopt;
  561. }
  562. /// getWarningOptionForDiag - Return the lowest-level warning option that
  563. /// enables the specified diagnostic. If there is no -Wfoo flag that controls
  564. /// the diagnostic, this returns null.
  565. StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
  566. if (auto G = getGroupForDiag(DiagID))
  567. return getWarningOptionForGroup(*G);
  568. return StringRef();
  569. }
  570. std::vector<std::string> DiagnosticIDs::getDiagnosticFlags() {
  571. std::vector<std::string> Res{"-W", "-Wno-"};
  572. for (size_t I = 1; DiagGroupNames[I] != '\0';) {
  573. std::string Diag(DiagGroupNames + I + 1, DiagGroupNames[I]);
  574. I += DiagGroupNames[I] + 1;
  575. Res.push_back("-W" + Diag);
  576. Res.push_back("-Wno-" + Diag);
  577. }
  578. return Res;
  579. }
  580. /// Return \c true if any diagnostics were found in this group, even if they
  581. /// were filtered out due to having the wrong flavor.
  582. static bool getDiagnosticsInGroup(diag::Flavor Flavor,
  583. const WarningOption *Group,
  584. SmallVectorImpl<diag::kind> &Diags) {
  585. // An empty group is considered to be a warning group: we have empty groups
  586. // for GCC compatibility, and GCC does not have remarks.
  587. if (!Group->Members && !Group->SubGroups)
  588. return Flavor == diag::Flavor::Remark;
  589. bool NotFound = true;
  590. // Add the members of the option diagnostic set.
  591. const int16_t *Member = DiagArrays + Group->Members;
  592. for (; *Member != -1; ++Member) {
  593. if (GetDiagInfo(*Member)->getFlavor() == Flavor) {
  594. NotFound = false;
  595. Diags.push_back(*Member);
  596. }
  597. }
  598. // Add the members of the subgroups.
  599. const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
  600. for (; *SubGroups != (int16_t)-1; ++SubGroups)
  601. NotFound &= getDiagnosticsInGroup(Flavor, &OptionTable[(short)*SubGroups],
  602. Diags);
  603. return NotFound;
  604. }
  605. bool
  606. DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
  607. SmallVectorImpl<diag::kind> &Diags) const {
  608. if (std::optional<diag::Group> G = getGroupForWarningOption(Group))
  609. return ::getDiagnosticsInGroup(
  610. Flavor, &OptionTable[static_cast<unsigned>(*G)], Diags);
  611. return true;
  612. }
  613. void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
  614. std::vector<diag::kind> &Diags) {
  615. for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
  616. if (StaticDiagInfo[i].getFlavor() == Flavor)
  617. Diags.push_back(StaticDiagInfo[i].DiagID);
  618. }
  619. StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor,
  620. StringRef Group) {
  621. StringRef Best;
  622. unsigned BestDistance = Group.size() + 1; // Maximum threshold.
  623. for (const WarningOption &O : OptionTable) {
  624. // Don't suggest ignored warning flags.
  625. if (!O.Members && !O.SubGroups)
  626. continue;
  627. unsigned Distance = O.getName().edit_distance(Group, true, BestDistance);
  628. if (Distance > BestDistance)
  629. continue;
  630. // Don't suggest groups that are not of this kind.
  631. llvm::SmallVector<diag::kind, 8> Diags;
  632. if (::getDiagnosticsInGroup(Flavor, &O, Diags) || Diags.empty())
  633. continue;
  634. if (Distance == BestDistance) {
  635. // Two matches with the same distance, don't prefer one over the other.
  636. Best = "";
  637. } else if (Distance < BestDistance) {
  638. // This is a better match.
  639. Best = O.getName();
  640. BestDistance = Distance;
  641. }
  642. }
  643. return Best;
  644. }
  645. /// ProcessDiag - This is the method used to report a diagnostic that is
  646. /// finally fully formed.
  647. bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const {
  648. Diagnostic Info(&Diag);
  649. assert(Diag.getClient() && "DiagnosticClient not set!");
  650. // Figure out the diagnostic level of this message.
  651. unsigned DiagID = Info.getID();
  652. DiagnosticIDs::Level DiagLevel
  653. = getDiagnosticLevel(DiagID, Info.getLocation(), Diag);
  654. // Update counts for DiagnosticErrorTrap even if a fatal error occurred
  655. // or diagnostics are suppressed.
  656. if (DiagLevel >= DiagnosticIDs::Error) {
  657. ++Diag.TrapNumErrorsOccurred;
  658. if (isUnrecoverable(DiagID))
  659. ++Diag.TrapNumUnrecoverableErrorsOccurred;
  660. }
  661. if (Diag.SuppressAllDiagnostics)
  662. return false;
  663. if (DiagLevel != DiagnosticIDs::Note) {
  664. // Record that a fatal error occurred only when we see a second
  665. // non-note diagnostic. This allows notes to be attached to the
  666. // fatal error, but suppresses any diagnostics that follow those
  667. // notes.
  668. if (Diag.LastDiagLevel == DiagnosticIDs::Fatal)
  669. Diag.FatalErrorOccurred = true;
  670. Diag.LastDiagLevel = DiagLevel;
  671. }
  672. // If a fatal error has already been emitted, silence all subsequent
  673. // diagnostics.
  674. if (Diag.FatalErrorOccurred) {
  675. if (DiagLevel >= DiagnosticIDs::Error &&
  676. Diag.Client->IncludeInDiagnosticCounts()) {
  677. ++Diag.NumErrors;
  678. }
  679. return false;
  680. }
  681. // If the client doesn't care about this message, don't issue it. If this is
  682. // a note and the last real diagnostic was ignored, ignore it too.
  683. if (DiagLevel == DiagnosticIDs::Ignored ||
  684. (DiagLevel == DiagnosticIDs::Note &&
  685. Diag.LastDiagLevel == DiagnosticIDs::Ignored))
  686. return false;
  687. if (DiagLevel >= DiagnosticIDs::Error) {
  688. if (isUnrecoverable(DiagID))
  689. Diag.UnrecoverableErrorOccurred = true;
  690. // Warnings which have been upgraded to errors do not prevent compilation.
  691. if (isDefaultMappingAsError(DiagID))
  692. Diag.UncompilableErrorOccurred = true;
  693. Diag.ErrorOccurred = true;
  694. if (Diag.Client->IncludeInDiagnosticCounts()) {
  695. ++Diag.NumErrors;
  696. }
  697. // If we've emitted a lot of errors, emit a fatal error instead of it to
  698. // stop a flood of bogus errors.
  699. if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit &&
  700. DiagLevel == DiagnosticIDs::Error) {
  701. Diag.SetDelayedDiagnostic(diag::fatal_too_many_errors);
  702. return false;
  703. }
  704. }
  705. // Make sure we set FatalErrorOccurred to ensure that the notes from the
  706. // diagnostic that caused `fatal_too_many_errors` won't be emitted.
  707. if (Diag.CurDiagID == diag::fatal_too_many_errors)
  708. Diag.FatalErrorOccurred = true;
  709. // Finally, report it.
  710. EmitDiag(Diag, DiagLevel);
  711. return true;
  712. }
  713. void DiagnosticIDs::EmitDiag(DiagnosticsEngine &Diag, Level DiagLevel) const {
  714. Diagnostic Info(&Diag);
  715. assert(DiagLevel != DiagnosticIDs::Ignored && "Cannot emit ignored diagnostics!");
  716. Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info);
  717. if (Diag.Client->IncludeInDiagnosticCounts()) {
  718. if (DiagLevel == DiagnosticIDs::Warning)
  719. ++Diag.NumWarnings;
  720. }
  721. Diag.CurDiagID = ~0U;
  722. }
  723. bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const {
  724. if (DiagID >= diag::DIAG_UPPER_LIMIT) {
  725. assert(CustomDiagInfo && "Invalid CustomDiagInfo");
  726. // Custom diagnostics.
  727. return CustomDiagInfo->getLevel(DiagID) >= DiagnosticIDs::Error;
  728. }
  729. // Only errors may be unrecoverable.
  730. if (getBuiltinDiagClass(DiagID) < CLASS_ERROR)
  731. return false;
  732. if (DiagID == diag::err_unavailable ||
  733. DiagID == diag::err_unavailable_message)
  734. return false;
  735. // Currently we consider all ARC errors as recoverable.
  736. if (isARCDiagnostic(DiagID))
  737. return false;
  738. return true;
  739. }
  740. bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
  741. unsigned cat = getCategoryNumberForDiag(DiagID);
  742. return DiagnosticIDs::getCategoryNameFromID(cat).startswith("ARC ");
  743. }