blob: 21933f474ff5c8d50cc0ac672287e1fff04d7c6e [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===//
Daniel Dunbar34818552009-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 Blaikie69609dc2011-09-26 00:38:03 +000014#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000015#include "clang/Basic/CharInfo.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/FileManager.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000019#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TokenKinds.h"
Daniel Dunbar34818552009-11-14 03:23:19 +000023#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticBuffer.h"
Jordan Roseb00073d2012-08-10 01:06:16 +000025#include "clang/Lex/HeaderSearch.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000026#include "clang/Lex/Lexer.h"
27#include "clang/Lex/PPCallbacks.h"
Daniel Dunbar34818552009-11-14 03:23:19 +000028#include "clang/Lex/Preprocessor.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000029#include "clang/Lex/Token.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
Daniel Dunbar34818552009-11-14 03:23:19 +000032#include "llvm/ADT/SmallString.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000033#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/Twine.h"
35#include "llvm/Support/ErrorHandling.h"
Chris Lattnere82411b2010-04-28 20:02:30 +000036#include "llvm/Support/Regex.h"
Daniel Dunbar34818552009-11-14 03:23:19 +000037#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000038#include <algorithm>
39#include <cassert>
40#include <cstddef>
41#include <cstring>
42#include <iterator>
43#include <memory>
44#include <string>
45#include <utility>
46#include <vector>
Anna Zaks2c74eed2011-12-15 02:58:00 +000047
Daniel Dunbar34818552009-11-14 03:23:19 +000048using namespace clang;
Eugene Zelenko4f233182018-03-22 00:53:26 +000049
50using Directive = VerifyDiagnosticConsumer::Directive;
51using DirectiveList = VerifyDiagnosticConsumer::DirectiveList;
52using ExpectedData = VerifyDiagnosticConsumer::ExpectedData;
Daniel Dunbar34818552009-11-14 03:23:19 +000053
Justin Bognerba7add32014-10-16 06:00:55 +000054VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &Diags_)
Eugene Zelenko4f233182018-03-22 00:53:26 +000055 : Diags(Diags_), PrimaryClient(Diags.getClient()),
56 PrimaryClientOwner(Diags.takeClient()),
57 Buffer(new TextDiagnosticBuffer()), Status(HasNoDirectives) {
Jordan Rose8c1ac0c2012-08-18 16:58:52 +000058 if (Diags.hasSourceManager())
59 setSourceManager(Diags.getSourceManager());
Daniel Dunbar34818552009-11-14 03:23:19 +000060}
61
David Blaikie69609dc2011-09-26 00:38:03 +000062VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
Jordan Roseb00073d2012-08-10 01:06:16 +000063 assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
64 assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
Craig Topper49a27902014-05-22 04:46:25 +000065 SrcManager = nullptr;
Alexander Kornienko41c247a2014-11-17 23:46:02 +000066 CheckDiagnostics();
Chandler Carrutha667ace2016-11-03 18:03:14 +000067 assert(!Diags.ownsClient() &&
68 "The VerifyDiagnosticConsumer takes over ownership of the client!");
Daniel Dunbar34818552009-11-14 03:23:19 +000069}
70
Jordan Roseb00073d2012-08-10 01:06:16 +000071#ifndef NDEBUG
Eugene Zelenko4f233182018-03-22 00:53:26 +000072
Jordan Roseb00073d2012-08-10 01:06:16 +000073namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +000074
Jordan Roseb00073d2012-08-10 01:06:16 +000075class VerifyFileTracker : public PPCallbacks {
Jordan Rose8c1ac0c2012-08-18 16:58:52 +000076 VerifyDiagnosticConsumer &Verify;
Jordan Roseb00073d2012-08-10 01:06:16 +000077 SourceManager &SM;
78
79public:
Jordan Rose8c1ac0c2012-08-18 16:58:52 +000080 VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
Eugene Zelenko4f233182018-03-22 00:53:26 +000081 : Verify(Verify), SM(SM) {}
Jordan Roseb00073d2012-08-10 01:06:16 +000082
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000083 /// Hook into the preprocessor and update the list of parsed
Jordan Roseb00073d2012-08-10 01:06:16 +000084 /// files when the preprocessor indicates a new file is entered.
Alexander Kornienko34eb2072015-04-11 02:00:23 +000085 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
86 SrcMgr::CharacteristicKind FileType,
87 FileID PrevFID) override {
Jordan Rose8c1ac0c2012-08-18 16:58:52 +000088 Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
89 VerifyDiagnosticConsumer::IsParsed);
Jordan Roseb00073d2012-08-10 01:06:16 +000090 }
91};
Eugene Zelenko4f233182018-03-22 00:53:26 +000092
93} // namespace
94
Jordan Roseb00073d2012-08-10 01:06:16 +000095#endif
96
David Blaikiee2eefae2011-09-25 23:39:51 +000097// DiagnosticConsumer interface.
Daniel Dunbar34818552009-11-14 03:23:19 +000098
David Blaikie69609dc2011-09-26 00:38:03 +000099void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000100 const Preprocessor *PP) {
Jordan Roseb00073d2012-08-10 01:06:16 +0000101 // Attach comment handler on first invocation.
102 if (++ActiveSourceFiles == 1) {
103 if (PP) {
104 CurrentPreprocessor = PP;
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000105 this->LangOpts = &LangOpts;
106 setSourceManager(PP->getSourceManager());
Eugene Zelenko4f233182018-03-22 00:53:26 +0000107 const_cast<Preprocessor *>(PP)->addCommentHandler(this);
Jordan Roseb00073d2012-08-10 01:06:16 +0000108#ifndef NDEBUG
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000109 // Debug build tracks parsed files.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000110 const_cast<Preprocessor *>(PP)->addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000111 llvm::make_unique<VerifyFileTracker>(*this, *SrcManager));
Jordan Roseb00073d2012-08-10 01:06:16 +0000112#endif
113 }
114 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000115
Jordan Roseb00073d2012-08-10 01:06:16 +0000116 assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
Daniel Dunbar34818552009-11-14 03:23:19 +0000117 PrimaryClient->BeginSourceFile(LangOpts, PP);
118}
119
David Blaikie69609dc2011-09-26 00:38:03 +0000120void VerifyDiagnosticConsumer::EndSourceFile() {
Jordan Roseb00073d2012-08-10 01:06:16 +0000121 assert(ActiveSourceFiles && "No active source files!");
Daniel Dunbar34818552009-11-14 03:23:19 +0000122 PrimaryClient->EndSourceFile();
123
Jordan Roseb00073d2012-08-10 01:06:16 +0000124 // Detach comment handler once last active source file completed.
125 if (--ActiveSourceFiles == 0) {
126 if (CurrentPreprocessor)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000127 const_cast<Preprocessor *>(CurrentPreprocessor)->
128 removeCommentHandler(this);
Jordan Roseb00073d2012-08-10 01:06:16 +0000129
130 // Check diagnostics once last file completed.
131 CheckDiagnostics();
Craig Topper49a27902014-05-22 04:46:25 +0000132 CurrentPreprocessor = nullptr;
133 LangOpts = nullptr;
Jordan Roseb00073d2012-08-10 01:06:16 +0000134 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000135}
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000136
David Blaikie69609dc2011-09-26 00:38:03 +0000137void VerifyDiagnosticConsumer::HandleDiagnostic(
David Blaikieb5784322011-09-26 01:18:08 +0000138 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
Douglas Gregor6b930962013-05-03 22:58:43 +0000139 if (Info.hasSourceManager()) {
140 // If this diagnostic is for a different source manager, ignore it.
141 if (SrcManager && &Info.getSourceManager() != SrcManager)
142 return;
143
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000144 setSourceManager(Info.getSourceManager());
Douglas Gregor6b930962013-05-03 22:58:43 +0000145 }
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000146
Jordan Roseb00073d2012-08-10 01:06:16 +0000147#ifndef NDEBUG
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000148 // Debug build tracks unparsed files for possible
149 // unparsed expected-* directives.
150 if (SrcManager) {
151 SourceLocation Loc = Info.getLocation();
152 if (Loc.isValid()) {
153 ParsedStatus PS = IsUnparsed;
154
155 Loc = SrcManager->getExpansionLoc(Loc);
156 FileID FID = SrcManager->getFileID(Loc);
157
158 const FileEntry *FE = SrcManager->getFileEntryForID(FID);
159 if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
160 // If the file is a modules header file it shall not be parsed
161 // for expected-* directives.
162 HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
163 if (HS.findModuleForHeader(FE))
164 PS = IsUnparsedNoDirectives;
165 }
166
167 UpdateParsedFileStatus(*SrcManager, FID, PS);
168 }
Axel Naumannac50dcf2011-07-25 19:18:12 +0000169 }
Jordan Roseb00073d2012-08-10 01:06:16 +0000170#endif
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000171
Daniel Dunbar34818552009-11-14 03:23:19 +0000172 // Send the diagnostic to the buffer, we will check it once we reach the end
173 // of the source file (or are destructed).
174 Buffer->HandleDiagnostic(DiagLevel, Info);
175}
176
Daniel Dunbar34818552009-11-14 03:23:19 +0000177//===----------------------------------------------------------------------===//
178// Checking diagnostics implementation.
179//===----------------------------------------------------------------------===//
180
Eugene Zelenko4f233182018-03-22 00:53:26 +0000181using DiagList = TextDiagnosticBuffer::DiagList;
182using const_diag_iterator = TextDiagnosticBuffer::const_iterator;
Daniel Dunbar34818552009-11-14 03:23:19 +0000183
Chris Lattnere82411b2010-04-28 20:02:30 +0000184namespace {
185
Chris Lattnere82411b2010-04-28 20:02:30 +0000186/// StandardDirective - Directive with string matching.
Chris Lattnere82411b2010-04-28 20:02:30 +0000187class StandardDirective : public Directive {
188public:
Jordan Rosee1572eb2012-07-10 02:57:03 +0000189 StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000190 bool MatchAnyLine, StringRef Text, unsigned Min,
191 unsigned Max)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000192 : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max) {}
Chris Lattnere82411b2010-04-28 20:02:30 +0000193
Craig Topperafa7cb32014-03-13 06:07:04 +0000194 bool isValid(std::string &Error) override {
Chris Lattnere82411b2010-04-28 20:02:30 +0000195 // all strings are considered valid; even empty ones
196 return true;
197 }
198
Craig Topperafa7cb32014-03-13 06:07:04 +0000199 bool match(StringRef S) override {
Jordan Rose6dae7612012-07-10 02:56:15 +0000200 return S.find(Text) != StringRef::npos;
Chris Lattnere82411b2010-04-28 20:02:30 +0000201 }
202};
203
204/// RegexDirective - Directive with regular-expression matching.
Chris Lattnere82411b2010-04-28 20:02:30 +0000205class RegexDirective : public Directive {
206public:
Jordan Rosee1572eb2012-07-10 02:57:03 +0000207 RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000208 bool MatchAnyLine, StringRef Text, unsigned Min, unsigned Max,
209 StringRef RegexStr)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000210 : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max),
211 Regex(RegexStr) {}
Chris Lattnere82411b2010-04-28 20:02:30 +0000212
Craig Topperafa7cb32014-03-13 06:07:04 +0000213 bool isValid(std::string &Error) override {
Alexander Kornienko5583e6f2015-12-28 15:15:16 +0000214 return Regex.isValid(Error);
Chris Lattnere82411b2010-04-28 20:02:30 +0000215 }
216
Craig Topperafa7cb32014-03-13 06:07:04 +0000217 bool match(StringRef S) override {
Chris Lattnere82411b2010-04-28 20:02:30 +0000218 return Regex.match(S);
219 }
220
221private:
222 llvm::Regex Regex;
223};
224
Chris Lattnere82411b2010-04-28 20:02:30 +0000225class ParseHelper
226{
227public:
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000228 ParseHelper(StringRef S)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000229 : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {}
Chris Lattnere82411b2010-04-28 20:02:30 +0000230
231 // Return true if string literal is next.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000232 bool Next(StringRef S) {
Chris Lattnere82411b2010-04-28 20:02:30 +0000233 P = C;
Benjamin Kramer2bd4cee2010-09-01 17:28:48 +0000234 PEnd = C + S.size();
Chris Lattnere82411b2010-04-28 20:02:30 +0000235 if (PEnd > End)
236 return false;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000237 return memcmp(P, S.data(), S.size()) == 0;
Chris Lattnere82411b2010-04-28 20:02:30 +0000238 }
239
240 // Return true if number is next.
241 // Output N only if number is next.
242 bool Next(unsigned &N) {
243 unsigned TMP = 0;
244 P = C;
245 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
246 TMP *= 10;
247 TMP += P[0] - '0';
248 }
249 if (P == C)
250 return false;
251 PEnd = P;
252 N = TMP;
253 return true;
254 }
255
Hal Finkel05e46482017-12-16 02:23:22 +0000256 // Return true if string literal S is matched in content.
257 // When true, P marks begin-position of the match, and calling Advance sets C
258 // to end-position of the match.
259 // If S is the empty string, then search for any letter instead (makes sense
260 // with FinishDirectiveToken=true).
261 // If EnsureStartOfWord, then skip matches that don't start a new word.
262 // If FinishDirectiveToken, then assume the match is the start of a comment
263 // directive for -verify, and extend the match to include the entire first
264 // token of that directive.
265 bool Search(StringRef S, bool EnsureStartOfWord = false,
266 bool FinishDirectiveToken = false) {
Andy Gibbsac51de62012-10-19 12:36:49 +0000267 do {
Hal Finkel05e46482017-12-16 02:23:22 +0000268 if (!S.empty()) {
269 P = std::search(C, End, S.begin(), S.end());
270 PEnd = P + S.size();
271 }
272 else {
273 P = C;
274 while (P != End && !isLetter(*P))
275 ++P;
276 PEnd = P + 1;
277 }
Andy Gibbsac51de62012-10-19 12:36:49 +0000278 if (P == End)
279 break;
Hal Finkel05e46482017-12-16 02:23:22 +0000280 // If not start of word but required, skip and search again.
281 if (EnsureStartOfWord
282 // Check if string literal starts a new word.
283 && !(P == Begin || isWhitespace(P[-1])
284 // Or it could be preceded by the start of a comment.
285 || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
286 && P[-2] == '/')))
287 continue;
288 if (FinishDirectiveToken) {
289 while (PEnd != End && (isAlphanumeric(*PEnd)
290 || *PEnd == '-' || *PEnd == '_'))
291 ++PEnd;
292 // Put back trailing digits and hyphens to be parsed later as a count
293 // or count range. Because -verify prefixes must start with letters,
294 // we know the actual directive we found starts with a letter, so
295 // we won't put back the entire directive word and thus record an empty
296 // string.
297 assert(isLetter(*P) && "-verify prefix must start with a letter");
298 while (isDigit(PEnd[-1]) || PEnd[-1] == '-')
299 --PEnd;
300 }
301 return true;
Andy Gibbsac51de62012-10-19 12:36:49 +0000302 } while (Advance());
303 return false;
Chris Lattnere82411b2010-04-28 20:02:30 +0000304 }
305
Hans Wennborgcda4b6d2013-12-11 23:40:50 +0000306 // Return true if a CloseBrace that closes the OpenBrace at the current nest
307 // level is found. When true, P marks begin-position of CloseBrace.
308 bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
309 unsigned Depth = 1;
310 P = C;
311 while (P < End) {
312 StringRef S(P, End - P);
313 if (S.startswith(OpenBrace)) {
314 ++Depth;
315 P += OpenBrace.size();
316 } else if (S.startswith(CloseBrace)) {
317 --Depth;
318 if (Depth == 0) {
319 PEnd = P + CloseBrace.size();
320 return true;
321 }
322 P += CloseBrace.size();
323 } else {
324 ++P;
325 }
326 }
327 return false;
328 }
329
Chris Lattnere82411b2010-04-28 20:02:30 +0000330 // Advance 1-past previous next/search.
331 // Behavior is undefined if previous next/search failed.
332 bool Advance() {
333 C = PEnd;
334 return C < End;
335 }
336
337 // Skip zero or more whitespace.
338 void SkipWhitespace() {
Jordan Rosea7d03842013-02-08 22:30:41 +0000339 for (; C < End && isWhitespace(*C); ++C)
Chris Lattnere82411b2010-04-28 20:02:30 +0000340 ;
341 }
342
343 // Return true if EOF reached.
344 bool Done() {
345 return !(C < End);
346 }
347
Eugene Zelenko4f233182018-03-22 00:53:26 +0000348 // Beginning of expected content.
349 const char * const Begin;
350
351 // End of expected content (1-past).
352 const char * const End;
353
354 // Position of next char in content.
355 const char *C;
356
Chris Lattnere82411b2010-04-28 20:02:30 +0000357 const char *P;
358
359private:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000360 // Previous next/search subject end (1-past).
361 const char *PEnd = nullptr;
Chris Lattnere82411b2010-04-28 20:02:30 +0000362};
363
Eugene Zelenko4f233182018-03-22 00:53:26 +0000364} // anonymous
Chris Lattnere82411b2010-04-28 20:02:30 +0000365
366/// ParseDirective - Go through the comment and see if it indicates expected
367/// diagnostics. If so, then put them in the appropriate directive list.
368///
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000369/// Returns true if any valid directives were found.
Jordan Roseb00073d2012-08-10 01:06:16 +0000370static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000371 Preprocessor *PP, SourceLocation Pos,
Andy Gibbs0fea0452012-10-19 12:49:32 +0000372 VerifyDiagnosticConsumer::DirectiveStatus &Status) {
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000373 DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics();
374
Chris Lattnere82411b2010-04-28 20:02:30 +0000375 // A single comment may contain multiple directives.
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000376 bool FoundDirective = false;
377 for (ParseHelper PH(S); !PH.Done();) {
Hal Finkel05e46482017-12-16 02:23:22 +0000378 // Search for the initial directive token.
379 // If one prefix, save time by searching only for its directives.
380 // Otherwise, search for any potential directive token and check it later.
381 const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes;
382 if (!(Prefixes.size() == 1 ? PH.Search(*Prefixes.begin(), true, true)
383 : PH.Search("", true, true)))
Chris Lattnere82411b2010-04-28 20:02:30 +0000384 break;
385 PH.Advance();
386
Hal Finkel05e46482017-12-16 02:23:22 +0000387 // Default directive kind.
388 bool RegexKind = false;
389 const char* KindStr = "string";
Chris Lattnere82411b2010-04-28 20:02:30 +0000390
Hal Finkel05e46482017-12-16 02:23:22 +0000391 // Parse the initial directive token in reverse so we can easily determine
392 // its exact actual prefix. If we were to parse it from the front instead,
393 // it would be harder to determine where the prefix ends because there
394 // might be multiple matching -verify prefixes because some might prefix
395 // others.
396 StringRef DToken(PH.P, PH.C - PH.P);
397
398 // Regex in initial directive token: -re
399 if (DToken.endswith("-re")) {
400 RegexKind = true;
401 KindStr = "regex";
402 DToken = DToken.substr(0, DToken.size()-3);
403 }
404
405 // Type in initial directive token: -{error|warning|note|no-diagnostics}
Craig Topper49a27902014-05-22 04:46:25 +0000406 DirectiveList *DL = nullptr;
Hal Finkel05e46482017-12-16 02:23:22 +0000407 bool NoDiag = false;
408 StringRef DType;
409 if (DToken.endswith(DType="-error"))
Craig Topper49a27902014-05-22 04:46:25 +0000410 DL = ED ? &ED->Errors : nullptr;
Hal Finkel05e46482017-12-16 02:23:22 +0000411 else if (DToken.endswith(DType="-warning"))
Craig Topper49a27902014-05-22 04:46:25 +0000412 DL = ED ? &ED->Warnings : nullptr;
Hal Finkel05e46482017-12-16 02:23:22 +0000413 else if (DToken.endswith(DType="-remark"))
Craig Topper49a27902014-05-22 04:46:25 +0000414 DL = ED ? &ED->Remarks : nullptr;
Hal Finkel05e46482017-12-16 02:23:22 +0000415 else if (DToken.endswith(DType="-note"))
Craig Topper49a27902014-05-22 04:46:25 +0000416 DL = ED ? &ED->Notes : nullptr;
Hal Finkel05e46482017-12-16 02:23:22 +0000417 else if (DToken.endswith(DType="-no-diagnostics")) {
418 NoDiag = true;
419 if (RegexKind)
420 continue;
421 }
422 else
423 continue;
424 DToken = DToken.substr(0, DToken.size()-DType.size());
425
426 // What's left in DToken is the actual prefix. That might not be a -verify
427 // prefix even if there is only one -verify prefix (for example, the full
428 // DToken is foo-bar-warning, but foo is the only -verify prefix).
429 if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
430 continue;
431
432 if (NoDiag) {
Andy Gibbs0fea0452012-10-19 12:49:32 +0000433 if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
434 Diags.Report(Pos, diag::err_verify_invalid_no_diags)
435 << /*IsExpectedNoDiagnostics=*/true;
436 else
437 Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
438 continue;
Hal Finkel05e46482017-12-16 02:23:22 +0000439 }
Andy Gibbs0fea0452012-10-19 12:49:32 +0000440 if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
441 Diags.Report(Pos, diag::err_verify_invalid_no_diags)
442 << /*IsExpectedNoDiagnostics=*/false;
443 continue;
444 }
445 Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
446
Jordan Roseb00073d2012-08-10 01:06:16 +0000447 // If a directive has been found but we're not interested
448 // in storing the directive information, return now.
449 if (!DL)
450 return true;
451
Jordan Rosee1572eb2012-07-10 02:57:03 +0000452 // Next optional token: @
453 SourceLocation ExpectedLoc;
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000454 bool MatchAnyLine = false;
Jordan Rosee1572eb2012-07-10 02:57:03 +0000455 if (!PH.Next("@")) {
456 ExpectedLoc = Pos;
457 } else {
458 PH.Advance();
459 unsigned Line = 0;
460 bool FoundPlus = PH.Next("+");
461 if (FoundPlus || PH.Next("-")) {
462 // Relative to current line.
463 PH.Advance();
464 bool Invalid = false;
465 unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
466 if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
467 if (FoundPlus) ExpectedLine += Line;
468 else ExpectedLine -= Line;
469 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
470 }
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000471 } else if (PH.Next(Line)) {
Jordan Rosee1572eb2012-07-10 02:57:03 +0000472 // Absolute line number.
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000473 if (Line > 0)
Jordan Rosee1572eb2012-07-10 02:57:03 +0000474 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000475 } else if (PP && PH.Search(":")) {
476 // Specific source file.
477 StringRef Filename(PH.C, PH.P-PH.C);
478 PH.Advance();
479
480 // Lookup file via Preprocessor, like a #include.
481 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000482 const FileEntry *FE =
483 PP->LookupFile(Pos, Filename, false, nullptr, nullptr, CurDir,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000484 nullptr, nullptr, nullptr, nullptr);
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000485 if (!FE) {
486 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
487 diag::err_verify_missing_file) << Filename << KindStr;
488 continue;
489 }
490
491 if (SM.translateFile(FE).isInvalid())
492 SM.createFileID(FE, Pos, SrcMgr::C_User);
493
494 if (PH.Next(Line) && Line > 0)
495 ExpectedLoc = SM.translateFileLineCol(FE, Line, 1);
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000496 else if (PH.Next("*")) {
497 MatchAnyLine = true;
498 ExpectedLoc = SM.translateFileLineCol(FE, 1, 1);
499 }
Richard Smith17ad3ac2017-10-18 01:41:38 +0000500 } else if (PH.Next("*")) {
501 MatchAnyLine = true;
502 ExpectedLoc = SourceLocation();
Jordan Rosee1572eb2012-07-10 02:57:03 +0000503 }
504
Richard Smith17ad3ac2017-10-18 01:41:38 +0000505 if (ExpectedLoc.isInvalid() && !MatchAnyLine) {
Jordan Rosee1572eb2012-07-10 02:57:03 +0000506 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
507 diag::err_verify_missing_line) << KindStr;
508 continue;
509 }
510 PH.Advance();
511 }
512
513 // Skip optional whitespace.
Chris Lattnere82411b2010-04-28 20:02:30 +0000514 PH.SkipWhitespace();
515
Jordan Rosee1572eb2012-07-10 02:57:03 +0000516 // Next optional token: positive integer or a '+'.
Jordan Roseb8b2ca62012-07-10 02:57:26 +0000517 unsigned Min = 1;
518 unsigned Max = 1;
519 if (PH.Next(Min)) {
Chris Lattnere82411b2010-04-28 20:02:30 +0000520 PH.Advance();
Jordan Roseb8b2ca62012-07-10 02:57:26 +0000521 // A positive integer can be followed by a '+' meaning min
522 // or more, or by a '-' meaning a range from min to max.
523 if (PH.Next("+")) {
524 Max = Directive::MaxCount;
525 PH.Advance();
526 } else if (PH.Next("-")) {
527 PH.Advance();
528 if (!PH.Next(Max) || Max < Min) {
529 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
530 diag::err_verify_invalid_range) << KindStr;
531 continue;
532 }
533 PH.Advance();
534 } else {
535 Max = Min;
536 }
537 } else if (PH.Next("+")) {
538 // '+' on its own means "1 or more".
539 Max = Directive::MaxCount;
Anna Zaksa2510072011-12-15 02:28:16 +0000540 PH.Advance();
541 }
Chris Lattnere82411b2010-04-28 20:02:30 +0000542
Jordan Rosee1572eb2012-07-10 02:57:03 +0000543 // Skip optional whitespace.
Chris Lattnere82411b2010-04-28 20:02:30 +0000544 PH.SkipWhitespace();
545
Jordan Rosee1572eb2012-07-10 02:57:03 +0000546 // Next token: {{
Chris Lattnere82411b2010-04-28 20:02:30 +0000547 if (!PH.Next("{{")) {
Jordan Rose6dae7612012-07-10 02:56:15 +0000548 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
549 diag::err_verify_missing_start) << KindStr;
Daniel Dunbar34818552009-11-14 03:23:19 +0000550 continue;
551 }
Chris Lattnere82411b2010-04-28 20:02:30 +0000552 PH.Advance();
553 const char* const ContentBegin = PH.C; // mark content begin
Daniel Dunbar34818552009-11-14 03:23:19 +0000554
Jordan Rosee1572eb2012-07-10 02:57:03 +0000555 // Search for token: }}
Hans Wennborgcda4b6d2013-12-11 23:40:50 +0000556 if (!PH.SearchClosingBrace("{{", "}}")) {
Jordan Rose6dae7612012-07-10 02:56:15 +0000557 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
558 diag::err_verify_missing_end) << KindStr;
Chris Lattnere82411b2010-04-28 20:02:30 +0000559 continue;
Daniel Dunbar34818552009-11-14 03:23:19 +0000560 }
Chris Lattnere82411b2010-04-28 20:02:30 +0000561 const char* const ContentEnd = PH.P; // mark content end
562 PH.Advance();
Daniel Dunbar34818552009-11-14 03:23:19 +0000563
Jordan Rosee1572eb2012-07-10 02:57:03 +0000564 // Build directive text; convert \n to newlines.
Chris Lattnere82411b2010-04-28 20:02:30 +0000565 std::string Text;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000566 StringRef NewlineStr = "\\n";
567 StringRef Content(ContentBegin, ContentEnd-ContentBegin);
Chris Lattnere82411b2010-04-28 20:02:30 +0000568 size_t CPos = 0;
569 size_t FPos;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000570 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
Chris Lattnere82411b2010-04-28 20:02:30 +0000571 Text += Content.substr(CPos, FPos-CPos);
572 Text += '\n';
573 CPos = FPos + NewlineStr.size();
Daniel Dunbar34818552009-11-14 03:23:19 +0000574 }
Chris Lattnere82411b2010-04-28 20:02:30 +0000575 if (Text.empty())
576 Text.assign(ContentBegin, ContentEnd);
Daniel Dunbar34818552009-11-14 03:23:19 +0000577
Alp Toker6ed72512013-12-14 01:07:05 +0000578 // Check that regex directives contain at least one regex.
579 if (RegexKind && Text.find("{{") == StringRef::npos) {
580 Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
581 diag::err_verify_missing_regex) << Text;
582 return false;
583 }
584
Jordan Rosee1572eb2012-07-10 02:57:03 +0000585 // Construct new directive.
David Blaikie93106512014-08-29 16:30:23 +0000586 std::unique_ptr<Directive> D = Directive::create(
587 RegexKind, Pos, ExpectedLoc, MatchAnyLine, Text, Min, Max);
Nico Weber568dacc2014-04-24 05:32:03 +0000588
Chris Lattnere82411b2010-04-28 20:02:30 +0000589 std::string Error;
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000590 if (D->isValid(Error)) {
David Blaikie93106512014-08-29 16:30:23 +0000591 DL->push_back(std::move(D));
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000592 FoundDirective = true;
593 } else {
Jordan Rose6dae7612012-07-10 02:56:15 +0000594 Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
595 diag::err_verify_invalid_content)
Chris Lattnere82411b2010-04-28 20:02:30 +0000596 << KindStr << Error;
Daniel Dunbar34818552009-11-14 03:23:19 +0000597 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000598 }
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000599
600 return FoundDirective;
601}
602
603/// HandleComment - Hook into the preprocessor and extract comments containing
604/// expected errors and warnings.
605bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
606 SourceRange Comment) {
607 SourceManager &SM = PP.getSourceManager();
Douglas Gregor6b930962013-05-03 22:58:43 +0000608
609 // If this comment is for a different source manager, ignore it.
610 if (SrcManager && &SM != SrcManager)
611 return false;
612
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000613 SourceLocation CommentBegin = Comment.getBegin();
614
615 const char *CommentRaw = SM.getCharacterData(CommentBegin);
616 StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
617
618 if (C.empty())
619 return false;
620
621 // Fold any "\<EOL>" sequences
622 size_t loc = C.find('\\');
623 if (loc == StringRef::npos) {
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000624 ParseDirective(C, &ED, SM, &PP, CommentBegin, Status);
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000625 return false;
626 }
627
628 std::string C2;
629 C2.reserve(C.size());
630
631 for (size_t last = 0;; loc = C.find('\\', last)) {
632 if (loc == StringRef::npos || loc == C.size()) {
633 C2 += C.substr(last);
634 break;
635 }
636 C2 += C.substr(last, loc-last);
637 last = loc + 1;
638
639 if (C[last] == '\n' || C[last] == '\r') {
640 ++last;
641
642 // Escape \r\n or \n\r, but not \n\n.
643 if (last < C.size())
644 if (C[last] == '\n' || C[last] == '\r')
645 if (C[last] != C[last-1])
646 ++last;
647 } else {
648 // This was just a normal backslash.
649 C2 += '\\';
650 }
651 }
652
653 if (!C2.empty())
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000654 ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status);
Jordan Roseb13eb8d2012-07-11 19:58:23 +0000655 return false;
Daniel Dunbar34818552009-11-14 03:23:19 +0000656}
657
Jordan Roseb00073d2012-08-10 01:06:16 +0000658#ifndef NDEBUG
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000659/// Lex the specified source file to determine whether it contains
Jordan Roseb00073d2012-08-10 01:06:16 +0000660/// any expected-* directives. As a Lexer is used rather than a full-blown
661/// Preprocessor, directives inside skipped #if blocks will still be found.
662///
663/// \return true if any directives were found.
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000664static bool findDirectives(SourceManager &SM, FileID FID,
665 const LangOptions &LangOpts) {
Axel Naumannac50dcf2011-07-25 19:18:12 +0000666 // Create a raw lexer to pull all the comments out of FID.
667 if (FID.isInvalid())
Jordan Roseb00073d2012-08-10 01:06:16 +0000668 return false;
Daniel Dunbar34818552009-11-14 03:23:19 +0000669
670 // Create a lexer to lex all the tokens of the main file in raw mode.
Chris Lattner710bb872009-11-30 04:18:44 +0000671 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000672 Lexer RawLex(FID, FromFile, SM, LangOpts);
Daniel Dunbar34818552009-11-14 03:23:19 +0000673
674 // Return comments as tokens, this is how we find expected diagnostics.
675 RawLex.SetCommentRetentionState(true);
676
677 Token Tok;
678 Tok.setKind(tok::comment);
Andy Gibbs0fea0452012-10-19 12:49:32 +0000679 VerifyDiagnosticConsumer::DirectiveStatus Status =
680 VerifyDiagnosticConsumer::HasNoDirectives;
Daniel Dunbar34818552009-11-14 03:23:19 +0000681 while (Tok.isNot(tok::eof)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000682 RawLex.LexFromRawLexer(Tok);
Daniel Dunbar34818552009-11-14 03:23:19 +0000683 if (!Tok.is(tok::comment)) continue;
684
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000685 std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
Daniel Dunbar34818552009-11-14 03:23:19 +0000686 if (Comment.empty()) continue;
687
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000688 // Find first directive.
Craig Topper49a27902014-05-22 04:46:25 +0000689 if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
690 Status))
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000691 return true;
Jordan Roseb00073d2012-08-10 01:06:16 +0000692 }
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000693 return false;
Daniel Dunbar34818552009-11-14 03:23:19 +0000694}
Jordan Roseb00073d2012-08-10 01:06:16 +0000695#endif // !NDEBUG
Daniel Dunbar34818552009-11-14 03:23:19 +0000696
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000697/// Takes a list of diagnostics that have been generated but not matched
Jordan Rosee1572eb2012-07-10 02:57:03 +0000698/// by an expected-* directive and produces a diagnostic to the user from this.
699static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
700 const_diag_iterator diag_begin,
701 const_diag_iterator diag_end,
702 const char *Kind) {
Daniel Dunbar34818552009-11-14 03:23:19 +0000703 if (diag_begin == diag_end) return 0;
704
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000705 SmallString<256> Fmt;
Daniel Dunbar34818552009-11-14 03:23:19 +0000706 llvm::raw_svector_ostream OS(Fmt);
707 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000708 if (I->first.isInvalid() || !SourceMgr)
Daniel Dunbar34818552009-11-14 03:23:19 +0000709 OS << "\n (frontend)";
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000710 else {
711 OS << "\n ";
712 if (const FileEntry *File = SourceMgr->getFileEntryForID(
713 SourceMgr->getFileID(I->first)))
714 OS << " File " << File->getName();
715 OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
716 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000717 OS << ": " << I->second;
718 }
719
Jordan Rose6f524ac2012-07-11 16:50:36 +0000720 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
Jordan Rosee1572eb2012-07-10 02:57:03 +0000721 << Kind << /*Unexpected=*/true << OS.str();
Daniel Dunbar34818552009-11-14 03:23:19 +0000722 return std::distance(diag_begin, diag_end);
723}
724
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000725/// Takes a list of diagnostics that were expected to have been generated
Jordan Rosee1572eb2012-07-10 02:57:03 +0000726/// but were not and produces a diagnostic to the user from this.
David Blaikie93106512014-08-29 16:30:23 +0000727static unsigned PrintExpected(DiagnosticsEngine &Diags,
728 SourceManager &SourceMgr,
729 std::vector<Directive *> &DL, const char *Kind) {
Chris Lattnere82411b2010-04-28 20:02:30 +0000730 if (DL.empty())
731 return 0;
732
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000733 SmallString<256> Fmt;
Chris Lattnere82411b2010-04-28 20:02:30 +0000734 llvm::raw_svector_ostream OS(Fmt);
Eugene Zelenko4f233182018-03-22 00:53:26 +0000735 for (const auto *D : DL) {
736 if (D->DiagnosticLoc.isInvalid())
Richard Smith17ad3ac2017-10-18 01:41:38 +0000737 OS << "\n File *";
738 else
Eugene Zelenko4f233182018-03-22 00:53:26 +0000739 OS << "\n File " << SourceMgr.getFilename(D->DiagnosticLoc);
740 if (D->MatchAnyLine)
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000741 OS << " Line *";
742 else
Eugene Zelenko4f233182018-03-22 00:53:26 +0000743 OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc);
744 if (D->DirectiveLoc != D->DiagnosticLoc)
Jordan Rosee1572eb2012-07-10 02:57:03 +0000745 OS << " (directive at "
Eugene Zelenko4f233182018-03-22 00:53:26 +0000746 << SourceMgr.getFilename(D->DirectiveLoc) << ':'
747 << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')';
748 OS << ": " << D->Text;
Chris Lattnere82411b2010-04-28 20:02:30 +0000749 }
750
Jordan Rose6f524ac2012-07-11 16:50:36 +0000751 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
Jordan Rosee1572eb2012-07-10 02:57:03 +0000752 << Kind << /*Unexpected=*/false << OS.str();
Chris Lattnere82411b2010-04-28 20:02:30 +0000753 return DL.size();
754}
755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000756/// Determine whether two source locations come from the same file.
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000757static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
758 SourceLocation DiagnosticLoc) {
759 while (DiagnosticLoc.isMacroID())
760 DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
761
Eli Friedman5ba37d52013-08-22 00:27:10 +0000762 if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000763 return true;
764
765 const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
Eli Friedman5ba37d52013-08-22 00:27:10 +0000766 if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc))
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000767 return true;
768
769 return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
770}
771
Chris Lattnere82411b2010-04-28 20:02:30 +0000772/// CheckLists - Compare expected to seen diagnostic lists and return the
773/// the difference between them.
David Blaikie9c902b52011-09-25 23:23:43 +0000774static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
Chris Lattnere82411b2010-04-28 20:02:30 +0000775 const char *Label,
776 DirectiveList &Left,
777 const_diag_iterator d2_begin,
Eric Fiselier098e6de2015-06-13 07:11:40 +0000778 const_diag_iterator d2_end,
779 bool IgnoreUnexpected) {
David Blaikie93106512014-08-29 16:30:23 +0000780 std::vector<Directive *> LeftOnly;
Daniel Dunbar34818552009-11-14 03:23:19 +0000781 DiagList Right(d2_begin, d2_end);
782
David Blaikie93106512014-08-29 16:30:23 +0000783 for (auto &Owner : Left) {
784 Directive &D = *Owner;
Jordan Rosee1572eb2012-07-10 02:57:03 +0000785 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
Daniel Dunbar34818552009-11-14 03:23:19 +0000786
Jordan Roseb8b2ca62012-07-10 02:57:26 +0000787 for (unsigned i = 0; i < D.Max; ++i) {
Chris Lattnere82411b2010-04-28 20:02:30 +0000788 DiagList::iterator II, IE;
789 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
Andy Gibbsc1f152e2014-07-10 16:43:29 +0000790 if (!D.MatchAnyLine) {
791 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
792 if (LineNo1 != LineNo2)
793 continue;
794 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000795
Richard Smith17ad3ac2017-10-18 01:41:38 +0000796 if (!D.DiagnosticLoc.isInvalid() &&
797 !IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
Andy Gibbsfcc699a2013-04-17 08:06:46 +0000798 continue;
799
Chris Lattnere82411b2010-04-28 20:02:30 +0000800 const std::string &RightText = II->second;
Jordan Rose6dae7612012-07-10 02:56:15 +0000801 if (D.match(RightText))
Chris Lattnere82411b2010-04-28 20:02:30 +0000802 break;
Daniel Dunbar34818552009-11-14 03:23:19 +0000803 }
Chris Lattnere82411b2010-04-28 20:02:30 +0000804 if (II == IE) {
805 // Not found.
Jordan Roseb8b2ca62012-07-10 02:57:26 +0000806 if (i >= D.Min) break;
David Blaikie93106512014-08-29 16:30:23 +0000807 LeftOnly.push_back(&D);
Chris Lattnere82411b2010-04-28 20:02:30 +0000808 } else {
809 // Found. The same cannot be found twice.
810 Right.erase(II);
811 }
Daniel Dunbar34818552009-11-14 03:23:19 +0000812 }
813 }
814 // Now all that's left in Right are those that were not matched.
Jordan Rosee1572eb2012-07-10 02:57:03 +0000815 unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
Eric Fiselier098e6de2015-06-13 07:11:40 +0000816 if (!IgnoreUnexpected)
817 num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
NAKAMURA Takumi7bfba2f2011-12-17 13:00:31 +0000818 return num;
Daniel Dunbar34818552009-11-14 03:23:19 +0000819}
820
821/// CheckResults - This compares the expected results to those that
822/// were actually reported. It emits any discrepencies. Return "true" if there
823/// were problems. Return "false" otherwise.
David Blaikie9c902b52011-09-25 23:23:43 +0000824static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
Daniel Dunbar34818552009-11-14 03:23:19 +0000825 const TextDiagnosticBuffer &Buffer,
Chris Lattnere82411b2010-04-28 20:02:30 +0000826 ExpectedData &ED) {
Daniel Dunbar34818552009-11-14 03:23:19 +0000827 // We want to capture the delta between what was expected and what was
828 // seen.
829 //
830 // Expected \ Seen - set expected but not seen
831 // Seen \ Expected - set seen but not expected
832 unsigned NumProblems = 0;
833
Eric Fiselier098e6de2015-06-13 07:11:40 +0000834 const DiagnosticLevelMask DiagMask =
835 Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
836
Daniel Dunbar34818552009-11-14 03:23:19 +0000837 // See if there are error mismatches.
Chris Lattnere82411b2010-04-28 20:02:30 +0000838 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
Eric Fiselier098e6de2015-06-13 07:11:40 +0000839 Buffer.err_begin(), Buffer.err_end(),
840 bool(DiagnosticLevelMask::Error & DiagMask));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000841
Daniel Dunbar34818552009-11-14 03:23:19 +0000842 // See if there are warning mismatches.
Chris Lattnere82411b2010-04-28 20:02:30 +0000843 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
Eric Fiselier098e6de2015-06-13 07:11:40 +0000844 Buffer.warn_begin(), Buffer.warn_end(),
845 bool(DiagnosticLevelMask::Warning & DiagMask));
Daniel Dunbar34818552009-11-14 03:23:19 +0000846
Tobias Grosser86a85672014-05-01 14:06:01 +0000847 // See if there are remark mismatches.
848 NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
Eric Fiselier098e6de2015-06-13 07:11:40 +0000849 Buffer.remark_begin(), Buffer.remark_end(),
850 bool(DiagnosticLevelMask::Remark & DiagMask));
Tobias Grosser86a85672014-05-01 14:06:01 +0000851
Daniel Dunbar34818552009-11-14 03:23:19 +0000852 // See if there are note mismatches.
Chris Lattnere82411b2010-04-28 20:02:30 +0000853 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
Eric Fiselier098e6de2015-06-13 07:11:40 +0000854 Buffer.note_begin(), Buffer.note_end(),
855 bool(DiagnosticLevelMask::Note & DiagMask));
Daniel Dunbar34818552009-11-14 03:23:19 +0000856
857 return NumProblems;
858}
859
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000860void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
861 FileID FID,
862 ParsedStatus PS) {
863 // Check SourceManager hasn't changed.
864 setSourceManager(SM);
865
866#ifndef NDEBUG
867 if (FID.isInvalid())
868 return;
869
870 const FileEntry *FE = SM.getFileEntryForID(FID);
871
872 if (PS == IsParsed) {
873 // Move the FileID from the unparsed set to the parsed set.
874 UnparsedFiles.erase(FID);
875 ParsedFiles.insert(std::make_pair(FID, FE));
876 } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
877 // Add the FileID to the unparsed set if we haven't seen it before.
878
879 // Check for directives.
880 bool FoundDirectives;
881 if (PS == IsUnparsedNoDirectives)
882 FoundDirectives = false;
883 else
884 FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
885
886 // Add the FileID to the unparsed set.
887 UnparsedFiles.insert(std::make_pair(FID,
888 UnparsedFileStatus(FE, FoundDirectives)));
889 }
890#endif
891}
892
David Blaikie69609dc2011-09-26 00:38:03 +0000893void VerifyDiagnosticConsumer::CheckDiagnostics() {
Daniel Dunbar34818552009-11-14 03:23:19 +0000894 // Ensure any diagnostics go to the primary client.
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000895 DiagnosticConsumer *CurClient = Diags.getClient();
896 std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient();
Douglas Gregor2b9b4642011-09-13 01:26:44 +0000897 Diags.setClient(PrimaryClient, false);
Daniel Dunbar34818552009-11-14 03:23:19 +0000898
Jordan Roseb00073d2012-08-10 01:06:16 +0000899#ifndef NDEBUG
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000900 // In a debug build, scan through any files that may have been missed
901 // during parsing and issue a fatal error if directives are contained
902 // within these files. If a fatal error occurs, this suggests that
903 // this file is being parsed separately from the main file, in which
904 // case consider moving the directives to the correct place, if this
905 // is applicable.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000906 if (!UnparsedFiles.empty()) {
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000907 // Generate a cache of parsed FileEntry pointers for alias lookups.
908 llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000909 for (const auto &I : ParsedFiles)
910 if (const FileEntry *FE = I.second)
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000911 ParsedFileCache.insert(FE);
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000912
913 // Iterate through list of unparsed files.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000914 for (const auto &I : UnparsedFiles) {
915 const UnparsedFileStatus &Status = I.second;
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000916 const FileEntry *FE = Status.getFile();
917
918 // Skip files that have been parsed via an alias.
919 if (FE && ParsedFileCache.count(FE))
Jordan Roseb00073d2012-08-10 01:06:16 +0000920 continue;
921
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000922 // Report a fatal error if this file contained directives.
923 if (Status.foundDirectives()) {
Jordan Roseb00073d2012-08-10 01:06:16 +0000924 llvm::report_fatal_error(Twine("-verify directives found after rather"
925 " than during normal parsing of ",
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000926 StringRef(FE ? FE->getName() : "(unknown)")));
927 }
Axel Naumann744f1212011-08-24 13:36:19 +0000928 }
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000929
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000930 // UnparsedFiles has been processed now, so clear it.
931 UnparsedFiles.clear();
932 }
933#endif // !NDEBUG
934
935 if (SrcManager) {
Andy Gibbs0fea0452012-10-19 12:49:32 +0000936 // Produce an error if no expected-* directives could be found in the
937 // source file(s) processed.
938 if (Status == HasNoDirectives) {
939 Diags.Report(diag::err_verify_no_directives).setForceEmit();
940 ++NumErrors;
941 Status = HasNoDirectivesReported;
942 }
943
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000944 // Check that the expected diagnostics occurred.
Jordan Rose8c1ac0c2012-08-18 16:58:52 +0000945 NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000946 } else {
Eric Fiselier098e6de2015-06-13 07:11:40 +0000947 const DiagnosticLevelMask DiagMask =
948 ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
949 if (bool(DiagnosticLevelMask::Error & DiagMask))
950 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
951 Buffer->err_end(), "error");
952 if (bool(DiagnosticLevelMask::Warning & DiagMask))
953 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
954 Buffer->warn_end(), "warn");
955 if (bool(DiagnosticLevelMask::Remark & DiagMask))
956 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(),
957 Buffer->remark_end(), "remark");
958 if (bool(DiagnosticLevelMask::Note & DiagMask))
959 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
960 Buffer->note_end(), "note");
Daniel Dunbar34818552009-11-14 03:23:19 +0000961 }
962
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000963 Diags.setClient(CurClient, Owner.release() != nullptr);
Daniel Dunbar34818552009-11-14 03:23:19 +0000964
965 // Reset the buffer, we have processed all the diagnostics in it.
966 Buffer.reset(new TextDiagnosticBuffer());
Nico Weberdc493cf2014-04-24 05:39:55 +0000967 ED.Reset();
Daniel Dunbar34818552009-11-14 03:23:19 +0000968}
Chris Lattnere82411b2010-04-28 20:02:30 +0000969
David Blaikie93106512014-08-29 16:30:23 +0000970std::unique_ptr<Directive> Directive::create(bool RegexKind,
971 SourceLocation DirectiveLoc,
972 SourceLocation DiagnosticLoc,
973 bool MatchAnyLine, StringRef Text,
974 unsigned Min, unsigned Max) {
Alp Toker6ed72512013-12-14 01:07:05 +0000975 if (!RegexKind)
David Blaikie93106512014-08-29 16:30:23 +0000976 return llvm::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
977 MatchAnyLine, Text, Min, Max);
Hans Wennborgcda4b6d2013-12-11 23:40:50 +0000978
979 // Parse the directive into a regular expression.
980 std::string RegexStr;
981 StringRef S = Text;
982 while (!S.empty()) {
983 if (S.startswith("{{")) {
984 S = S.drop_front(2);
985 size_t RegexMatchLength = S.find("}}");
986 assert(RegexMatchLength != StringRef::npos);
987 // Append the regex, enclosed in parentheses.
988 RegexStr += "(";
989 RegexStr.append(S.data(), RegexMatchLength);
990 RegexStr += ")";
991 S = S.drop_front(RegexMatchLength + 2);
992 } else {
993 size_t VerbatimMatchLength = S.find("{{");
994 if (VerbatimMatchLength == StringRef::npos)
995 VerbatimMatchLength = S.size();
996 // Escape and append the fixed string.
Hans Wennborge6a87752013-12-12 00:27:31 +0000997 RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
Hans Wennborgcda4b6d2013-12-11 23:40:50 +0000998 S = S.drop_front(VerbatimMatchLength);
999 }
1000 }
1001
David Blaikie93106512014-08-29 16:30:23 +00001002 return llvm::make_unique<RegexDirective>(
1003 DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max, RegexStr);
Chris Lattnere82411b2010-04-28 20:02:30 +00001004}