Diagnostic.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. //===- Diagnostic.cpp - C Language Family Diagnostic 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-related interfaces.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/Diagnostic.h"
  13. #include "clang/Basic/CharInfo.h"
  14. #include "clang/Basic/DiagnosticError.h"
  15. #include "clang/Basic/DiagnosticIDs.h"
  16. #include "clang/Basic/DiagnosticOptions.h"
  17. #include "clang/Basic/IdentifierTable.h"
  18. #include "clang/Basic/PartialDiagnostic.h"
  19. #include "clang/Basic/SourceLocation.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Basic/Specifiers.h"
  22. #include "clang/Basic/TokenKinds.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/Support/CrashRecoveryContext.h"
  28. #include "llvm/Support/Locale.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <algorithm>
  31. #include <cassert>
  32. #include <cstddef>
  33. #include <cstdint>
  34. #include <cstring>
  35. #include <limits>
  36. #include <string>
  37. #include <utility>
  38. #include <vector>
  39. using namespace clang;
  40. const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
  41. DiagNullabilityKind nullability) {
  42. StringRef string;
  43. switch (nullability.first) {
  44. case NullabilityKind::NonNull:
  45. string = nullability.second ? "'nonnull'" : "'_Nonnull'";
  46. break;
  47. case NullabilityKind::Nullable:
  48. string = nullability.second ? "'nullable'" : "'_Nullable'";
  49. break;
  50. case NullabilityKind::Unspecified:
  51. string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
  52. break;
  53. case NullabilityKind::NullableResult:
  54. assert(!nullability.second &&
  55. "_Nullable_result isn't supported as context-sensitive keyword");
  56. string = "_Nullable_result";
  57. break;
  58. }
  59. DB.AddString(string);
  60. return DB;
  61. }
  62. const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
  63. llvm::Error &&E) {
  64. DB.AddString(toString(std::move(E)));
  65. return DB;
  66. }
  67. static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
  68. StringRef Modifier, StringRef Argument,
  69. ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
  70. SmallVectorImpl<char> &Output,
  71. void *Cookie,
  72. ArrayRef<intptr_t> QualTypeVals) {
  73. StringRef Str = "<can't format argument>";
  74. Output.append(Str.begin(), Str.end());
  75. }
  76. DiagnosticsEngine::DiagnosticsEngine(
  77. IntrusiveRefCntPtr<DiagnosticIDs> diags,
  78. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,
  79. bool ShouldOwnClient)
  80. : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
  81. setClient(client, ShouldOwnClient);
  82. ArgToStringFn = DummyArgToStringFn;
  83. Reset();
  84. }
  85. DiagnosticsEngine::~DiagnosticsEngine() {
  86. // If we own the diagnostic client, destroy it first so that it can access the
  87. // engine from its destructor.
  88. setClient(nullptr);
  89. }
  90. void DiagnosticsEngine::dump() const {
  91. DiagStatesByLoc.dump(*SourceMgr);
  92. }
  93. void DiagnosticsEngine::dump(StringRef DiagName) const {
  94. DiagStatesByLoc.dump(*SourceMgr, DiagName);
  95. }
  96. void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
  97. bool ShouldOwnClient) {
  98. Owner.reset(ShouldOwnClient ? client : nullptr);
  99. Client = client;
  100. }
  101. void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
  102. DiagStateOnPushStack.push_back(GetCurDiagState());
  103. }
  104. bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
  105. if (DiagStateOnPushStack.empty())
  106. return false;
  107. if (DiagStateOnPushStack.back() != GetCurDiagState()) {
  108. // State changed at some point between push/pop.
  109. PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
  110. }
  111. DiagStateOnPushStack.pop_back();
  112. return true;
  113. }
  114. void DiagnosticsEngine::Reset() {
  115. ErrorOccurred = false;
  116. UncompilableErrorOccurred = false;
  117. FatalErrorOccurred = false;
  118. UnrecoverableErrorOccurred = false;
  119. NumWarnings = 0;
  120. NumErrors = 0;
  121. TrapNumErrorsOccurred = 0;
  122. TrapNumUnrecoverableErrorsOccurred = 0;
  123. CurDiagID = std::numeric_limits<unsigned>::max();
  124. LastDiagLevel = DiagnosticIDs::Ignored;
  125. DelayedDiagID = 0;
  126. // Clear state related to #pragma diagnostic.
  127. DiagStates.clear();
  128. DiagStatesByLoc.clear();
  129. DiagStateOnPushStack.clear();
  130. // Create a DiagState and DiagStatePoint representing diagnostic changes
  131. // through command-line.
  132. DiagStates.emplace_back();
  133. DiagStatesByLoc.appendFirst(&DiagStates.back());
  134. }
  135. void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
  136. StringRef Arg2, StringRef Arg3) {
  137. if (DelayedDiagID)
  138. return;
  139. DelayedDiagID = DiagID;
  140. DelayedDiagArg1 = Arg1.str();
  141. DelayedDiagArg2 = Arg2.str();
  142. DelayedDiagArg3 = Arg3.str();
  143. }
  144. void DiagnosticsEngine::ReportDelayed() {
  145. unsigned ID = DelayedDiagID;
  146. DelayedDiagID = 0;
  147. Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
  148. }
  149. void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
  150. assert(Files.empty() && "not first");
  151. FirstDiagState = CurDiagState = State;
  152. CurDiagStateLoc = SourceLocation();
  153. }
  154. void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
  155. SourceLocation Loc,
  156. DiagState *State) {
  157. CurDiagState = State;
  158. CurDiagStateLoc = Loc;
  159. std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
  160. unsigned Offset = Decomp.second;
  161. for (File *F = getFile(SrcMgr, Decomp.first); F;
  162. Offset = F->ParentOffset, F = F->Parent) {
  163. F->HasLocalTransitions = true;
  164. auto &Last = F->StateTransitions.back();
  165. assert(Last.Offset <= Offset && "state transitions added out of order");
  166. if (Last.Offset == Offset) {
  167. if (Last.State == State)
  168. break;
  169. Last.State = State;
  170. continue;
  171. }
  172. F->StateTransitions.push_back({State, Offset});
  173. }
  174. }
  175. DiagnosticsEngine::DiagState *
  176. DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
  177. SourceLocation Loc) const {
  178. // Common case: we have not seen any diagnostic pragmas.
  179. if (Files.empty())
  180. return FirstDiagState;
  181. std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
  182. const File *F = getFile(SrcMgr, Decomp.first);
  183. return F->lookup(Decomp.second);
  184. }
  185. DiagnosticsEngine::DiagState *
  186. DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
  187. auto OnePastIt =
  188. llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
  189. return P.Offset <= Offset;
  190. });
  191. assert(OnePastIt != StateTransitions.begin() && "missing initial state");
  192. return OnePastIt[-1].State;
  193. }
  194. DiagnosticsEngine::DiagStateMap::File *
  195. DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
  196. FileID ID) const {
  197. // Get or insert the File for this ID.
  198. auto Range = Files.equal_range(ID);
  199. if (Range.first != Range.second)
  200. return &Range.first->second;
  201. auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
  202. // We created a new File; look up the diagnostic state at the start of it and
  203. // initialize it.
  204. if (ID.isValid()) {
  205. std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
  206. F.Parent = getFile(SrcMgr, Decomp.first);
  207. F.ParentOffset = Decomp.second;
  208. F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
  209. } else {
  210. // This is the (imaginary) root file into which we pretend all top-level
  211. // files are included; it descends from the initial state.
  212. //
  213. // FIXME: This doesn't guarantee that we use the same ordering as
  214. // isBeforeInTranslationUnit in the cases where someone invented another
  215. // top-level file and added diagnostic pragmas to it. See the code at the
  216. // end of isBeforeInTranslationUnit for the quirks it deals with.
  217. F.StateTransitions.push_back({FirstDiagState, 0});
  218. }
  219. return &F;
  220. }
  221. void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
  222. StringRef DiagName) const {
  223. llvm::errs() << "diagnostic state at ";
  224. CurDiagStateLoc.print(llvm::errs(), SrcMgr);
  225. llvm::errs() << ": " << CurDiagState << "\n";
  226. for (auto &F : Files) {
  227. FileID ID = F.first;
  228. File &File = F.second;
  229. bool PrintedOuterHeading = false;
  230. auto PrintOuterHeading = [&] {
  231. if (PrintedOuterHeading) return;
  232. PrintedOuterHeading = true;
  233. llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
  234. << ">: " << SrcMgr.getBufferOrFake(ID).getBufferIdentifier();
  235. if (F.second.Parent) {
  236. std::pair<FileID, unsigned> Decomp =
  237. SrcMgr.getDecomposedIncludedLoc(ID);
  238. assert(File.ParentOffset == Decomp.second);
  239. llvm::errs() << " parent " << File.Parent << " <FileID "
  240. << Decomp.first.getHashValue() << "> ";
  241. SrcMgr.getLocForStartOfFile(Decomp.first)
  242. .getLocWithOffset(Decomp.second)
  243. .print(llvm::errs(), SrcMgr);
  244. }
  245. if (File.HasLocalTransitions)
  246. llvm::errs() << " has_local_transitions";
  247. llvm::errs() << "\n";
  248. };
  249. if (DiagName.empty())
  250. PrintOuterHeading();
  251. for (DiagStatePoint &Transition : File.StateTransitions) {
  252. bool PrintedInnerHeading = false;
  253. auto PrintInnerHeading = [&] {
  254. if (PrintedInnerHeading) return;
  255. PrintedInnerHeading = true;
  256. PrintOuterHeading();
  257. llvm::errs() << " ";
  258. SrcMgr.getLocForStartOfFile(ID)
  259. .getLocWithOffset(Transition.Offset)
  260. .print(llvm::errs(), SrcMgr);
  261. llvm::errs() << ": state " << Transition.State << ":\n";
  262. };
  263. if (DiagName.empty())
  264. PrintInnerHeading();
  265. for (auto &Mapping : *Transition.State) {
  266. StringRef Option =
  267. DiagnosticIDs::getWarningOptionForDiag(Mapping.first);
  268. if (!DiagName.empty() && DiagName != Option)
  269. continue;
  270. PrintInnerHeading();
  271. llvm::errs() << " ";
  272. if (Option.empty())
  273. llvm::errs() << "<unknown " << Mapping.first << ">";
  274. else
  275. llvm::errs() << Option;
  276. llvm::errs() << ": ";
  277. switch (Mapping.second.getSeverity()) {
  278. case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
  279. case diag::Severity::Remark: llvm::errs() << "remark"; break;
  280. case diag::Severity::Warning: llvm::errs() << "warning"; break;
  281. case diag::Severity::Error: llvm::errs() << "error"; break;
  282. case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
  283. }
  284. if (!Mapping.second.isUser())
  285. llvm::errs() << " default";
  286. if (Mapping.second.isPragma())
  287. llvm::errs() << " pragma";
  288. if (Mapping.second.hasNoWarningAsError())
  289. llvm::errs() << " no-error";
  290. if (Mapping.second.hasNoErrorAsFatal())
  291. llvm::errs() << " no-fatal";
  292. if (Mapping.second.wasUpgradedFromWarning())
  293. llvm::errs() << " overruled";
  294. llvm::errs() << "\n";
  295. }
  296. }
  297. }
  298. }
  299. void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
  300. SourceLocation Loc) {
  301. assert(Loc.isValid() && "Adding invalid loc point");
  302. DiagStatesByLoc.append(*SourceMgr, Loc, State);
  303. }
  304. void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
  305. SourceLocation L) {
  306. assert(Diag < diag::DIAG_UPPER_LIMIT &&
  307. "Can only map builtin diagnostics");
  308. assert((Diags->isBuiltinWarningOrExtension(Diag) ||
  309. (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
  310. "Cannot map errors into warnings!");
  311. assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
  312. // Don't allow a mapping to a warning override an error/fatal mapping.
  313. bool WasUpgradedFromWarning = false;
  314. if (Map == diag::Severity::Warning) {
  315. DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
  316. if (Info.getSeverity() == diag::Severity::Error ||
  317. Info.getSeverity() == diag::Severity::Fatal) {
  318. Map = Info.getSeverity();
  319. WasUpgradedFromWarning = true;
  320. }
  321. }
  322. DiagnosticMapping Mapping = makeUserMapping(Map, L);
  323. Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
  324. // Make sure we propagate the NoWarningAsError flag from an existing
  325. // mapping (which may be the default mapping).
  326. DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
  327. Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
  328. Mapping.hasNoWarningAsError());
  329. // Common case; setting all the diagnostics of a group in one place.
  330. if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
  331. DiagStatesByLoc.getCurDiagState()) {
  332. // FIXME: This is theoretically wrong: if the current state is shared with
  333. // some other location (via push/pop) we will change the state for that
  334. // other location as well. This cannot currently happen, as we can't update
  335. // the diagnostic state at the same location at which we pop.
  336. DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
  337. return;
  338. }
  339. // A diagnostic pragma occurred, create a new DiagState initialized with
  340. // the current one and a new DiagStatePoint to record at which location
  341. // the new state became active.
  342. DiagStates.push_back(*GetCurDiagState());
  343. DiagStates.back().setMapping(Diag, Mapping);
  344. PushDiagStatePoint(&DiagStates.back(), L);
  345. }
  346. bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
  347. StringRef Group, diag::Severity Map,
  348. SourceLocation Loc) {
  349. // Get the diagnostics in this group.
  350. SmallVector<diag::kind, 256> GroupDiags;
  351. if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
  352. return true;
  353. // Set the mapping.
  354. for (diag::kind Diag : GroupDiags)
  355. setSeverity(Diag, Map, Loc);
  356. return false;
  357. }
  358. bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
  359. diag::Group Group,
  360. diag::Severity Map,
  361. SourceLocation Loc) {
  362. return setSeverityForGroup(Flavor, Diags->getWarningOptionForGroup(Group),
  363. Map, Loc);
  364. }
  365. bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
  366. bool Enabled) {
  367. // If we are enabling this feature, just set the diagnostic mappings to map to
  368. // errors.
  369. if (Enabled)
  370. return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
  371. diag::Severity::Error);
  372. // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
  373. // potentially downgrade anything already mapped to be a warning.
  374. // Get the diagnostics in this group.
  375. SmallVector<diag::kind, 8> GroupDiags;
  376. if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
  377. GroupDiags))
  378. return true;
  379. // Perform the mapping change.
  380. for (diag::kind Diag : GroupDiags) {
  381. DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
  382. if (Info.getSeverity() == diag::Severity::Error ||
  383. Info.getSeverity() == diag::Severity::Fatal)
  384. Info.setSeverity(diag::Severity::Warning);
  385. Info.setNoWarningAsError(true);
  386. }
  387. return false;
  388. }
  389. bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
  390. bool Enabled) {
  391. // If we are enabling this feature, just set the diagnostic mappings to map to
  392. // fatal errors.
  393. if (Enabled)
  394. return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
  395. diag::Severity::Fatal);
  396. // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
  397. // and potentially downgrade anything already mapped to be a fatal error.
  398. // Get the diagnostics in this group.
  399. SmallVector<diag::kind, 8> GroupDiags;
  400. if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
  401. GroupDiags))
  402. return true;
  403. // Perform the mapping change.
  404. for (diag::kind Diag : GroupDiags) {
  405. DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
  406. if (Info.getSeverity() == diag::Severity::Fatal)
  407. Info.setSeverity(diag::Severity::Error);
  408. Info.setNoErrorAsFatal(true);
  409. }
  410. return false;
  411. }
  412. void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
  413. diag::Severity Map,
  414. SourceLocation Loc) {
  415. // Get all the diagnostics.
  416. std::vector<diag::kind> AllDiags;
  417. DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
  418. // Set the mapping.
  419. for (diag::kind Diag : AllDiags)
  420. if (Diags->isBuiltinWarningOrExtension(Diag))
  421. setSeverity(Diag, Map, Loc);
  422. }
  423. void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
  424. assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
  425. "Multiple diagnostics in flight at once!");
  426. CurDiagLoc = storedDiag.getLocation();
  427. CurDiagID = storedDiag.getID();
  428. DiagStorage.NumDiagArgs = 0;
  429. DiagStorage.DiagRanges.clear();
  430. DiagStorage.DiagRanges.append(storedDiag.range_begin(),
  431. storedDiag.range_end());
  432. DiagStorage.FixItHints.clear();
  433. DiagStorage.FixItHints.append(storedDiag.fixit_begin(),
  434. storedDiag.fixit_end());
  435. assert(Client && "DiagnosticConsumer not set!");
  436. Level DiagLevel = storedDiag.getLevel();
  437. Diagnostic Info(this, storedDiag.getMessage());
  438. Client->HandleDiagnostic(DiagLevel, Info);
  439. if (Client->IncludeInDiagnosticCounts()) {
  440. if (DiagLevel == DiagnosticsEngine::Warning)
  441. ++NumWarnings;
  442. }
  443. CurDiagID = std::numeric_limits<unsigned>::max();
  444. }
  445. bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
  446. assert(getClient() && "DiagnosticClient not set!");
  447. bool Emitted;
  448. if (Force) {
  449. Diagnostic Info(this);
  450. // Figure out the diagnostic level of this message.
  451. DiagnosticIDs::Level DiagLevel
  452. = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
  453. Emitted = (DiagLevel != DiagnosticIDs::Ignored);
  454. if (Emitted) {
  455. // Emit the diagnostic regardless of suppression level.
  456. Diags->EmitDiag(*this, DiagLevel);
  457. }
  458. } else {
  459. // Process the diagnostic, sending the accumulated information to the
  460. // DiagnosticConsumer.
  461. Emitted = ProcessDiag();
  462. }
  463. // Clear out the current diagnostic object.
  464. Clear();
  465. // If there was a delayed diagnostic, emit it now.
  466. if (!Force && DelayedDiagID)
  467. ReportDelayed();
  468. return Emitted;
  469. }
  470. DiagnosticConsumer::~DiagnosticConsumer() = default;
  471. void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  472. const Diagnostic &Info) {
  473. if (!IncludeInDiagnosticCounts())
  474. return;
  475. if (DiagLevel == DiagnosticsEngine::Warning)
  476. ++NumWarnings;
  477. else if (DiagLevel >= DiagnosticsEngine::Error)
  478. ++NumErrors;
  479. }
  480. /// ModifierIs - Return true if the specified modifier matches specified string.
  481. template <std::size_t StrLen>
  482. static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
  483. const char (&Str)[StrLen]) {
  484. return StrLen-1 == ModifierLen && memcmp(Modifier, Str, StrLen-1) == 0;
  485. }
  486. /// ScanForward - Scans forward, looking for the given character, skipping
  487. /// nested clauses and escaped characters.
  488. static const char *ScanFormat(const char *I, const char *E, char Target) {
  489. unsigned Depth = 0;
  490. for ( ; I != E; ++I) {
  491. if (Depth == 0 && *I == Target) return I;
  492. if (Depth != 0 && *I == '}') Depth--;
  493. if (*I == '%') {
  494. I++;
  495. if (I == E) break;
  496. // Escaped characters get implicitly skipped here.
  497. // Format specifier.
  498. if (!isDigit(*I) && !isPunctuation(*I)) {
  499. for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
  500. if (I == E) break;
  501. if (*I == '{')
  502. Depth++;
  503. }
  504. }
  505. }
  506. return E;
  507. }
  508. /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
  509. /// like this: %select{foo|bar|baz}2. This means that the integer argument
  510. /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
  511. /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
  512. /// This is very useful for certain classes of variant diagnostics.
  513. static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
  514. const char *Argument, unsigned ArgumentLen,
  515. SmallVectorImpl<char> &OutStr) {
  516. const char *ArgumentEnd = Argument+ArgumentLen;
  517. // Skip over 'ValNo' |'s.
  518. while (ValNo) {
  519. const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
  520. assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
  521. " larger than the number of options in the diagnostic string!");
  522. Argument = NextVal+1; // Skip this string.
  523. --ValNo;
  524. }
  525. // Get the end of the value. This is either the } or the |.
  526. const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
  527. // Recursively format the result of the select clause into the output string.
  528. DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
  529. }
  530. /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
  531. /// letter 's' to the string if the value is not 1. This is used in cases like
  532. /// this: "you idiot, you have %4 parameter%s4!".
  533. static void HandleIntegerSModifier(unsigned ValNo,
  534. SmallVectorImpl<char> &OutStr) {
  535. if (ValNo != 1)
  536. OutStr.push_back('s');
  537. }
  538. /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
  539. /// prints the ordinal form of the given integer, with 1 corresponding
  540. /// to the first ordinal. Currently this is hard-coded to use the
  541. /// English form.
  542. static void HandleOrdinalModifier(unsigned ValNo,
  543. SmallVectorImpl<char> &OutStr) {
  544. assert(ValNo != 0 && "ValNo must be strictly positive!");
  545. llvm::raw_svector_ostream Out(OutStr);
  546. // We could use text forms for the first N ordinals, but the numeric
  547. // forms are actually nicer in diagnostics because they stand out.
  548. Out << ValNo << llvm::getOrdinalSuffix(ValNo);
  549. }
  550. /// PluralNumber - Parse an unsigned integer and advance Start.
  551. static unsigned PluralNumber(const char *&Start, const char *End) {
  552. // Programming 101: Parse a decimal number :-)
  553. unsigned Val = 0;
  554. while (Start != End && *Start >= '0' && *Start <= '9') {
  555. Val *= 10;
  556. Val += *Start - '0';
  557. ++Start;
  558. }
  559. return Val;
  560. }
  561. /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
  562. static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
  563. if (*Start != '[') {
  564. unsigned Ref = PluralNumber(Start, End);
  565. return Ref == Val;
  566. }
  567. ++Start;
  568. unsigned Low = PluralNumber(Start, End);
  569. assert(*Start == ',' && "Bad plural expression syntax: expected ,");
  570. ++Start;
  571. unsigned High = PluralNumber(Start, End);
  572. assert(*Start == ']' && "Bad plural expression syntax: expected )");
  573. ++Start;
  574. return Low <= Val && Val <= High;
  575. }
  576. /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
  577. static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
  578. // Empty condition?
  579. if (*Start == ':')
  580. return true;
  581. while (true) {
  582. char C = *Start;
  583. if (C == '%') {
  584. // Modulo expression
  585. ++Start;
  586. unsigned Arg = PluralNumber(Start, End);
  587. assert(*Start == '=' && "Bad plural expression syntax: expected =");
  588. ++Start;
  589. unsigned ValMod = ValNo % Arg;
  590. if (TestPluralRange(ValMod, Start, End))
  591. return true;
  592. } else {
  593. assert((C == '[' || (C >= '0' && C <= '9')) &&
  594. "Bad plural expression syntax: unexpected character");
  595. // Range expression
  596. if (TestPluralRange(ValNo, Start, End))
  597. return true;
  598. }
  599. // Scan for next or-expr part.
  600. Start = std::find(Start, End, ',');
  601. if (Start == End)
  602. break;
  603. ++Start;
  604. }
  605. return false;
  606. }
  607. /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
  608. /// for complex plural forms, or in languages where all plurals are complex.
  609. /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
  610. /// conditions that are tested in order, the form corresponding to the first
  611. /// that applies being emitted. The empty condition is always true, making the
  612. /// last form a default case.
  613. /// Conditions are simple boolean expressions, where n is the number argument.
  614. /// Here are the rules.
  615. /// condition := expression | empty
  616. /// empty := -> always true
  617. /// expression := numeric [',' expression] -> logical or
  618. /// numeric := range -> true if n in range
  619. /// | '%' number '=' range -> true if n % number in range
  620. /// range := number
  621. /// | '[' number ',' number ']' -> ranges are inclusive both ends
  622. ///
  623. /// Here are some examples from the GNU gettext manual written in this form:
  624. /// English:
  625. /// {1:form0|:form1}
  626. /// Latvian:
  627. /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
  628. /// Gaeilge:
  629. /// {1:form0|2:form1|:form2}
  630. /// Romanian:
  631. /// {1:form0|0,%100=[1,19]:form1|:form2}
  632. /// Lithuanian:
  633. /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
  634. /// Russian (requires repeated form):
  635. /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
  636. /// Slovak
  637. /// {1:form0|[2,4]:form1|:form2}
  638. /// Polish (requires repeated form):
  639. /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
  640. static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
  641. const char *Argument, unsigned ArgumentLen,
  642. SmallVectorImpl<char> &OutStr) {
  643. const char *ArgumentEnd = Argument + ArgumentLen;
  644. while (true) {
  645. assert(Argument < ArgumentEnd && "Plural expression didn't match.");
  646. const char *ExprEnd = Argument;
  647. while (*ExprEnd != ':') {
  648. assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
  649. ++ExprEnd;
  650. }
  651. if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
  652. Argument = ExprEnd + 1;
  653. ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
  654. // Recursively format the result of the plural clause into the
  655. // output string.
  656. DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
  657. return;
  658. }
  659. Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
  660. }
  661. }
  662. /// Returns the friendly description for a token kind that will appear
  663. /// without quotes in diagnostic messages. These strings may be translatable in
  664. /// future.
  665. static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
  666. switch (Kind) {
  667. case tok::identifier:
  668. return "identifier";
  669. default:
  670. return nullptr;
  671. }
  672. }
  673. /// FormatDiagnostic - Format this diagnostic into a string, substituting the
  674. /// formal arguments into the %0 slots. The result is appended onto the Str
  675. /// array.
  676. void Diagnostic::
  677. FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
  678. if (!StoredDiagMessage.empty()) {
  679. OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
  680. return;
  681. }
  682. StringRef Diag =
  683. getDiags()->getDiagnosticIDs()->getDescription(getID());
  684. FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
  685. }
  686. void Diagnostic::
  687. FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
  688. SmallVectorImpl<char> &OutStr) const {
  689. // When the diagnostic string is only "%0", the entire string is being given
  690. // by an outside source. Remove unprintable characters from this string
  691. // and skip all the other string processing.
  692. if (DiagEnd - DiagStr == 2 &&
  693. StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
  694. getArgKind(0) == DiagnosticsEngine::ak_std_string) {
  695. const std::string &S = getArgStdStr(0);
  696. for (char c : S) {
  697. if (llvm::sys::locale::isPrint(c) || c == '\t') {
  698. OutStr.push_back(c);
  699. }
  700. }
  701. return;
  702. }
  703. /// FormattedArgs - Keep track of all of the arguments formatted by
  704. /// ConvertArgToString and pass them into subsequent calls to
  705. /// ConvertArgToString, allowing the implementation to avoid redundancies in
  706. /// obvious cases.
  707. SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
  708. /// QualTypeVals - Pass a vector of arrays so that QualType names can be
  709. /// compared to see if more information is needed to be printed.
  710. SmallVector<intptr_t, 2> QualTypeVals;
  711. SmallString<64> Tree;
  712. for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
  713. if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
  714. QualTypeVals.push_back(getRawArg(i));
  715. while (DiagStr != DiagEnd) {
  716. if (DiagStr[0] != '%') {
  717. // Append non-%0 substrings to Str if we have one.
  718. const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
  719. OutStr.append(DiagStr, StrEnd);
  720. DiagStr = StrEnd;
  721. continue;
  722. } else if (isPunctuation(DiagStr[1])) {
  723. OutStr.push_back(DiagStr[1]); // %% -> %.
  724. DiagStr += 2;
  725. continue;
  726. }
  727. // Skip the %.
  728. ++DiagStr;
  729. // This must be a placeholder for a diagnostic argument. The format for a
  730. // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
  731. // The digit is a number from 0-9 indicating which argument this comes from.
  732. // The modifier is a string of digits from the set [-a-z]+, arguments is a
  733. // brace enclosed string.
  734. const char *Modifier = nullptr, *Argument = nullptr;
  735. unsigned ModifierLen = 0, ArgumentLen = 0;
  736. // Check to see if we have a modifier. If so eat it.
  737. if (!isDigit(DiagStr[0])) {
  738. Modifier = DiagStr;
  739. while (DiagStr[0] == '-' ||
  740. (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
  741. ++DiagStr;
  742. ModifierLen = DiagStr-Modifier;
  743. // If we have an argument, get it next.
  744. if (DiagStr[0] == '{') {
  745. ++DiagStr; // Skip {.
  746. Argument = DiagStr;
  747. DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
  748. assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
  749. ArgumentLen = DiagStr-Argument;
  750. ++DiagStr; // Skip }.
  751. }
  752. }
  753. assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
  754. unsigned ArgNo = *DiagStr++ - '0';
  755. // Only used for type diffing.
  756. unsigned ArgNo2 = ArgNo;
  757. DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
  758. if (ModifierIs(Modifier, ModifierLen, "diff")) {
  759. assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
  760. "Invalid format for diff modifier");
  761. ++DiagStr; // Comma.
  762. ArgNo2 = *DiagStr++ - '0';
  763. DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
  764. if (Kind == DiagnosticsEngine::ak_qualtype &&
  765. Kind2 == DiagnosticsEngine::ak_qualtype)
  766. Kind = DiagnosticsEngine::ak_qualtype_pair;
  767. else {
  768. // %diff only supports QualTypes. For other kinds of arguments,
  769. // use the default printing. For example, if the modifier is:
  770. // "%diff{compare $ to $|other text}1,2"
  771. // treat it as:
  772. // "compare %1 to %2"
  773. const char *ArgumentEnd = Argument + ArgumentLen;
  774. const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
  775. assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
  776. "Found too many '|'s in a %diff modifier!");
  777. const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
  778. const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
  779. const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
  780. const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
  781. FormatDiagnostic(Argument, FirstDollar, OutStr);
  782. FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
  783. FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
  784. FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
  785. FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
  786. continue;
  787. }
  788. }
  789. switch (Kind) {
  790. // ---- STRINGS ----
  791. case DiagnosticsEngine::ak_std_string: {
  792. const std::string &S = getArgStdStr(ArgNo);
  793. assert(ModifierLen == 0 && "No modifiers for strings yet");
  794. OutStr.append(S.begin(), S.end());
  795. break;
  796. }
  797. case DiagnosticsEngine::ak_c_string: {
  798. const char *S = getArgCStr(ArgNo);
  799. assert(ModifierLen == 0 && "No modifiers for strings yet");
  800. // Don't crash if get passed a null pointer by accident.
  801. if (!S)
  802. S = "(null)";
  803. OutStr.append(S, S + strlen(S));
  804. break;
  805. }
  806. // ---- INTEGERS ----
  807. case DiagnosticsEngine::ak_sint: {
  808. int64_t Val = getArgSInt(ArgNo);
  809. if (ModifierIs(Modifier, ModifierLen, "select")) {
  810. HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
  811. OutStr);
  812. } else if (ModifierIs(Modifier, ModifierLen, "s")) {
  813. HandleIntegerSModifier(Val, OutStr);
  814. } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
  815. HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
  816. OutStr);
  817. } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
  818. HandleOrdinalModifier((unsigned)Val, OutStr);
  819. } else {
  820. assert(ModifierLen == 0 && "Unknown integer modifier");
  821. llvm::raw_svector_ostream(OutStr) << Val;
  822. }
  823. break;
  824. }
  825. case DiagnosticsEngine::ak_uint: {
  826. uint64_t Val = getArgUInt(ArgNo);
  827. if (ModifierIs(Modifier, ModifierLen, "select")) {
  828. HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
  829. } else if (ModifierIs(Modifier, ModifierLen, "s")) {
  830. HandleIntegerSModifier(Val, OutStr);
  831. } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
  832. HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
  833. OutStr);
  834. } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
  835. HandleOrdinalModifier(Val, OutStr);
  836. } else {
  837. assert(ModifierLen == 0 && "Unknown integer modifier");
  838. llvm::raw_svector_ostream(OutStr) << Val;
  839. }
  840. break;
  841. }
  842. // ---- TOKEN SPELLINGS ----
  843. case DiagnosticsEngine::ak_tokenkind: {
  844. tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
  845. assert(ModifierLen == 0 && "No modifiers for token kinds yet");
  846. llvm::raw_svector_ostream Out(OutStr);
  847. if (const char *S = tok::getPunctuatorSpelling(Kind))
  848. // Quoted token spelling for punctuators.
  849. Out << '\'' << S << '\'';
  850. else if (const char *S = tok::getKeywordSpelling(Kind))
  851. // Unquoted token spelling for keywords.
  852. Out << S;
  853. else if (const char *S = getTokenDescForDiagnostic(Kind))
  854. // Unquoted translatable token name.
  855. Out << S;
  856. else if (const char *S = tok::getTokenName(Kind))
  857. // Debug name, shouldn't appear in user-facing diagnostics.
  858. Out << '<' << S << '>';
  859. else
  860. Out << "(null)";
  861. break;
  862. }
  863. // ---- NAMES and TYPES ----
  864. case DiagnosticsEngine::ak_identifierinfo: {
  865. const IdentifierInfo *II = getArgIdentifier(ArgNo);
  866. assert(ModifierLen == 0 && "No modifiers for strings yet");
  867. // Don't crash if get passed a null pointer by accident.
  868. if (!II) {
  869. const char *S = "(null)";
  870. OutStr.append(S, S + strlen(S));
  871. continue;
  872. }
  873. llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
  874. break;
  875. }
  876. case DiagnosticsEngine::ak_addrspace:
  877. case DiagnosticsEngine::ak_qual:
  878. case DiagnosticsEngine::ak_qualtype:
  879. case DiagnosticsEngine::ak_declarationname:
  880. case DiagnosticsEngine::ak_nameddecl:
  881. case DiagnosticsEngine::ak_nestednamespec:
  882. case DiagnosticsEngine::ak_declcontext:
  883. case DiagnosticsEngine::ak_attr:
  884. getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
  885. StringRef(Modifier, ModifierLen),
  886. StringRef(Argument, ArgumentLen),
  887. FormattedArgs,
  888. OutStr, QualTypeVals);
  889. break;
  890. case DiagnosticsEngine::ak_qualtype_pair: {
  891. // Create a struct with all the info needed for printing.
  892. TemplateDiffTypes TDT;
  893. TDT.FromType = getRawArg(ArgNo);
  894. TDT.ToType = getRawArg(ArgNo2);
  895. TDT.ElideType = getDiags()->ElideType;
  896. TDT.ShowColors = getDiags()->ShowColors;
  897. TDT.TemplateDiffUsed = false;
  898. intptr_t val = reinterpret_cast<intptr_t>(&TDT);
  899. const char *ArgumentEnd = Argument + ArgumentLen;
  900. const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
  901. // Print the tree. If this diagnostic already has a tree, skip the
  902. // second tree.
  903. if (getDiags()->PrintTemplateTree && Tree.empty()) {
  904. TDT.PrintFromType = true;
  905. TDT.PrintTree = true;
  906. getDiags()->ConvertArgToString(Kind, val,
  907. StringRef(Modifier, ModifierLen),
  908. StringRef(Argument, ArgumentLen),
  909. FormattedArgs,
  910. Tree, QualTypeVals);
  911. // If there is no tree information, fall back to regular printing.
  912. if (!Tree.empty()) {
  913. FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
  914. break;
  915. }
  916. }
  917. // Non-tree printing, also the fall-back when tree printing fails.
  918. // The fall-back is triggered when the types compared are not templates.
  919. const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
  920. const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
  921. // Append before text
  922. FormatDiagnostic(Argument, FirstDollar, OutStr);
  923. // Append first type
  924. TDT.PrintTree = false;
  925. TDT.PrintFromType = true;
  926. getDiags()->ConvertArgToString(Kind, val,
  927. StringRef(Modifier, ModifierLen),
  928. StringRef(Argument, ArgumentLen),
  929. FormattedArgs,
  930. OutStr, QualTypeVals);
  931. if (!TDT.TemplateDiffUsed)
  932. FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
  933. TDT.FromType));
  934. // Append middle text
  935. FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
  936. // Append second type
  937. TDT.PrintFromType = false;
  938. getDiags()->ConvertArgToString(Kind, val,
  939. StringRef(Modifier, ModifierLen),
  940. StringRef(Argument, ArgumentLen),
  941. FormattedArgs,
  942. OutStr, QualTypeVals);
  943. if (!TDT.TemplateDiffUsed)
  944. FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
  945. TDT.ToType));
  946. // Append end text
  947. FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
  948. break;
  949. }
  950. }
  951. // Remember this argument info for subsequent formatting operations. Turn
  952. // std::strings into a null terminated string to make it be the same case as
  953. // all the other ones.
  954. if (Kind == DiagnosticsEngine::ak_qualtype_pair)
  955. continue;
  956. else if (Kind != DiagnosticsEngine::ak_std_string)
  957. FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
  958. else
  959. FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
  960. (intptr_t)getArgStdStr(ArgNo).c_str()));
  961. }
  962. // Append the type tree to the end of the diagnostics.
  963. OutStr.append(Tree.begin(), Tree.end());
  964. }
  965. StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
  966. StringRef Message)
  967. : ID(ID), Level(Level), Message(Message) {}
  968. StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
  969. const Diagnostic &Info)
  970. : ID(Info.getID()), Level(Level) {
  971. assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
  972. "Valid source location without setting a source manager for diagnostic");
  973. if (Info.getLocation().isValid())
  974. Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
  975. SmallString<64> Message;
  976. Info.FormatDiagnostic(Message);
  977. this->Message.assign(Message.begin(), Message.end());
  978. this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
  979. this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
  980. }
  981. StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
  982. StringRef Message, FullSourceLoc Loc,
  983. ArrayRef<CharSourceRange> Ranges,
  984. ArrayRef<FixItHint> FixIts)
  985. : ID(ID), Level(Level), Loc(Loc), Message(Message),
  986. Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
  987. {
  988. }
  989. /// IncludeInDiagnosticCounts - This method (whose default implementation
  990. /// returns true) indicates whether the diagnostics handled by this
  991. /// DiagnosticConsumer should be included in the number of diagnostics
  992. /// reported by DiagnosticsEngine.
  993. bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
  994. void IgnoringDiagConsumer::anchor() {}
  995. ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;
  996. void ForwardingDiagnosticConsumer::HandleDiagnostic(
  997. DiagnosticsEngine::Level DiagLevel,
  998. const Diagnostic &Info) {
  999. Target.HandleDiagnostic(DiagLevel, Info);
  1000. }
  1001. void ForwardingDiagnosticConsumer::clear() {
  1002. DiagnosticConsumer::clear();
  1003. Target.clear();
  1004. }
  1005. bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
  1006. return Target.IncludeInDiagnosticCounts();
  1007. }
  1008. PartialDiagnostic::DiagStorageAllocator::DiagStorageAllocator() {
  1009. for (unsigned I = 0; I != NumCached; ++I)
  1010. FreeList[I] = Cached + I;
  1011. NumFreeListEntries = NumCached;
  1012. }
  1013. PartialDiagnostic::DiagStorageAllocator::~DiagStorageAllocator() {
  1014. // Don't assert if we are in a CrashRecovery context, as this invariant may
  1015. // be invalidated during a crash.
  1016. assert((NumFreeListEntries == NumCached ||
  1017. llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
  1018. "A partial is on the lam");
  1019. }
  1020. char DiagnosticError::ID;