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"
21 using namespace clang;
23 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
24 : Diags(_Diags), PrimaryClient(Diags.getClient()),
25 OwnsPrimaryClient(Diags.ownsClient()),
26 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0)
31 VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
34 if (OwnsPrimaryClient)
38 // DiagnosticConsumer interface.
40 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
41 const Preprocessor *PP) {
42 // FIXME: Const hack, we screw up the preprocessor but in practice its ok
43 // because it doesn't get reused. It would be better if we could make a copy
45 CurrentPreprocessor = const_cast<Preprocessor*>(PP);
47 PrimaryClient->BeginSourceFile(LangOpts, PP);
50 void VerifyDiagnosticConsumer::EndSourceFile() {
53 PrimaryClient->EndSourceFile();
55 CurrentPreprocessor = 0;
58 void VerifyDiagnosticConsumer::HandleDiagnostic(
59 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
60 if (FirstErrorFID.isInvalid() && Info.hasSourceManager()) {
61 const SourceManager &SM = Info.getSourceManager();
62 FirstErrorFID = SM.getFileID(Info.getLocation());
64 // Send the diagnostic to the buffer, we will check it once we reach the end
65 // of the source file (or are destructed).
66 Buffer->HandleDiagnostic(DiagLevel, Info);
69 //===----------------------------------------------------------------------===//
70 // Checking diagnostics implementation.
71 //===----------------------------------------------------------------------===//
73 typedef TextDiagnosticBuffer::DiagList DiagList;
74 typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
78 /// Directive - Abstract class representing a parsed verify directive.
82 static Directive* Create(bool RegexKind, const SourceLocation &Location,
83 const std::string &Text, unsigned Count);
85 SourceLocation Location;
86 const std::string Text;
89 virtual ~Directive() { }
91 // Returns true if directive text is valid.
92 // Otherwise returns false and populates E.
93 virtual bool isValid(std::string &Error) = 0;
95 // Returns true on match.
96 virtual bool Match(const std::string &S) = 0;
99 Directive(const SourceLocation &Location, const std::string &Text,
101 : Location(Location), Text(Text), Count(Count) { }
104 Directive(const Directive&); // DO NOT IMPLEMENT
105 void operator=(const Directive&); // DO NOT IMPLEMENT
108 /// StandardDirective - Directive with string matching.
110 class StandardDirective : public Directive {
112 StandardDirective(const SourceLocation &Location, const std::string &Text,
114 : Directive(Location, Text, Count) { }
116 virtual bool isValid(std::string &Error) {
117 // all strings are considered valid; even empty ones
121 virtual bool Match(const std::string &S) {
122 return S.find(Text) != std::string::npos ||
123 Text.find(S) != std::string::npos;
127 /// RegexDirective - Directive with regular-expression matching.
129 class RegexDirective : public Directive {
131 RegexDirective(const SourceLocation &Location, const std::string &Text,
133 : Directive(Location, Text, Count), Regex(Text) { }
135 virtual bool isValid(std::string &Error) {
136 if (Regex.isValid(Error))
141 virtual bool Match(const std::string &S) {
142 return Regex.match(S);
149 typedef std::vector<Directive*> DirectiveList;
151 /// ExpectedData - owns directive objects and deletes on destructor.
153 struct ExpectedData {
154 DirectiveList Errors;
155 DirectiveList Warnings;
159 DirectiveList* Lists[] = { &Errors, &Warnings, &Notes, 0 };
160 for (DirectiveList **PL = Lists; *PL; ++PL) {
161 DirectiveList * const L = *PL;
162 for (DirectiveList::iterator I = L->begin(), E = L->end(); I != E; ++I)
171 ParseHelper(const char *Begin, const char *End)
172 : Begin(Begin), End(End), C(Begin), P(Begin), PEnd(NULL) { }
174 // Return true if string literal is next.
175 bool Next(StringRef S) {
180 return !memcmp(P, S.data(), S.size());
183 // Return true if number is next.
184 // Output N only if number is next.
185 bool Next(unsigned &N) {
188 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
199 // Return true if string literal is found.
200 // When true, P marks begin-position of S in content.
201 bool Search(StringRef S) {
202 P = std::search(C, End, S.begin(), S.end());
207 // Advance 1-past previous next/search.
208 // Behavior is undefined if previous next/search failed.
214 // Skip zero or more whitespace.
215 void SkipWhitespace() {
216 for (; C < End && isspace(*C); ++C)
220 // Return true if EOF reached.
225 const char * const Begin; // beginning of expected content
226 const char * const End; // end of expected content (1-past)
227 const char *C; // position of next char in content
231 const char *PEnd; // previous next/search subject end (1-past)
234 } // namespace anonymous
236 /// ParseDirective - Go through the comment and see if it indicates expected
237 /// diagnostics. If so, then put them in the appropriate directive list.
239 static void ParseDirective(const char *CommentStart, unsigned CommentLen,
240 ExpectedData &ED, Preprocessor &PP,
241 SourceLocation Pos) {
242 // A single comment may contain multiple directives.
243 for (ParseHelper PH(CommentStart, CommentStart+CommentLen); !PH.Done();) {
244 // search for token: expected
245 if (!PH.Search("expected"))
254 // next token: { error | warning | note }
255 DirectiveList* DL = NULL;
256 if (PH.Next("error"))
258 else if (PH.Next("warning"))
260 else if (PH.Next("note"))
266 // default directive kind
267 bool RegexKind = false;
268 const char* KindStr = "string";
270 // next optional token: -
271 if (PH.Next("-re")) {
277 // skip optional whitespace
280 // next optional token: positive integer
285 // skip optional whitespace
289 if (!PH.Next("{{")) {
290 PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
291 diag::err_verify_missing_start) << KindStr;
295 const char* const ContentBegin = PH.C; // mark content begin
297 // search for token: }}
298 if (!PH.Search("}}")) {
299 PP.Diag(Pos.getLocWithOffset(PH.C-PH.Begin),
300 diag::err_verify_missing_end) << KindStr;
303 const char* const ContentEnd = PH.P; // mark content end
306 // build directive text; convert \n to newlines
308 StringRef NewlineStr = "\\n";
309 StringRef Content(ContentBegin, ContentEnd-ContentBegin);
312 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
313 Text += Content.substr(CPos, FPos-CPos);
315 CPos = FPos + NewlineStr.size();
318 Text.assign(ContentBegin, ContentEnd);
320 // construct new directive
321 Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
323 if (D->isValid(Error))
326 PP.Diag(Pos.getLocWithOffset(ContentBegin-PH.Begin),
327 diag::err_verify_invalid_content)
333 /// FindExpectedDiags - Lex the main source file to find all of the
334 // expected errors and warnings.
335 static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED, FileID FID) {
336 // Create a raw lexer to pull all the comments out of FID.
340 SourceManager& SM = PP.getSourceManager();
341 // Create a lexer to lex all the tokens of the main file in raw mode.
342 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
343 Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
345 // Return comments as tokens, this is how we find expected diagnostics.
346 RawLex.SetCommentRetentionState(true);
349 Tok.setKind(tok::comment);
350 while (Tok.isNot(tok::eof)) {
352 if (!Tok.is(tok::comment)) continue;
354 std::string Comment = PP.getSpelling(Tok);
355 if (Comment.empty()) continue;
357 // Find all expected errors/warnings/notes.
358 ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
362 /// PrintProblem - This takes a diagnostic map of the delta between expected and
363 /// seen diagnostics. If there's anything in it, then something unexpected
364 /// happened. Print the map out in a nice format and return "true". If the map
365 /// is empty and we're not going to print things, then return "false".
367 static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
368 const_diag_iterator diag_begin,
369 const_diag_iterator diag_end,
370 const char *Kind, bool Expected) {
371 if (diag_begin == diag_end) return 0;
373 llvm::SmallString<256> Fmt;
374 llvm::raw_svector_ostream OS(Fmt);
375 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
376 if (I->first.isInvalid() || !SourceMgr)
377 OS << "\n (frontend)";
379 OS << "\n Line " << SourceMgr->getPresumedLineNumber(I->first);
380 OS << ": " << I->second;
383 Diags.Report(diag::err_verify_inconsistent_diags)
384 << Kind << !Expected << OS.str();
385 return std::distance(diag_begin, diag_end);
388 static unsigned PrintProblem(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
389 DirectiveList &DL, const char *Kind,
394 llvm::SmallString<256> Fmt;
395 llvm::raw_svector_ostream OS(Fmt);
396 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
398 if (D.Location.isInvalid() || !SourceMgr)
399 OS << "\n (frontend)";
401 OS << "\n Line " << SourceMgr->getPresumedLineNumber(D.Location);
402 OS << ": " << D.Text;
405 Diags.Report(diag::err_verify_inconsistent_diags)
406 << Kind << !Expected << OS.str();
410 /// CheckLists - Compare expected to seen diagnostic lists and return the
411 /// the difference between them.
413 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
416 const_diag_iterator d2_begin,
417 const_diag_iterator d2_end) {
418 DirectiveList LeftOnly;
419 DiagList Right(d2_begin, d2_end);
421 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
423 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.Location);
425 for (unsigned i = 0; i < D.Count; ++i) {
426 DiagList::iterator II, IE;
427 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
428 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
429 if (LineNo1 != LineNo2)
432 const std::string &RightText = II->second;
433 if (D.Match(RightText))
438 LeftOnly.push_back(*I);
440 // Found. The same cannot be found twice.
445 // Now all that's left in Right are those that were not matched.
447 return (PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true) +
448 PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
452 /// CheckResults - This compares the expected results to those that
453 /// were actually reported. It emits any discrepencies. Return "true" if there
454 /// were problems. Return "false" otherwise.
456 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
457 const TextDiagnosticBuffer &Buffer,
459 // We want to capture the delta between what was expected and what was
462 // Expected \ Seen - set expected but not seen
463 // Seen \ Expected - set seen but not expected
464 unsigned NumProblems = 0;
466 // See if there are error mismatches.
467 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
468 Buffer.err_begin(), Buffer.err_end());
470 // See if there are warning mismatches.
471 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
472 Buffer.warn_begin(), Buffer.warn_end());
474 // See if there are note mismatches.
475 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
476 Buffer.note_begin(), Buffer.note_end());
481 void VerifyDiagnosticConsumer::CheckDiagnostics() {
484 // Ensure any diagnostics go to the primary client.
485 bool OwnsCurClient = Diags.ownsClient();
486 DiagnosticConsumer *CurClient = Diags.takeClient();
487 Diags.setClient(PrimaryClient, false);
489 // If we have a preprocessor, scan the source for expected diagnostic
490 // markers. If not then any diagnostics are unexpected.
491 if (CurrentPreprocessor) {
492 SourceManager &SM = CurrentPreprocessor->getSourceManager();
493 // Extract expected-error strings from main file.
494 FindExpectedDiags(*CurrentPreprocessor, ED, SM.getMainFileID());
495 // Only check for expectations in other diagnostic locations
496 // if they are not the main file (via ID or FileEntry) - the main
497 // file has already been looked at, and its expectations must not
499 if (!FirstErrorFID.isInvalid() && FirstErrorFID != SM.getMainFileID()
500 && (!SM.getFileEntryForID(FirstErrorFID)
501 || (SM.getFileEntryForID(FirstErrorFID) !=
502 SM.getFileEntryForID(SM.getMainFileID())))) {
503 FindExpectedDiags(*CurrentPreprocessor, ED, FirstErrorFID);
504 FirstErrorFID = FileID();
507 // Check that the expected diagnostics occurred.
508 NumErrors += CheckResults(Diags, SM, *Buffer, ED);
510 NumErrors += (PrintProblem(Diags, 0,
511 Buffer->err_begin(), Buffer->err_end(),
513 PrintProblem(Diags, 0,
514 Buffer->warn_begin(), Buffer->warn_end(),
516 PrintProblem(Diags, 0,
517 Buffer->note_begin(), Buffer->note_end(),
522 Diags.setClient(CurClient, OwnsCurClient);
524 // Reset the buffer, we have processed all the diagnostics in it.
525 Buffer.reset(new TextDiagnosticBuffer());
529 VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const {
530 if (!Diags.getClient())
531 Diags.setClient(PrimaryClient->clone(Diags));
533 return new VerifyDiagnosticConsumer(Diags);
536 Directive* Directive::Create(bool RegexKind, const SourceLocation &Location,
537 const std::string &Text, unsigned Count) {
539 return new RegexDirective(Location, Text, Count);
540 return new StandardDirective(Location, Text, Count);