1 //===--- VerifyDiagnosticsClient.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/VerifyDiagnosticsClient.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 VerifyDiagnosticsClient::VerifyDiagnosticsClient(Diagnostic &_Diags,
24 DiagnosticClient *_Primary)
25 : Diags(_Diags), PrimaryClient(_Primary),
26 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0) {
29 VerifyDiagnosticsClient::~VerifyDiagnosticsClient() {
33 // DiagnosticClient interface.
35 void VerifyDiagnosticsClient::BeginSourceFile(const LangOptions &LangOpts,
36 const Preprocessor *PP) {
37 // FIXME: Const hack, we screw up the preprocessor but in practice its ok
38 // because it doesn't get reused. It would be better if we could make a copy
40 CurrentPreprocessor = const_cast<Preprocessor*>(PP);
42 PrimaryClient->BeginSourceFile(LangOpts, PP);
45 void VerifyDiagnosticsClient::EndSourceFile() {
48 PrimaryClient->EndSourceFile();
50 CurrentPreprocessor = 0;
53 void VerifyDiagnosticsClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
54 const DiagnosticInfo &Info) {
55 // Send the diagnostic to the buffer, we will check it once we reach the end
56 // of the source file (or are destructed).
57 Buffer->HandleDiagnostic(DiagLevel, Info);
60 //===----------------------------------------------------------------------===//
61 // Checking diagnostics implementation.
62 //===----------------------------------------------------------------------===//
64 typedef TextDiagnosticBuffer::DiagList DiagList;
65 typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
69 /// Directive - Abstract class representing a parsed verify directive.
73 static Directive* Create(bool RegexKind, const SourceLocation &Location,
74 const std::string &Text, unsigned Count);
76 SourceLocation Location;
77 const std::string Text;
80 virtual ~Directive() { }
82 // Returns true if directive text is valid.
83 // Otherwise returns false and populates E.
84 virtual bool isValid(std::string &Error) = 0;
86 // Returns true on match.
87 virtual bool Match(const std::string &S) = 0;
90 Directive(const SourceLocation &Location, const std::string &Text,
92 : Location(Location), Text(Text), Count(Count) { }
95 Directive(const Directive&); // DO NOT IMPLEMENT
96 void operator=(const Directive&); // DO NOT IMPLEMENT
99 /// StandardDirective - Directive with string matching.
101 class StandardDirective : public Directive {
103 StandardDirective(const SourceLocation &Location, const std::string &Text,
105 : Directive(Location, Text, Count) { }
107 virtual bool isValid(std::string &Error) {
108 // all strings are considered valid; even empty ones
112 virtual bool Match(const std::string &S) {
113 return S.find(Text) != std::string::npos ||
114 Text.find(S) != std::string::npos;
118 /// RegexDirective - Directive with regular-expression matching.
120 class RegexDirective : public Directive {
122 RegexDirective(const SourceLocation &Location, const std::string &Text,
124 : Directive(Location, Text, Count), Regex(Text) { }
126 virtual bool isValid(std::string &Error) {
127 if (Regex.isValid(Error))
132 virtual bool Match(const std::string &S) {
133 return Regex.match(S);
140 typedef std::vector<Directive*> DirectiveList;
142 /// ExpectedData - owns directive objects and deletes on destructor.
144 struct ExpectedData {
145 DirectiveList Errors;
146 DirectiveList Warnings;
150 DirectiveList* Lists[] = { &Errors, &Warnings, &Notes, 0 };
151 for (DirectiveList **PL = Lists; *PL; ++PL) {
152 DirectiveList * const L = *PL;
153 for (DirectiveList::iterator I = L->begin(), E = L->end(); I != E; ++I)
162 ParseHelper(const char *Begin, const char *End)
163 : Begin(Begin), End(End), C(Begin), P(Begin), PEnd(NULL) { }
165 // Return true if string literal is next.
166 bool Next(llvm::StringRef S) {
171 return !memcmp(P, S.data(), S.size());
174 // Return true if number is next.
175 // Output N only if number is next.
176 bool Next(unsigned &N) {
179 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
190 // Return true if string literal is found.
191 // When true, P marks begin-position of S in content.
192 bool Search(llvm::StringRef S) {
193 P = std::search(C, End, S.begin(), S.end());
198 // Advance 1-past previous next/search.
199 // Behavior is undefined if previous next/search failed.
205 // Skip zero or more whitespace.
206 void SkipWhitespace() {
207 for (; C < End && isspace(*C); ++C)
211 // Return true if EOF reached.
216 const char * const Begin; // beginning of expected content
217 const char * const End; // end of expected content (1-past)
218 const char *C; // position of next char in content
222 const char *PEnd; // previous next/search subject end (1-past)
225 } // namespace anonymous
227 /// ParseDirective - Go through the comment and see if it indicates expected
228 /// diagnostics. If so, then put them in the appropriate directive list.
230 static void ParseDirective(const char *CommentStart, unsigned CommentLen,
231 ExpectedData &ED, Preprocessor &PP,
232 SourceLocation Pos) {
233 // A single comment may contain multiple directives.
234 for (ParseHelper PH(CommentStart, CommentStart+CommentLen); !PH.Done();) {
235 // search for token: expected
236 if (!PH.Search("expected"))
245 // next token: { error | warning | note }
246 DirectiveList* DL = NULL;
247 if (PH.Next("error"))
249 else if (PH.Next("warning"))
251 else if (PH.Next("note"))
257 // default directive kind
258 bool RegexKind = false;
259 const char* KindStr = "string";
261 // next optional token: -
262 if (PH.Next("-re")) {
268 // skip optional whitespace
271 // next optional token: positive integer
276 // skip optional whitespace
280 if (!PH.Next("{{")) {
281 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
282 diag::err_verify_missing_start) << KindStr;
286 const char* const ContentBegin = PH.C; // mark content begin
288 // search for token: }}
289 if (!PH.Search("}}")) {
290 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
291 diag::err_verify_missing_end) << KindStr;
294 const char* const ContentEnd = PH.P; // mark content end
297 // build directive text; convert \n to newlines
299 llvm::StringRef NewlineStr = "\\n";
300 llvm::StringRef Content(ContentBegin, ContentEnd-ContentBegin);
303 while ((FPos = Content.find(NewlineStr, CPos)) != llvm::StringRef::npos) {
304 Text += Content.substr(CPos, FPos-CPos);
306 CPos = FPos + NewlineStr.size();
309 Text.assign(ContentBegin, ContentEnd);
311 // construct new directive
312 Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
314 if (D->isValid(Error))
317 PP.Diag(Pos.getFileLocWithOffset(ContentBegin-PH.Begin),
318 diag::err_verify_invalid_content)
324 /// FindExpectedDiags - Lex the main source file to find all of the
325 // expected errors and warnings.
326 static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED) {
327 // Create a raw lexer to pull all the comments out of the main file. We don't
328 // want to look in #include'd headers for expected-error strings.
329 SourceManager &SM = PP.getSourceManager();
330 FileID FID = SM.getMainFileID();
331 if (SM.getMainFileID().isInvalid())
334 // Create a lexer to lex all the tokens of the main file in raw mode.
335 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
336 Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
338 // Return comments as tokens, this is how we find expected diagnostics.
339 RawLex.SetCommentRetentionState(true);
342 Tok.setKind(tok::comment);
343 while (Tok.isNot(tok::eof)) {
345 if (!Tok.is(tok::comment)) continue;
347 std::string Comment = PP.getSpelling(Tok);
348 if (Comment.empty()) continue;
350 // Find all expected errors/warnings/notes.
351 ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
355 /// PrintProblem - This takes a diagnostic map of the delta between expected and
356 /// seen diagnostics. If there's anything in it, then something unexpected
357 /// happened. Print the map out in a nice format and return "true". If the map
358 /// is empty and we're not going to print things, then return "false".
360 static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
361 const_diag_iterator diag_begin,
362 const_diag_iterator diag_end,
363 const char *Kind, bool Expected) {
364 if (diag_begin == diag_end) return 0;
366 llvm::SmallString<256> Fmt;
367 llvm::raw_svector_ostream OS(Fmt);
368 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
369 if (I->first.isInvalid() || !SourceMgr)
370 OS << "\n (frontend)";
372 OS << "\n Line " << SourceMgr->getPresumedLineNumber(I->first);
373 OS << ": " << I->second;
376 Diags.Report(diag::err_verify_inconsistent_diags)
377 << Kind << !Expected << OS.str();
378 return std::distance(diag_begin, diag_end);
381 static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
382 DirectiveList &DL, const char *Kind,
387 llvm::SmallString<256> Fmt;
388 llvm::raw_svector_ostream OS(Fmt);
389 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
391 if (D.Location.isInvalid() || !SourceMgr)
392 OS << "\n (frontend)";
394 OS << "\n Line " << SourceMgr->getPresumedLineNumber(D.Location);
395 OS << ": " << D.Text;
398 Diags.Report(diag::err_verify_inconsistent_diags)
399 << Kind << !Expected << OS.str();
403 /// CheckLists - Compare expected to seen diagnostic lists and return the
404 /// the difference between them.
406 static unsigned CheckLists(Diagnostic &Diags, SourceManager &SourceMgr,
409 const_diag_iterator d2_begin,
410 const_diag_iterator d2_end) {
411 DirectiveList LeftOnly;
412 DiagList Right(d2_begin, d2_end);
414 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
416 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.Location);
418 for (unsigned i = 0; i < D.Count; ++i) {
419 DiagList::iterator II, IE;
420 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
421 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
422 if (LineNo1 != LineNo2)
425 const std::string &RightText = II->second;
426 if (D.Match(RightText))
431 LeftOnly.push_back(*I);
433 // Found. The same cannot be found twice.
438 // Now all that's left in Right are those that were not matched.
440 return (PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true) +
441 PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
445 /// CheckResults - This compares the expected results to those that
446 /// were actually reported. It emits any discrepencies. Return "true" if there
447 /// were problems. Return "false" otherwise.
449 static unsigned CheckResults(Diagnostic &Diags, SourceManager &SourceMgr,
450 const TextDiagnosticBuffer &Buffer,
452 // We want to capture the delta between what was expected and what was
455 // Expected \ Seen - set expected but not seen
456 // Seen \ Expected - set seen but not expected
457 unsigned NumProblems = 0;
459 // See if there are error mismatches.
460 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
461 Buffer.err_begin(), Buffer.err_end());
463 // See if there are warning mismatches.
464 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
465 Buffer.warn_begin(), Buffer.warn_end());
467 // See if there are note mismatches.
468 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
469 Buffer.note_begin(), Buffer.note_end());
474 void VerifyDiagnosticsClient::CheckDiagnostics() {
477 // Ensure any diagnostics go to the primary client.
478 DiagnosticClient *CurClient = Diags.takeClient();
479 Diags.setClient(PrimaryClient.get());
481 // If we have a preprocessor, scan the source for expected diagnostic
482 // markers. If not then any diagnostics are unexpected.
483 if (CurrentPreprocessor) {
484 FindExpectedDiags(*CurrentPreprocessor, ED);
486 // Check that the expected diagnostics occurred.
487 NumErrors += CheckResults(Diags, CurrentPreprocessor->getSourceManager(),
490 NumErrors += (PrintProblem(Diags, 0,
491 Buffer->err_begin(), Buffer->err_end(),
493 PrintProblem(Diags, 0,
494 Buffer->warn_begin(), Buffer->warn_end(),
496 PrintProblem(Diags, 0,
497 Buffer->note_begin(), Buffer->note_end(),
502 Diags.setClient(CurClient);
504 // Reset the buffer, we have processed all the diagnostics in it.
505 Buffer.reset(new TextDiagnosticBuffer());
508 Directive* Directive::Create(bool RegexKind, const SourceLocation &Location,
509 const std::string &Text, unsigned Count) {
511 return new RegexDirective(Location, Text, Count);
512 return new StandardDirective(Location, Text, Count);