clang  16.0.0git
Diagnostic.cpp
Go to the documentation of this file.
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 
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/CharInfo.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "clang/Basic/TokenKinds.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/CrashRecoveryContext.h"
30 #include "llvm/Support/Unicode.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <cstring>
37 #include <limits>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 using namespace clang;
43 
45  DiagNullabilityKind nullability) {
46  StringRef string;
47  switch (nullability.first) {
49  string = nullability.second ? "'nonnull'" : "'_Nonnull'";
50  break;
51 
53  string = nullability.second ? "'nullable'" : "'_Nullable'";
54  break;
55 
57  string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
58  break;
59 
61  assert(!nullability.second &&
62  "_Nullable_result isn't supported as context-sensitive keyword");
63  string = "_Nullable_result";
64  break;
65  }
66 
67  DB.AddString(string);
68  return DB;
69 }
70 
72  llvm::Error &&E) {
73  DB.AddString(toString(std::move(E)));
74  return DB;
75 }
76 
78  StringRef Modifier, StringRef Argument,
80  SmallVectorImpl<char> &Output,
81  void *Cookie,
82  ArrayRef<intptr_t> QualTypeVals) {
83  StringRef Str = "<can't format argument>";
84  Output.append(Str.begin(), Str.end());
85 }
86 
90  bool ShouldOwnClient)
91  : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
92  setClient(client, ShouldOwnClient);
93  ArgToStringFn = DummyArgToStringFn;
94 
95  Reset();
96 }
97 
99  // If we own the diagnostic client, destroy it first so that it can access the
100  // engine from its destructor.
101  setClient(nullptr);
102 }
103 
105  DiagStatesByLoc.dump(*SourceMgr);
106 }
107 
108 void DiagnosticsEngine::dump(StringRef DiagName) const {
109  DiagStatesByLoc.dump(*SourceMgr, DiagName);
110 }
111 
113  bool ShouldOwnClient) {
114  Owner.reset(ShouldOwnClient ? client : nullptr);
115  Client = client;
116 }
117 
119  DiagStateOnPushStack.push_back(GetCurDiagState());
120 }
121 
123  if (DiagStateOnPushStack.empty())
124  return false;
125 
126  if (DiagStateOnPushStack.back() != GetCurDiagState()) {
127  // State changed at some point between push/pop.
128  PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
129  }
130  DiagStateOnPushStack.pop_back();
131  return true;
132 }
133 
134 void DiagnosticsEngine::Reset(bool soft /*=false*/) {
135  ErrorOccurred = false;
136  UncompilableErrorOccurred = false;
137  FatalErrorOccurred = false;
138  UnrecoverableErrorOccurred = false;
139 
140  NumWarnings = 0;
141  NumErrors = 0;
142  TrapNumErrorsOccurred = 0;
143  TrapNumUnrecoverableErrorsOccurred = 0;
144 
146  LastDiagLevel = DiagnosticIDs::Ignored;
147  DelayedDiagID = 0;
148 
149  if (!soft) {
150  // Clear state related to #pragma diagnostic.
151  DiagStates.clear();
152  DiagStatesByLoc.clear();
153  DiagStateOnPushStack.clear();
154 
155  // Create a DiagState and DiagStatePoint representing diagnostic changes
156  // through command-line.
157  DiagStates.emplace_back();
158  DiagStatesByLoc.appendFirst(&DiagStates.back());
159  }
160 }
161 
162 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
163  StringRef Arg2, StringRef Arg3) {
164  if (DelayedDiagID)
165  return;
166 
167  DelayedDiagID = DiagID;
168  DelayedDiagArg1 = Arg1.str();
169  DelayedDiagArg2 = Arg2.str();
170  DelayedDiagArg3 = Arg3.str();
171 }
172 
173 void DiagnosticsEngine::ReportDelayed() {
174  unsigned ID = DelayedDiagID;
175  DelayedDiagID = 0;
176  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
177 }
178 
179 void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
180  assert(Files.empty() && "not first");
181  FirstDiagState = CurDiagState = State;
182  CurDiagStateLoc = SourceLocation();
183 }
184 
185 void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
186  SourceLocation Loc,
187  DiagState *State) {
188  CurDiagState = State;
189  CurDiagStateLoc = Loc;
190 
191  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
192  unsigned Offset = Decomp.second;
193  for (File *F = getFile(SrcMgr, Decomp.first); F;
194  Offset = F->ParentOffset, F = F->Parent) {
195  F->HasLocalTransitions = true;
196  auto &Last = F->StateTransitions.back();
197  assert(Last.Offset <= Offset && "state transitions added out of order");
198 
199  if (Last.Offset == Offset) {
200  if (Last.State == State)
201  break;
202  Last.State = State;
203  continue;
204  }
205 
206  F->StateTransitions.push_back({State, Offset});
207  }
208 }
209 
210 DiagnosticsEngine::DiagState *
211 DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
212  SourceLocation Loc) const {
213  // Common case: we have not seen any diagnostic pragmas.
214  if (Files.empty())
215  return FirstDiagState;
216 
217  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
218  const File *F = getFile(SrcMgr, Decomp.first);
219  return F->lookup(Decomp.second);
220 }
221 
222 DiagnosticsEngine::DiagState *
223 DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
224  auto OnePastIt =
225  llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
226  return P.Offset <= Offset;
227  });
228  assert(OnePastIt != StateTransitions.begin() && "missing initial state");
229  return OnePastIt[-1].State;
230 }
231 
232 DiagnosticsEngine::DiagStateMap::File *
233 DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
234  FileID ID) const {
235  // Get or insert the File for this ID.
236  auto Range = Files.equal_range(ID);
237  if (Range.first != Range.second)
238  return &Range.first->second;
239  auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
240 
241  // We created a new File; look up the diagnostic state at the start of it and
242  // initialize it.
243  if (ID.isValid()) {
244  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
245  F.Parent = getFile(SrcMgr, Decomp.first);
246  F.ParentOffset = Decomp.second;
247  F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
248  } else {
249  // This is the (imaginary) root file into which we pretend all top-level
250  // files are included; it descends from the initial state.
251  //
252  // FIXME: This doesn't guarantee that we use the same ordering as
253  // isBeforeInTranslationUnit in the cases where someone invented another
254  // top-level file and added diagnostic pragmas to it. See the code at the
255  // end of isBeforeInTranslationUnit for the quirks it deals with.
256  F.StateTransitions.push_back({FirstDiagState, 0});
257  }
258  return &F;
259 }
260 
262  StringRef DiagName) const {
263  llvm::errs() << "diagnostic state at ";
264  CurDiagStateLoc.print(llvm::errs(), SrcMgr);
265  llvm::errs() << ": " << CurDiagState << "\n";
266 
267  for (auto &F : Files) {
268  FileID ID = F.first;
269  File &File = F.second;
270 
271  bool PrintedOuterHeading = false;
272  auto PrintOuterHeading = [&] {
273  if (PrintedOuterHeading) return;
274  PrintedOuterHeading = true;
275 
276  llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
277  << ">: " << SrcMgr.getBufferOrFake(ID).getBufferIdentifier();
278 
279  if (F.second.Parent) {
280  std::pair<FileID, unsigned> Decomp =
282  assert(File.ParentOffset == Decomp.second);
283  llvm::errs() << " parent " << File.Parent << " <FileID "
284  << Decomp.first.getHashValue() << "> ";
285  SrcMgr.getLocForStartOfFile(Decomp.first)
286  .getLocWithOffset(Decomp.second)
287  .print(llvm::errs(), SrcMgr);
288  }
289  if (File.HasLocalTransitions)
290  llvm::errs() << " has_local_transitions";
291  llvm::errs() << "\n";
292  };
293 
294  if (DiagName.empty())
295  PrintOuterHeading();
296 
297  for (DiagStatePoint &Transition : File.StateTransitions) {
298  bool PrintedInnerHeading = false;
299  auto PrintInnerHeading = [&] {
300  if (PrintedInnerHeading) return;
301  PrintedInnerHeading = true;
302 
303  PrintOuterHeading();
304  llvm::errs() << " ";
305  SrcMgr.getLocForStartOfFile(ID)
306  .getLocWithOffset(Transition.Offset)
307  .print(llvm::errs(), SrcMgr);
308  llvm::errs() << ": state " << Transition.State << ":\n";
309  };
310 
311  if (DiagName.empty())
312  PrintInnerHeading();
313 
314  for (auto &Mapping : *Transition.State) {
315  StringRef Option =
317  if (!DiagName.empty() && DiagName != Option)
318  continue;
319 
320  PrintInnerHeading();
321  llvm::errs() << " ";
322  if (Option.empty())
323  llvm::errs() << "<unknown " << Mapping.first << ">";
324  else
325  llvm::errs() << Option;
326  llvm::errs() << ": ";
327 
328  switch (Mapping.second.getSeverity()) {
329  case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
330  case diag::Severity::Remark: llvm::errs() << "remark"; break;
331  case diag::Severity::Warning: llvm::errs() << "warning"; break;
332  case diag::Severity::Error: llvm::errs() << "error"; break;
333  case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
334  }
335 
336  if (!Mapping.second.isUser())
337  llvm::errs() << " default";
338  if (Mapping.second.isPragma())
339  llvm::errs() << " pragma";
340  if (Mapping.second.hasNoWarningAsError())
341  llvm::errs() << " no-error";
342  if (Mapping.second.hasNoErrorAsFatal())
343  llvm::errs() << " no-fatal";
344  if (Mapping.second.wasUpgradedFromWarning())
345  llvm::errs() << " overruled";
346  llvm::errs() << "\n";
347  }
348  }
349  }
350 }
351 
352 void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
353  SourceLocation Loc) {
354  assert(Loc.isValid() && "Adding invalid loc point");
355  DiagStatesByLoc.append(*SourceMgr, Loc, State);
356 }
357 
359  SourceLocation L) {
360  assert(Diag < diag::DIAG_UPPER_LIMIT &&
361  "Can only map builtin diagnostics");
362  assert((Diags->isBuiltinWarningOrExtension(Diag) ||
363  (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
364  "Cannot map errors into warnings!");
365  assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
366 
367  // Don't allow a mapping to a warning override an error/fatal mapping.
368  bool WasUpgradedFromWarning = false;
369  if (Map == diag::Severity::Warning) {
370  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
371  if (Info.getSeverity() == diag::Severity::Error ||
373  Map = Info.getSeverity();
374  WasUpgradedFromWarning = true;
375  }
376  }
377  DiagnosticMapping Mapping = makeUserMapping(Map, L);
378  Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
379 
380  // Make sure we propagate the NoWarningAsError flag from an existing
381  // mapping (which may be the default mapping).
382  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
383  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
384  Mapping.hasNoWarningAsError());
385 
386  // Common case; setting all the diagnostics of a group in one place.
387  if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
388  DiagStatesByLoc.getCurDiagState()) {
389  // FIXME: This is theoretically wrong: if the current state is shared with
390  // some other location (via push/pop) we will change the state for that
391  // other location as well. This cannot currently happen, as we can't update
392  // the diagnostic state at the same location at which we pop.
393  DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
394  return;
395  }
396 
397  // A diagnostic pragma occurred, create a new DiagState initialized with
398  // the current one and a new DiagStatePoint to record at which location
399  // the new state became active.
400  DiagStates.push_back(*GetCurDiagState());
401  DiagStates.back().setMapping(Diag, Mapping);
402  PushDiagStatePoint(&DiagStates.back(), L);
403 }
404 
406  StringRef Group, diag::Severity Map,
407  SourceLocation Loc) {
408  // Get the diagnostics in this group.
409  SmallVector<diag::kind, 256> GroupDiags;
410  if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
411  return true;
412 
413  // Set the mapping.
414  for (diag::kind Diag : GroupDiags)
415  setSeverity(Diag, Map, Loc);
416 
417  return false;
418 }
419 
422  diag::Severity Map,
423  SourceLocation Loc) {
424  return setSeverityForGroup(Flavor, Diags->getWarningOptionForGroup(Group),
425  Map, Loc);
426 }
427 
429  bool Enabled) {
430  // If we are enabling this feature, just set the diagnostic mappings to map to
431  // errors.
432  if (Enabled)
435 
436  // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
437  // potentially downgrade anything already mapped to be a warning.
438 
439  // Get the diagnostics in this group.
440  SmallVector<diag::kind, 8> GroupDiags;
441  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
442  GroupDiags))
443  return true;
444 
445  // Perform the mapping change.
446  for (diag::kind Diag : GroupDiags) {
447  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
448 
449  if (Info.getSeverity() == diag::Severity::Error ||
452 
453  Info.setNoWarningAsError(true);
454  }
455 
456  return false;
457 }
458 
460  bool Enabled) {
461  // If we are enabling this feature, just set the diagnostic mappings to map to
462  // fatal errors.
463  if (Enabled)
466 
467  // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
468  // and potentially downgrade anything already mapped to be a fatal error.
469 
470  // Get the diagnostics in this group.
471  SmallVector<diag::kind, 8> GroupDiags;
472  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
473  GroupDiags))
474  return true;
475 
476  // Perform the mapping change.
477  for (diag::kind Diag : GroupDiags) {
478  DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
479 
480  if (Info.getSeverity() == diag::Severity::Fatal)
482 
483  Info.setNoErrorAsFatal(true);
484  }
485 
486  return false;
487 }
488 
490  diag::Severity Map,
491  SourceLocation Loc) {
492  // Get all the diagnostics.
493  std::vector<diag::kind> AllDiags;
495 
496  // Set the mapping.
497  for (diag::kind Diag : AllDiags)
498  if (Diags->isBuiltinWarningOrExtension(Diag))
499  setSeverity(Diag, Map, Loc);
500 }
501 
503  assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
504  "Multiple diagnostics in flight at once!");
505 
506  CurDiagLoc = storedDiag.getLocation();
507  CurDiagID = storedDiag.getID();
508  DiagStorage.NumDiagArgs = 0;
509 
510  DiagStorage.DiagRanges.clear();
511  DiagStorage.DiagRanges.append(storedDiag.range_begin(),
512  storedDiag.range_end());
513 
514  DiagStorage.FixItHints.clear();
515  DiagStorage.FixItHints.append(storedDiag.fixit_begin(),
516  storedDiag.fixit_end());
517 
518  assert(Client && "DiagnosticConsumer not set!");
519  Level DiagLevel = storedDiag.getLevel();
520  Diagnostic Info(this, storedDiag.getMessage());
521  Client->HandleDiagnostic(DiagLevel, Info);
522  if (Client->IncludeInDiagnosticCounts()) {
523  if (DiagLevel == DiagnosticsEngine::Warning)
524  ++NumWarnings;
525  }
526 
528 }
529 
531  assert(getClient() && "DiagnosticClient not set!");
532 
533  bool Emitted;
534  if (Force) {
535  Diagnostic Info(this);
536 
537  // Figure out the diagnostic level of this message.
538  DiagnosticIDs::Level DiagLevel
539  = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
540 
541  Emitted = (DiagLevel != DiagnosticIDs::Ignored);
542  if (Emitted) {
543  // Emit the diagnostic regardless of suppression level.
544  Diags->EmitDiag(*this, DiagLevel);
545  }
546  } else {
547  // Process the diagnostic, sending the accumulated information to the
548  // DiagnosticConsumer.
549  Emitted = ProcessDiag();
550  }
551 
552  // Clear out the current diagnostic object.
553  Clear();
554 
555  // If there was a delayed diagnostic, emit it now.
556  if (!Force && DelayedDiagID)
557  ReportDelayed();
558 
559  return Emitted;
560 }
561 
563 
565  const Diagnostic &Info) {
567  return;
568 
569  if (DiagLevel == DiagnosticsEngine::Warning)
570  ++NumWarnings;
571  else if (DiagLevel >= DiagnosticsEngine::Error)
572  ++NumErrors;
573 }
574 
575 /// ModifierIs - Return true if the specified modifier matches specified string.
576 template <std::size_t StrLen>
577 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
578  const char (&Str)[StrLen]) {
579  return StrLen-1 == ModifierLen && memcmp(Modifier, Str, StrLen-1) == 0;
580 }
581 
582 /// ScanForward - Scans forward, looking for the given character, skipping
583 /// nested clauses and escaped characters.
584 static const char *ScanFormat(const char *I, const char *E, char Target) {
585  unsigned Depth = 0;
586 
587  for ( ; I != E; ++I) {
588  if (Depth == 0 && *I == Target) return I;
589  if (Depth != 0 && *I == '}') Depth--;
590 
591  if (*I == '%') {
592  I++;
593  if (I == E) break;
594 
595  // Escaped characters get implicitly skipped here.
596 
597  // Format specifier.
598  if (!isDigit(*I) && !isPunctuation(*I)) {
599  for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
600  if (I == E) break;
601  if (*I == '{')
602  Depth++;
603  }
604  }
605  }
606  return E;
607 }
608 
609 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used
610 /// like this: %select{foo|bar|baz}2. This means that the integer argument
611 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
612 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
613 /// This is very useful for certain classes of variant diagnostics.
614 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
615  const char *Argument, unsigned ArgumentLen,
616  SmallVectorImpl<char> &OutStr) {
617  const char *ArgumentEnd = Argument+ArgumentLen;
618 
619  // Skip over 'ValNo' |'s.
620  while (ValNo) {
621  const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
622  assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
623  " larger than the number of options in the diagnostic string!");
624  Argument = NextVal+1; // Skip this string.
625  --ValNo;
626  }
627 
628  // Get the end of the value. This is either the } or the |.
629  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
630 
631  // Recursively format the result of the select clause into the output string.
632  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
633 }
634 
635 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
636 /// letter 's' to the string if the value is not 1. This is used in cases like
637 /// this: "you idiot, you have %4 parameter%s4!".
638 static void HandleIntegerSModifier(unsigned ValNo,
639  SmallVectorImpl<char> &OutStr) {
640  if (ValNo != 1)
641  OutStr.push_back('s');
642 }
643 
644 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
645 /// prints the ordinal form of the given integer, with 1 corresponding
646 /// to the first ordinal. Currently this is hard-coded to use the
647 /// English form.
648 static void HandleOrdinalModifier(unsigned ValNo,
649  SmallVectorImpl<char> &OutStr) {
650  assert(ValNo != 0 && "ValNo must be strictly positive!");
651 
652  llvm::raw_svector_ostream Out(OutStr);
653 
654  // We could use text forms for the first N ordinals, but the numeric
655  // forms are actually nicer in diagnostics because they stand out.
656  Out << ValNo << llvm::getOrdinalSuffix(ValNo);
657 }
658 
659 /// PluralNumber - Parse an unsigned integer and advance Start.
660 static unsigned PluralNumber(const char *&Start, const char *End) {
661  // Programming 101: Parse a decimal number :-)
662  unsigned Val = 0;
663  while (Start != End && *Start >= '0' && *Start <= '9') {
664  Val *= 10;
665  Val += *Start - '0';
666  ++Start;
667  }
668  return Val;
669 }
670 
671 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
672 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
673  if (*Start != '[') {
674  unsigned Ref = PluralNumber(Start, End);
675  return Ref == Val;
676  }
677 
678  ++Start;
679  unsigned Low = PluralNumber(Start, End);
680  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
681  ++Start;
682  unsigned High = PluralNumber(Start, End);
683  assert(*Start == ']' && "Bad plural expression syntax: expected )");
684  ++Start;
685  return Low <= Val && Val <= High;
686 }
687 
688 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
689 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
690  // Empty condition?
691  if (*Start == ':')
692  return true;
693 
694  while (true) {
695  char C = *Start;
696  if (C == '%') {
697  // Modulo expression
698  ++Start;
699  unsigned Arg = PluralNumber(Start, End);
700  assert(*Start == '=' && "Bad plural expression syntax: expected =");
701  ++Start;
702  unsigned ValMod = ValNo % Arg;
703  if (TestPluralRange(ValMod, Start, End))
704  return true;
705  } else {
706  assert((C == '[' || (C >= '0' && C <= '9')) &&
707  "Bad plural expression syntax: unexpected character");
708  // Range expression
709  if (TestPluralRange(ValNo, Start, End))
710  return true;
711  }
712 
713  // Scan for next or-expr part.
714  Start = std::find(Start, End, ',');
715  if (Start == End)
716  break;
717  ++Start;
718  }
719  return false;
720 }
721 
722 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
723 /// for complex plural forms, or in languages where all plurals are complex.
724 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
725 /// conditions that are tested in order, the form corresponding to the first
726 /// that applies being emitted. The empty condition is always true, making the
727 /// last form a default case.
728 /// Conditions are simple boolean expressions, where n is the number argument.
729 /// Here are the rules.
730 /// condition := expression | empty
731 /// empty := -> always true
732 /// expression := numeric [',' expression] -> logical or
733 /// numeric := range -> true if n in range
734 /// | '%' number '=' range -> true if n % number in range
735 /// range := number
736 /// | '[' number ',' number ']' -> ranges are inclusive both ends
737 ///
738 /// Here are some examples from the GNU gettext manual written in this form:
739 /// English:
740 /// {1:form0|:form1}
741 /// Latvian:
742 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
743 /// Gaeilge:
744 /// {1:form0|2:form1|:form2}
745 /// Romanian:
746 /// {1:form0|0,%100=[1,19]:form1|:form2}
747 /// Lithuanian:
748 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
749 /// Russian (requires repeated form):
750 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
751 /// Slovak
752 /// {1:form0|[2,4]:form1|:form2}
753 /// Polish (requires repeated form):
754 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
755 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
756  const char *Argument, unsigned ArgumentLen,
757  SmallVectorImpl<char> &OutStr) {
758  const char *ArgumentEnd = Argument + ArgumentLen;
759  while (true) {
760  assert(Argument < ArgumentEnd && "Plural expression didn't match.");
761  const char *ExprEnd = Argument;
762  while (*ExprEnd != ':') {
763  assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
764  ++ExprEnd;
765  }
766  if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
767  Argument = ExprEnd + 1;
768  ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
769 
770  // Recursively format the result of the plural clause into the
771  // output string.
772  DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
773  return;
774  }
775  Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
776  }
777 }
778 
779 /// Returns the friendly description for a token kind that will appear
780 /// without quotes in diagnostic messages. These strings may be translatable in
781 /// future.
783  switch (Kind) {
784  case tok::identifier:
785  return "identifier";
786  default:
787  return nullptr;
788  }
789 }
790 
791 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
792 /// formal arguments into the %0 slots. The result is appended onto the Str
793 /// array.
794 void Diagnostic::
796  if (!StoredDiagMessage.empty()) {
797  OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
798  return;
799  }
800 
801  StringRef Diag =
802  getDiags()->getDiagnosticIDs()->getDescription(getID());
803 
804  FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
805 }
806 
807 /// pushEscapedString - Append Str to the diagnostic buffer,
808 /// escaping non-printable characters and ill-formed code unit sequences.
809 static void pushEscapedString(StringRef Str, SmallVectorImpl<char> &OutStr) {
810  OutStr.reserve(OutStr.size() + Str.size());
811  auto *Begin = reinterpret_cast<const unsigned char *>(Str.data());
812  llvm::raw_svector_ostream OutStream(OutStr);
813  const unsigned char *End = Begin + Str.size();
814  while (Begin != End) {
815  // ASCII case
816  if (isPrintable(*Begin) || isWhitespace(*Begin)) {
817  OutStream << *Begin;
818  ++Begin;
819  continue;
820  }
821  if (llvm::isLegalUTF8Sequence(Begin, End)) {
822  llvm::UTF32 CodepointValue;
823  llvm::UTF32 *CpPtr = &CodepointValue;
824  const unsigned char *CodepointBegin = Begin;
825  const unsigned char *CodepointEnd =
826  Begin + llvm::getNumBytesForUTF8(*Begin);
827  llvm::ConversionResult Res = llvm::ConvertUTF8toUTF32(
828  &Begin, CodepointEnd, &CpPtr, CpPtr + 1, llvm::strictConversion);
829  (void)Res;
830  assert(
831  llvm::conversionOK == Res &&
832  "the sequence is legal UTF-8 but we couldn't convert it to UTF-32");
833  assert(Begin == CodepointEnd &&
834  "we must be further along in the string now");
835  if (llvm::sys::unicode::isPrintable(CodepointValue) ||
836  llvm::sys::unicode::isFormatting(CodepointValue)) {
837  OutStr.append(CodepointBegin, CodepointEnd);
838  continue;
839  }
840  // Unprintable code point.
841  OutStream << "<U+" << llvm::format_hex_no_prefix(CodepointValue, 4, true)
842  << ">";
843  continue;
844  }
845  // Invalid code unit.
846  OutStream << "<" << llvm::format_hex_no_prefix(*Begin, 2, true) << ">";
847  ++Begin;
848  }
849 }
850 
851 void Diagnostic::
852 FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
853  SmallVectorImpl<char> &OutStr) const {
854  // When the diagnostic string is only "%0", the entire string is being given
855  // by an outside source. Remove unprintable characters from this string
856  // and skip all the other string processing.
857  if (DiagEnd - DiagStr == 2 &&
858  StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
860  const std::string &S = getArgStdStr(0);
861  pushEscapedString(S, OutStr);
862  return;
863  }
864 
865  /// FormattedArgs - Keep track of all of the arguments formatted by
866  /// ConvertArgToString and pass them into subsequent calls to
867  /// ConvertArgToString, allowing the implementation to avoid redundancies in
868  /// obvious cases.
870 
871  /// QualTypeVals - Pass a vector of arrays so that QualType names can be
872  /// compared to see if more information is needed to be printed.
873  SmallVector<intptr_t, 2> QualTypeVals;
875 
876  for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
878  QualTypeVals.push_back(getRawArg(i));
879 
880  while (DiagStr != DiagEnd) {
881  if (DiagStr[0] != '%') {
882  // Append non-%0 substrings to Str if we have one.
883  const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
884  OutStr.append(DiagStr, StrEnd);
885  DiagStr = StrEnd;
886  continue;
887  } else if (isPunctuation(DiagStr[1])) {
888  OutStr.push_back(DiagStr[1]); // %% -> %.
889  DiagStr += 2;
890  continue;
891  }
892 
893  // Skip the %.
894  ++DiagStr;
895 
896  // This must be a placeholder for a diagnostic argument. The format for a
897  // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
898  // The digit is a number from 0-9 indicating which argument this comes from.
899  // The modifier is a string of digits from the set [-a-z]+, arguments is a
900  // brace enclosed string.
901  const char *Modifier = nullptr, *Argument = nullptr;
902  unsigned ModifierLen = 0, ArgumentLen = 0;
903 
904  // Check to see if we have a modifier. If so eat it.
905  if (!isDigit(DiagStr[0])) {
906  Modifier = DiagStr;
907  while (DiagStr[0] == '-' ||
908  (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
909  ++DiagStr;
910  ModifierLen = DiagStr-Modifier;
911 
912  // If we have an argument, get it next.
913  if (DiagStr[0] == '{') {
914  ++DiagStr; // Skip {.
915  Argument = DiagStr;
916 
917  DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
918  assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
919  ArgumentLen = DiagStr-Argument;
920  ++DiagStr; // Skip }.
921  }
922  }
923 
924  assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
925  unsigned ArgNo = *DiagStr++ - '0';
926 
927  // Only used for type diffing.
928  unsigned ArgNo2 = ArgNo;
929 
931  if (ModifierIs(Modifier, ModifierLen, "diff")) {
932  assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
933  "Invalid format for diff modifier");
934  ++DiagStr; // Comma.
935  ArgNo2 = *DiagStr++ - '0';
940  else {
941  // %diff only supports QualTypes. For other kinds of arguments,
942  // use the default printing. For example, if the modifier is:
943  // "%diff{compare $ to $|other text}1,2"
944  // treat it as:
945  // "compare %1 to %2"
946  const char *ArgumentEnd = Argument + ArgumentLen;
947  const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
948  assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
949  "Found too many '|'s in a %diff modifier!");
950  const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
951  const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
952  const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
953  const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
954  FormatDiagnostic(Argument, FirstDollar, OutStr);
955  FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
956  FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
957  FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
958  FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
959  continue;
960  }
961  }
962 
963  switch (Kind) {
964  // ---- STRINGS ----
966  const std::string &S = getArgStdStr(ArgNo);
967  assert(ModifierLen == 0 && "No modifiers for strings yet");
968  pushEscapedString(S, OutStr);
969  break;
970  }
972  const char *S = getArgCStr(ArgNo);
973  assert(ModifierLen == 0 && "No modifiers for strings yet");
974 
975  // Don't crash if get passed a null pointer by accident.
976  if (!S)
977  S = "(null)";
978  pushEscapedString(S, OutStr);
979  break;
980  }
981  // ---- INTEGERS ----
983  int64_t Val = getArgSInt(ArgNo);
984 
985  if (ModifierIs(Modifier, ModifierLen, "select")) {
986  HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
987  OutStr);
988  } else if (ModifierIs(Modifier, ModifierLen, "s")) {
989  HandleIntegerSModifier(Val, OutStr);
990  } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
991  HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
992  OutStr);
993  } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
994  HandleOrdinalModifier((unsigned)Val, OutStr);
995  } else {
996  assert(ModifierLen == 0 && "Unknown integer modifier");
997  llvm::raw_svector_ostream(OutStr) << Val;
998  }
999  break;
1000  }
1002  uint64_t Val = getArgUInt(ArgNo);
1003 
1004  if (ModifierIs(Modifier, ModifierLen, "select")) {
1005  HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
1006  } else if (ModifierIs(Modifier, ModifierLen, "s")) {
1007  HandleIntegerSModifier(Val, OutStr);
1008  } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
1009  HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
1010  OutStr);
1011  } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
1012  HandleOrdinalModifier(Val, OutStr);
1013  } else {
1014  assert(ModifierLen == 0 && "Unknown integer modifier");
1015  llvm::raw_svector_ostream(OutStr) << Val;
1016  }
1017  break;
1018  }
1019  // ---- TOKEN SPELLINGS ----
1021  tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
1022  assert(ModifierLen == 0 && "No modifiers for token kinds yet");
1023 
1024  llvm::raw_svector_ostream Out(OutStr);
1025  if (const char *S = tok::getPunctuatorSpelling(Kind))
1026  // Quoted token spelling for punctuators.
1027  Out << '\'' << S << '\'';
1028  else if ((S = tok::getKeywordSpelling(Kind)))
1029  // Unquoted token spelling for keywords.
1030  Out << S;
1031  else if ((S = getTokenDescForDiagnostic(Kind)))
1032  // Unquoted translatable token name.
1033  Out << S;
1034  else if ((S = tok::getTokenName(Kind)))
1035  // Debug name, shouldn't appear in user-facing diagnostics.
1036  Out << '<' << S << '>';
1037  else
1038  Out << "(null)";
1039  break;
1040  }
1041  // ---- NAMES and TYPES ----
1042  case DiagnosticsEngine::ak_identifierinfo: {
1043  const IdentifierInfo *II = getArgIdentifier(ArgNo);
1044  assert(ModifierLen == 0 && "No modifiers for strings yet");
1045 
1046  // Don't crash if get passed a null pointer by accident.
1047  if (!II) {
1048  const char *S = "(null)";
1049  OutStr.append(S, S + strlen(S));
1050  continue;
1051  }
1052 
1053  llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
1054  break;
1055  }
1065  StringRef(Modifier, ModifierLen),
1066  StringRef(Argument, ArgumentLen),
1067  FormattedArgs,
1068  OutStr, QualTypeVals);
1069  break;
1071  // Create a struct with all the info needed for printing.
1072  TemplateDiffTypes TDT;
1073  TDT.FromType = getRawArg(ArgNo);
1074  TDT.ToType = getRawArg(ArgNo2);
1075  TDT.ElideType = getDiags()->ElideType;
1076  TDT.ShowColors = getDiags()->ShowColors;
1077  TDT.TemplateDiffUsed = false;
1078  intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1079 
1080  const char *ArgumentEnd = Argument + ArgumentLen;
1081  const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1082 
1083  // Print the tree. If this diagnostic already has a tree, skip the
1084  // second tree.
1085  if (getDiags()->PrintTemplateTree && Tree.empty()) {
1086  TDT.PrintFromType = true;
1087  TDT.PrintTree = true;
1089  StringRef(Modifier, ModifierLen),
1090  StringRef(Argument, ArgumentLen),
1091  FormattedArgs,
1092  Tree, QualTypeVals);
1093  // If there is no tree information, fall back to regular printing.
1094  if (!Tree.empty()) {
1095  FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1096  break;
1097  }
1098  }
1099 
1100  // Non-tree printing, also the fall-back when tree printing fails.
1101  // The fall-back is triggered when the types compared are not templates.
1102  const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1103  const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1104 
1105  // Append before text
1106  FormatDiagnostic(Argument, FirstDollar, OutStr);
1107 
1108  // Append first type
1109  TDT.PrintTree = false;
1110  TDT.PrintFromType = true;
1112  StringRef(Modifier, ModifierLen),
1113  StringRef(Argument, ArgumentLen),
1114  FormattedArgs,
1115  OutStr, QualTypeVals);
1116  if (!TDT.TemplateDiffUsed)
1117  FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1118  TDT.FromType));
1119 
1120  // Append middle text
1121  FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1122 
1123  // Append second type
1124  TDT.PrintFromType = false;
1126  StringRef(Modifier, ModifierLen),
1127  StringRef(Argument, ArgumentLen),
1128  FormattedArgs,
1129  OutStr, QualTypeVals);
1130  if (!TDT.TemplateDiffUsed)
1131  FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1132  TDT.ToType));
1133 
1134  // Append end text
1135  FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1136  break;
1137  }
1138  }
1139 
1140  // Remember this argument info for subsequent formatting operations. Turn
1141  // std::strings into a null terminated string to make it be the same case as
1142  // all the other ones.
1144  continue;
1146  FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1147  else
1148  FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
1149  (intptr_t)getArgStdStr(ArgNo).c_str()));
1150  }
1151 
1152  // Append the type tree to the end of the diagnostics.
1153  OutStr.append(Tree.begin(), Tree.end());
1154 }
1155 
1157  StringRef Message)
1158  : ID(ID), Level(Level), Message(Message) {}
1159 
1161  const Diagnostic &Info)
1162  : ID(Info.getID()), Level(Level) {
1163  assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1164  "Valid source location without setting a source manager for diagnostic");
1165  if (Info.getLocation().isValid())
1166  Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1167  SmallString<64> Message;
1168  Info.FormatDiagnostic(Message);
1169  this->Message.assign(Message.begin(), Message.end());
1170  this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1171  this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1172 }
1173 
1175  StringRef Message, FullSourceLoc Loc,
1177  ArrayRef<FixItHint> FixIts)
1178  : ID(ID), Level(Level), Loc(Loc), Message(Message),
1179  Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1180 {
1181 }
1182 
1183 llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
1184  const StoredDiagnostic &SD) {
1185  if (SD.getLocation().hasManager())
1186  OS << SD.getLocation().printToString(SD.getLocation().getManager()) << ": ";
1187  OS << SD.getMessage();
1188  return OS;
1189 }
1190 
1191 /// IncludeInDiagnosticCounts - This method (whose default implementation
1192 /// returns true) indicates whether the diagnostics handled by this
1193 /// DiagnosticConsumer should be included in the number of diagnostics
1194 /// reported by DiagnosticsEngine.
1196 
1197 void IgnoringDiagConsumer::anchor() {}
1198 
1200 
1202  DiagnosticsEngine::Level DiagLevel,
1203  const Diagnostic &Info) {
1204  Target.HandleDiagnostic(DiagLevel, Info);
1205 }
1206 
1209  Target.clear();
1210 }
1211 
1213  return Target.IncludeInDiagnosticCounts();
1214 }
1215 
1217  for (unsigned I = 0; I != NumCached; ++I)
1218  FreeList[I] = Cached + I;
1219  NumFreeListEntries = NumCached;
1220 }
1221 
1223  // Don't assert if we are in a CrashRecovery context, as this invariant may
1224  // be invalidated during a crash.
1225  assert((NumFreeListEntries == NumCached ||
1226  llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1227  "A partial is on the lam");
1228 }
1229 
1230 char DiagnosticError::ID;
clang::DiagnosticsEngine::Level
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:195
clang::diag::Severity
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:82
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::FullSourceLoc::getManager
const SourceManager & getManager() const
Definition: SourceLocation.h:382
clang::FullSourceLoc::hasManager
bool hasManager() const
Checks whether the SourceManager is present.
Definition: SourceLocation.h:379
clang::threadSafety::sx::equals
bool equals(const til::SExpr *E1, const til::SExpr *E2)
Definition: ThreadSafetyCommon.h:64
clang::DiagnosticsEngine::ak_qual
@ ak_qual
Qualifiers.
Definition: Diagnostic.h:227
clang::DiagnosticIDs::getAllDiagnostics
static void getAllDiagnostics(diag::Flavor Flavor, std::vector< diag::kind > &Diags)
Get the set of all diagnostic IDs.
Definition: DiagnosticIDs.cpp:712
clang::isPrintable
LLVM_READONLY bool isPrintable(unsigned char c)
Return true if this character is an ASCII printable character; that is, a character that should take ...
Definition: CharInfo.h:145
Specifiers.h
clang::diag::Severity::Error
@ Error
Present this diagnostic as an error.
clang::FullSourceLoc
A SourceLocation and its associated SourceManager.
Definition: SourceLocation.h:368
clang::DeclaratorContext::File
@ File
clang::DiagnosticsEngine::setSeverity
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
Definition: Diagnostic.cpp:358
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::DiagnosticsEngine::setClient
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:112
clang::Diagnostic::getArgStdStr
const std::string & getArgStdStr(unsigned Idx) const
Return the provided argument string specified by Idx.
Definition: Diagnostic.h:1592
clang::TemplateDiffTypes::TemplateDiffUsed
unsigned TemplateDiffUsed
Definition: Diagnostic.h:1830
clang::DiagnosticsEngine::popMappings
bool popMappings(SourceLocation Loc)
Pops the current DiagMappings off the top of the stack, causing the new top of the stack to be the ac...
Definition: Diagnostic.cpp:122
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:79
llvm::SmallVector
Definition: LLVM.h:38
clang::DiagnosticsEngine::setDiagnosticGroupErrorAsFatal
bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled)
Set the error-as-fatal flag for the given diagnostic group.
Definition: Diagnostic.cpp:459
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::StoredDiagnostic::StoredDiagnostic
StoredDiagnostic()=default
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
HandleSelectModifier
static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl< char > &OutStr)
HandleSelectModifier - Handle the integer 'select' modifier.
Definition: Diagnostic.cpp:614
clang::MultiVersionKind::Target
@ Target
clang::DiagnosticConsumer
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1739
clang::DiagnosticConsumer::NumErrors
unsigned NumErrors
Number of errors reported.
Definition: Diagnostic.h:1742
clang::tok::getPunctuatorSpelling
const char * getPunctuatorSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple punctuation tokens like '!' or '', and returns NULL for literal and...
Definition: TokenKinds.cpp:31
clang::diag::Severity::Remark
@ Remark
Present this diagnostic as a remark.
clang::Diagnostic::getRawArg
uint64_t getRawArg(unsigned Idx) const
Return the specified non-string argument in an opaque form.
Definition: Diagnostic.h:1634
clang::DiagnosticMapping::hasNoWarningAsError
bool hasNoWarningAsError() const
Definition: DiagnosticIDs.h:133
clang::DiagnosticIDs::Level
Level
The level of the diagnostic, after it has been through mapping.
Definition: DiagnosticIDs.h:169
SourceManager.h
clang::TemplateDiffTypes::ToType
intptr_t ToType
Definition: Diagnostic.h:1823
DiagnosticError.h
clang::DiagnosticsEngine::Reset
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Definition: Diagnostic.cpp:134
clang::DiagnosticsEngine::setSeverityForGroup
bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc=SourceLocation())
Change an entire diagnostic group (e.g.
Definition: Diagnostic.cpp:405
clang::StoredDiagnostic::getMessage
StringRef getMessage() const
Definition: Diagnostic.h:1709
clang::isPunctuation
LLVM_READONLY bool isPunctuation(unsigned char c)
Return true if this character is an ASCII punctuation character.
Definition: CharInfo.h:137
DiagnosticIDs.h
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
clang::Diagnostic::getDiags
const DiagnosticsEngine * getDiags() const
Definition: Diagnostic.h:1570
HandleOrdinalModifier
static void HandleOrdinalModifier(unsigned ValNo, SmallVectorImpl< char > &OutStr)
HandleOrdinalModifier - Handle the integer 'ord' modifier.
Definition: Diagnostic.cpp:648
clang::DiagnosticMapping::setUpgradedFromWarning
void setUpgradedFromWarning(bool Value)
Definition: DiagnosticIDs.h:143
End
SourceLocation End
Definition: USRLocFinder.cpp:167
getTokenDescForDiagnostic
static const char * getTokenDescForDiagnostic(tok::TokenKind Kind)
Returns the friendly description for a token kind that will appear without quotes in diagnostic messa...
Definition: Diagnostic.cpp:782
clang::StoredDiagnostic::getID
unsigned getID() const
Definition: Diagnostic.h:1706
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:627
clang::DiagnosticStorage::DiagRanges
SmallVector< CharSourceRange, 8 > DiagRanges
The list of ranges added to this diagnostic.
Definition: Diagnostic.h:177
Offset
unsigned Offset
Definition: Format.cpp:2590
pushEscapedString
static void pushEscapedString(StringRef Str, SmallVectorImpl< char > &OutStr)
pushEscapedString - Append Str to the diagnostic buffer, escaping non-printable characters and ill-fo...
Definition: Diagnostic.cpp:809
uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:24
clang::Diagnostic
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1561
clang::TemplateDiffTypes
Definition: Diagnostic.h:1821
TokenKinds.h
clang::DiagnosticConsumer::NumWarnings
unsigned NumWarnings
Number of warnings reported.
Definition: Diagnostic.h:1741
clang::DiagnosticsEngine::setDiagnosticGroupWarningAsError
bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled)
Set the warning-as-error flag for the given diagnostic group.
Definition: Diagnostic.cpp:428
clang::diag::Severity::Ignored
@ Ignored
Do not present this diagnostic, ignore it.
clang::DiagnosticConsumer::HandleDiagnostic
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Definition: Diagnostic.cpp:564
clang::DiagnosticsEngine::ArgumentKind
ArgumentKind
Definition: Diagnostic.h:204
clang::StoredDiagnostic::range_begin
range_iterator range_begin() const
Definition: Diagnostic.h:1715
clang::SourceLocation::print
void print(raw_ostream &OS, const SourceManager &SM) const
Definition: SourceLocation.cpp:62
clang::ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts
bool IncludeInDiagnosticCounts() const override
Indicates whether the diagnostics handled by this DiagnosticConsumer should be included in the number...
Definition: Diagnostic.cpp:1212
clang::diag::Flavor::WarningOrError
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
EvalPluralExpr
static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End)
EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Definition: Diagnostic.cpp:689
clang::TemplateDiffTypes::FromType
intptr_t FromType
Definition: Diagnostic.h:1822
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:90
clang::diag::Severity::Fatal
@ Fatal
Present this diagnostic as a fatal error.
clang::StreamingDiagnostic
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1110
clang::DiagnosticsEngine::Clear
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:977
Diagnostic.h
clang::DiagnosticsEngine::EmitCurrentDiagnostic
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:530
clang::Diagnostic::getNumArgs
unsigned getNumArgs() const
Definition: Diagnostic.h:1576
Depth
int Depth
Definition: ASTDiff.cpp:191
clang::DiagnosticMapping
Definition: DiagnosticIDs.h:101
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
clang::Diagnostic::getArgCStr
const char * getArgCStr(unsigned Idx) const
Return the specified C string argument.
Definition: Diagnostic.h:1600
intptr_t
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
Definition: opencl-c-base.h:133
clang::DiagnosticsEngine::ak_attr
@ ak_attr
Attr *.
Definition: Diagnostic.h:248
clang::DiagnosticsEngine::getDiagnosticIDs
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:552
clang::DiagNullabilityKind
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1532
IdentifierTable.h
clang::DiagnosticsEngine::getClient
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:567
clang::tok::getTokenName
const char * getTokenName(TokenKind Kind) LLVM_READNONE
Determines the name of a token as used within the front end.
Definition: TokenKinds.cpp:24
llvm::SmallString
Definition: LLVM.h:37
clang::DiagnosticsEngine::ak_qualtype_pair
@ ak_qualtype_pair
pair<QualType, QualType>
Definition: Diagnostic.h:245
clang::DiagnosticsEngine::ak_sint
@ ak_sint
int
Definition: Diagnostic.h:212
clang::StoredDiagnostic::range_end
range_iterator range_end() const
Definition: Diagnostic.h:1716
clang::diag::DIAG_UPPER_LIMIT
@ DIAG_UPPER_LIMIT
Definition: DiagnosticIDs.h:59
clang::Diagnostic::getArgUInt
uint64_t getArgUInt(unsigned Idx) const
Return the specified unsigned integer argument.
Definition: Diagnostic.h:1617
clang::operator<<
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Definition: ASTContext.cpp:13331
clang::DiagnosticConsumer::~DiagnosticConsumer
virtual ~DiagnosticConsumer()
clang::DiagnosticsEngine::ak_tokenkind
@ ak_tokenkind
enum TokenKind : unsigned
Definition: Diagnostic.h:218
clang::DiagnosticConsumer::IncludeInDiagnosticCounts
virtual bool IncludeInDiagnosticCounts() const
Indicates whether the diagnostics handled by this DiagnosticConsumer should be included in the number...
Definition: Diagnostic.cpp:1195
clang::SourceManager::getDecomposedLoc
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1241
clang::StreamingDiagnostic::DiagStorageAllocator::DiagStorageAllocator
DiagStorageAllocator()
clang::Diagnostic::getArgSInt
int64_t getArgSInt(unsigned Idx) const
Return the specified signed integer argument.
Definition: Diagnostic.h:1609
clang::StoredDiagnostic
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
Definition: Diagnostic.h:1685
clang::SourceManager::getLocForStartOfFile
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Definition: SourceManager.h:1123
clang::diag::Severity::Warning
@ Warning
Present this diagnostic as a warning.
clang::transformer::EditKind::Range
@ Range
clang::DiagnosticsEngine::ak_declarationname
@ ak_declarationname
DeclarationName.
Definition: Diagnostic.h:233
clang::DiagnosticMapping::getSeverity
diag::Severity getSeverity() const
Definition: DiagnosticIDs.h:122
clang::isWhitespace
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:93
ScanFormat
static const char * ScanFormat(const char *I, const char *E, char Target)
ScanForward - Scans forward, looking for the given character, skipping nested clauses and escaped cha...
Definition: Diagnostic.cpp:584
clang::TypeSpecifiersPipe::Pipe
@ Pipe
SourceLocation.h
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::DiagnosticsEngine::~DiagnosticsEngine
~DiagnosticsEngine()
Definition: Diagnostic.cpp:98
clang::StoredDiagnostic::getLocation
const FullSourceLoc & getLocation() const
Definition: Diagnostic.h:1708
CharInfo.h
clang::NullabilityKind::Unspecified
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
clang::Diagnostic::getLocation
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1572
dump
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Definition: CoverageMappingGen.cpp:1539
clang::ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer
~ForwardingDiagnosticConsumer() override
clang::tok::getKeywordSpelling
const char * getKeywordSpelling(TokenKind Kind) LLVM_READNONE
Determines the spelling of simple keyword and contextual keyword tokens like 'int' and 'dynamic_cast'...
Definition: TokenKinds.cpp:40
Begin
SourceLocation Begin
Definition: USRLocFinder.cpp:165
llvm::ArrayRef
Definition: LLVM.h:34
clang::StreamingDiagnostic::AddString
void AddString(StringRef V) const
Definition: Diagnostic.h:1194
clang::StreamingDiagnostic::DiagStorageAllocator::~DiagStorageAllocator
~DiagStorageAllocator()
clang::Diagnostic::getFixItHints
ArrayRef< FixItHint > getFixItHints() const
Definition: Diagnostic.h:1665
HandleIntegerSModifier
static void HandleIntegerSModifier(unsigned ValNo, SmallVectorImpl< char > &OutStr)
HandleIntegerSModifier - Handle the integer 's' modifier.
Definition: Diagnostic.cpp:638
clang::DiagnosticsEngine::ak_nameddecl
@ ak_nameddecl
NamedDecl *.
Definition: Diagnostic.h:236
clang::StoredDiagnostic::fixit_end
fixit_iterator fixit_end() const
Definition: Diagnostic.h:1726
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1139
clang::ForwardingDiagnosticConsumer::HandleDiagnostic
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
Definition: Diagnostic.cpp:1201
DummyArgToStringFn
static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
Definition: Diagnostic.cpp:77
clang::Diagnostic::getSourceManager
SourceManager & getSourceManager() const
Definition: Diagnostic.h:1574
clang::StoredDiagnostic::getLevel
DiagnosticsEngine::Level getLevel() const
Definition: Diagnostic.h:1707
clang::diag::Flavor
Flavor
Flavors of diagnostics we can emit.
Definition: DiagnosticIDs.h:93
clang::DiagnosticMapping::setNoErrorAsFatal
void setNoErrorAsFatal(bool Value)
Definition: DiagnosticIDs.h:137
clang::DiagnosticMapping::setSeverity
void setSeverity(diag::Severity Value)
Definition: DiagnosticIDs.h:123
clang::DiagnosticsEngine::DiagnosticsEngine
DiagnosticsEngine(IntrusiveRefCntPtr< DiagnosticIDs > Diags, IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, DiagnosticConsumer *client=nullptr, bool ShouldOwnClient=true)
Definition: Diagnostic.cpp:87
clang::Diagnostic::getArgKind
DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const
Return the kind of the specified index.
Definition: Diagnostic.h:1584
clang::DiagnosticsEngine::ak_addrspace
@ ak_addrspace
address space
Definition: Diagnostic.h:224
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
int64_t
long int64_t
Definition: hlsl_basic_types.h:25
std
Definition: Format.h:4321
clang::DiagnosticsEngine::dump
LLVM_DUMP_METHOD void dump() const
Definition: Diagnostic.cpp:104
clang::Builtin::ID
ID
Definition: Builtins.h:52
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::DiagnosticsEngine::ConvertArgToString
void ConvertArgToString(ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, ArrayRef< intptr_t > QualTypeVals) const
Converts a diagnostic argument (as an intptr_t) into the string that represents it.
Definition: Diagnostic.h:875
ModifierIs
static bool ModifierIs(const char *Modifier, unsigned ModifierLen, const char(&Str)[StrLen])
ModifierIs - Return true if the specified modifier matches specified string.
Definition: Diagnostic.cpp:577
PartialDiagnostic.h
clang
Definition: CalledOnceCheck.h:17
clang::DiagnosticsEngine::ak_uint
@ ak_uint
unsigned
Definition: Diagnostic.h:215
clang::SourceManager::getDecomposedIncludedLoc
std::pair< FileID, unsigned > getDecomposedIncludedLoc(FileID FID) const
Returns the "included/expanded in" decomposed location of the given FileID.
Definition: SourceManager.cpp:1946
clang::Diagnostic::getRanges
ArrayRef< CharSourceRange > getRanges() const
Return an array reference for this diagnostic's ranges.
Definition: Diagnostic.h:1652
clang::DiagnosticsEngine::ak_c_string
@ ak_c_string
const char *
Definition: Diagnostic.h:209
clang::ComparisonCategoryType::Last
@ Last
clang::DiagnosticIDs::Ignored
@ Ignored
Definition: DiagnosticIDs.h:170
clang::DiagnosticError::ID
static char ID
Definition: DiagnosticError.h:47
clang::DiagnosticsEngine::SetDelayedDiagnostic
void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1="", StringRef Arg2="", StringRef Arg3="")
Set the "delayed" diagnostic that will be emitted once the current diagnostic completes.
Definition: Diagnostic.cpp:162
clang::DiagnosticStorage::NumDiagArgs
unsigned char NumDiagArgs
The number of entries in Arguments.
Definition: Diagnostic.h:159
clang::isDigit
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:99
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::NullabilityKind::NullableResult
@ NullableResult
clang::DiagnosticConsumer::clear
virtual void clear()
Definition: Diagnostic.h:1750
unsigned
clang::ForwardingDiagnosticConsumer::clear
void clear() override
Definition: Diagnostic.cpp:1207
clang::NullabilityKind::Nullable
@ Nullable
Values of this type can be null.
DiagnosticOptions.h
clang::DiagnosticsEngine::setSeverityForAll
void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map, SourceLocation Loc=SourceLocation())
Add the specified mapping to all diagnostics of the specified flavor.
Definition: Diagnostic.cpp:489
clang::Diagnostic::hasSourceManager
bool hasSourceManager() const
Definition: Diagnostic.h:1573
clang::DiagnosticsEngine::pushMappings
void pushMappings(SourceLocation Loc)
Copies the current DiagMappings and pushes the new copy onto the top of the stack.
Definition: Diagnostic.cpp:118
clang::TemplateDiffTypes::PrintFromType
unsigned PrintFromType
Definition: Diagnostic.h:1825
clang::TemplateDiffTypes::ShowColors
unsigned ShowColors
Definition: Diagnostic.h:1827
Tree
SyntaxTree::Impl & Tree
Definition: ASTDiff.cpp:193
clang::Diagnostic::getID
unsigned getID() const
Definition: Diagnostic.h:1571
llvm::SmallVectorImpl< char >
clang::TemplateDiffTypes::ElideType
unsigned ElideType
Definition: Diagnostic.h:1826
clang::TemplateDiffTypes::PrintTree
unsigned PrintTree
Definition: Diagnostic.h:1824
TestPluralRange
static bool TestPluralRange(unsigned Val, const char *&Start, const char *End)
TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Definition: Diagnostic.cpp:672
clang::DiagnosticMapping::setNoWarningAsError
void setNoWarningAsError(bool Value)
Definition: DiagnosticIDs.h:134
clang::DiagnosticsEngine::ak_qualtype
@ ak_qualtype
QualType.
Definition: Diagnostic.h:230
clang::Diagnostic::FormatDiagnostic
void FormatDiagnostic(SmallVectorImpl< char > &OutStr) const
Format this diagnostic into a string, substituting the formal arguments into the %0 slots.
Definition: Diagnostic.cpp:795
clang::DiagnosticsEngine::Warning
@ Warning
Definition: Diagnostic.h:199
clang::NullabilityKind::NonNull
@ NonNull
Values of this type can never be null.
clang::SourceManager::getBufferOrFake
llvm::MemoryBufferRef getBufferOrFake(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
Definition: SourceManager.h:1028
clang::DiagnosticsEngine::ak_std_string
@ ak_std_string
std::string
Definition: Diagnostic.h:206
clang::DiagnosticsEngine::ak_declcontext
@ ak_declcontext
DeclContext *.
Definition: Diagnostic.h:242
clang::DiagnosticStorage::FixItHints
SmallVector< FixItHint, 6 > FixItHints
If valid, provides a hint with some code to insert, remove, or modify at a particular position.
Definition: Diagnostic.h:181
clang::DiagnosticIDs::getWarningOptionForDiag
static StringRef getWarningOptionForDiag(unsigned DiagID)
Return the lowest-level warning option that enables the specified diagnostic.
Definition: DiagnosticIDs.cpp:655
HandlePluralModifier
static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl< char > &OutStr)
HandlePluralModifier - Handle the integer 'plural' modifier.
Definition: Diagnostic.cpp:755
llvm::IntrusiveRefCntPtr
Definition: LLVM.h:47
clang::StoredDiagnostic::fixit_begin
fixit_iterator fixit_begin() const
Definition: Diagnostic.h:1725
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
PluralNumber
static unsigned PluralNumber(const char *&Start, const char *End)
PluralNumber - Parse an unsigned integer and advance Start.
Definition: Diagnostic.cpp:660
clang::SourceLocation::printToString
std::string printToString(const SourceManager &SM) const
Definition: SourceLocation.cpp:89
clang::DiagnosticsEngine::ak_nestednamespec
@ ak_nestednamespec
NestedNameSpecifier *.
Definition: Diagnostic.h:239