blob: 31eb28f912ca7eb13460c80894a63d439033c02a [file] [log] [blame]
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +00001//===--- VerifyDiagnosticsClient.cpp - Verifying Diagnostic Client --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a concrete diagnostic client, which buffers the diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
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"
Chris Lattner60909e12010-04-28 20:02:30 +000019#include "llvm/Support/Regex.h"
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000020#include "llvm/Support/raw_ostream.h"
21using namespace clang;
22
Daniel Dunbar221c7212009-11-14 07:53:24 +000023VerifyDiagnosticsClient::VerifyDiagnosticsClient(Diagnostic &_Diags,
24 DiagnosticClient *_Primary)
25 : Diags(_Diags), PrimaryClient(_Primary),
26 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0), NumErrors(0) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000027}
28
29VerifyDiagnosticsClient::~VerifyDiagnosticsClient() {
30 CheckDiagnostics();
31}
32
33// DiagnosticClient interface.
34
35void 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
39 // though.
40 CurrentPreprocessor = const_cast<Preprocessor*>(PP);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000041
42 PrimaryClient->BeginSourceFile(LangOpts, PP);
43}
44
45void VerifyDiagnosticsClient::EndSourceFile() {
46 CheckDiagnostics();
47
48 PrimaryClient->EndSourceFile();
49
50 CurrentPreprocessor = 0;
51}
Daniel Dunbar221c7212009-11-14 07:53:24 +000052
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000053void 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);
58}
59
60// FIXME: It would be nice to just get this from the primary diagnostic client
61// or something.
62bool VerifyDiagnosticsClient::HadErrors() {
63 CheckDiagnostics();
64
65 return NumErrors != 0;
66}
67
68//===----------------------------------------------------------------------===//
69// Checking diagnostics implementation.
70//===----------------------------------------------------------------------===//
71
72typedef TextDiagnosticBuffer::DiagList DiagList;
73typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
74
Chris Lattner60909e12010-04-28 20:02:30 +000075namespace {
76
77/// Directive - Abstract class representing a parsed verify directive.
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000078///
Chris Lattner60909e12010-04-28 20:02:30 +000079class Directive {
80public:
81 static Directive* Create(bool RegexKind, const SourceLocation &Location,
82 const std::string &Text, unsigned Count);
83public:
84 SourceLocation Location;
85 const std::string Text;
86 unsigned Count;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000087
Chris Lattner60909e12010-04-28 20:02:30 +000088 virtual ~Directive() { }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000089
Chris Lattner60909e12010-04-28 20:02:30 +000090 // Returns true if directive text is valid.
91 // Otherwise returns false and populates E.
92 virtual bool isValid(std::string &Error) = 0;
93
94 // Returns true on match.
95 virtual bool Match(const std::string &S) = 0;
96
97protected:
98 Directive(const SourceLocation &Location, const std::string &Text,
99 unsigned Count)
100 : Location(Location), Text(Text), Count(Count) { }
101
102private:
Argyrios Kyrtzidisc83d2d72010-08-15 10:17:39 +0000103 Directive(const Directive&); // DO NOT IMPLEMENT
104 void operator=(const Directive&); // DO NOT IMPLEMENT
Chris Lattner60909e12010-04-28 20:02:30 +0000105};
106
107/// StandardDirective - Directive with string matching.
108///
109class StandardDirective : public Directive {
110public:
111 StandardDirective(const SourceLocation &Location, const std::string &Text,
112 unsigned Count)
113 : Directive(Location, Text, Count) { }
114
115 virtual bool isValid(std::string &Error) {
116 // all strings are considered valid; even empty ones
117 return true;
118 }
119
120 virtual bool Match(const std::string &S) {
121 return S.find(Text) != std::string::npos ||
122 Text.find(S) != std::string::npos;
123 }
124};
125
126/// RegexDirective - Directive with regular-expression matching.
127///
128class RegexDirective : public Directive {
129public:
130 RegexDirective(const SourceLocation &Location, const std::string &Text,
131 unsigned Count)
132 : Directive(Location, Text, Count), Regex(Text) { }
133
134 virtual bool isValid(std::string &Error) {
135 if (Regex.isValid(Error))
136 return true;
137 return false;
138 }
139
140 virtual bool Match(const std::string &S) {
141 return Regex.match(S);
142 }
143
144private:
145 llvm::Regex Regex;
146};
147
148typedef std::vector<Directive*> DirectiveList;
149
150/// ExpectedData - owns directive objects and deletes on destructor.
151///
152struct ExpectedData {
153 DirectiveList Errors;
154 DirectiveList Warnings;
155 DirectiveList Notes;
156
157 ~ExpectedData() {
158 DirectiveList* Lists[] = { &Errors, &Warnings, &Notes, 0 };
159 for (DirectiveList **PL = Lists; *PL; ++PL) {
160 DirectiveList * const L = *PL;
161 for (DirectiveList::iterator I = L->begin(), E = L->end(); I != E; ++I)
162 delete *I;
163 }
164 }
165};
166
167class ParseHelper
168{
169public:
170 ParseHelper(const char *Begin, const char *End)
171 : Begin(Begin), End(End), C(Begin), P(Begin), PEnd(NULL) { }
172
173 // Return true if string literal is next.
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000174 bool Next(llvm::StringRef S) {
Chris Lattner60909e12010-04-28 20:02:30 +0000175 P = C;
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000176 PEnd = C + S.size();
Chris Lattner60909e12010-04-28 20:02:30 +0000177 if (PEnd > End)
178 return false;
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000179 return !memcmp(P, S.data(), S.size());
Chris Lattner60909e12010-04-28 20:02:30 +0000180 }
181
182 // Return true if number is next.
183 // Output N only if number is next.
184 bool Next(unsigned &N) {
185 unsigned TMP = 0;
186 P = C;
187 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
188 TMP *= 10;
189 TMP += P[0] - '0';
190 }
191 if (P == C)
192 return false;
193 PEnd = P;
194 N = TMP;
195 return true;
196 }
197
198 // Return true if string literal is found.
199 // When true, P marks begin-position of S in content.
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000200 bool Search(llvm::StringRef S) {
Chris Lattner60909e12010-04-28 20:02:30 +0000201 P = std::search(C, End, S.begin(), S.end());
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000202 PEnd = P + S.size();
Chris Lattner60909e12010-04-28 20:02:30 +0000203 return P != End;
204 }
205
206 // Advance 1-past previous next/search.
207 // Behavior is undefined if previous next/search failed.
208 bool Advance() {
209 C = PEnd;
210 return C < End;
211 }
212
213 // Skip zero or more whitespace.
214 void SkipWhitespace() {
215 for (; C < End && isspace(*C); ++C)
216 ;
217 }
218
219 // Return true if EOF reached.
220 bool Done() {
221 return !(C < End);
222 }
223
224 const char * const Begin; // beginning of expected content
225 const char * const End; // end of expected content (1-past)
226 const char *C; // position of next char in content
227 const char *P;
228
229private:
230 const char *PEnd; // previous next/search subject end (1-past)
231};
232
233} // namespace anonymous
234
235/// ParseDirective - Go through the comment and see if it indicates expected
236/// diagnostics. If so, then put them in the appropriate directive list.
237///
238static void ParseDirective(const char *CommentStart, unsigned CommentLen,
239 ExpectedData &ED, Preprocessor &PP,
240 SourceLocation Pos) {
241 // A single comment may contain multiple directives.
242 for (ParseHelper PH(CommentStart, CommentStart+CommentLen); !PH.Done();) {
243 // search for token: expected
244 if (!PH.Search("expected"))
245 break;
246 PH.Advance();
247
248 // next token: -
249 if (!PH.Next("-"))
250 continue;
251 PH.Advance();
252
253 // next token: { error | warning | note }
254 DirectiveList* DL = NULL;
255 if (PH.Next("error"))
256 DL = &ED.Errors;
257 else if (PH.Next("warning"))
258 DL = &ED.Warnings;
259 else if (PH.Next("note"))
260 DL = &ED.Notes;
261 else
262 continue;
263 PH.Advance();
264
265 // default directive kind
266 bool RegexKind = false;
267 const char* KindStr = "string";
268
269 // next optional token: -
270 if (PH.Next("-re")) {
271 PH.Advance();
272 RegexKind = true;
273 KindStr = "regex";
274 }
275
276 // skip optional whitespace
277 PH.SkipWhitespace();
278
279 // next optional token: positive integer
280 unsigned Count = 1;
281 if (PH.Next(Count))
282 PH.Advance();
283
284 // skip optional whitespace
285 PH.SkipWhitespace();
286
287 // next token: {{
288 if (!PH.Next("{{")) {
289 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
290 diag::err_verify_missing_start) << KindStr;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000291 continue;
292 }
Chris Lattner60909e12010-04-28 20:02:30 +0000293 PH.Advance();
294 const char* const ContentBegin = PH.C; // mark content begin
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000295
Chris Lattner60909e12010-04-28 20:02:30 +0000296 // search for token: }}
297 if (!PH.Search("}}")) {
298 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
299 diag::err_verify_missing_end) << KindStr;
300 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000301 }
Chris Lattner60909e12010-04-28 20:02:30 +0000302 const char* const ContentEnd = PH.P; // mark content end
303 PH.Advance();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000304
Chris Lattner60909e12010-04-28 20:02:30 +0000305 // build directive text; convert \n to newlines
306 std::string Text;
307 llvm::StringRef NewlineStr = "\\n";
308 llvm::StringRef Content(ContentBegin, ContentEnd-ContentBegin);
309 size_t CPos = 0;
310 size_t FPos;
311 while ((FPos = Content.find(NewlineStr, CPos)) != llvm::StringRef::npos) {
312 Text += Content.substr(CPos, FPos-CPos);
313 Text += '\n';
314 CPos = FPos + NewlineStr.size();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000315 }
Chris Lattner60909e12010-04-28 20:02:30 +0000316 if (Text.empty())
317 Text.assign(ContentBegin, ContentEnd);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000318
Chris Lattner60909e12010-04-28 20:02:30 +0000319 // construct new directive
320 Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
321 std::string Error;
322 if (D->isValid(Error))
323 DL->push_back(D);
324 else {
325 PP.Diag(Pos.getFileLocWithOffset(ContentBegin-PH.Begin),
326 diag::err_verify_invalid_content)
327 << KindStr << Error;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000328 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000329 }
330}
331
332/// FindExpectedDiags - Lex the main source file to find all of the
333// expected errors and warnings.
Chris Lattner60909e12010-04-28 20:02:30 +0000334static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000335 // Create a raw lexer to pull all the comments out of the main file. We don't
336 // want to look in #include'd headers for expected-error strings.
Chris Lattner6e290142009-11-30 04:18:44 +0000337 SourceManager &SM = PP.getSourceManager();
338 FileID FID = SM.getMainFileID();
339 if (SM.getMainFileID().isInvalid())
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000340 return;
341
342 // Create a lexer to lex all the tokens of the main file in raw mode.
Chris Lattner6e290142009-11-30 04:18:44 +0000343 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
344 Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000345
346 // Return comments as tokens, this is how we find expected diagnostics.
347 RawLex.SetCommentRetentionState(true);
348
349 Token Tok;
350 Tok.setKind(tok::comment);
351 while (Tok.isNot(tok::eof)) {
352 RawLex.Lex(Tok);
353 if (!Tok.is(tok::comment)) continue;
354
355 std::string Comment = PP.getSpelling(Tok);
356 if (Comment.empty()) continue;
357
Chris Lattner60909e12010-04-28 20:02:30 +0000358 // Find all expected errors/warnings/notes.
359 ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000360 };
361}
362
363/// PrintProblem - This takes a diagnostic map of the delta between expected and
364/// seen diagnostics. If there's anything in it, then something unexpected
365/// happened. Print the map out in a nice format and return "true". If the map
366/// is empty and we're not going to print things, then return "false".
367///
Daniel Dunbar221c7212009-11-14 07:53:24 +0000368static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000369 const_diag_iterator diag_begin,
370 const_diag_iterator diag_end,
371 const char *Kind, bool Expected) {
372 if (diag_begin == diag_end) return 0;
373
374 llvm::SmallString<256> Fmt;
375 llvm::raw_svector_ostream OS(Fmt);
376 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000377 if (I->first.isInvalid() || !SourceMgr)
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000378 OS << "\n (frontend)";
379 else
Daniel Dunbar221c7212009-11-14 07:53:24 +0000380 OS << "\n Line " << SourceMgr->getInstantiationLineNumber(I->first);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000381 OS << ": " << I->second;
382 }
383
384 Diags.Report(diag::err_verify_inconsistent_diags)
Daniel Dunbar221c7212009-11-14 07:53:24 +0000385 << Kind << !Expected << OS.str();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000386 return std::distance(diag_begin, diag_end);
387}
388
Chris Lattner60909e12010-04-28 20:02:30 +0000389static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
390 DirectiveList &DL, const char *Kind,
391 bool Expected) {
392 if (DL.empty())
393 return 0;
394
395 llvm::SmallString<256> Fmt;
396 llvm::raw_svector_ostream OS(Fmt);
397 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
398 Directive& D = **I;
399 if (D.Location.isInvalid() || !SourceMgr)
400 OS << "\n (frontend)";
401 else
402 OS << "\n Line " << SourceMgr->getInstantiationLineNumber(D.Location);
403 OS << ": " << D.Text;
404 }
405
406 Diags.Report(diag::err_verify_inconsistent_diags)
407 << Kind << !Expected << OS.str();
408 return DL.size();
409}
410
411/// CheckLists - Compare expected to seen diagnostic lists and return the
412/// the difference between them.
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000413///
Chris Lattner60909e12010-04-28 20:02:30 +0000414static unsigned CheckLists(Diagnostic &Diags, SourceManager &SourceMgr,
415 const char *Label,
416 DirectiveList &Left,
417 const_diag_iterator d2_begin,
418 const_diag_iterator d2_end) {
419 DirectiveList LeftOnly;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000420 DiagList Right(d2_begin, d2_end);
421
Chris Lattner60909e12010-04-28 20:02:30 +0000422 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
423 Directive& D = **I;
424 unsigned LineNo1 = SourceMgr.getInstantiationLineNumber(D.Location);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000425
Chris Lattner60909e12010-04-28 20:02:30 +0000426 for (unsigned i = 0; i < D.Count; ++i) {
427 DiagList::iterator II, IE;
428 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
429 unsigned LineNo2 = SourceMgr.getInstantiationLineNumber(II->first);
430 if (LineNo1 != LineNo2)
431 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000432
Chris Lattner60909e12010-04-28 20:02:30 +0000433 const std::string &RightText = II->second;
434 if (D.Match(RightText))
435 break;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000436 }
Chris Lattner60909e12010-04-28 20:02:30 +0000437 if (II == IE) {
438 // Not found.
439 LeftOnly.push_back(*I);
440 } else {
441 // Found. The same cannot be found twice.
442 Right.erase(II);
443 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000444 }
445 }
446 // Now all that's left in Right are those that were not matched.
447
Chris Lattner60909e12010-04-28 20:02:30 +0000448 return (PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true) +
449 PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
450 Label, false));
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000451}
452
453/// CheckResults - This compares the expected results to those that
454/// were actually reported. It emits any discrepencies. Return "true" if there
455/// were problems. Return "false" otherwise.
456///
457static unsigned CheckResults(Diagnostic &Diags, SourceManager &SourceMgr,
458 const TextDiagnosticBuffer &Buffer,
Chris Lattner60909e12010-04-28 20:02:30 +0000459 ExpectedData &ED) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000460 // We want to capture the delta between what was expected and what was
461 // seen.
462 //
463 // Expected \ Seen - set expected but not seen
464 // Seen \ Expected - set seen but not expected
465 unsigned NumProblems = 0;
466
467 // See if there are error mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000468 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
469 Buffer.err_begin(), Buffer.err_end());
Daniel Dunbar221c7212009-11-14 07:53:24 +0000470
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000471 // See if there are warning mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000472 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
473 Buffer.warn_begin(), Buffer.warn_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000474
475 // See if there are note mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000476 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
477 Buffer.note_begin(), Buffer.note_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000478
479 return NumProblems;
480}
481
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000482void VerifyDiagnosticsClient::CheckDiagnostics() {
Chris Lattner60909e12010-04-28 20:02:30 +0000483 ExpectedData ED;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000484
485 // Ensure any diagnostics go to the primary client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000486 DiagnosticClient *CurClient = Diags.takeClient();
Daniel Dunbar221c7212009-11-14 07:53:24 +0000487 Diags.setClient(PrimaryClient.get());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000488
489 // If we have a preprocessor, scan the source for expected diagnostic
490 // markers. If not then any diagnostics are unexpected.
491 if (CurrentPreprocessor) {
Chris Lattner60909e12010-04-28 20:02:30 +0000492 FindExpectedDiags(*CurrentPreprocessor, ED);
Daniel Dunbar221c7212009-11-14 07:53:24 +0000493
494 // Check that the expected diagnostics occurred.
495 NumErrors += CheckResults(Diags, CurrentPreprocessor->getSourceManager(),
Chris Lattner60909e12010-04-28 20:02:30 +0000496 *Buffer, ED);
Daniel Dunbar221c7212009-11-14 07:53:24 +0000497 } else {
498 NumErrors += (PrintProblem(Diags, 0,
499 Buffer->err_begin(), Buffer->err_end(),
500 "error", false) +
501 PrintProblem(Diags, 0,
502 Buffer->warn_begin(), Buffer->warn_end(),
503 "warn", false) +
504 PrintProblem(Diags, 0,
505 Buffer->note_begin(), Buffer->note_end(),
506 "note", false));
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000507 }
508
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000509 Diags.takeClient();
Daniel Dunbar221c7212009-11-14 07:53:24 +0000510 Diags.setClient(CurClient);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000511
512 // Reset the buffer, we have processed all the diagnostics in it.
513 Buffer.reset(new TextDiagnosticBuffer());
514}
Chris Lattner60909e12010-04-28 20:02:30 +0000515
516Directive* Directive::Create(bool RegexKind, const SourceLocation &Location,
517 const std::string &Text, unsigned Count) {
518 if (RegexKind)
519 return new RegexDirective(Location, Text, Count);
520 return new StandardDirective(Location, Text, Count);
521}