DiagnosticIDs.cpp 31 KB

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