clang  14.0.0git
VerifyDiagnosticConsumer.cpp
Go to the documentation of this file.
1 //===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===//
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 is a concrete diagnostic client, which buffers the diagnostic messages.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/TokenKinds.h"
24 #include "clang/Lex/HeaderSearch.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Lex/PPCallbacks.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Lex/Token.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Regex.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstring>
41 #include <iterator>
42 #include <memory>
43 #include <string>
44 #include <utility>
45 #include <vector>
46 
47 using namespace clang;
48 
52 
53 #ifndef NDEBUG
54 
55 namespace {
56 
57 class VerifyFileTracker : public PPCallbacks {
60 
61 public:
62  VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
63  : Verify(Verify), SM(SM) {}
64 
65  /// Hook into the preprocessor and update the list of parsed
66  /// files when the preprocessor indicates a new file is entered.
67  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
69  FileID PrevFID) override {
70  Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
72  }
73 };
74 
75 } // namespace
76 
77 #endif
78 
79 //===----------------------------------------------------------------------===//
80 // Checking diagnostics implementation.
81 //===----------------------------------------------------------------------===//
82 
85 
86 namespace {
87 
88 /// StandardDirective - Directive with string matching.
89 class StandardDirective : public Directive {
90 public:
91  StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
92  bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
93  unsigned Min, unsigned Max)
94  : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
95  MatchAnyLine, Text, Min, Max) {}
96 
97  bool isValid(std::string &Error) override {
98  // all strings are considered valid; even empty ones
99  return true;
100  }
101 
102  bool match(StringRef S) override { return S.contains(Text); }
103 };
104 
105 /// RegexDirective - Directive with regular-expression matching.
106 class RegexDirective : public Directive {
107 public:
108  RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
109  bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
110  unsigned Min, unsigned Max, StringRef RegexStr)
111  : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
112  MatchAnyLine, Text, Min, Max),
113  Regex(RegexStr) {}
114 
115  bool isValid(std::string &Error) override {
116  return Regex.isValid(Error);
117  }
118 
119  bool match(StringRef S) override {
120  return Regex.match(S);
121  }
122 
123 private:
124  llvm::Regex Regex;
125 };
126 
127 class ParseHelper
128 {
129 public:
130  ParseHelper(StringRef S)
131  : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {}
132 
133  // Return true if string literal is next.
134  bool Next(StringRef S) {
135  P = C;
136  PEnd = C + S.size();
137  if (PEnd > End)
138  return false;
139  return memcmp(P, S.data(), S.size()) == 0;
140  }
141 
142  // Return true if number is next.
143  // Output N only if number is next.
144  bool Next(unsigned &N) {
145  unsigned TMP = 0;
146  P = C;
147  PEnd = P;
148  for (; PEnd < End && *PEnd >= '0' && *PEnd <= '9'; ++PEnd) {
149  TMP *= 10;
150  TMP += *PEnd - '0';
151  }
152  if (PEnd == C)
153  return false;
154  N = TMP;
155  return true;
156  }
157 
158  // Return true if a marker is next.
159  // A marker is the longest match for /#[A-Za-z0-9_-]+/.
160  bool NextMarker() {
161  P = C;
162  if (P == End || *P != '#')
163  return false;
164  PEnd = P;
165  ++PEnd;
166  while ((isAlphanumeric(*PEnd) || *PEnd == '-' || *PEnd == '_') &&
167  PEnd < End)
168  ++PEnd;
169  return PEnd > P + 1;
170  }
171 
172  // Return true if string literal S is matched in content.
173  // When true, P marks begin-position of the match, and calling Advance sets C
174  // to end-position of the match.
175  // If S is the empty string, then search for any letter instead (makes sense
176  // with FinishDirectiveToken=true).
177  // If EnsureStartOfWord, then skip matches that don't start a new word.
178  // If FinishDirectiveToken, then assume the match is the start of a comment
179  // directive for -verify, and extend the match to include the entire first
180  // token of that directive.
181  bool Search(StringRef S, bool EnsureStartOfWord = false,
182  bool FinishDirectiveToken = false) {
183  do {
184  if (!S.empty()) {
185  P = std::search(C, End, S.begin(), S.end());
186  PEnd = P + S.size();
187  }
188  else {
189  P = C;
190  while (P != End && !isLetter(*P))
191  ++P;
192  PEnd = P + 1;
193  }
194  if (P == End)
195  break;
196  // If not start of word but required, skip and search again.
197  if (EnsureStartOfWord
198  // Check if string literal starts a new word.
199  && !(P == Begin || isWhitespace(P[-1])
200  // Or it could be preceded by the start of a comment.
201  || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
202  && P[-2] == '/')))
203  continue;
204  if (FinishDirectiveToken) {
205  while (PEnd != End && (isAlphanumeric(*PEnd)
206  || *PEnd == '-' || *PEnd == '_'))
207  ++PEnd;
208  // Put back trailing digits and hyphens to be parsed later as a count
209  // or count range. Because -verify prefixes must start with letters,
210  // we know the actual directive we found starts with a letter, so
211  // we won't put back the entire directive word and thus record an empty
212  // string.
213  assert(isLetter(*P) && "-verify prefix must start with a letter");
214  while (isDigit(PEnd[-1]) || PEnd[-1] == '-')
215  --PEnd;
216  }
217  return true;
218  } while (Advance());
219  return false;
220  }
221 
222  // Return true if a CloseBrace that closes the OpenBrace at the current nest
223  // level is found. When true, P marks begin-position of CloseBrace.
224  bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
225  unsigned Depth = 1;
226  P = C;
227  while (P < End) {
228  StringRef S(P, End - P);
229  if (S.startswith(OpenBrace)) {
230  ++Depth;
231  P += OpenBrace.size();
232  } else if (S.startswith(CloseBrace)) {
233  --Depth;
234  if (Depth == 0) {
235  PEnd = P + CloseBrace.size();
236  return true;
237  }
238  P += CloseBrace.size();
239  } else {
240  ++P;
241  }
242  }
243  return false;
244  }
245 
246  // Advance 1-past previous next/search.
247  // Behavior is undefined if previous next/search failed.
248  bool Advance() {
249  C = PEnd;
250  return C < End;
251  }
252 
253  // Return the text matched by the previous next/search.
254  // Behavior is undefined if previous next/search failed.
255  StringRef Match() { return StringRef(P, PEnd - P); }
256 
257  // Skip zero or more whitespace.
258  void SkipWhitespace() {
259  for (; C < End && isWhitespace(*C); ++C)
260  ;
261  }
262 
263  // Return true if EOF reached.
264  bool Done() {
265  return !(C < End);
266  }
267 
268  // Beginning of expected content.
269  const char * const Begin;
270 
271  // End of expected content (1-past).
272  const char * const End;
273 
274  // Position of next char in content.
275  const char *C;
276 
277  // Previous next/search subject start.
278  const char *P;
279 
280 private:
281  // Previous next/search subject end (1-past).
282  const char *PEnd = nullptr;
283 };
284 
285 // The information necessary to create a directive.
286 struct UnattachedDirective {
287  DirectiveList *DL = nullptr;
288  bool RegexKind = false;
289  SourceLocation DirectivePos, ContentBegin;
291  unsigned Min = 1, Max = 1;
292 };
293 
294 // Attach the specified directive to the line of code indicated by
295 // \p ExpectedLoc.
296 void attachDirective(DiagnosticsEngine &Diags, const UnattachedDirective &UD,
297  SourceLocation ExpectedLoc,
298  bool MatchAnyFileAndLine = false,
299  bool MatchAnyLine = false) {
300  // Construct new directive.
301  std::unique_ptr<Directive> D = Directive::create(
302  UD.RegexKind, UD.DirectivePos, ExpectedLoc, MatchAnyFileAndLine,
303  MatchAnyLine, UD.Text, UD.Min, UD.Max);
304 
306  if (!D->isValid(Error)) {
307  Diags.Report(UD.ContentBegin, diag::err_verify_invalid_content)
308  << (UD.RegexKind ? "regex" : "string") << Error;
309  }
310 
311  UD.DL->push_back(std::move(D));
312 }
313 
314 } // anonymous
315 
316 // Tracker for markers in the input files. A marker is a comment of the form
317 //
318 // n = 123; // #123
319 //
320 // ... that can be referred to by a later expected-* directive:
321 //
322 // // expected-error@#123 {{undeclared identifier 'n'}}
323 //
324 // Marker declarations must be at the start of a comment or preceded by
325 // whitespace to distinguish them from uses of markers in directives.
327  DiagnosticsEngine &Diags;
328 
329  struct Marker {
330  SourceLocation DefLoc;
331  SourceLocation RedefLoc;
332  SourceLocation UseLoc;
333  };
334  llvm::StringMap<Marker> Markers;
335 
336  // Directives that couldn't be created yet because they name an unknown
337  // marker.
338  llvm::StringMap<llvm::SmallVector<UnattachedDirective, 2>> DeferredDirectives;
339 
340 public:
341  MarkerTracker(DiagnosticsEngine &Diags) : Diags(Diags) {}
342 
343  // Register a marker.
344  void addMarker(StringRef MarkerName, SourceLocation Pos) {
345  auto InsertResult = Markers.insert(
346  {MarkerName, Marker{Pos, SourceLocation(), SourceLocation()}});
347 
348  Marker &M = InsertResult.first->second;
349  if (!InsertResult.second) {
350  // Marker was redefined.
351  M.RedefLoc = Pos;
352  } else {
353  // First definition: build any deferred directives.
354  auto Deferred = DeferredDirectives.find(MarkerName);
355  if (Deferred != DeferredDirectives.end()) {
356  for (auto &UD : Deferred->second) {
357  if (M.UseLoc.isInvalid())
358  M.UseLoc = UD.DirectivePos;
359  attachDirective(Diags, UD, Pos);
360  }
361  DeferredDirectives.erase(Deferred);
362  }
363  }
364  }
365 
366  // Register a directive at the specified marker.
367  void addDirective(StringRef MarkerName, const UnattachedDirective &UD) {
368  auto MarkerIt = Markers.find(MarkerName);
369  if (MarkerIt != Markers.end()) {
370  Marker &M = MarkerIt->second;
371  if (M.UseLoc.isInvalid())
372  M.UseLoc = UD.DirectivePos;
373  return attachDirective(Diags, UD, M.DefLoc);
374  }
375  DeferredDirectives[MarkerName].push_back(UD);
376  }
377 
378  // Ensure we have no remaining deferred directives, and no
379  // multiply-defined-and-used markers.
380  void finalize() {
381  for (auto &MarkerInfo : Markers) {
382  StringRef Name = MarkerInfo.first();
383  Marker &M = MarkerInfo.second;
384  if (M.RedefLoc.isValid() && M.UseLoc.isValid()) {
385  Diags.Report(M.UseLoc, diag::err_verify_ambiguous_marker) << Name;
386  Diags.Report(M.DefLoc, diag::note_verify_ambiguous_marker) << Name;
387  Diags.Report(M.RedefLoc, diag::note_verify_ambiguous_marker) << Name;
388  }
389  }
390 
391  for (auto &DeferredPair : DeferredDirectives) {
392  Diags.Report(DeferredPair.second.front().DirectivePos,
393  diag::err_verify_no_such_marker)
394  << DeferredPair.first();
395  }
396  }
397 };
398 
399 /// ParseDirective - Go through the comment and see if it indicates expected
400 /// diagnostics. If so, then put them in the appropriate directive list.
401 ///
402 /// Returns true if any valid directives were found.
403 static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
404  Preprocessor *PP, SourceLocation Pos,
407  DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics();
408 
409  // First, scan the comment looking for markers.
410  for (ParseHelper PH(S); !PH.Done();) {
411  if (!PH.Search("#", true))
412  break;
413  PH.C = PH.P;
414  if (!PH.NextMarker()) {
415  PH.Next("#");
416  PH.Advance();
417  continue;
418  }
419  PH.Advance();
420  Markers.addMarker(PH.Match(), Pos);
421  }
422 
423  // A single comment may contain multiple directives.
424  bool FoundDirective = false;
425  for (ParseHelper PH(S); !PH.Done();) {
426  // Search for the initial directive token.
427  // If one prefix, save time by searching only for its directives.
428  // Otherwise, search for any potential directive token and check it later.
429  const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes;
430  if (!(Prefixes.size() == 1 ? PH.Search(*Prefixes.begin(), true, true)
431  : PH.Search("", true, true)))
432  break;
433 
434  StringRef DToken = PH.Match();
435  PH.Advance();
436 
437  // Default directive kind.
438  UnattachedDirective D;
439  const char *KindStr = "string";
440 
441  // Parse the initial directive token in reverse so we can easily determine
442  // its exact actual prefix. If we were to parse it from the front instead,
443  // it would be harder to determine where the prefix ends because there
444  // might be multiple matching -verify prefixes because some might prefix
445  // others.
446 
447  // Regex in initial directive token: -re
448  if (DToken.endswith("-re")) {
449  D.RegexKind = true;
450  KindStr = "regex";
451  DToken = DToken.substr(0, DToken.size()-3);
452  }
453 
454  // Type in initial directive token: -{error|warning|note|no-diagnostics}
455  bool NoDiag = false;
456  StringRef DType;
457  if (DToken.endswith(DType="-error"))
458  D.DL = ED ? &ED->Errors : nullptr;
459  else if (DToken.endswith(DType="-warning"))
460  D.DL = ED ? &ED->Warnings : nullptr;
461  else if (DToken.endswith(DType="-remark"))
462  D.DL = ED ? &ED->Remarks : nullptr;
463  else if (DToken.endswith(DType="-note"))
464  D.DL = ED ? &ED->Notes : nullptr;
465  else if (DToken.endswith(DType="-no-diagnostics")) {
466  NoDiag = true;
467  if (D.RegexKind)
468  continue;
469  }
470  else
471  continue;
472  DToken = DToken.substr(0, DToken.size()-DType.size());
473 
474  // What's left in DToken is the actual prefix. That might not be a -verify
475  // prefix even if there is only one -verify prefix (for example, the full
476  // DToken is foo-bar-warning, but foo is the only -verify prefix).
477  if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
478  continue;
479 
480  if (NoDiag) {
482  Diags.Report(Pos, diag::err_verify_invalid_no_diags)
483  << /*IsExpectedNoDiagnostics=*/true;
484  else
486  continue;
487  }
489  Diags.Report(Pos, diag::err_verify_invalid_no_diags)
490  << /*IsExpectedNoDiagnostics=*/false;
491  continue;
492  }
494 
495  // If a directive has been found but we're not interested
496  // in storing the directive information, return now.
497  if (!D.DL)
498  return true;
499 
500  // Next optional token: @
501  SourceLocation ExpectedLoc;
502  StringRef Marker;
503  bool MatchAnyFileAndLine = false;
504  bool MatchAnyLine = false;
505  if (!PH.Next("@")) {
506  ExpectedLoc = Pos;
507  } else {
508  PH.Advance();
509  unsigned Line = 0;
510  bool FoundPlus = PH.Next("+");
511  if (FoundPlus || PH.Next("-")) {
512  // Relative to current line.
513  PH.Advance();
514  bool Invalid = false;
515  unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
516  if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
517  if (FoundPlus) ExpectedLine += Line;
518  else ExpectedLine -= Line;
519  ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
520  }
521  } else if (PH.Next(Line)) {
522  // Absolute line number.
523  if (Line > 0)
524  ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
525  } else if (PH.NextMarker()) {
526  Marker = PH.Match();
527  } else if (PP && PH.Search(":")) {
528  // Specific source file.
529  StringRef Filename(PH.C, PH.P-PH.C);
530  PH.Advance();
531 
532  if (Filename == "*") {
533  MatchAnyFileAndLine = true;
534  if (!PH.Next("*")) {
535  Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
536  diag::err_verify_missing_line)
537  << "'*'";
538  continue;
539  }
540  MatchAnyLine = true;
541  ExpectedLoc = SourceLocation();
542  } else {
543  // Lookup file via Preprocessor, like a #include.
545  PP->LookupFile(Pos, Filename, false, nullptr, nullptr, nullptr,
546  nullptr, nullptr, nullptr, nullptr, nullptr);
547  if (!File) {
548  Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
549  diag::err_verify_missing_file)
550  << Filename << KindStr;
551  continue;
552  }
553 
554  FileID FID = SM.translateFile(*File);
555  if (FID.isInvalid())
556  FID = SM.createFileID(*File, Pos, SrcMgr::C_User);
557 
558  if (PH.Next(Line) && Line > 0)
559  ExpectedLoc = SM.translateLineCol(FID, Line, 1);
560  else if (PH.Next("*")) {
561  MatchAnyLine = true;
562  ExpectedLoc = SM.translateLineCol(FID, 1, 1);
563  }
564  }
565  } else if (PH.Next("*")) {
566  MatchAnyLine = true;
567  ExpectedLoc = SourceLocation();
568  }
569 
570  if (ExpectedLoc.isInvalid() && !MatchAnyLine && Marker.empty()) {
571  Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
572  diag::err_verify_missing_line) << KindStr;
573  continue;
574  }
575  PH.Advance();
576  }
577 
578  // Skip optional whitespace.
579  PH.SkipWhitespace();
580 
581  // Next optional token: positive integer or a '+'.
582  if (PH.Next(D.Min)) {
583  PH.Advance();
584  // A positive integer can be followed by a '+' meaning min
585  // or more, or by a '-' meaning a range from min to max.
586  if (PH.Next("+")) {
587  D.Max = Directive::MaxCount;
588  PH.Advance();
589  } else if (PH.Next("-")) {
590  PH.Advance();
591  if (!PH.Next(D.Max) || D.Max < D.Min) {
592  Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
593  diag::err_verify_invalid_range) << KindStr;
594  continue;
595  }
596  PH.Advance();
597  } else {
598  D.Max = D.Min;
599  }
600  } else if (PH.Next("+")) {
601  // '+' on its own means "1 or more".
602  D.Max = Directive::MaxCount;
603  PH.Advance();
604  }
605 
606  // Skip optional whitespace.
607  PH.SkipWhitespace();
608 
609  // Next token: {{
610  if (!PH.Next("{{")) {
611  Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
612  diag::err_verify_missing_start) << KindStr;
613  continue;
614  }
615  PH.Advance();
616  const char* const ContentBegin = PH.C; // mark content begin
617  // Search for token: }}
618  if (!PH.SearchClosingBrace("{{", "}}")) {
619  Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
620  diag::err_verify_missing_end) << KindStr;
621  continue;
622  }
623  const char* const ContentEnd = PH.P; // mark content end
624  PH.Advance();
625 
626  D.DirectivePos = Pos;
627  D.ContentBegin = Pos.getLocWithOffset(ContentBegin - PH.Begin);
628 
629  // Build directive text; convert \n to newlines.
630  StringRef NewlineStr = "\\n";
631  StringRef Content(ContentBegin, ContentEnd-ContentBegin);
632  size_t CPos = 0;
633  size_t FPos;
634  while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
635  D.Text += Content.substr(CPos, FPos-CPos);
636  D.Text += '\n';
637  CPos = FPos + NewlineStr.size();
638  }
639  if (D.Text.empty())
640  D.Text.assign(ContentBegin, ContentEnd);
641 
642  // Check that regex directives contain at least one regex.
643  if (D.RegexKind && D.Text.find("{{") == StringRef::npos) {
644  Diags.Report(D.ContentBegin, diag::err_verify_missing_regex) << D.Text;
645  return false;
646  }
647 
648  if (Marker.empty())
649  attachDirective(Diags, D, ExpectedLoc, MatchAnyFileAndLine, MatchAnyLine);
650  else
651  Markers.addDirective(Marker, D);
652  FoundDirective = true;
653  }
654 
655  return FoundDirective;
656 }
657 
659  : Diags(Diags_), PrimaryClient(Diags.getClient()),
660  PrimaryClientOwner(Diags.takeClient()),
661  Buffer(new TextDiagnosticBuffer()), Markers(new MarkerTracker(Diags)),
662  Status(HasNoDirectives) {
663  if (Diags.hasSourceManager())
664  setSourceManager(Diags.getSourceManager());
665 }
666 
668  assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
669  assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
670  SrcManager = nullptr;
671  CheckDiagnostics();
672  assert(!Diags.ownsClient() &&
673  "The VerifyDiagnosticConsumer takes over ownership of the client!");
674 }
675 
676 // DiagnosticConsumer interface.
677 
679  const Preprocessor *PP) {
680  // Attach comment handler on first invocation.
681  if (++ActiveSourceFiles == 1) {
682  if (PP) {
683  CurrentPreprocessor = PP;
684  this->LangOpts = &LangOpts;
685  setSourceManager(PP->getSourceManager());
686  const_cast<Preprocessor *>(PP)->addCommentHandler(this);
687 #ifndef NDEBUG
688  // Debug build tracks parsed files.
689  const_cast<Preprocessor *>(PP)->addPPCallbacks(
690  std::make_unique<VerifyFileTracker>(*this, *SrcManager));
691 #endif
692  }
693  }
694 
695  assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
696  PrimaryClient->BeginSourceFile(LangOpts, PP);
697 }
698 
700  assert(ActiveSourceFiles && "No active source files!");
701  PrimaryClient->EndSourceFile();
702 
703  // Detach comment handler once last active source file completed.
704  if (--ActiveSourceFiles == 0) {
705  if (CurrentPreprocessor)
706  const_cast<Preprocessor *>(CurrentPreprocessor)->
707  removeCommentHandler(this);
708 
709  // Diagnose any used-but-not-defined markers.
710  Markers->finalize();
711 
712  // Check diagnostics once last file completed.
713  CheckDiagnostics();
714  CurrentPreprocessor = nullptr;
715  LangOpts = nullptr;
716  }
717 }
718 
720  DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
721  if (Info.hasSourceManager()) {
722  // If this diagnostic is for a different source manager, ignore it.
723  if (SrcManager && &Info.getSourceManager() != SrcManager)
724  return;
725 
726  setSourceManager(Info.getSourceManager());
727  }
728 
729 #ifndef NDEBUG
730  // Debug build tracks unparsed files for possible
731  // unparsed expected-* directives.
732  if (SrcManager) {
733  SourceLocation Loc = Info.getLocation();
734  if (Loc.isValid()) {
736 
737  Loc = SrcManager->getExpansionLoc(Loc);
738  FileID FID = SrcManager->getFileID(Loc);
739 
740  const FileEntry *FE = SrcManager->getFileEntryForID(FID);
741  if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
742  // If the file is a modules header file it shall not be parsed
743  // for expected-* directives.
744  HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
745  if (HS.findModuleForHeader(FE))
747  }
748 
749  UpdateParsedFileStatus(*SrcManager, FID, PS);
750  }
751  }
752 #endif
753 
754  // Send the diagnostic to the buffer, we will check it once we reach the end
755  // of the source file (or are destructed).
756  Buffer->HandleDiagnostic(DiagLevel, Info);
757 }
758 
759 /// HandleComment - Hook into the preprocessor and extract comments containing
760 /// expected errors and warnings.
762  SourceRange Comment) {
764 
765  // If this comment is for a different source manager, ignore it.
766  if (SrcManager && &SM != SrcManager)
767  return false;
768 
769  SourceLocation CommentBegin = Comment.getBegin();
770 
771  const char *CommentRaw = SM.getCharacterData(CommentBegin);
772  StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
773 
774  if (C.empty())
775  return false;
776 
777  // Fold any "<EOL>" sequences
778  size_t loc = C.find('\\');
779  if (loc == StringRef::npos) {
780  ParseDirective(C, &ED, SM, &PP, CommentBegin, Status, *Markers);
781  return false;
782  }
783 
784  std::string C2;
785  C2.reserve(C.size());
786 
787  for (size_t last = 0;; loc = C.find('\\', last)) {
788  if (loc == StringRef::npos || loc == C.size()) {
789  C2 += C.substr(last);
790  break;
791  }
792  C2 += C.substr(last, loc-last);
793  last = loc + 1;
794 
795  if (C[last] == '\n' || C[last] == '\r') {
796  ++last;
797 
798  // Escape \r\n or \n\r, but not \n\n.
799  if (last < C.size())
800  if (C[last] == '\n' || C[last] == '\r')
801  if (C[last] != C[last-1])
802  ++last;
803  } else {
804  // This was just a normal backslash.
805  C2 += '\\';
806  }
807  }
808 
809  if (!C2.empty())
810  ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status, *Markers);
811  return false;
812 }
813 
814 #ifndef NDEBUG
815 /// Lex the specified source file to determine whether it contains
816 /// any expected-* directives. As a Lexer is used rather than a full-blown
817 /// Preprocessor, directives inside skipped #if blocks will still be found.
818 ///
819 /// \return true if any directives were found.
821  const LangOptions &LangOpts) {
822  // Create a raw lexer to pull all the comments out of FID.
823  if (FID.isInvalid())
824  return false;
825 
826  // Create a lexer to lex all the tokens of the main file in raw mode.
827  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
828  Lexer RawLex(FID, FromFile, SM, LangOpts);
829 
830  // Return comments as tokens, this is how we find expected diagnostics.
831  RawLex.SetCommentRetentionState(true);
832 
833  Token Tok;
834  Tok.setKind(tok::comment);
837  while (Tok.isNot(tok::eof)) {
838  RawLex.LexFromRawLexer(Tok);
839  if (!Tok.is(tok::comment)) continue;
840 
841  std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
842  if (Comment.empty()) continue;
843 
844  // We don't care about tracking markers for this phase.
845  VerifyDiagnosticConsumer::MarkerTracker Markers(SM.getDiagnostics());
846 
847  // Find first directive.
848  if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
849  Status, Markers))
850  return true;
851  }
852  return false;
853 }
854 #endif // !NDEBUG
855 
856 /// Takes a list of diagnostics that have been generated but not matched
857 /// by an expected-* directive and produces a diagnostic to the user from this.
858 static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
859  const_diag_iterator diag_begin,
860  const_diag_iterator diag_end,
861  const char *Kind) {
862  if (diag_begin == diag_end) return 0;
863 
864  SmallString<256> Fmt;
865  llvm::raw_svector_ostream OS(Fmt);
866  for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
867  if (I->first.isInvalid() || !SourceMgr)
868  OS << "\n (frontend)";
869  else {
870  OS << "\n ";
871  if (const FileEntry *File = SourceMgr->getFileEntryForID(
872  SourceMgr->getFileID(I->first)))
873  OS << " File " << File->getName();
874  OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
875  }
876  OS << ": " << I->second;
877  }
878 
879  Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
880  << Kind << /*Unexpected=*/true << OS.str();
881  return std::distance(diag_begin, diag_end);
882 }
883 
884 /// Takes a list of diagnostics that were expected to have been generated
885 /// but were not and produces a diagnostic to the user from this.
886 static unsigned PrintExpected(DiagnosticsEngine &Diags,
887  SourceManager &SourceMgr,
888  std::vector<Directive *> &DL, const char *Kind) {
889  if (DL.empty())
890  return 0;
891 
892  SmallString<256> Fmt;
893  llvm::raw_svector_ostream OS(Fmt);
894  for (const auto *D : DL) {
895  if (D->DiagnosticLoc.isInvalid() || D->MatchAnyFileAndLine)
896  OS << "\n File *";
897  else
898  OS << "\n File " << SourceMgr.getFilename(D->DiagnosticLoc);
899  if (D->MatchAnyLine)
900  OS << " Line *";
901  else
902  OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc);
903  if (D->DirectiveLoc != D->DiagnosticLoc)
904  OS << " (directive at "
905  << SourceMgr.getFilename(D->DirectiveLoc) << ':'
906  << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')';
907  OS << ": " << D->Text;
908  }
909 
910  Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
911  << Kind << /*Unexpected=*/false << OS.str();
912  return DL.size();
913 }
914 
915 /// Determine whether two source locations come from the same file.
916 static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
917  SourceLocation DiagnosticLoc) {
918  while (DiagnosticLoc.isMacroID())
919  DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
920 
921  if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
922  return true;
923 
924  const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
925  if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc))
926  return true;
927 
928  return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
929 }
930 
931 /// CheckLists - Compare expected to seen diagnostic lists and return the
932 /// the difference between them.
933 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
934  const char *Label,
935  DirectiveList &Left,
936  const_diag_iterator d2_begin,
937  const_diag_iterator d2_end,
938  bool IgnoreUnexpected) {
939  std::vector<Directive *> LeftOnly;
940  DiagList Right(d2_begin, d2_end);
941 
942  for (auto &Owner : Left) {
943  Directive &D = *Owner;
944  unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
945 
946  for (unsigned i = 0; i < D.Max; ++i) {
947  DiagList::iterator II, IE;
948  for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
949  if (!D.MatchAnyLine) {
950  unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
951  if (LineNo1 != LineNo2)
952  continue;
953  }
954 
956  !IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
957  continue;
958 
959  const std::string &RightText = II->second;
960  if (D.match(RightText))
961  break;
962  }
963  if (II == IE) {
964  // Not found.
965  if (i >= D.Min) break;
966  LeftOnly.push_back(&D);
967  } else {
968  // Found. The same cannot be found twice.
969  Right.erase(II);
970  }
971  }
972  }
973  // Now all that's left in Right are those that were not matched.
974  unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
975  if (!IgnoreUnexpected)
976  num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
977  return num;
978 }
979 
980 /// CheckResults - This compares the expected results to those that
981 /// were actually reported. It emits any discrepencies. Return "true" if there
982 /// were problems. Return "false" otherwise.
983 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
984  const TextDiagnosticBuffer &Buffer,
985  ExpectedData &ED) {
986  // We want to capture the delta between what was expected and what was
987  // seen.
988  //
989  // Expected \ Seen - set expected but not seen
990  // Seen \ Expected - set seen but not expected
991  unsigned NumProblems = 0;
992 
993  const DiagnosticLevelMask DiagMask =
994  Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
995 
996  // See if there are error mismatches.
997  NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
998  Buffer.err_begin(), Buffer.err_end(),
999  bool(DiagnosticLevelMask::Error & DiagMask));
1000 
1001  // See if there are warning mismatches.
1002  NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
1003  Buffer.warn_begin(), Buffer.warn_end(),
1004  bool(DiagnosticLevelMask::Warning & DiagMask));
1005 
1006  // See if there are remark mismatches.
1007  NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
1008  Buffer.remark_begin(), Buffer.remark_end(),
1009  bool(DiagnosticLevelMask::Remark & DiagMask));
1010 
1011  // See if there are note mismatches.
1012  NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
1013  Buffer.note_begin(), Buffer.note_end(),
1014  bool(DiagnosticLevelMask::Note & DiagMask));
1015 
1016  return NumProblems;
1017 }
1018 
1020  FileID FID,
1021  ParsedStatus PS) {
1022  // Check SourceManager hasn't changed.
1023  setSourceManager(SM);
1024 
1025 #ifndef NDEBUG
1026  if (FID.isInvalid())
1027  return;
1028 
1029  const FileEntry *FE = SM.getFileEntryForID(FID);
1030 
1031  if (PS == IsParsed) {
1032  // Move the FileID from the unparsed set to the parsed set.
1033  UnparsedFiles.erase(FID);
1034  ParsedFiles.insert(std::make_pair(FID, FE));
1035  } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
1036  // Add the FileID to the unparsed set if we haven't seen it before.
1037 
1038  // Check for directives.
1039  bool FoundDirectives;
1040  if (PS == IsUnparsedNoDirectives)
1041  FoundDirectives = false;
1042  else
1043  FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
1044 
1045  // Add the FileID to the unparsed set.
1046  UnparsedFiles.insert(std::make_pair(FID,
1047  UnparsedFileStatus(FE, FoundDirectives)));
1048  }
1049 #endif
1050 }
1051 
1052 void VerifyDiagnosticConsumer::CheckDiagnostics() {
1053  // Ensure any diagnostics go to the primary client.
1054  DiagnosticConsumer *CurClient = Diags.getClient();
1055  std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient();
1056  Diags.setClient(PrimaryClient, false);
1057 
1058 #ifndef NDEBUG
1059  // In a debug build, scan through any files that may have been missed
1060  // during parsing and issue a fatal error if directives are contained
1061  // within these files. If a fatal error occurs, this suggests that
1062  // this file is being parsed separately from the main file, in which
1063  // case consider moving the directives to the correct place, if this
1064  // is applicable.
1065  if (!UnparsedFiles.empty()) {
1066  // Generate a cache of parsed FileEntry pointers for alias lookups.
1068  for (const auto &I : ParsedFiles)
1069  if (const FileEntry *FE = I.second)
1070  ParsedFileCache.insert(FE);
1071 
1072  // Iterate through list of unparsed files.
1073  for (const auto &I : UnparsedFiles) {
1074  const UnparsedFileStatus &Status = I.second;
1075  const FileEntry *FE = Status.getFile();
1076 
1077  // Skip files that have been parsed via an alias.
1078  if (FE && ParsedFileCache.count(FE))
1079  continue;
1080 
1081  // Report a fatal error if this file contained directives.
1082  if (Status.foundDirectives()) {
1083  llvm::report_fatal_error(Twine("-verify directives found after rather"
1084  " than during normal parsing of ",
1085  StringRef(FE ? FE->getName() : "(unknown)")));
1086  }
1087  }
1088 
1089  // UnparsedFiles has been processed now, so clear it.
1090  UnparsedFiles.clear();
1091  }
1092 #endif // !NDEBUG
1093 
1094  if (SrcManager) {
1095  // Produce an error if no expected-* directives could be found in the
1096  // source file(s) processed.
1097  if (Status == HasNoDirectives) {
1098  Diags.Report(diag::err_verify_no_directives).setForceEmit();
1099  ++NumErrors;
1100  Status = HasNoDirectivesReported;
1101  }
1102 
1103  // Check that the expected diagnostics occurred.
1104  NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
1105  } else {
1106  const DiagnosticLevelMask DiagMask =
1107  ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
1108  if (bool(DiagnosticLevelMask::Error & DiagMask))
1109  NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
1110  Buffer->err_end(), "error");
1111  if (bool(DiagnosticLevelMask::Warning & DiagMask))
1112  NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
1113  Buffer->warn_end(), "warn");
1114  if (bool(DiagnosticLevelMask::Remark & DiagMask))
1115  NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(),
1116  Buffer->remark_end(), "remark");
1117  if (bool(DiagnosticLevelMask::Note & DiagMask))
1118  NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
1119  Buffer->note_end(), "note");
1120  }
1121 
1122  Diags.setClient(CurClient, Owner.release() != nullptr);
1123 
1124  // Reset the buffer, we have processed all the diagnostics in it.
1125  Buffer.reset(new TextDiagnosticBuffer());
1126  ED.Reset();
1127 }
1128 
1129 std::unique_ptr<Directive> Directive::create(bool RegexKind,
1130  SourceLocation DirectiveLoc,
1131  SourceLocation DiagnosticLoc,
1132  bool MatchAnyFileAndLine,
1133  bool MatchAnyLine, StringRef Text,
1134  unsigned Min, unsigned Max) {
1135  if (!RegexKind)
1136  return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
1137  MatchAnyFileAndLine,
1138  MatchAnyLine, Text, Min, Max);
1139 
1140  // Parse the directive into a regular expression.
1141  std::string RegexStr;
1142  StringRef S = Text;
1143  while (!S.empty()) {
1144  if (S.startswith("{{")) {
1145  S = S.drop_front(2);
1146  size_t RegexMatchLength = S.find("}}");
1147  assert(RegexMatchLength != StringRef::npos);
1148  // Append the regex, enclosed in parentheses.
1149  RegexStr += "(";
1150  RegexStr.append(S.data(), RegexMatchLength);
1151  RegexStr += ")";
1152  S = S.drop_front(RegexMatchLength + 2);
1153  } else {
1154  size_t VerbatimMatchLength = S.find("{{");
1155  if (VerbatimMatchLength == StringRef::npos)
1156  VerbatimMatchLength = S.size();
1157  // Escape and append the fixed string.
1158  RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
1159  S = S.drop_front(VerbatimMatchLength);
1160  }
1161  }
1162 
1163  return std::make_unique<RegexDirective>(DirectiveLoc, DiagnosticLoc,
1164  MatchAnyFileAndLine, MatchAnyLine,
1165  Text, Min, Max, RegexStr);
1166 }
clang::DiagnosticsEngine::Level
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:194
clang::VerifyDiagnosticConsumer::ExpectedData::Remarks
DirectiveList Remarks
Definition: VerifyDiagnosticConsumer.h:239
clang::SourceManager::getFilename
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
Definition: SourceManager.cpp:1015
clang::VerifyDiagnosticConsumer
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
Definition: VerifyDiagnosticConsumer.h:186
clang::Lexer::SetCommentRetentionState
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition: Lexer.h:237
clang::VerifyDiagnosticConsumer::ExpectedData
ExpectedData - owns directive objects and deletes on destructor.
Definition: VerifyDiagnosticConsumer.h:236
clang::DeclaratorContext::File
@ File
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
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:111
clang::TextDiagnosticBuffer::remark_end
const_iterator remark_end() const
Definition: TextDiagnosticBuffer.h:48
clang::VerifyDiagnosticConsumer::BeginSourceFile
void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP) override
Callback to inform the diagnostic client that processing of a source file is beginning.
Definition: VerifyDiagnosticConsumer.cpp:678
clang::DiagnosticLevelMask::Error
@ Error
clang::Lexer::getSpelling
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition: Lexer.cpp:404
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::PPCallbacks
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:35
clang::DiagnosticsEngine::getDiagnosticOptions
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:555
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::VerifyDiagnosticConsumer::Directive::DiagnosticLoc
SourceLocation DiagnosticLoc
Definition: VerifyDiagnosticConsumer.h:203
clang::VerifyDiagnosticConsumer::IsUnparsedNoDirectives
@ IsUnparsedNoDirectives
File has diagnostics but guaranteed no directives.
Definition: VerifyDiagnosticConsumer.h:317
clang::DiagnosticConsumer
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1722
clang::DiagnosticConsumer::NumErrors
unsigned NumErrors
Number of errors reported.
Definition: Diagnostic.h:1725
clang::VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer
~VerifyDiagnosticConsumer() override
Definition: VerifyDiagnosticConsumer.cpp:667
Filename
StringRef Filename
Definition: Format.cpp:2429
clang::VerifyDiagnosticConsumer::Directive::isValid
virtual bool isValid(std::string &Error)=0
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
clang::DiagnosticsEngine::hasSourceManager
bool hasSourceManager() const
Definition: Diagnostic.h:575
clang::VerifyDiagnosticConsumer::MarkerTracker::addMarker
void addMarker(StringRef MarkerName, SourceLocation Pos)
Definition: VerifyDiagnosticConsumer.cpp:344
clang::VerifyDiagnosticConsumer::UpdateParsedFileStatus
void UpdateParsedFileStatus(SourceManager &SM, FileID FID, ParsedStatus PS)
Update lists of parsed and unparsed files.
Definition: VerifyDiagnosticConsumer.cpp:1019
distance
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
llvm::Optional< FileEntryRef >
llvm::SmallPtrSet
Definition: ASTContext.h:82
SourceManager.h
clang::SrcMgr::CharacteristicKind
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:78
PrintUnexpected
static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr, const_diag_iterator diag_begin, const_diag_iterator diag_end, const char *Kind)
Takes a list of diagnostics that have been generated but not matched by an expected-* directive and p...
Definition: VerifyDiagnosticConsumer.cpp:858
clang::VerifyDiagnosticConsumer::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: VerifyDiagnosticConsumer.cpp:719
clang::Lexer::LexFromRawLexer
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition: Lexer.h:204
clang::TextDiagnosticBuffer::err_end
const_iterator err_end() const
Definition: TextDiagnosticBuffer.h:42
clang::DiagnosticConsumer::EndSourceFile
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: Diagnostic.h:1754
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
End
SourceLocation End
Definition: USRLocFinder.cpp:167
CheckLists
static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const char *Label, DirectiveList &Left, const_diag_iterator d2_begin, const_diag_iterator d2_end, bool IgnoreUnexpected)
CheckLists - Compare expected to seen diagnostic lists and return the the difference between them.
Definition: VerifyDiagnosticConsumer.cpp:933
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
CheckResults
static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const TextDiagnosticBuffer &Buffer, ExpectedData &ED)
CheckResults - This compares the expected results to those that were actually reported.
Definition: VerifyDiagnosticConsumer.cpp:983
Preprocessor.h
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:168
clang::Lexer
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:76
clang::Preprocessor::LookupFile
Optional< FileEntryRef > LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup **CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false)
Given a "foo" or <foo> reference, look up the indicated file.
Definition: PPDirectives.cpp:818
VerifyDiagnosticConsumer.h
clang::Diagnostic
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1547
clang::VerifyDiagnosticConsumer::EndSourceFile
void EndSourceFile() override
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: VerifyDiagnosticConsumer.cpp:699
TokenKinds.h
clang::TextDiagnosticBuffer::const_iterator
DiagList::const_iterator const_iterator
Definition: TextDiagnosticBuffer.h:29
clang::VerifyDiagnosticConsumer::Directive::MaxCount
static const unsigned MaxCount
Constant representing n or more matches.
Definition: VerifyDiagnosticConsumer.h:200
const_diag_iterator
TextDiagnosticBuffer::const_iterator const_diag_iterator
Definition: VerifyDiagnosticConsumer.cpp:84
clang::TextDiagnosticBuffer::note_end
const_iterator note_end() const
Definition: TextDiagnosticBuffer.h:51
clang::TextDiagnosticBuffer::err_begin
const_iterator err_begin() const
Definition: TextDiagnosticBuffer.h:41
clang::TextDiagnosticBuffer::note_begin
const_iterator note_begin() const
Definition: TextDiagnosticBuffer.h:50
clang::DiagnosticsEngine::takeClient
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:573
clang::VerifyDiagnosticConsumer::MarkerTracker::MarkerTracker
MarkerTracker(DiagnosticsEngine &Diags)
Definition: VerifyDiagnosticConsumer.cpp:341
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
clang::VerifyDiagnosticConsumer::HasOtherExpectedDirectives
@ HasOtherExpectedDirectives
Definition: VerifyDiagnosticConsumer.h:254
Diagnostic.h
Depth
int Depth
Definition: ASTDiff.cpp:191
clang::isLetter
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:116
clang::VerifyDiagnosticConsumer::Directive::match
virtual bool match(StringRef S)=0
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:97
clang::VerifyDiagnosticConsumer::ExpectedData::Warnings
DirectiveList Warnings
Definition: VerifyDiagnosticConsumer.h:238
clang::TextDiagnosticBuffer::DiagList
std::vector< std::pair< SourceLocation, std::string > > DiagList
Definition: TextDiagnosticBuffer.h:27
clang::VerifyDiagnosticConsumer::Directive::Max
unsigned Max
Definition: VerifyDiagnosticConsumer.h:205
clang::VerifyDiagnosticConsumer::VerifyDiagnosticConsumer
VerifyDiagnosticConsumer(DiagnosticsEngine &Diags)
Create a new verifying diagnostic client, which will issue errors to the currently-attached diagnosti...
Definition: VerifyDiagnosticConsumer.cpp:658
clang::VerifyDiagnosticConsumer::HasNoDirectivesReported
@ HasNoDirectivesReported
Definition: VerifyDiagnosticConsumer.h:252
clang::SourceManager::getFileID
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Definition: SourceManager.h:1103
clang::DiagnosticsEngine::getClient
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:565
llvm::SmallString
Definition: LLVM.h:37
TextDiagnosticBuffer.h
clang::VerifyDiagnosticConsumer::Directive::MatchAnyLine
bool MatchAnyLine
Definition: VerifyDiagnosticConsumer.h:206
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:79
clang::DiagnosticsEngine::ownsClient
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition: Diagnostic.h:569
Label
std::string Label
Definition: UsingDeclarationsSorter.cpp:69
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:331
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:964
clang::isWhitespace
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:92
ParseDirective
static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM, Preprocessor *PP, SourceLocation Pos, VerifyDiagnosticConsumer::DirectiveStatus &Status, VerifyDiagnosticConsumer::MarkerTracker &Markers)
ParseDirective - Go through the comment and see if it indicates expected diagnostics.
Definition: VerifyDiagnosticConsumer.cpp:403
SourceLocation.h
clang::VerifyDiagnosticConsumer::Directive::Min
unsigned Min
Definition: VerifyDiagnosticConsumer.h:205
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
CharInfo.h
clang::DiagnosticConsumer::BeginSourceFile
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
Definition: Diagnostic.h:1746
Directive
VerifyDiagnosticConsumer::Directive Directive
Definition: VerifyDiagnosticConsumer.cpp:49
clang::VerifyDiagnosticConsumer::IsParsed
@ IsParsed
File has been processed via HandleComment.
Definition: VerifyDiagnosticConsumer.h:311
clang::Diagnostic::getLocation
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1558
clang::HeaderSearch::findModuleForHeader
ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false) const
Retrieve the module that corresponds to the given file, if any.
Definition: HeaderSearch.cpp:1505
Begin
SourceLocation Begin
Definition: USRLocFinder.cpp:165
clang::isAlphanumeric
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:122
Lexer.h
HeaderSearch.h
IsFromSameFile
static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc)
Determine whether two source locations come from the same file.
Definition: VerifyDiagnosticConsumer.cpp:916
clang::VerifyDiagnosticConsumer::DirectiveStatus
DirectiveStatus
Definition: VerifyDiagnosticConsumer.h:250
DirectiveList
VerifyDiagnosticConsumer::DirectiveList DirectiveList
Definition: VerifyDiagnosticConsumer.cpp:50
LLVM.h
clang::DiagnosticLevelMask
DiagnosticLevelMask
A bitmask representing the diagnostic levels used by VerifyDiagnosticConsumer.
Definition: DiagnosticOptions.h:39
clang::VerifyDiagnosticConsumer::MarkerTracker::addDirective
void addDirective(StringRef MarkerName, const UnattachedDirective &UD)
Definition: VerifyDiagnosticConsumer.cpp:367
clang::Diagnostic::getSourceManager
SourceManager & getSourceManager() const
Definition: Diagnostic.h:1560
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::VerifyDiagnosticConsumer::HasNoDirectives
@ HasNoDirectives
Definition: VerifyDiagnosticConsumer.h:251
clang::SourceManager::isLoadedFileID
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
Definition: SourceManager.h:1735
clang::DiagnosticLevelMask::Remark
@ Remark
clang::TextDiagnosticBuffer
Definition: TextDiagnosticBuffer.h:25
clang::DiagnosticLevelMask::Note
@ Note
clang::VerifyDiagnosticConsumer::IsUnparsed
@ IsUnparsed
File has diagnostics and may have directives.
Definition: VerifyDiagnosticConsumer.h:314
clang::VerifyDiagnosticConsumer::ExpectedData::Errors
DirectiveList Errors
Definition: VerifyDiagnosticConsumer.h:237
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang
Definition: CalledOnceCheck.h:17
Text
StringRef Text
Definition: Format.cpp:2430
clang::TextDiagnosticBuffer::warn_end
const_iterator warn_end() const
Definition: TextDiagnosticBuffer.h:45
PPCallbacks.h
FrontendDiagnostic.h
clang::Preprocessor::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:957
clang::ast_matchers::match
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
Definition: ASTMatchFinder.h:312
clang::VerifyDiagnosticConsumer::MarkerTracker::finalize
void finalize()
Definition: VerifyDiagnosticConsumer.cpp:380
clang::isDigit
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:98
clang::FileEntry::getName
StringRef getName() const
Definition: FileEntry.h:364
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::FileID::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:45
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1030
clang::TextDiagnosticBuffer::remark_begin
const_iterator remark_begin() const
Definition: TextDiagnosticBuffer.h:47
PrintExpected
static unsigned PrintExpected(DiagnosticsEngine &Diags, SourceManager &SourceMgr, std::vector< Directive * > &DL, const char *Kind)
Takes a list of diagnostics that were expected to have been generated but were not and produces a dia...
Definition: VerifyDiagnosticConsumer.cpp:886
clang::Token::setKind
void setKind(tok::TokenKind K)
Definition: Token.h:93
clang::VerifyDiagnosticConsumer::DirectiveList
std::vector< std::unique_ptr< Directive > > DirectiveList
Definition: VerifyDiagnosticConsumer.h:233
findDirectives
static bool findDirectives(SourceManager &SM, FileID FID, const LangOptions &LangOpts)
Lex the specified source file to determine whether it contains any expected-* directives.
Definition: VerifyDiagnosticConsumer.cpp:820
clang::VerifyDiagnosticConsumer::Directive
Directive - Abstract class representing a parsed verify directive.
Definition: VerifyDiagnosticConsumer.h:191
DiagnosticOptions.h
clang::Diagnostic::hasSourceManager
bool hasSourceManager() const
Definition: Diagnostic.h:1559
clang::SourceManager::getExpansionLoc
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Definition: SourceManager.h:1158
clang::VerifyDiagnosticConsumer::HasExpectedNoDiagnostics
@ HasExpectedNoDiagnostics
Definition: VerifyDiagnosticConsumer.h:253
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
FileManager.h
clang::VerifyDiagnosticConsumer::ExpectedData::Reset
void Reset()
Definition: VerifyDiagnosticConsumer.h:242
clang::DiagnosticsEngine::getSourceManager
SourceManager & getSourceManager() const
Definition: Diagnostic.h:577
clang::VerifyDiagnosticConsumer::ParsedStatus
ParsedStatus
Definition: VerifyDiagnosticConsumer.h:309
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::Preprocessor::getHeaderSearchInfo
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:965
clang::DiagnosticBuilder::setForceEmit
const DiagnosticBuilder & setForceEmit() const
Forces the diagnostic to be emitted.
Definition: Diagnostic.h:1362
Token.h
clang::VerifyDiagnosticConsumer::MarkerTracker
Definition: VerifyDiagnosticConsumer.cpp:326
clang::TextDiagnosticBuffer::warn_begin
const_iterator warn_begin() const
Definition: TextDiagnosticBuffer.h:44
DiagList
TextDiagnosticBuffer::DiagList DiagList
Definition: VerifyDiagnosticConsumer.cpp:83
clang::VerifyDiagnosticConsumer::HandleComment
bool HandleComment(Preprocessor &PP, SourceRange Comment) override
HandleComment - Hook into the preprocessor and extract comments containing expected errors and warnin...
Definition: VerifyDiagnosticConsumer.cpp:761
clang::VerifyDiagnosticConsumer::Directive::create
static std::unique_ptr< Directive > create(bool RegexKind, SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc, bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text, unsigned Min, unsigned Max)
Definition: VerifyDiagnosticConsumer.cpp:1129
clang::DiagnosticLevelMask::Warning
@ Warning
ExpectedData
VerifyDiagnosticConsumer::ExpectedData ExpectedData
Definition: VerifyDiagnosticConsumer.cpp:51
clang::VerifyDiagnosticConsumer::Directive::MatchAnyFileAndLine
bool MatchAnyFileAndLine
Definition: VerifyDiagnosticConsumer.h:207
NoDiag
static ICEDiag NoDiag()
Definition: ExprConstant.cpp:15180
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1523
clang::SourceManager::getPresumedLineNumber
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1453
clang::DiagnosticOptions::VerifyPrefixes
std::vector< std::string > VerifyPrefixes
The prefixes for comment directives sought by -verify ("expected" by default).
Definition: DiagnosticOptions.h:123
clang::VerifyDiagnosticConsumer::ExpectedData::Notes
DirectiveList Notes
Definition: VerifyDiagnosticConsumer.h:240