1 //===---- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a concrete diagnostic client, which buffers the diagnostic messages.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/TextDiagnosticBuffer.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/Regex.h"
20 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
25 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
26 : Diags(_Diags), PrimaryClient(Diags.getClient()),
27 OwnsPrimaryClient(Diags.ownsClient()),
28 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0)
33 VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
36 if (OwnsPrimaryClient)
40 // DiagnosticConsumer interface.
42 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
43 const Preprocessor *PP) {
44 // FIXME: Const hack, we screw up the preprocessor but in practice its ok
45 // because it doesn't get reused. It would be better if we could make a copy
47 CurrentPreprocessor = const_cast<Preprocessor*>(PP);
49 PrimaryClient->BeginSourceFile(LangOpts, PP);
52 void VerifyDiagnosticConsumer::EndSourceFile() {
55 PrimaryClient->EndSourceFile();
57 CurrentPreprocessor = 0;
60 void VerifyDiagnosticConsumer::HandleDiagnostic(
61 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
62 if (FirstErrorFID.isInvalid() && Info.hasSourceManager()) {
63 const SourceManager &SM = Info.getSourceManager();
64 FirstErrorFID = SM.getFileID(Info.getLocation());
66 // Send the diagnostic to the buffer, we will check it once we reach the end
67 // of the source file (or are destructed).
68 Buffer->HandleDiagnostic(DiagLevel, Info);
71 //===----------------------------------------------------------------------===//
72 // Checking diagnostics implementation.
73 //===----------------------------------------------------------------------===//
75 typedef TextDiagnosticBuffer::DiagList DiagList;
76 typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
80 /// Directive - Abstract class representing a parsed verify directive.
84 static Directive* Create(bool RegexKind, const SourceLocation &Location,
85 const std::string &Text, unsigned Count);
87 /// Constant representing one or more matches aka regex "+".
88 static const unsigned OneOrMoreCount = UINT_MAX;
90 SourceLocation Location;
91 const std::string Text;
94 virtual ~Directive() { }
96 // Returns true if directive text is valid.
97 // Otherwise returns false and populates E.
98 virtual bool isValid(std::string &Error) = 0;
100 // Returns true on match.
101 virtual bool Match(const std::string &S) = 0;
104 Directive(const SourceLocation &Location, const std::string &Text,
106 : Location(Location), Text(Text), Count(Count) { }
109 Directive(const Directive&); // DO NOT IMPLEMENT
110 void operator=(const Directive&); // DO NOT IMPLEMENT
113 /// StandardDirective - Directive with string matching.
115 class StandardDirective : public Directive {
117 StandardDirective(const SourceLocation &Location, const std::string &Text,
119 : Directive(Location, Text, Count) { }
121 virtual bool isValid(std::string &Error) {
122 // all strings are considered valid; even empty ones
126 virtual bool Match(const std::string &S) {
127 return S.find(Text) != std::string::npos;
131 /// RegexDirective - Directive with regular-expression matching.
133 class RegexDirective : public Directive {
135 RegexDirective(const SourceLocation &Location, const std::string &Text,
137 : Directive(Location, Text, Count), Regex(Text) { }
139 virtual bool isValid(std::string &Error) {
140 if (Regex.isValid(Error))
145 virtual bool Match(const std::string &S) {
146 return Regex.match(S);
153 typedef std::vector<Directive*> DirectiveList;
155 /// ExpectedData - owns directive objects and deletes on destructor.
157 struct ExpectedData {
158 DirectiveList Errors;
159 DirectiveList Warnings;
163 DirectiveList* Lists[] = { &Errors, &Warnings, &Notes, 0 };
164 for (DirectiveList **PL = Lists; *PL; ++PL) {
165 DirectiveList * const L = *PL;
166 for (DirectiveList::iterator I = L->begin(), E = L->end(); I != E; ++I)
175 ParseHelper(const char *Begin, const char *End)
176 : Begin(Begin), End(End), C(Begin), P(Begin), PEnd(NULL) { }
178 // Return true if string literal is next.
179 bool Next(StringRef S) {
184 return !memcmp(P, S.data(), S.size());
187 // Return true if number is next.
188 // Output N only if number is next.
189 bool Next(unsigned &N) {
192 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
203 // Return true if string literal is found.
204 // When true, P marks begin-position of S in content.
205 bool Search(StringRef S) {
206 P = std::search(C, End, S.begin(), S.end());
211 // Advance 1-past previous next/search.
212 // Behavior is undefined if previous next/search failed.
218 // Skip zero or more whitespace.
219 void SkipWhitespace() {
220 for (; C < End && isspace(*C); ++C)
224 // Return true if EOF reached.
229 const char * const Begin; // beginning of expected content
230 const char * const End; // end of expected content (1-past)
231 const char *C; // position of next char in content
235 const char *PEnd; // previous next/search subject end (1-past)
238 } // namespace anonymous
240 /// ParseDirective - Go through the comment and see if it indicates expected
241 /// diagnostics. If so, then put them in the appropriate directive list.
243 static void ParseDirective(const char *CommentStart, unsigned CommentLen,
244 ExpectedData &ED, Preprocessor &PP,
245 SourceLocation Pos) {
246 // A single comment may contain multiple directives.
247 for (ParseHelper PH(CommentStart, CommentStart+CommentLen); !PH.Done();) {
248 // search for token: expected
249 if (!PH.Search("expected"))
258 // next token: { error | warning | note }
259 DirectiveList* DL = NULL;
260 if (PH.Next("error"))
262 else if (PH.Next("warning"))
264 else if (PH.Next("note"))
270 // default directive kind
271 bool RegexKind = false;
272 const char* KindStr = "string";
274 // next optional token: -
275 if (PH.Next("-re")) {
281 // skip optional whitespace
284 // next optional token: positive integer or a '+'.
288 else if (PH.Next("+")) {
289 Count = Directive::OneOrMoreCount;
293 // skip optional whitespace
297 if (!PH.Next("{{")) {
298 PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
299 diag::err_verify_missing_start) << KindStr;
303 const char* const ContentBegin = PH.C; // mark content begin
305 // search for token: }}
306 if (!PH.Search("}}")) {
307 PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
308 diag::err_verify_missing_end) << KindStr;
311 const char* const ContentEnd = PH.P; // mark content end
314 // build directive text; convert \n to newlines
316 StringRef NewlineStr = "\\n";
317 StringRef Content(ContentBegin, ContentEnd-ContentBegin);
320 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
321 Text += Content.substr(CPos, FPos-CPos);
323 CPos = FPos + NewlineStr.size();
326 Text.assign(ContentBegin, ContentEnd);
328 // construct new directive
329 Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
331 if (D->isValid(Error))
334 PP.Diag(Pos.getLocWithOffset(ContentBegin-PH.Begin),
335 diag::err_verify_invalid_content)
341 /// FindExpectedDiags - Lex the main source file to find all of the
342 // expected errors and warnings.
343 static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED, FileID FID) {
344 // Create a raw lexer to pull all the comments out of FID.
348 SourceManager& SM = PP.getSourceManager();
349 // Create a lexer to lex all the tokens of the main file in raw mode.
350 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
351 Lexer RawLex(FID, FromFile, SM, PP.getLangOpts());
353 // Return comments as tokens, this is how we find expected diagnostics.
354 RawLex.SetCommentRetentionState(true);
357 Tok.setKind(tok::comment);
358 while (Tok.isNot(tok::eof)) {
360 if (!Tok.is(tok::comment)) continue;
362 std::string Comment = PP.getSpelling(Tok);
363 if (Comment.empty()) continue;
365 // Find all expected errors/warnings/notes.
366 ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
370 /// PrintProblem - This takes a diagnostic map of the delta between expected and
371 /// seen diagnostics. If there's anything in it, then something unexpected
372 /// happened. Print the map out in a nice format and return "true". If the map
373 /// is empty and we're not going to print things, then return "false".
375 static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
376 const_diag_iterator diag_begin,
377 const_diag_iterator diag_end,
378 const char *Kind, bool Expected) {
379 if (diag_begin == diag_end) return 0;
381 SmallString<256> Fmt;
382 llvm::raw_svector_ostream OS(Fmt);
383 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
384 if (I->first.isInvalid() || !SourceMgr)
385 OS << "\n (frontend)";
387 OS << "\n Line " << SourceMgr->getPresumedLineNumber(I->first);
388 OS << ": " << I->second;
391 Diags.Report(diag::err_verify_inconsistent_diags)
392 << Kind << !Expected << OS.str();
393 return std::distance(diag_begin, diag_end);
396 static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
397 DirectiveList &DL, const char *Kind,
402 SmallString<256> Fmt;
403 llvm::raw_svector_ostream OS(Fmt);
404 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
406 if (D.Location.isInvalid() || !SourceMgr)
407 OS << "\n (frontend)";
409 OS << "\n Line " << SourceMgr->getPresumedLineNumber(D.Location);
410 OS << ": " << D.Text;
413 Diags.Report(diag::err_verify_inconsistent_diags)
414 << Kind << !Expected << OS.str();
418 /// CheckLists - Compare expected to seen diagnostic lists and return the
419 /// the difference between them.
421 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
424 const_diag_iterator d2_begin,
425 const_diag_iterator d2_end) {
426 DirectiveList LeftOnly;
427 DiagList Right(d2_begin, d2_end);
429 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
431 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.Location);
432 bool FoundOnce = false;
434 for (unsigned i = 0; i < D.Count; ++i) {
435 DiagList::iterator II, IE;
436 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
437 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
438 if (LineNo1 != LineNo2)
441 const std::string &RightText = II->second;
442 if (D.Match(RightText))
446 if (D.Count == D.OneOrMoreCount) {
448 LeftOnly.push_back(*I);
449 // We are only interested in at least one match, so exit the loop.
453 LeftOnly.push_back(*I);
455 // Found. The same cannot be found twice.
461 // Now all that's left in Right are those that were not matched.
462 unsigned num = PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true);
463 num += PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
468 /// CheckResults - This compares the expected results to those that
469 /// were actually reported. It emits any discrepencies. Return "true" if there
470 /// were problems. Return "false" otherwise.
472 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
473 const TextDiagnosticBuffer &Buffer,
475 // We want to capture the delta between what was expected and what was
478 // Expected \ Seen - set expected but not seen
479 // Seen \ Expected - set seen but not expected
480 unsigned NumProblems = 0;
482 // See if there are error mismatches.
483 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
484 Buffer.err_begin(), Buffer.err_end());
486 // See if there are warning mismatches.
487 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
488 Buffer.warn_begin(), Buffer.warn_end());
490 // See if there are note mismatches.
491 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
492 Buffer.note_begin(), Buffer.note_end());
497 void VerifyDiagnosticConsumer::CheckDiagnostics() {
500 // Ensure any diagnostics go to the primary client.
501 bool OwnsCurClient = Diags.ownsClient();
502 DiagnosticConsumer *CurClient = Diags.takeClient();
503 Diags.setClient(PrimaryClient, false);
505 // If we have a preprocessor, scan the source for expected diagnostic
506 // markers. If not then any diagnostics are unexpected.
507 if (CurrentPreprocessor) {
508 SourceManager &SM = CurrentPreprocessor->getSourceManager();
509 // Extract expected-error strings from main file.
510 FindExpectedDiags(*CurrentPreprocessor, ED, SM.getMainFileID());
511 // Only check for expectations in other diagnostic locations
512 // if they are not the main file (via ID or FileEntry) - the main
513 // file has already been looked at, and its expectations must not
515 if (!FirstErrorFID.isInvalid() && FirstErrorFID != SM.getMainFileID()
516 && (!SM.getFileEntryForID(FirstErrorFID)
517 || (SM.getFileEntryForID(FirstErrorFID) !=
518 SM.getFileEntryForID(SM.getMainFileID())))) {
519 FindExpectedDiags(*CurrentPreprocessor, ED, FirstErrorFID);
520 FirstErrorFID = FileID();
523 // Check that the expected diagnostics occurred.
524 NumErrors += CheckResults(Diags, SM, *Buffer, ED);
526 NumErrors += (PrintProblem(Diags, 0,
527 Buffer->err_begin(), Buffer->err_end(),
529 PrintProblem(Diags, 0,
530 Buffer->warn_begin(), Buffer->warn_end(),
532 PrintProblem(Diags, 0,
533 Buffer->note_begin(), Buffer->note_end(),
538 Diags.setClient(CurClient, OwnsCurClient);
540 // Reset the buffer, we have processed all the diagnostics in it.
541 Buffer.reset(new TextDiagnosticBuffer());
545 VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const {
546 if (!Diags.getClient())
547 Diags.setClient(PrimaryClient->clone(Diags));
549 return new VerifyDiagnosticConsumer(Diags);
552 Directive* Directive::Create(bool RegexKind, const SourceLocation &Location,
553 const std::string &Text, unsigned Count) {
555 return new RegexDirective(Location, Text, Count);
556 return new StandardDirective(Location, Text, Count);