Diagnostic.cpp 36 KB

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