blob: 82f6e916e58d91e388b414610bc1065485c61577 [file] [log] [blame]
David Blaikie621bc692011-09-26 00:38:03 +00001//===---- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ------===//
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +00002//
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
David Blaikie621bc692011-09-26 00:38:03 +000014#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000015#include "clang/Basic/CharInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/Basic/FileManager.h"
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000017#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/TextDiagnosticBuffer.h"
Jordan Rose7c304f52012-08-10 01:06:16 +000019#include "clang/Lex/HeaderSearch.h"
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000020#include "clang/Lex/Preprocessor.h"
21#include "llvm/ADT/SmallString.h"
Chris Lattner60909e12010-04-28 20:02:30 +000022#include "llvm/Support/Regex.h"
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000023#include "llvm/Support/raw_ostream.h"
Anna Zaksc035e092011-12-15 02:58:00 +000024
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000025using namespace clang;
Jordan Rose4313c012012-07-10 02:56:15 +000026typedef VerifyDiagnosticConsumer::Directive Directive;
27typedef VerifyDiagnosticConsumer::DirectiveList DirectiveList;
28typedef VerifyDiagnosticConsumer::ExpectedData ExpectedData;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000029
David Blaikie621bc692011-09-26 00:38:03 +000030VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
Jordan Rose7c304f52012-08-10 01:06:16 +000031 : Diags(_Diags),
32 PrimaryClient(Diags.getClient()), OwnsPrimaryClient(Diags.ownsClient()),
33 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0),
Andy Gibbs266dba32012-10-19 12:49:32 +000034 LangOpts(0), SrcManager(0), ActiveSourceFiles(0), Status(HasNoDirectives)
Douglas Gregor78243652011-09-13 01:26:44 +000035{
36 Diags.takeClient();
Jordan Rose7eaaa182012-08-18 16:58:52 +000037 if (Diags.hasSourceManager())
38 setSourceManager(Diags.getSourceManager());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000039}
40
David Blaikie621bc692011-09-26 00:38:03 +000041VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
Jordan Rose7c304f52012-08-10 01:06:16 +000042 assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
43 assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
Jordan Rose7eaaa182012-08-18 16:58:52 +000044 SrcManager = 0;
Douglas Gregor78243652011-09-13 01:26:44 +000045 CheckDiagnostics();
46 Diags.takeClient();
47 if (OwnsPrimaryClient)
48 delete PrimaryClient;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000049}
50
Jordan Rose7c304f52012-08-10 01:06:16 +000051#ifndef NDEBUG
52namespace {
53class VerifyFileTracker : public PPCallbacks {
Jordan Rose7eaaa182012-08-18 16:58:52 +000054 VerifyDiagnosticConsumer &Verify;
Jordan Rose7c304f52012-08-10 01:06:16 +000055 SourceManager &SM;
56
57public:
Jordan Rose7eaaa182012-08-18 16:58:52 +000058 VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
59 : Verify(Verify), SM(SM) { }
Jordan Rose7c304f52012-08-10 01:06:16 +000060
61 /// \brief Hook into the preprocessor and update the list of parsed
62 /// files when the preprocessor indicates a new file is entered.
63 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
64 SrcMgr::CharacteristicKind FileType,
65 FileID PrevFID) {
Jordan Rose7eaaa182012-08-18 16:58:52 +000066 Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
67 VerifyDiagnosticConsumer::IsParsed);
Jordan Rose7c304f52012-08-10 01:06:16 +000068 }
69};
70} // End anonymous namespace.
71#endif
72
David Blaikie78ad0b92011-09-25 23:39:51 +000073// DiagnosticConsumer interface.
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000074
David Blaikie621bc692011-09-26 00:38:03 +000075void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +000076 const Preprocessor *PP) {
Jordan Rose7c304f52012-08-10 01:06:16 +000077 // Attach comment handler on first invocation.
78 if (++ActiveSourceFiles == 1) {
79 if (PP) {
80 CurrentPreprocessor = PP;
Jordan Rose7eaaa182012-08-18 16:58:52 +000081 this->LangOpts = &LangOpts;
82 setSourceManager(PP->getSourceManager());
Jordan Rose7c304f52012-08-10 01:06:16 +000083 const_cast<Preprocessor*>(PP)->addCommentHandler(this);
84#ifndef NDEBUG
Jordan Rose7eaaa182012-08-18 16:58:52 +000085 // Debug build tracks parsed files.
86 VerifyFileTracker *V = new VerifyFileTracker(*this, *SrcManager);
Jordan Rose7c304f52012-08-10 01:06:16 +000087 const_cast<Preprocessor*>(PP)->addPPCallbacks(V);
88#endif
89 }
90 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000091
Jordan Rose7c304f52012-08-10 01:06:16 +000092 assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000093 PrimaryClient->BeginSourceFile(LangOpts, PP);
94}
95
David Blaikie621bc692011-09-26 00:38:03 +000096void VerifyDiagnosticConsumer::EndSourceFile() {
Jordan Rose7c304f52012-08-10 01:06:16 +000097 assert(ActiveSourceFiles && "No active source files!");
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +000098 PrimaryClient->EndSourceFile();
99
Jordan Rose7c304f52012-08-10 01:06:16 +0000100 // Detach comment handler once last active source file completed.
101 if (--ActiveSourceFiles == 0) {
102 if (CurrentPreprocessor)
103 const_cast<Preprocessor*>(CurrentPreprocessor)->removeCommentHandler(this);
104
105 // Check diagnostics once last file completed.
106 CheckDiagnostics();
107 CurrentPreprocessor = 0;
Jordan Rose7eaaa182012-08-18 16:58:52 +0000108 LangOpts = 0;
Jordan Rose7c304f52012-08-10 01:06:16 +0000109 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000110}
Daniel Dunbar221c7212009-11-14 07:53:24 +0000111
David Blaikie621bc692011-09-26 00:38:03 +0000112void VerifyDiagnosticConsumer::HandleDiagnostic(
David Blaikie40847cf2011-09-26 01:18:08 +0000113 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
Jordan Rose7eaaa182012-08-18 16:58:52 +0000114 if (Info.hasSourceManager())
115 setSourceManager(Info.getSourceManager());
116
Jordan Rose7c304f52012-08-10 01:06:16 +0000117#ifndef NDEBUG
Jordan Rose7eaaa182012-08-18 16:58:52 +0000118 // Debug build tracks unparsed files for possible
119 // unparsed expected-* directives.
120 if (SrcManager) {
121 SourceLocation Loc = Info.getLocation();
122 if (Loc.isValid()) {
123 ParsedStatus PS = IsUnparsed;
124
125 Loc = SrcManager->getExpansionLoc(Loc);
126 FileID FID = SrcManager->getFileID(Loc);
127
128 const FileEntry *FE = SrcManager->getFileEntryForID(FID);
129 if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
130 // If the file is a modules header file it shall not be parsed
131 // for expected-* directives.
132 HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
133 if (HS.findModuleForHeader(FE))
134 PS = IsUnparsedNoDirectives;
135 }
136
137 UpdateParsedFileStatus(*SrcManager, FID, PS);
138 }
Axel Naumann01231612011-07-25 19:18:12 +0000139 }
Jordan Rose7c304f52012-08-10 01:06:16 +0000140#endif
Jordan Rose7eaaa182012-08-18 16:58:52 +0000141
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000142 // Send the diagnostic to the buffer, we will check it once we reach the end
143 // of the source file (or are destructed).
144 Buffer->HandleDiagnostic(DiagLevel, Info);
145}
146
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000147//===----------------------------------------------------------------------===//
148// Checking diagnostics implementation.
149//===----------------------------------------------------------------------===//
150
151typedef TextDiagnosticBuffer::DiagList DiagList;
152typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
153
Chris Lattner60909e12010-04-28 20:02:30 +0000154namespace {
155
Chris Lattner60909e12010-04-28 20:02:30 +0000156/// StandardDirective - Directive with string matching.
157///
158class StandardDirective : public Directive {
159public:
Jordan Roseaa48fe82012-07-10 02:57:03 +0000160 StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000161 StringRef Text, unsigned Min, unsigned Max)
162 : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max) { }
Chris Lattner60909e12010-04-28 20:02:30 +0000163
164 virtual bool isValid(std::string &Error) {
165 // all strings are considered valid; even empty ones
166 return true;
167 }
168
Jordan Rose4313c012012-07-10 02:56:15 +0000169 virtual bool match(StringRef S) {
170 return S.find(Text) != StringRef::npos;
Chris Lattner60909e12010-04-28 20:02:30 +0000171 }
172};
173
174/// RegexDirective - Directive with regular-expression matching.
175///
176class RegexDirective : public Directive {
177public:
Jordan Roseaa48fe82012-07-10 02:57:03 +0000178 RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000179 StringRef Text, unsigned Min, unsigned Max)
180 : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max), Regex(Text) { }
Chris Lattner60909e12010-04-28 20:02:30 +0000181
182 virtual bool isValid(std::string &Error) {
183 if (Regex.isValid(Error))
184 return true;
185 return false;
186 }
187
Jordan Rose4313c012012-07-10 02:56:15 +0000188 virtual bool match(StringRef S) {
Chris Lattner60909e12010-04-28 20:02:30 +0000189 return Regex.match(S);
190 }
191
192private:
193 llvm::Regex Regex;
194};
195
Chris Lattner60909e12010-04-28 20:02:30 +0000196class ParseHelper
197{
198public:
Jordan Rose78541c42012-07-11 19:58:23 +0000199 ParseHelper(StringRef S)
200 : Begin(S.begin()), End(S.end()), C(Begin), P(Begin), PEnd(NULL) { }
Chris Lattner60909e12010-04-28 20:02:30 +0000201
202 // Return true if string literal is next.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000203 bool Next(StringRef S) {
Chris Lattner60909e12010-04-28 20:02:30 +0000204 P = C;
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000205 PEnd = C + S.size();
Chris Lattner60909e12010-04-28 20:02:30 +0000206 if (PEnd > End)
207 return false;
Benjamin Kramer0080f0c2010-09-01 17:28:48 +0000208 return !memcmp(P, S.data(), S.size());
Chris Lattner60909e12010-04-28 20:02:30 +0000209 }
210
211 // Return true if number is next.
212 // Output N only if number is next.
213 bool Next(unsigned &N) {
214 unsigned TMP = 0;
215 P = C;
216 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
217 TMP *= 10;
218 TMP += P[0] - '0';
219 }
220 if (P == C)
221 return false;
222 PEnd = P;
223 N = TMP;
224 return true;
225 }
226
227 // Return true if string literal is found.
228 // When true, P marks begin-position of S in content.
Andy Gibbs4a529d22012-10-19 12:36:49 +0000229 bool Search(StringRef S, bool EnsureStartOfWord = false) {
230 do {
231 P = std::search(C, End, S.begin(), S.end());
232 PEnd = P + S.size();
233 if (P == End)
234 break;
235 if (!EnsureStartOfWord
236 // Check if string literal starts a new word.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000237 || P == Begin || isWhitespace(P[-1])
Andy Gibbs4a529d22012-10-19 12:36:49 +0000238 // Or it could be preceeded by the start of a comment.
239 || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
240 && P[-2] == '/'))
241 return true;
242 // Otherwise, skip and search again.
243 } while (Advance());
244 return false;
Chris Lattner60909e12010-04-28 20:02:30 +0000245 }
246
247 // Advance 1-past previous next/search.
248 // Behavior is undefined if previous next/search failed.
249 bool Advance() {
250 C = PEnd;
251 return C < End;
252 }
253
254 // Skip zero or more whitespace.
255 void SkipWhitespace() {
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000256 for (; C < End && isWhitespace(*C); ++C)
Chris Lattner60909e12010-04-28 20:02:30 +0000257 ;
258 }
259
260 // Return true if EOF reached.
261 bool Done() {
262 return !(C < End);
263 }
264
265 const char * const Begin; // beginning of expected content
266 const char * const End; // end of expected content (1-past)
267 const char *C; // position of next char in content
268 const char *P;
269
270private:
271 const char *PEnd; // previous next/search subject end (1-past)
272};
273
274} // namespace anonymous
275
276/// ParseDirective - Go through the comment and see if it indicates expected
277/// diagnostics. If so, then put them in the appropriate directive list.
278///
Jordan Rose78541c42012-07-11 19:58:23 +0000279/// Returns true if any valid directives were found.
Jordan Rose7c304f52012-08-10 01:06:16 +0000280static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
Andy Gibbs266dba32012-10-19 12:49:32 +0000281 SourceLocation Pos, DiagnosticsEngine &Diags,
282 VerifyDiagnosticConsumer::DirectiveStatus &Status) {
Chris Lattner60909e12010-04-28 20:02:30 +0000283 // A single comment may contain multiple directives.
Jordan Rose78541c42012-07-11 19:58:23 +0000284 bool FoundDirective = false;
285 for (ParseHelper PH(S); !PH.Done();) {
Jordan Roseaa48fe82012-07-10 02:57:03 +0000286 // Search for token: expected
Andy Gibbs4a529d22012-10-19 12:36:49 +0000287 if (!PH.Search("expected", true))
Chris Lattner60909e12010-04-28 20:02:30 +0000288 break;
289 PH.Advance();
290
Jordan Roseaa48fe82012-07-10 02:57:03 +0000291 // Next token: -
Chris Lattner60909e12010-04-28 20:02:30 +0000292 if (!PH.Next("-"))
293 continue;
294 PH.Advance();
295
Jordan Roseaa48fe82012-07-10 02:57:03 +0000296 // Next token: { error | warning | note }
Chris Lattner60909e12010-04-28 20:02:30 +0000297 DirectiveList* DL = NULL;
298 if (PH.Next("error"))
Jordan Rose7c304f52012-08-10 01:06:16 +0000299 DL = ED ? &ED->Errors : NULL;
Chris Lattner60909e12010-04-28 20:02:30 +0000300 else if (PH.Next("warning"))
Jordan Rose7c304f52012-08-10 01:06:16 +0000301 DL = ED ? &ED->Warnings : NULL;
Chris Lattner60909e12010-04-28 20:02:30 +0000302 else if (PH.Next("note"))
Jordan Rose7c304f52012-08-10 01:06:16 +0000303 DL = ED ? &ED->Notes : NULL;
Andy Gibbs266dba32012-10-19 12:49:32 +0000304 else if (PH.Next("no-diagnostics")) {
305 if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
306 Diags.Report(Pos, diag::err_verify_invalid_no_diags)
307 << /*IsExpectedNoDiagnostics=*/true;
308 else
309 Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
310 continue;
311 } else
Chris Lattner60909e12010-04-28 20:02:30 +0000312 continue;
313 PH.Advance();
314
Andy Gibbs266dba32012-10-19 12:49:32 +0000315 if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
316 Diags.Report(Pos, diag::err_verify_invalid_no_diags)
317 << /*IsExpectedNoDiagnostics=*/false;
318 continue;
319 }
320 Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
321
Jordan Rose7c304f52012-08-10 01:06:16 +0000322 // If a directive has been found but we're not interested
323 // in storing the directive information, return now.
324 if (!DL)
325 return true;
326
Jordan Roseaa48fe82012-07-10 02:57:03 +0000327 // Default directive kind.
Chris Lattner60909e12010-04-28 20:02:30 +0000328 bool RegexKind = false;
329 const char* KindStr = "string";
330
Jordan Roseaa48fe82012-07-10 02:57:03 +0000331 // Next optional token: -
Chris Lattner60909e12010-04-28 20:02:30 +0000332 if (PH.Next("-re")) {
333 PH.Advance();
334 RegexKind = true;
335 KindStr = "regex";
336 }
337
Jordan Roseaa48fe82012-07-10 02:57:03 +0000338 // Next optional token: @
339 SourceLocation ExpectedLoc;
340 if (!PH.Next("@")) {
341 ExpectedLoc = Pos;
342 } else {
343 PH.Advance();
344 unsigned Line = 0;
345 bool FoundPlus = PH.Next("+");
346 if (FoundPlus || PH.Next("-")) {
347 // Relative to current line.
348 PH.Advance();
349 bool Invalid = false;
350 unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
351 if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
352 if (FoundPlus) ExpectedLine += Line;
353 else ExpectedLine -= Line;
354 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
355 }
356 } else {
357 // Absolute line number.
358 if (PH.Next(Line) && Line > 0)
359 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
360 }
361
362 if (ExpectedLoc.isInvalid()) {
363 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
364 diag::err_verify_missing_line) << KindStr;
365 continue;
366 }
367 PH.Advance();
368 }
369
370 // Skip optional whitespace.
Chris Lattner60909e12010-04-28 20:02:30 +0000371 PH.SkipWhitespace();
372
Jordan Roseaa48fe82012-07-10 02:57:03 +0000373 // Next optional token: positive integer or a '+'.
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000374 unsigned Min = 1;
375 unsigned Max = 1;
376 if (PH.Next(Min)) {
Chris Lattner60909e12010-04-28 20:02:30 +0000377 PH.Advance();
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000378 // A positive integer can be followed by a '+' meaning min
379 // or more, or by a '-' meaning a range from min to max.
380 if (PH.Next("+")) {
381 Max = Directive::MaxCount;
382 PH.Advance();
383 } else if (PH.Next("-")) {
384 PH.Advance();
385 if (!PH.Next(Max) || Max < Min) {
386 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
387 diag::err_verify_invalid_range) << KindStr;
388 continue;
389 }
390 PH.Advance();
391 } else {
392 Max = Min;
393 }
394 } else if (PH.Next("+")) {
395 // '+' on its own means "1 or more".
396 Max = Directive::MaxCount;
Anna Zaks2135ebb2011-12-15 02:28:16 +0000397 PH.Advance();
398 }
Chris Lattner60909e12010-04-28 20:02:30 +0000399
Jordan Roseaa48fe82012-07-10 02:57:03 +0000400 // Skip optional whitespace.
Chris Lattner60909e12010-04-28 20:02:30 +0000401 PH.SkipWhitespace();
402
Jordan Roseaa48fe82012-07-10 02:57:03 +0000403 // Next token: {{
Chris Lattner60909e12010-04-28 20:02:30 +0000404 if (!PH.Next("{{")) {
Jordan Rose4313c012012-07-10 02:56:15 +0000405 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
406 diag::err_verify_missing_start) << KindStr;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000407 continue;
408 }
Chris Lattner60909e12010-04-28 20:02:30 +0000409 PH.Advance();
410 const char* const ContentBegin = PH.C; // mark content begin
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000411
Jordan Roseaa48fe82012-07-10 02:57:03 +0000412 // Search for token: }}
Chris Lattner60909e12010-04-28 20:02:30 +0000413 if (!PH.Search("}}")) {
Jordan Rose4313c012012-07-10 02:56:15 +0000414 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
415 diag::err_verify_missing_end) << KindStr;
Chris Lattner60909e12010-04-28 20:02:30 +0000416 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000417 }
Chris Lattner60909e12010-04-28 20:02:30 +0000418 const char* const ContentEnd = PH.P; // mark content end
419 PH.Advance();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000420
Jordan Roseaa48fe82012-07-10 02:57:03 +0000421 // Build directive text; convert \n to newlines.
Chris Lattner60909e12010-04-28 20:02:30 +0000422 std::string Text;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000423 StringRef NewlineStr = "\\n";
424 StringRef Content(ContentBegin, ContentEnd-ContentBegin);
Chris Lattner60909e12010-04-28 20:02:30 +0000425 size_t CPos = 0;
426 size_t FPos;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000427 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
Chris Lattner60909e12010-04-28 20:02:30 +0000428 Text += Content.substr(CPos, FPos-CPos);
429 Text += '\n';
430 CPos = FPos + NewlineStr.size();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000431 }
Chris Lattner60909e12010-04-28 20:02:30 +0000432 if (Text.empty())
433 Text.assign(ContentBegin, ContentEnd);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000434
Jordan Roseaa48fe82012-07-10 02:57:03 +0000435 // Construct new directive.
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000436 Directive *D = Directive::create(RegexKind, Pos, ExpectedLoc, Text,
437 Min, Max);
Chris Lattner60909e12010-04-28 20:02:30 +0000438 std::string Error;
Jordan Rose78541c42012-07-11 19:58:23 +0000439 if (D->isValid(Error)) {
Chris Lattner60909e12010-04-28 20:02:30 +0000440 DL->push_back(D);
Jordan Rose78541c42012-07-11 19:58:23 +0000441 FoundDirective = true;
442 } else {
Jordan Rose4313c012012-07-10 02:56:15 +0000443 Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
444 diag::err_verify_invalid_content)
Chris Lattner60909e12010-04-28 20:02:30 +0000445 << KindStr << Error;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000446 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000447 }
Jordan Rose78541c42012-07-11 19:58:23 +0000448
449 return FoundDirective;
450}
451
452/// HandleComment - Hook into the preprocessor and extract comments containing
453/// expected errors and warnings.
454bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
455 SourceRange Comment) {
456 SourceManager &SM = PP.getSourceManager();
457 SourceLocation CommentBegin = Comment.getBegin();
458
459 const char *CommentRaw = SM.getCharacterData(CommentBegin);
460 StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
461
462 if (C.empty())
463 return false;
464
465 // Fold any "\<EOL>" sequences
466 size_t loc = C.find('\\');
467 if (loc == StringRef::npos) {
Andy Gibbs266dba32012-10-19 12:49:32 +0000468 ParseDirective(C, &ED, SM, CommentBegin, PP.getDiagnostics(), Status);
Jordan Rose78541c42012-07-11 19:58:23 +0000469 return false;
470 }
471
472 std::string C2;
473 C2.reserve(C.size());
474
475 for (size_t last = 0;; loc = C.find('\\', last)) {
476 if (loc == StringRef::npos || loc == C.size()) {
477 C2 += C.substr(last);
478 break;
479 }
480 C2 += C.substr(last, loc-last);
481 last = loc + 1;
482
483 if (C[last] == '\n' || C[last] == '\r') {
484 ++last;
485
486 // Escape \r\n or \n\r, but not \n\n.
487 if (last < C.size())
488 if (C[last] == '\n' || C[last] == '\r')
489 if (C[last] != C[last-1])
490 ++last;
491 } else {
492 // This was just a normal backslash.
493 C2 += '\\';
494 }
495 }
496
497 if (!C2.empty())
Andy Gibbs266dba32012-10-19 12:49:32 +0000498 ParseDirective(C2, &ED, SM, CommentBegin, PP.getDiagnostics(), Status);
Jordan Rose78541c42012-07-11 19:58:23 +0000499 return false;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000500}
501
Jordan Rose7c304f52012-08-10 01:06:16 +0000502#ifndef NDEBUG
503/// \brief Lex the specified source file to determine whether it contains
504/// any expected-* directives. As a Lexer is used rather than a full-blown
505/// Preprocessor, directives inside skipped #if blocks will still be found.
506///
507/// \return true if any directives were found.
Jordan Rose7eaaa182012-08-18 16:58:52 +0000508static bool findDirectives(SourceManager &SM, FileID FID,
509 const LangOptions &LangOpts) {
Axel Naumann01231612011-07-25 19:18:12 +0000510 // Create a raw lexer to pull all the comments out of FID.
511 if (FID.isInvalid())
Jordan Rose7c304f52012-08-10 01:06:16 +0000512 return false;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000513
514 // Create a lexer to lex all the tokens of the main file in raw mode.
Chris Lattner6e290142009-11-30 04:18:44 +0000515 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
Jordan Rose7eaaa182012-08-18 16:58:52 +0000516 Lexer RawLex(FID, FromFile, SM, LangOpts);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000517
518 // Return comments as tokens, this is how we find expected diagnostics.
519 RawLex.SetCommentRetentionState(true);
520
521 Token Tok;
522 Tok.setKind(tok::comment);
Andy Gibbs266dba32012-10-19 12:49:32 +0000523 VerifyDiagnosticConsumer::DirectiveStatus Status =
524 VerifyDiagnosticConsumer::HasNoDirectives;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000525 while (Tok.isNot(tok::eof)) {
526 RawLex.Lex(Tok);
527 if (!Tok.is(tok::comment)) continue;
528
Jordan Rose7eaaa182012-08-18 16:58:52 +0000529 std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000530 if (Comment.empty()) continue;
531
Jordan Rose7eaaa182012-08-18 16:58:52 +0000532 // Find first directive.
533 if (ParseDirective(Comment, 0, SM, Tok.getLocation(),
Andy Gibbs266dba32012-10-19 12:49:32 +0000534 SM.getDiagnostics(), Status))
Jordan Rose7eaaa182012-08-18 16:58:52 +0000535 return true;
Jordan Rose7c304f52012-08-10 01:06:16 +0000536 }
Jordan Rose7eaaa182012-08-18 16:58:52 +0000537 return false;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000538}
Jordan Rose7c304f52012-08-10 01:06:16 +0000539#endif // !NDEBUG
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000540
Jordan Roseaa48fe82012-07-10 02:57:03 +0000541/// \brief Takes a list of diagnostics that have been generated but not matched
542/// by an expected-* directive and produces a diagnostic to the user from this.
543static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
544 const_diag_iterator diag_begin,
545 const_diag_iterator diag_end,
546 const char *Kind) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000547 if (diag_begin == diag_end) return 0;
548
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000549 SmallString<256> Fmt;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000550 llvm::raw_svector_ostream OS(Fmt);
551 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000552 if (I->first.isInvalid() || !SourceMgr)
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000553 OS << "\n (frontend)";
554 else
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000555 OS << "\n Line " << SourceMgr->getPresumedLineNumber(I->first);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000556 OS << ": " << I->second;
557 }
558
Jordan Rosec6d64a22012-07-11 16:50:36 +0000559 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
Jordan Roseaa48fe82012-07-10 02:57:03 +0000560 << Kind << /*Unexpected=*/true << OS.str();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000561 return std::distance(diag_begin, diag_end);
562}
563
Jordan Roseaa48fe82012-07-10 02:57:03 +0000564/// \brief Takes a list of diagnostics that were expected to have been generated
565/// but were not and produces a diagnostic to the user from this.
566static unsigned PrintExpected(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
567 DirectiveList &DL, const char *Kind) {
Chris Lattner60909e12010-04-28 20:02:30 +0000568 if (DL.empty())
569 return 0;
570
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000571 SmallString<256> Fmt;
Chris Lattner60909e12010-04-28 20:02:30 +0000572 llvm::raw_svector_ostream OS(Fmt);
573 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
Jordan Roseaa48fe82012-07-10 02:57:03 +0000574 Directive &D = **I;
575 OS << "\n Line " << SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
576 if (D.DirectiveLoc != D.DiagnosticLoc)
577 OS << " (directive at "
578 << SourceMgr.getFilename(D.DirectiveLoc) << ":"
579 << SourceMgr.getPresumedLineNumber(D.DirectiveLoc) << ")";
Chris Lattner60909e12010-04-28 20:02:30 +0000580 OS << ": " << D.Text;
581 }
582
Jordan Rosec6d64a22012-07-11 16:50:36 +0000583 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
Jordan Roseaa48fe82012-07-10 02:57:03 +0000584 << Kind << /*Unexpected=*/false << OS.str();
Chris Lattner60909e12010-04-28 20:02:30 +0000585 return DL.size();
586}
587
588/// CheckLists - Compare expected to seen diagnostic lists and return the
589/// the difference between them.
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000590///
David Blaikied6471f72011-09-25 23:23:43 +0000591static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
Chris Lattner60909e12010-04-28 20:02:30 +0000592 const char *Label,
593 DirectiveList &Left,
594 const_diag_iterator d2_begin,
595 const_diag_iterator d2_end) {
596 DirectiveList LeftOnly;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000597 DiagList Right(d2_begin, d2_end);
598
Chris Lattner60909e12010-04-28 20:02:30 +0000599 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
600 Directive& D = **I;
Jordan Roseaa48fe82012-07-10 02:57:03 +0000601 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000602
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000603 for (unsigned i = 0; i < D.Max; ++i) {
Chris Lattner60909e12010-04-28 20:02:30 +0000604 DiagList::iterator II, IE;
605 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000606 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
Chris Lattner60909e12010-04-28 20:02:30 +0000607 if (LineNo1 != LineNo2)
608 continue;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000609
Chris Lattner60909e12010-04-28 20:02:30 +0000610 const std::string &RightText = II->second;
Jordan Rose4313c012012-07-10 02:56:15 +0000611 if (D.match(RightText))
Chris Lattner60909e12010-04-28 20:02:30 +0000612 break;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000613 }
Chris Lattner60909e12010-04-28 20:02:30 +0000614 if (II == IE) {
615 // Not found.
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000616 if (i >= D.Min) break;
Chris Lattner60909e12010-04-28 20:02:30 +0000617 LeftOnly.push_back(*I);
618 } else {
619 // Found. The same cannot be found twice.
620 Right.erase(II);
621 }
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000622 }
623 }
624 // Now all that's left in Right are those that were not matched.
Jordan Roseaa48fe82012-07-10 02:57:03 +0000625 unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
626 num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
NAKAMURA Takumiad646842011-12-17 13:00:31 +0000627 return num;
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000628}
629
630/// CheckResults - This compares the expected results to those that
631/// were actually reported. It emits any discrepencies. Return "true" if there
632/// were problems. Return "false" otherwise.
633///
David Blaikied6471f72011-09-25 23:23:43 +0000634static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000635 const TextDiagnosticBuffer &Buffer,
Chris Lattner60909e12010-04-28 20:02:30 +0000636 ExpectedData &ED) {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000637 // We want to capture the delta between what was expected and what was
638 // seen.
639 //
640 // Expected \ Seen - set expected but not seen
641 // Seen \ Expected - set seen but not expected
642 unsigned NumProblems = 0;
643
644 // See if there are error mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000645 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
646 Buffer.err_begin(), Buffer.err_end());
Daniel Dunbar221c7212009-11-14 07:53:24 +0000647
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000648 // See if there are warning mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000649 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
650 Buffer.warn_begin(), Buffer.warn_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000651
652 // See if there are note mismatches.
Chris Lattner60909e12010-04-28 20:02:30 +0000653 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
654 Buffer.note_begin(), Buffer.note_end());
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000655
656 return NumProblems;
657}
658
Jordan Rose7eaaa182012-08-18 16:58:52 +0000659void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
660 FileID FID,
661 ParsedStatus PS) {
662 // Check SourceManager hasn't changed.
663 setSourceManager(SM);
664
665#ifndef NDEBUG
666 if (FID.isInvalid())
667 return;
668
669 const FileEntry *FE = SM.getFileEntryForID(FID);
670
671 if (PS == IsParsed) {
672 // Move the FileID from the unparsed set to the parsed set.
673 UnparsedFiles.erase(FID);
674 ParsedFiles.insert(std::make_pair(FID, FE));
675 } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
676 // Add the FileID to the unparsed set if we haven't seen it before.
677
678 // Check for directives.
679 bool FoundDirectives;
680 if (PS == IsUnparsedNoDirectives)
681 FoundDirectives = false;
682 else
683 FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
684
685 // Add the FileID to the unparsed set.
686 UnparsedFiles.insert(std::make_pair(FID,
687 UnparsedFileStatus(FE, FoundDirectives)));
688 }
689#endif
690}
691
David Blaikie621bc692011-09-26 00:38:03 +0000692void VerifyDiagnosticConsumer::CheckDiagnostics() {
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000693 // Ensure any diagnostics go to the primary client.
Douglas Gregor78243652011-09-13 01:26:44 +0000694 bool OwnsCurClient = Diags.ownsClient();
David Blaikie78ad0b92011-09-25 23:39:51 +0000695 DiagnosticConsumer *CurClient = Diags.takeClient();
Douglas Gregor78243652011-09-13 01:26:44 +0000696 Diags.setClient(PrimaryClient, false);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000697
Jordan Rose7c304f52012-08-10 01:06:16 +0000698#ifndef NDEBUG
Jordan Rose7eaaa182012-08-18 16:58:52 +0000699 // In a debug build, scan through any files that may have been missed
700 // during parsing and issue a fatal error if directives are contained
701 // within these files. If a fatal error occurs, this suggests that
702 // this file is being parsed separately from the main file, in which
703 // case consider moving the directives to the correct place, if this
704 // is applicable.
705 if (UnparsedFiles.size() > 0) {
706 // Generate a cache of parsed FileEntry pointers for alias lookups.
707 llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
708 for (ParsedFilesMap::iterator I = ParsedFiles.begin(),
709 End = ParsedFiles.end(); I != End; ++I) {
710 if (const FileEntry *FE = I->second)
711 ParsedFileCache.insert(FE);
712 }
713
714 // Iterate through list of unparsed files.
715 for (UnparsedFilesMap::iterator I = UnparsedFiles.begin(),
716 End = UnparsedFiles.end(); I != End; ++I) {
717 const UnparsedFileStatus &Status = I->second;
718 const FileEntry *FE = Status.getFile();
719
720 // Skip files that have been parsed via an alias.
721 if (FE && ParsedFileCache.count(FE))
Jordan Rose7c304f52012-08-10 01:06:16 +0000722 continue;
723
Jordan Rose7eaaa182012-08-18 16:58:52 +0000724 // Report a fatal error if this file contained directives.
725 if (Status.foundDirectives()) {
Jordan Rose7c304f52012-08-10 01:06:16 +0000726 llvm::report_fatal_error(Twine("-verify directives found after rather"
727 " than during normal parsing of ",
Jordan Rose7eaaa182012-08-18 16:58:52 +0000728 StringRef(FE ? FE->getName() : "(unknown)")));
729 }
Axel Naumann84c05e32011-08-24 13:36:19 +0000730 }
Daniel Dunbar221c7212009-11-14 07:53:24 +0000731
Jordan Rose7eaaa182012-08-18 16:58:52 +0000732 // UnparsedFiles has been processed now, so clear it.
733 UnparsedFiles.clear();
734 }
735#endif // !NDEBUG
736
737 if (SrcManager) {
Andy Gibbs266dba32012-10-19 12:49:32 +0000738 // Produce an error if no expected-* directives could be found in the
739 // source file(s) processed.
740 if (Status == HasNoDirectives) {
741 Diags.Report(diag::err_verify_no_directives).setForceEmit();
742 ++NumErrors;
743 Status = HasNoDirectivesReported;
744 }
745
Daniel Dunbar221c7212009-11-14 07:53:24 +0000746 // Check that the expected diagnostics occurred.
Jordan Rose7eaaa182012-08-18 16:58:52 +0000747 NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
Daniel Dunbar221c7212009-11-14 07:53:24 +0000748 } else {
Jordan Roseaa48fe82012-07-10 02:57:03 +0000749 NumErrors += (PrintUnexpected(Diags, 0, Buffer->err_begin(),
750 Buffer->err_end(), "error") +
751 PrintUnexpected(Diags, 0, Buffer->warn_begin(),
752 Buffer->warn_end(), "warn") +
753 PrintUnexpected(Diags, 0, Buffer->note_begin(),
754 Buffer->note_end(), "note"));
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000755 }
756
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000757 Diags.takeClient();
Douglas Gregor78243652011-09-13 01:26:44 +0000758 Diags.setClient(CurClient, OwnsCurClient);
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000759
760 // Reset the buffer, we have processed all the diagnostics in it.
761 Buffer.reset(new TextDiagnosticBuffer());
Axel Naumanne445e5d2012-07-10 16:24:07 +0000762 ED.Errors.clear();
763 ED.Warnings.clear();
764 ED.Notes.clear();
Daniel Dunbar81f5a1e2009-11-14 03:23:19 +0000765}
Chris Lattner60909e12010-04-28 20:02:30 +0000766
Douglas Gregoraee526e2011-09-29 00:38:00 +0000767DiagnosticConsumer *
768VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const {
769 if (!Diags.getClient())
770 Diags.setClient(PrimaryClient->clone(Diags));
771
772 return new VerifyDiagnosticConsumer(Diags);
773}
774
Jordan Roseaa48fe82012-07-10 02:57:03 +0000775Directive *Directive::create(bool RegexKind, SourceLocation DirectiveLoc,
776 SourceLocation DiagnosticLoc, StringRef Text,
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000777 unsigned Min, unsigned Max) {
Chris Lattner60909e12010-04-28 20:02:30 +0000778 if (RegexKind)
Jordan Rose3b81b7d2012-07-10 02:57:26 +0000779 return new RegexDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max);
780 return new StandardDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max);
Chris Lattner60909e12010-04-28 20:02:30 +0000781}