blob: ae36481444da0406eaa6b718f50d34a96798233a [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:
103 Directive(const Directive&); // DO NOT IMPLEMENT
104 void operator=(const Directive&); // DO NOT IMPLEMENT
105};
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.
174 bool Next(const std::string &S) {
175 std::string::size_type LEN = S.length();
176 P = C;
177 PEnd = C + LEN;
178 if (PEnd > End)
179 return false;
180 return !memcmp(P, S.c_str(), LEN);
181 }
182
183 // Return true if number is next.
184 // Output N only if number is next.
185 bool Next(unsigned &N) {
186 unsigned TMP = 0;
187 P = C;
188 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
189 TMP *= 10;
190 TMP += P[0] - '0';
191 }
192 if (P == C)
193 return false;
194 PEnd = P;
195 N = TMP;
196 return true;
197 }
198
199 // Return true if string literal is found.
200 // When true, P marks begin-position of S in content.
201 bool Search(const std::string &S) {
202 P = std::search(C, End, S.begin(), S.end());
203 PEnd = P + S.length();
204 return P != End;
205 }
206
207 // Advance 1-past previous next/search.
208 // Behavior is undefined if previous next/search failed.
209 bool Advance() {
210 C = PEnd;
211 return C < End;
212 }
213
214 // Skip zero or more whitespace.
215 void SkipWhitespace() {
216 for (; C < End && isspace(*C); ++C)
217 ;
218 }
219
220 // Return true if EOF reached.
221 bool Done() {
222 return !(C < End);
223 }
224
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
228 const char *P;
229
230private:
231 const char *PEnd; // previous next/search subject end (1-past)
232};
233
234} // namespace anonymous
235
236/// ParseDirective - Go through the comment and see if it indicates expected
237/// diagnostics. If so, then put them in the appropriate directive list.
238///
239static 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"))
246 break;
247 PH.Advance();
248
249 // next token: -
250 if (!PH.Next("-"))
251 continue;
252 PH.Advance();
253
254 // next token: { error | warning | note }
255 DirectiveList* DL = NULL;
256 if (PH.Next("error"))
257 DL = &ED.Errors;
258 else if (PH.Next("warning"))
259 DL = &ED.Warnings;
260 else if (PH.Next("note"))
261 DL = &ED.Notes;
262 else
263 continue;
264 PH.Advance();
265
266 // default directive kind
267 bool RegexKind = false;
268 const char* KindStr = "string";
269
270 // next optional token: -
271 if (PH.Next("-re")) {
272 PH.Advance();
273 RegexKind = true;
274 KindStr = "regex";
275 }
276
277 // skip optional whitespace
278 PH.SkipWhitespace();
279
280 // next optional token: positive integer
281 unsigned Count = 1;
282 if (PH.Next(Count))
283 PH.Advance();
284
285 // skip optional whitespace
286 PH.SkipWhitespace();
287
288 // next token: {{
289 if (!PH.Next("{{")) {
290 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
291 diag::err_verify_missing_start) << KindStr;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000292 continue;
293 }
Chris Lattner60909e12010-04-28 20:02:30 +0000294 PH.Advance();
295 const char* const ContentBegin = PH.C; // mark content begin
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000296
Chris Lattner60909e12010-04-28 20:02:30 +0000297 // search for token: }}
298 if (!PH.Search("}}")) {
299 PP.Diag(Pos.getFileLocWithOffset(PH.C-PH.Begin),
300 diag::err_verify_missing_end) << KindStr;
301 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000302 }
Chris Lattner60909e12010-04-28 20:02:30 +0000303 const char* const ContentEnd = PH.P; // mark content end
304 PH.Advance();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000305
Chris Lattner60909e12010-04-28 20:02:30 +0000306 // build directive text; convert \n to newlines
307 std::string Text;
308 llvm::StringRef NewlineStr = "\\n";
309 llvm::StringRef Content(ContentBegin, ContentEnd-ContentBegin);
310 size_t CPos = 0;
311 size_t FPos;
312 while ((FPos = Content.find(NewlineStr, CPos)) != llvm::StringRef::npos) {
313 Text += Content.substr(CPos, FPos-CPos);
314 Text += '\n';
315 CPos = FPos + NewlineStr.size();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000316 }
Chris Lattner60909e12010-04-28 20:02:30 +0000317 if (Text.empty())
318 Text.assign(ContentBegin, ContentEnd);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000319
Chris Lattner60909e12010-04-28 20:02:30 +0000320 // construct new directive
321 Directive *D = Directive::Create(RegexKind, Pos, Text, Count);
322 std::string Error;
323 if (D->isValid(Error))
324 DL->push_back(D);
325 else {
326 PP.Diag(Pos.getFileLocWithOffset(ContentBegin-PH.Begin),
327 diag::err_verify_invalid_content)
328 << KindStr << Error;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000329 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000330 }
331}
332
333/// FindExpectedDiags - Lex the main source file to find all of the
334// expected errors and warnings.
Chris Lattner60909e12010-04-28 20:02:30 +0000335static void FindExpectedDiags(Preprocessor &PP, ExpectedData &ED) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000336 // Create a raw lexer to pull all the comments out of the main file. We don't
337 // want to look in #include'd headers for expected-error strings.
Chris Lattner6e290142009-11-30 04:18:44 +0000338 SourceManager &SM = PP.getSourceManager();
339 FileID FID = SM.getMainFileID();
340 if (SM.getMainFileID().isInvalid())
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000341 return;
342
343 // Create a lexer to lex all the tokens of the main file in raw mode.
Chris Lattner6e290142009-11-30 04:18:44 +0000344 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
345 Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000346
347 // Return comments as tokens, this is how we find expected diagnostics.
348 RawLex.SetCommentRetentionState(true);
349
350 Token Tok;
351 Tok.setKind(tok::comment);
352 while (Tok.isNot(tok::eof)) {
353 RawLex.Lex(Tok);
354 if (!Tok.is(tok::comment)) continue;
355
356 std::string Comment = PP.getSpelling(Tok);
357 if (Comment.empty()) continue;
358
Chris Lattner60909e12010-04-28 20:02:30 +0000359 // Find all expected errors/warnings/notes.
360 ParseDirective(&Comment[0], Comment.size(), ED, PP, Tok.getLocation());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000361 };
362}
363
364/// PrintProblem - This takes a diagnostic map of the delta between expected and
365/// seen diagnostics. If there's anything in it, then something unexpected
366/// happened. Print the map out in a nice format and return "true". If the map
367/// is empty and we're not going to print things, then return "false".
368///
Daniel Dunbar221c7212009-11-14 07:53:24 +0000369static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000370 const_diag_iterator diag_begin,
371 const_diag_iterator diag_end,
372 const char *Kind, bool Expected) {
373 if (diag_begin == diag_end) return 0;
374
375 llvm::SmallString<256> Fmt;
376 llvm::raw_svector_ostream OS(Fmt);
377 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000378 if (I->first.isInvalid() || !SourceMgr)
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000379 OS << "\n (frontend)";
380 else
Daniel Dunbar221c7212009-11-14 07:53:24 +0000381 OS << "\n Line " << SourceMgr->getInstantiationLineNumber(I->first);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000382 OS << ": " << I->second;
383 }
384
385 Diags.Report(diag::err_verify_inconsistent_diags)
Daniel Dunbar221c7212009-11-14 07:53:24 +0000386 << Kind << !Expected << OS.str();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000387 return std::distance(diag_begin, diag_end);
388}
389
Chris Lattner60909e12010-04-28 20:02:30 +0000390static unsigned PrintProblem(Diagnostic &Diags, SourceManager *SourceMgr,
391 DirectiveList &DL, const char *Kind,
392 bool Expected) {
393 if (DL.empty())
394 return 0;
395
396 llvm::SmallString<256> Fmt;
397 llvm::raw_svector_ostream OS(Fmt);
398 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
399 Directive& D = **I;
400 if (D.Location.isInvalid() || !SourceMgr)
401 OS << "\n (frontend)";
402 else
403 OS << "\n Line " << SourceMgr->getInstantiationLineNumber(D.Location);
404 OS << ": " << D.Text;
405 }
406
407 Diags.Report(diag::err_verify_inconsistent_diags)
408 << Kind << !Expected << OS.str();
409 return DL.size();
410}
411
412/// CheckLists - Compare expected to seen diagnostic lists and return the
413/// the difference between them.
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000414///
Chris Lattner60909e12010-04-28 20:02:30 +0000415static unsigned CheckLists(Diagnostic &Diags, SourceManager &SourceMgr,
416 const char *Label,
417 DirectiveList &Left,
418 const_diag_iterator d2_begin,
419 const_diag_iterator d2_end) {
420 DirectiveList LeftOnly;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000421 DiagList Right(d2_begin, d2_end);
422
Chris Lattner60909e12010-04-28 20:02:30 +0000423 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
424 Directive& D = **I;
425 unsigned LineNo1 = SourceMgr.getInstantiationLineNumber(D.Location);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000426
Chris Lattner60909e12010-04-28 20:02:30 +0000427 for (unsigned i = 0; i < D.Count; ++i) {
428 DiagList::iterator II, IE;
429 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
430 unsigned LineNo2 = SourceMgr.getInstantiationLineNumber(II->first);
431 if (LineNo1 != LineNo2)
432 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000433
Chris Lattner60909e12010-04-28 20:02:30 +0000434 const std::string &RightText = II->second;
435 if (D.Match(RightText))
436 break;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000437 }
Chris Lattner60909e12010-04-28 20:02:30 +0000438 if (II == IE) {
439 // Not found.
440 LeftOnly.push_back(*I);
441 } else {
442 // Found. The same cannot be found twice.
443 Right.erase(II);
444 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000445 }
446 }
447 // Now all that's left in Right are those that were not matched.
448
Chris Lattner60909e12010-04-28 20:02:30 +0000449 return (PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true) +
450 PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
451 Label, false));
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000452}
453
454/// CheckResults - This compares the expected results to those that
455/// were actually reported. It emits any discrepencies. Return "true" if there
456/// were problems. Return "false" otherwise.
457///
458static unsigned CheckResults(Diagnostic &Diags, SourceManager &SourceMgr,
459 const TextDiagnosticBuffer &Buffer,
Chris Lattner60909e12010-04-28 20:02:30 +0000460 ExpectedData &ED) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000461 // We want to capture the delta between what was expected and what was
462 // seen.
463 //
464 // Expected \ Seen - set expected but not seen
465 // Seen \ Expected - set seen but not expected
466 unsigned NumProblems = 0;
467
468 // See if there are error mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000469 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
470 Buffer.err_begin(), Buffer.err_end());
Daniel Dunbar221c7212009-11-14 07:53:24 +0000471
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000472 // See if there are warning mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000473 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
474 Buffer.warn_begin(), Buffer.warn_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000475
476 // See if there are note mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000477 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
478 Buffer.note_begin(), Buffer.note_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000479
480 return NumProblems;
481}
482
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000483void VerifyDiagnosticsClient::CheckDiagnostics() {
Chris Lattner60909e12010-04-28 20:02:30 +0000484 ExpectedData ED;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000485
486 // Ensure any diagnostics go to the primary client.
Daniel Dunbar221c7212009-11-14 07:53:24 +0000487 DiagnosticClient *CurClient = Diags.getClient();
488 Diags.setClient(PrimaryClient.get());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000489
490 // If we have a preprocessor, scan the source for expected diagnostic
491 // markers. If not then any diagnostics are unexpected.
492 if (CurrentPreprocessor) {
Chris Lattner60909e12010-04-28 20:02:30 +0000493 FindExpectedDiags(*CurrentPreprocessor, ED);
Daniel Dunbar221c7212009-11-14 07:53:24 +0000494
495 // Check that the expected diagnostics occurred.
496 NumErrors += CheckResults(Diags, CurrentPreprocessor->getSourceManager(),
Chris Lattner60909e12010-04-28 20:02:30 +0000497 *Buffer, ED);
Daniel Dunbar221c7212009-11-14 07:53:24 +0000498 } else {
499 NumErrors += (PrintProblem(Diags, 0,
500 Buffer->err_begin(), Buffer->err_end(),
501 "error", false) +
502 PrintProblem(Diags, 0,
503 Buffer->warn_begin(), Buffer->warn_end(),
504 "warn", false) +
505 PrintProblem(Diags, 0,
506 Buffer->note_begin(), Buffer->note_end(),
507 "note", false));
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000508 }
509
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}