DiagnosticIDs.cpp 26 KB

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