VerifyDiagnosticConsumer.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. //===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is a concrete diagnostic client, which buffers the diagnostic messages.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  13. #include "clang/Basic/CharInfo.h"
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/DiagnosticOptions.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/LLVM.h"
  18. #include "clang/Basic/SourceLocation.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Basic/TokenKinds.h"
  21. #include "clang/Frontend/FrontendDiagnostic.h"
  22. #include "clang/Frontend/TextDiagnosticBuffer.h"
  23. #include "clang/Lex/HeaderSearch.h"
  24. #include "clang/Lex/Lexer.h"
  25. #include "clang/Lex/PPCallbacks.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Lex/Token.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/StringRef.h"
  32. #include "llvm/ADT/Twine.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/Regex.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <cstddef>
  39. #include <cstring>
  40. #include <iterator>
  41. #include <memory>
  42. #include <string>
  43. #include <utility>
  44. #include <vector>
  45. using namespace clang;
  46. using Directive = VerifyDiagnosticConsumer::Directive;
  47. using DirectiveList = VerifyDiagnosticConsumer::DirectiveList;
  48. using ExpectedData = VerifyDiagnosticConsumer::ExpectedData;
  49. #ifndef NDEBUG
  50. namespace {
  51. class VerifyFileTracker : public PPCallbacks {
  52. VerifyDiagnosticConsumer &Verify;
  53. SourceManager &SM;
  54. public:
  55. VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
  56. : Verify(Verify), SM(SM) {}
  57. /// Hook into the preprocessor and update the list of parsed
  58. /// files when the preprocessor indicates a new file is entered.
  59. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  60. SrcMgr::CharacteristicKind FileType,
  61. FileID PrevFID) override {
  62. Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
  63. VerifyDiagnosticConsumer::IsParsed);
  64. }
  65. };
  66. } // namespace
  67. #endif
  68. //===----------------------------------------------------------------------===//
  69. // Checking diagnostics implementation.
  70. //===----------------------------------------------------------------------===//
  71. using DiagList = TextDiagnosticBuffer::DiagList;
  72. using const_diag_iterator = TextDiagnosticBuffer::const_iterator;
  73. namespace {
  74. /// StandardDirective - Directive with string matching.
  75. class StandardDirective : public Directive {
  76. public:
  77. StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
  78. bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
  79. unsigned Min, unsigned Max)
  80. : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
  81. MatchAnyLine, Text, Min, Max) {}
  82. bool isValid(std::string &Error) override {
  83. // all strings are considered valid; even empty ones
  84. return true;
  85. }
  86. bool match(StringRef S) override { return S.contains(Text); }
  87. };
  88. /// RegexDirective - Directive with regular-expression matching.
  89. class RegexDirective : public Directive {
  90. public:
  91. RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
  92. bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
  93. unsigned Min, unsigned Max, StringRef RegexStr)
  94. : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
  95. MatchAnyLine, Text, Min, Max),
  96. Regex(RegexStr) {}
  97. bool isValid(std::string &Error) override {
  98. return Regex.isValid(Error);
  99. }
  100. bool match(StringRef S) override {
  101. return Regex.match(S);
  102. }
  103. private:
  104. llvm::Regex Regex;
  105. };
  106. class ParseHelper
  107. {
  108. public:
  109. ParseHelper(StringRef S)
  110. : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {}
  111. // Return true if string literal is next.
  112. bool Next(StringRef S) {
  113. P = C;
  114. PEnd = C + S.size();
  115. if (PEnd > End)
  116. return false;
  117. return memcmp(P, S.data(), S.size()) == 0;
  118. }
  119. // Return true if number is next.
  120. // Output N only if number is next.
  121. bool Next(unsigned &N) {
  122. unsigned TMP = 0;
  123. P = C;
  124. PEnd = P;
  125. for (; PEnd < End && *PEnd >= '0' && *PEnd <= '9'; ++PEnd) {
  126. TMP *= 10;
  127. TMP += *PEnd - '0';
  128. }
  129. if (PEnd == C)
  130. return false;
  131. N = TMP;
  132. return true;
  133. }
  134. // Return true if a marker is next.
  135. // A marker is the longest match for /#[A-Za-z0-9_-]+/.
  136. bool NextMarker() {
  137. P = C;
  138. if (P == End || *P != '#')
  139. return false;
  140. PEnd = P;
  141. ++PEnd;
  142. while ((isAlphanumeric(*PEnd) || *PEnd == '-' || *PEnd == '_') &&
  143. PEnd < End)
  144. ++PEnd;
  145. return PEnd > P + 1;
  146. }
  147. // Return true if string literal S is matched in content.
  148. // When true, P marks begin-position of the match, and calling Advance sets C
  149. // to end-position of the match.
  150. // If S is the empty string, then search for any letter instead (makes sense
  151. // with FinishDirectiveToken=true).
  152. // If EnsureStartOfWord, then skip matches that don't start a new word.
  153. // If FinishDirectiveToken, then assume the match is the start of a comment
  154. // directive for -verify, and extend the match to include the entire first
  155. // token of that directive.
  156. bool Search(StringRef S, bool EnsureStartOfWord = false,
  157. bool FinishDirectiveToken = false) {
  158. do {
  159. if (!S.empty()) {
  160. P = std::search(C, End, S.begin(), S.end());
  161. PEnd = P + S.size();
  162. }
  163. else {
  164. P = C;
  165. while (P != End && !isLetter(*P))
  166. ++P;
  167. PEnd = P + 1;
  168. }
  169. if (P == End)
  170. break;
  171. // If not start of word but required, skip and search again.
  172. if (EnsureStartOfWord
  173. // Check if string literal starts a new word.
  174. && !(P == Begin || isWhitespace(P[-1])
  175. // Or it could be preceded by the start of a comment.
  176. || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
  177. && P[-2] == '/')))
  178. continue;
  179. if (FinishDirectiveToken) {
  180. while (PEnd != End && (isAlphanumeric(*PEnd)
  181. || *PEnd == '-' || *PEnd == '_'))
  182. ++PEnd;
  183. // Put back trailing digits and hyphens to be parsed later as a count
  184. // or count range. Because -verify prefixes must start with letters,
  185. // we know the actual directive we found starts with a letter, so
  186. // we won't put back the entire directive word and thus record an empty
  187. // string.
  188. assert(isLetter(*P) && "-verify prefix must start with a letter");
  189. while (isDigit(PEnd[-1]) || PEnd[-1] == '-')
  190. --PEnd;
  191. }
  192. return true;
  193. } while (Advance());
  194. return false;
  195. }
  196. // Return true if a CloseBrace that closes the OpenBrace at the current nest
  197. // level is found. When true, P marks begin-position of CloseBrace.
  198. bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
  199. unsigned Depth = 1;
  200. P = C;
  201. while (P < End) {
  202. StringRef S(P, End - P);
  203. if (S.startswith(OpenBrace)) {
  204. ++Depth;
  205. P += OpenBrace.size();
  206. } else if (S.startswith(CloseBrace)) {
  207. --Depth;
  208. if (Depth == 0) {
  209. PEnd = P + CloseBrace.size();
  210. return true;
  211. }
  212. P += CloseBrace.size();
  213. } else {
  214. ++P;
  215. }
  216. }
  217. return false;
  218. }
  219. // Advance 1-past previous next/search.
  220. // Behavior is undefined if previous next/search failed.
  221. bool Advance() {
  222. C = PEnd;
  223. return C < End;
  224. }
  225. // Return the text matched by the previous next/search.
  226. // Behavior is undefined if previous next/search failed.
  227. StringRef Match() { return StringRef(P, PEnd - P); }
  228. // Skip zero or more whitespace.
  229. void SkipWhitespace() {
  230. for (; C < End && isWhitespace(*C); ++C)
  231. ;
  232. }
  233. // Return true if EOF reached.
  234. bool Done() {
  235. return !(C < End);
  236. }
  237. // Beginning of expected content.
  238. const char * const Begin;
  239. // End of expected content (1-past).
  240. const char * const End;
  241. // Position of next char in content.
  242. const char *C;
  243. // Previous next/search subject start.
  244. const char *P;
  245. private:
  246. // Previous next/search subject end (1-past).
  247. const char *PEnd = nullptr;
  248. };
  249. // The information necessary to create a directive.
  250. struct UnattachedDirective {
  251. DirectiveList *DL = nullptr;
  252. bool RegexKind = false;
  253. SourceLocation DirectivePos, ContentBegin;
  254. std::string Text;
  255. unsigned Min = 1, Max = 1;
  256. };
  257. // Attach the specified directive to the line of code indicated by
  258. // \p ExpectedLoc.
  259. void attachDirective(DiagnosticsEngine &Diags, const UnattachedDirective &UD,
  260. SourceLocation ExpectedLoc,
  261. bool MatchAnyFileAndLine = false,
  262. bool MatchAnyLine = false) {
  263. // Construct new directive.
  264. std::unique_ptr<Directive> D = Directive::create(
  265. UD.RegexKind, UD.DirectivePos, ExpectedLoc, MatchAnyFileAndLine,
  266. MatchAnyLine, UD.Text, UD.Min, UD.Max);
  267. std::string Error;
  268. if (!D->isValid(Error)) {
  269. Diags.Report(UD.ContentBegin, diag::err_verify_invalid_content)
  270. << (UD.RegexKind ? "regex" : "string") << Error;
  271. }
  272. UD.DL->push_back(std::move(D));
  273. }
  274. } // anonymous
  275. // Tracker for markers in the input files. A marker is a comment of the form
  276. //
  277. // n = 123; // #123
  278. //
  279. // ... that can be referred to by a later expected-* directive:
  280. //
  281. // // expected-error@#123 {{undeclared identifier 'n'}}
  282. //
  283. // Marker declarations must be at the start of a comment or preceded by
  284. // whitespace to distinguish them from uses of markers in directives.
  285. class VerifyDiagnosticConsumer::MarkerTracker {
  286. DiagnosticsEngine &Diags;
  287. struct Marker {
  288. SourceLocation DefLoc;
  289. SourceLocation RedefLoc;
  290. SourceLocation UseLoc;
  291. };
  292. llvm::StringMap<Marker> Markers;
  293. // Directives that couldn't be created yet because they name an unknown
  294. // marker.
  295. llvm::StringMap<llvm::SmallVector<UnattachedDirective, 2>> DeferredDirectives;
  296. public:
  297. MarkerTracker(DiagnosticsEngine &Diags) : Diags(Diags) {}
  298. // Register a marker.
  299. void addMarker(StringRef MarkerName, SourceLocation Pos) {
  300. auto InsertResult = Markers.insert(
  301. {MarkerName, Marker{Pos, SourceLocation(), SourceLocation()}});
  302. Marker &M = InsertResult.first->second;
  303. if (!InsertResult.second) {
  304. // Marker was redefined.
  305. M.RedefLoc = Pos;
  306. } else {
  307. // First definition: build any deferred directives.
  308. auto Deferred = DeferredDirectives.find(MarkerName);
  309. if (Deferred != DeferredDirectives.end()) {
  310. for (auto &UD : Deferred->second) {
  311. if (M.UseLoc.isInvalid())
  312. M.UseLoc = UD.DirectivePos;
  313. attachDirective(Diags, UD, Pos);
  314. }
  315. DeferredDirectives.erase(Deferred);
  316. }
  317. }
  318. }
  319. // Register a directive at the specified marker.
  320. void addDirective(StringRef MarkerName, const UnattachedDirective &UD) {
  321. auto MarkerIt = Markers.find(MarkerName);
  322. if (MarkerIt != Markers.end()) {
  323. Marker &M = MarkerIt->second;
  324. if (M.UseLoc.isInvalid())
  325. M.UseLoc = UD.DirectivePos;
  326. return attachDirective(Diags, UD, M.DefLoc);
  327. }
  328. DeferredDirectives[MarkerName].push_back(UD);
  329. }
  330. // Ensure we have no remaining deferred directives, and no
  331. // multiply-defined-and-used markers.
  332. void finalize() {
  333. for (auto &MarkerInfo : Markers) {
  334. StringRef Name = MarkerInfo.first();
  335. Marker &M = MarkerInfo.second;
  336. if (M.RedefLoc.isValid() && M.UseLoc.isValid()) {
  337. Diags.Report(M.UseLoc, diag::err_verify_ambiguous_marker) << Name;
  338. Diags.Report(M.DefLoc, diag::note_verify_ambiguous_marker) << Name;
  339. Diags.Report(M.RedefLoc, diag::note_verify_ambiguous_marker) << Name;
  340. }
  341. }
  342. for (auto &DeferredPair : DeferredDirectives) {
  343. Diags.Report(DeferredPair.second.front().DirectivePos,
  344. diag::err_verify_no_such_marker)
  345. << DeferredPair.first();
  346. }
  347. }
  348. };
  349. /// ParseDirective - Go through the comment and see if it indicates expected
  350. /// diagnostics. If so, then put them in the appropriate directive list.
  351. ///
  352. /// Returns true if any valid directives were found.
  353. static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
  354. Preprocessor *PP, SourceLocation Pos,
  355. VerifyDiagnosticConsumer::DirectiveStatus &Status,
  356. VerifyDiagnosticConsumer::MarkerTracker &Markers) {
  357. DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics();
  358. // First, scan the comment looking for markers.
  359. for (ParseHelper PH(S); !PH.Done();) {
  360. if (!PH.Search("#", true))
  361. break;
  362. PH.C = PH.P;
  363. if (!PH.NextMarker()) {
  364. PH.Next("#");
  365. PH.Advance();
  366. continue;
  367. }
  368. PH.Advance();
  369. Markers.addMarker(PH.Match(), Pos);
  370. }
  371. // A single comment may contain multiple directives.
  372. bool FoundDirective = false;
  373. for (ParseHelper PH(S); !PH.Done();) {
  374. // Search for the initial directive token.
  375. // If one prefix, save time by searching only for its directives.
  376. // Otherwise, search for any potential directive token and check it later.
  377. const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes;
  378. if (!(Prefixes.size() == 1 ? PH.Search(*Prefixes.begin(), true, true)
  379. : PH.Search("", true, true)))
  380. break;
  381. StringRef DToken = PH.Match();
  382. PH.Advance();
  383. // Default directive kind.
  384. UnattachedDirective D;
  385. const char *KindStr = "string";
  386. // Parse the initial directive token in reverse so we can easily determine
  387. // its exact actual prefix. If we were to parse it from the front instead,
  388. // it would be harder to determine where the prefix ends because there
  389. // might be multiple matching -verify prefixes because some might prefix
  390. // others.
  391. // Regex in initial directive token: -re
  392. if (DToken.endswith("-re")) {
  393. D.RegexKind = true;
  394. KindStr = "regex";
  395. DToken = DToken.substr(0, DToken.size()-3);
  396. }
  397. // Type in initial directive token: -{error|warning|note|no-diagnostics}
  398. bool NoDiag = false;
  399. StringRef DType;
  400. if (DToken.endswith(DType="-error"))
  401. D.DL = ED ? &ED->Errors : nullptr;
  402. else if (DToken.endswith(DType="-warning"))
  403. D.DL = ED ? &ED->Warnings : nullptr;
  404. else if (DToken.endswith(DType="-remark"))
  405. D.DL = ED ? &ED->Remarks : nullptr;
  406. else if (DToken.endswith(DType="-note"))
  407. D.DL = ED ? &ED->Notes : nullptr;
  408. else if (DToken.endswith(DType="-no-diagnostics")) {
  409. NoDiag = true;
  410. if (D.RegexKind)
  411. continue;
  412. }
  413. else
  414. continue;
  415. DToken = DToken.substr(0, DToken.size()-DType.size());
  416. // What's left in DToken is the actual prefix. That might not be a -verify
  417. // prefix even if there is only one -verify prefix (for example, the full
  418. // DToken is foo-bar-warning, but foo is the only -verify prefix).
  419. if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
  420. continue;
  421. if (NoDiag) {
  422. if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
  423. Diags.Report(Pos, diag::err_verify_invalid_no_diags)
  424. << /*IsExpectedNoDiagnostics=*/true;
  425. else
  426. Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
  427. continue;
  428. }
  429. if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
  430. Diags.Report(Pos, diag::err_verify_invalid_no_diags)
  431. << /*IsExpectedNoDiagnostics=*/false;
  432. continue;
  433. }
  434. Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
  435. // If a directive has been found but we're not interested
  436. // in storing the directive information, return now.
  437. if (!D.DL)
  438. return true;
  439. // Next optional token: @
  440. SourceLocation ExpectedLoc;
  441. StringRef Marker;
  442. bool MatchAnyFileAndLine = false;
  443. bool MatchAnyLine = false;
  444. if (!PH.Next("@")) {
  445. ExpectedLoc = Pos;
  446. } else {
  447. PH.Advance();
  448. unsigned Line = 0;
  449. bool FoundPlus = PH.Next("+");
  450. if (FoundPlus || PH.Next("-")) {
  451. // Relative to current line.
  452. PH.Advance();
  453. bool Invalid = false;
  454. unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
  455. if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
  456. if (FoundPlus) ExpectedLine += Line;
  457. else ExpectedLine -= Line;
  458. ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
  459. }
  460. } else if (PH.Next(Line)) {
  461. // Absolute line number.
  462. if (Line > 0)
  463. ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
  464. } else if (PH.NextMarker()) {
  465. Marker = PH.Match();
  466. } else if (PP && PH.Search(":")) {
  467. // Specific source file.
  468. StringRef Filename(PH.C, PH.P-PH.C);
  469. PH.Advance();
  470. if (Filename == "*") {
  471. MatchAnyFileAndLine = true;
  472. if (!PH.Next("*")) {
  473. Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
  474. diag::err_verify_missing_line)
  475. << "'*'";
  476. continue;
  477. }
  478. MatchAnyLine = true;
  479. ExpectedLoc = SourceLocation();
  480. } else {
  481. // Lookup file via Preprocessor, like a #include.
  482. OptionalFileEntryRef File =
  483. PP->LookupFile(Pos, Filename, false, nullptr, nullptr, nullptr,
  484. nullptr, nullptr, nullptr, nullptr, nullptr);
  485. if (!File) {
  486. Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
  487. diag::err_verify_missing_file)
  488. << Filename << KindStr;
  489. continue;
  490. }
  491. FileID FID = SM.translateFile(*File);
  492. if (FID.isInvalid())
  493. FID = SM.createFileID(*File, Pos, SrcMgr::C_User);
  494. if (PH.Next(Line) && Line > 0)
  495. ExpectedLoc = SM.translateLineCol(FID, Line, 1);
  496. else if (PH.Next("*")) {
  497. MatchAnyLine = true;
  498. ExpectedLoc = SM.translateLineCol(FID, 1, 1);
  499. }
  500. }
  501. } else if (PH.Next("*")) {
  502. MatchAnyLine = true;
  503. ExpectedLoc = SourceLocation();
  504. }
  505. if (ExpectedLoc.isInvalid() && !MatchAnyLine && Marker.empty()) {
  506. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  507. diag::err_verify_missing_line) << KindStr;
  508. continue;
  509. }
  510. PH.Advance();
  511. }
  512. // Skip optional whitespace.
  513. PH.SkipWhitespace();
  514. // Next optional token: positive integer or a '+'.
  515. if (PH.Next(D.Min)) {
  516. PH.Advance();
  517. // A positive integer can be followed by a '+' meaning min
  518. // or more, or by a '-' meaning a range from min to max.
  519. if (PH.Next("+")) {
  520. D.Max = Directive::MaxCount;
  521. PH.Advance();
  522. } else if (PH.Next("-")) {
  523. PH.Advance();
  524. if (!PH.Next(D.Max) || D.Max < D.Min) {
  525. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  526. diag::err_verify_invalid_range) << KindStr;
  527. continue;
  528. }
  529. PH.Advance();
  530. } else {
  531. D.Max = D.Min;
  532. }
  533. } else if (PH.Next("+")) {
  534. // '+' on its own means "1 or more".
  535. D.Max = Directive::MaxCount;
  536. PH.Advance();
  537. }
  538. // Skip optional whitespace.
  539. PH.SkipWhitespace();
  540. // Next token: {{
  541. if (!PH.Next("{{")) {
  542. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  543. diag::err_verify_missing_start) << KindStr;
  544. continue;
  545. }
  546. PH.Advance();
  547. const char* const ContentBegin = PH.C; // mark content begin
  548. // Search for token: }}
  549. if (!PH.SearchClosingBrace("{{", "}}")) {
  550. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  551. diag::err_verify_missing_end) << KindStr;
  552. continue;
  553. }
  554. const char* const ContentEnd = PH.P; // mark content end
  555. PH.Advance();
  556. D.DirectivePos = Pos;
  557. D.ContentBegin = Pos.getLocWithOffset(ContentBegin - PH.Begin);
  558. // Build directive text; convert \n to newlines.
  559. StringRef NewlineStr = "\\n";
  560. StringRef Content(ContentBegin, ContentEnd-ContentBegin);
  561. size_t CPos = 0;
  562. size_t FPos;
  563. while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
  564. D.Text += Content.substr(CPos, FPos-CPos);
  565. D.Text += '\n';
  566. CPos = FPos + NewlineStr.size();
  567. }
  568. if (D.Text.empty())
  569. D.Text.assign(ContentBegin, ContentEnd);
  570. // Check that regex directives contain at least one regex.
  571. if (D.RegexKind && D.Text.find("{{") == StringRef::npos) {
  572. Diags.Report(D.ContentBegin, diag::err_verify_missing_regex) << D.Text;
  573. return false;
  574. }
  575. if (Marker.empty())
  576. attachDirective(Diags, D, ExpectedLoc, MatchAnyFileAndLine, MatchAnyLine);
  577. else
  578. Markers.addDirective(Marker, D);
  579. FoundDirective = true;
  580. }
  581. return FoundDirective;
  582. }
  583. VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &Diags_)
  584. : Diags(Diags_), PrimaryClient(Diags.getClient()),
  585. PrimaryClientOwner(Diags.takeClient()),
  586. Buffer(new TextDiagnosticBuffer()), Markers(new MarkerTracker(Diags)),
  587. Status(HasNoDirectives) {
  588. if (Diags.hasSourceManager())
  589. setSourceManager(Diags.getSourceManager());
  590. }
  591. VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
  592. assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
  593. assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
  594. SrcManager = nullptr;
  595. CheckDiagnostics();
  596. assert(!Diags.ownsClient() &&
  597. "The VerifyDiagnosticConsumer takes over ownership of the client!");
  598. }
  599. // DiagnosticConsumer interface.
  600. void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
  601. const Preprocessor *PP) {
  602. // Attach comment handler on first invocation.
  603. if (++ActiveSourceFiles == 1) {
  604. if (PP) {
  605. CurrentPreprocessor = PP;
  606. this->LangOpts = &LangOpts;
  607. setSourceManager(PP->getSourceManager());
  608. const_cast<Preprocessor *>(PP)->addCommentHandler(this);
  609. #ifndef NDEBUG
  610. // Debug build tracks parsed files.
  611. const_cast<Preprocessor *>(PP)->addPPCallbacks(
  612. std::make_unique<VerifyFileTracker>(*this, *SrcManager));
  613. #endif
  614. }
  615. }
  616. assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
  617. PrimaryClient->BeginSourceFile(LangOpts, PP);
  618. }
  619. void VerifyDiagnosticConsumer::EndSourceFile() {
  620. assert(ActiveSourceFiles && "No active source files!");
  621. PrimaryClient->EndSourceFile();
  622. // Detach comment handler once last active source file completed.
  623. if (--ActiveSourceFiles == 0) {
  624. if (CurrentPreprocessor)
  625. const_cast<Preprocessor *>(CurrentPreprocessor)->
  626. removeCommentHandler(this);
  627. // Diagnose any used-but-not-defined markers.
  628. Markers->finalize();
  629. // Check diagnostics once last file completed.
  630. CheckDiagnostics();
  631. CurrentPreprocessor = nullptr;
  632. LangOpts = nullptr;
  633. }
  634. }
  635. void VerifyDiagnosticConsumer::HandleDiagnostic(
  636. DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
  637. if (Info.hasSourceManager()) {
  638. // If this diagnostic is for a different source manager, ignore it.
  639. if (SrcManager && &Info.getSourceManager() != SrcManager)
  640. return;
  641. setSourceManager(Info.getSourceManager());
  642. }
  643. #ifndef NDEBUG
  644. // Debug build tracks unparsed files for possible
  645. // unparsed expected-* directives.
  646. if (SrcManager) {
  647. SourceLocation Loc = Info.getLocation();
  648. if (Loc.isValid()) {
  649. ParsedStatus PS = IsUnparsed;
  650. Loc = SrcManager->getExpansionLoc(Loc);
  651. FileID FID = SrcManager->getFileID(Loc);
  652. const FileEntry *FE = SrcManager->getFileEntryForID(FID);
  653. if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
  654. // If the file is a modules header file it shall not be parsed
  655. // for expected-* directives.
  656. HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
  657. if (HS.findModuleForHeader(FE))
  658. PS = IsUnparsedNoDirectives;
  659. }
  660. UpdateParsedFileStatus(*SrcManager, FID, PS);
  661. }
  662. }
  663. #endif
  664. // Send the diagnostic to the buffer, we will check it once we reach the end
  665. // of the source file (or are destructed).
  666. Buffer->HandleDiagnostic(DiagLevel, Info);
  667. }
  668. /// HandleComment - Hook into the preprocessor and extract comments containing
  669. /// expected errors and warnings.
  670. bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
  671. SourceRange Comment) {
  672. SourceManager &SM = PP.getSourceManager();
  673. // If this comment is for a different source manager, ignore it.
  674. if (SrcManager && &SM != SrcManager)
  675. return false;
  676. SourceLocation CommentBegin = Comment.getBegin();
  677. const char *CommentRaw = SM.getCharacterData(CommentBegin);
  678. StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
  679. if (C.empty())
  680. return false;
  681. // Fold any "\<EOL>" sequences
  682. size_t loc = C.find('\\');
  683. if (loc == StringRef::npos) {
  684. ParseDirective(C, &ED, SM, &PP, CommentBegin, Status, *Markers);
  685. return false;
  686. }
  687. std::string C2;
  688. C2.reserve(C.size());
  689. for (size_t last = 0;; loc = C.find('\\', last)) {
  690. if (loc == StringRef::npos || loc == C.size()) {
  691. C2 += C.substr(last);
  692. break;
  693. }
  694. C2 += C.substr(last, loc-last);
  695. last = loc + 1;
  696. if (C[last] == '\n' || C[last] == '\r') {
  697. ++last;
  698. // Escape \r\n or \n\r, but not \n\n.
  699. if (last < C.size())
  700. if (C[last] == '\n' || C[last] == '\r')
  701. if (C[last] != C[last-1])
  702. ++last;
  703. } else {
  704. // This was just a normal backslash.
  705. C2 += '\\';
  706. }
  707. }
  708. if (!C2.empty())
  709. ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status, *Markers);
  710. return false;
  711. }
  712. #ifndef NDEBUG
  713. /// Lex the specified source file to determine whether it contains
  714. /// any expected-* directives. As a Lexer is used rather than a full-blown
  715. /// Preprocessor, directives inside skipped #if blocks will still be found.
  716. ///
  717. /// \return true if any directives were found.
  718. static bool findDirectives(SourceManager &SM, FileID FID,
  719. const LangOptions &LangOpts) {
  720. // Create a raw lexer to pull all the comments out of FID.
  721. if (FID.isInvalid())
  722. return false;
  723. // Create a lexer to lex all the tokens of the main file in raw mode.
  724. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
  725. Lexer RawLex(FID, FromFile, SM, LangOpts);
  726. // Return comments as tokens, this is how we find expected diagnostics.
  727. RawLex.SetCommentRetentionState(true);
  728. Token Tok;
  729. Tok.setKind(tok::comment);
  730. VerifyDiagnosticConsumer::DirectiveStatus Status =
  731. VerifyDiagnosticConsumer::HasNoDirectives;
  732. while (Tok.isNot(tok::eof)) {
  733. RawLex.LexFromRawLexer(Tok);
  734. if (!Tok.is(tok::comment)) continue;
  735. std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
  736. if (Comment.empty()) continue;
  737. // We don't care about tracking markers for this phase.
  738. VerifyDiagnosticConsumer::MarkerTracker Markers(SM.getDiagnostics());
  739. // Find first directive.
  740. if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
  741. Status, Markers))
  742. return true;
  743. }
  744. return false;
  745. }
  746. #endif // !NDEBUG
  747. /// Takes a list of diagnostics that have been generated but not matched
  748. /// by an expected-* directive and produces a diagnostic to the user from this.
  749. static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
  750. const_diag_iterator diag_begin,
  751. const_diag_iterator diag_end,
  752. const char *Kind) {
  753. if (diag_begin == diag_end) return 0;
  754. SmallString<256> Fmt;
  755. llvm::raw_svector_ostream OS(Fmt);
  756. for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
  757. if (I->first.isInvalid() || !SourceMgr)
  758. OS << "\n (frontend)";
  759. else {
  760. OS << "\n ";
  761. if (const FileEntry *File = SourceMgr->getFileEntryForID(
  762. SourceMgr->getFileID(I->first)))
  763. OS << " File " << File->getName();
  764. OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
  765. }
  766. OS << ": " << I->second;
  767. }
  768. Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
  769. << Kind << /*Unexpected=*/true << OS.str();
  770. return std::distance(diag_begin, diag_end);
  771. }
  772. /// Takes a list of diagnostics that were expected to have been generated
  773. /// but were not and produces a diagnostic to the user from this.
  774. static unsigned PrintExpected(DiagnosticsEngine &Diags,
  775. SourceManager &SourceMgr,
  776. std::vector<Directive *> &DL, const char *Kind) {
  777. if (DL.empty())
  778. return 0;
  779. SmallString<256> Fmt;
  780. llvm::raw_svector_ostream OS(Fmt);
  781. for (const auto *D : DL) {
  782. if (D->DiagnosticLoc.isInvalid() || D->MatchAnyFileAndLine)
  783. OS << "\n File *";
  784. else
  785. OS << "\n File " << SourceMgr.getFilename(D->DiagnosticLoc);
  786. if (D->MatchAnyLine)
  787. OS << " Line *";
  788. else
  789. OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc);
  790. if (D->DirectiveLoc != D->DiagnosticLoc)
  791. OS << " (directive at "
  792. << SourceMgr.getFilename(D->DirectiveLoc) << ':'
  793. << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')';
  794. OS << ": " << D->Text;
  795. }
  796. Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
  797. << Kind << /*Unexpected=*/false << OS.str();
  798. return DL.size();
  799. }
  800. /// Determine whether two source locations come from the same file.
  801. static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
  802. SourceLocation DiagnosticLoc) {
  803. while (DiagnosticLoc.isMacroID())
  804. DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
  805. if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
  806. return true;
  807. const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
  808. if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc))
  809. return true;
  810. return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
  811. }
  812. /// CheckLists - Compare expected to seen diagnostic lists and return the
  813. /// the difference between them.
  814. static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  815. const char *Label,
  816. DirectiveList &Left,
  817. const_diag_iterator d2_begin,
  818. const_diag_iterator d2_end,
  819. bool IgnoreUnexpected) {
  820. std::vector<Directive *> LeftOnly;
  821. DiagList Right(d2_begin, d2_end);
  822. for (auto &Owner : Left) {
  823. Directive &D = *Owner;
  824. unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
  825. for (unsigned i = 0; i < D.Max; ++i) {
  826. DiagList::iterator II, IE;
  827. for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
  828. if (!D.MatchAnyLine) {
  829. unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
  830. if (LineNo1 != LineNo2)
  831. continue;
  832. }
  833. if (!D.DiagnosticLoc.isInvalid() && !D.MatchAnyFileAndLine &&
  834. !IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
  835. continue;
  836. const std::string &RightText = II->second;
  837. if (D.match(RightText))
  838. break;
  839. }
  840. if (II == IE) {
  841. // Not found.
  842. if (i >= D.Min) break;
  843. LeftOnly.push_back(&D);
  844. } else {
  845. // Found. The same cannot be found twice.
  846. Right.erase(II);
  847. }
  848. }
  849. }
  850. // Now all that's left in Right are those that were not matched.
  851. unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
  852. if (!IgnoreUnexpected)
  853. num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
  854. return num;
  855. }
  856. /// CheckResults - This compares the expected results to those that
  857. /// were actually reported. It emits any discrepencies. Return "true" if there
  858. /// were problems. Return "false" otherwise.
  859. static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  860. const TextDiagnosticBuffer &Buffer,
  861. ExpectedData &ED) {
  862. // We want to capture the delta between what was expected and what was
  863. // seen.
  864. //
  865. // Expected \ Seen - set expected but not seen
  866. // Seen \ Expected - set seen but not expected
  867. unsigned NumProblems = 0;
  868. const DiagnosticLevelMask DiagMask =
  869. Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
  870. // See if there are error mismatches.
  871. NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
  872. Buffer.err_begin(), Buffer.err_end(),
  873. bool(DiagnosticLevelMask::Error & DiagMask));
  874. // See if there are warning mismatches.
  875. NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
  876. Buffer.warn_begin(), Buffer.warn_end(),
  877. bool(DiagnosticLevelMask::Warning & DiagMask));
  878. // See if there are remark mismatches.
  879. NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
  880. Buffer.remark_begin(), Buffer.remark_end(),
  881. bool(DiagnosticLevelMask::Remark & DiagMask));
  882. // See if there are note mismatches.
  883. NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
  884. Buffer.note_begin(), Buffer.note_end(),
  885. bool(DiagnosticLevelMask::Note & DiagMask));
  886. return NumProblems;
  887. }
  888. void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
  889. FileID FID,
  890. ParsedStatus PS) {
  891. // Check SourceManager hasn't changed.
  892. setSourceManager(SM);
  893. #ifndef NDEBUG
  894. if (FID.isInvalid())
  895. return;
  896. const FileEntry *FE = SM.getFileEntryForID(FID);
  897. if (PS == IsParsed) {
  898. // Move the FileID from the unparsed set to the parsed set.
  899. UnparsedFiles.erase(FID);
  900. ParsedFiles.insert(std::make_pair(FID, FE));
  901. } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
  902. // Add the FileID to the unparsed set if we haven't seen it before.
  903. // Check for directives.
  904. bool FoundDirectives;
  905. if (PS == IsUnparsedNoDirectives)
  906. FoundDirectives = false;
  907. else
  908. FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
  909. // Add the FileID to the unparsed set.
  910. UnparsedFiles.insert(std::make_pair(FID,
  911. UnparsedFileStatus(FE, FoundDirectives)));
  912. }
  913. #endif
  914. }
  915. void VerifyDiagnosticConsumer::CheckDiagnostics() {
  916. // Ensure any diagnostics go to the primary client.
  917. DiagnosticConsumer *CurClient = Diags.getClient();
  918. std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient();
  919. Diags.setClient(PrimaryClient, false);
  920. #ifndef NDEBUG
  921. // In a debug build, scan through any files that may have been missed
  922. // during parsing and issue a fatal error if directives are contained
  923. // within these files. If a fatal error occurs, this suggests that
  924. // this file is being parsed separately from the main file, in which
  925. // case consider moving the directives to the correct place, if this
  926. // is applicable.
  927. if (!UnparsedFiles.empty()) {
  928. // Generate a cache of parsed FileEntry pointers for alias lookups.
  929. llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
  930. for (const auto &I : ParsedFiles)
  931. if (const FileEntry *FE = I.second)
  932. ParsedFileCache.insert(FE);
  933. // Iterate through list of unparsed files.
  934. for (const auto &I : UnparsedFiles) {
  935. const UnparsedFileStatus &Status = I.second;
  936. const FileEntry *FE = Status.getFile();
  937. // Skip files that have been parsed via an alias.
  938. if (FE && ParsedFileCache.count(FE))
  939. continue;
  940. // Report a fatal error if this file contained directives.
  941. if (Status.foundDirectives()) {
  942. llvm::report_fatal_error(Twine("-verify directives found after rather"
  943. " than during normal parsing of ",
  944. StringRef(FE ? FE->getName() : "(unknown)")));
  945. }
  946. }
  947. // UnparsedFiles has been processed now, so clear it.
  948. UnparsedFiles.clear();
  949. }
  950. #endif // !NDEBUG
  951. if (SrcManager) {
  952. // Produce an error if no expected-* directives could be found in the
  953. // source file(s) processed.
  954. if (Status == HasNoDirectives) {
  955. Diags.Report(diag::err_verify_no_directives).setForceEmit();
  956. ++NumErrors;
  957. Status = HasNoDirectivesReported;
  958. }
  959. // Check that the expected diagnostics occurred.
  960. NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
  961. } else {
  962. const DiagnosticLevelMask DiagMask =
  963. ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
  964. if (bool(DiagnosticLevelMask::Error & DiagMask))
  965. NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
  966. Buffer->err_end(), "error");
  967. if (bool(DiagnosticLevelMask::Warning & DiagMask))
  968. NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
  969. Buffer->warn_end(), "warn");
  970. if (bool(DiagnosticLevelMask::Remark & DiagMask))
  971. NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(),
  972. Buffer->remark_end(), "remark");
  973. if (bool(DiagnosticLevelMask::Note & DiagMask))
  974. NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
  975. Buffer->note_end(), "note");
  976. }
  977. Diags.setClient(CurClient, Owner.release() != nullptr);
  978. // Reset the buffer, we have processed all the diagnostics in it.
  979. Buffer.reset(new TextDiagnosticBuffer());
  980. ED.Reset();
  981. }
  982. std::unique_ptr<Directive> Directive::create(bool RegexKind,
  983. SourceLocation DirectiveLoc,
  984. SourceLocation DiagnosticLoc,
  985. bool MatchAnyFileAndLine,
  986. bool MatchAnyLine, StringRef Text,
  987. unsigned Min, unsigned Max) {
  988. if (!RegexKind)
  989. return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
  990. MatchAnyFileAndLine,
  991. MatchAnyLine, Text, Min, Max);
  992. // Parse the directive into a regular expression.
  993. std::string RegexStr;
  994. StringRef S = Text;
  995. while (!S.empty()) {
  996. if (S.startswith("{{")) {
  997. S = S.drop_front(2);
  998. size_t RegexMatchLength = S.find("}}");
  999. assert(RegexMatchLength != StringRef::npos);
  1000. // Append the regex, enclosed in parentheses.
  1001. RegexStr += "(";
  1002. RegexStr.append(S.data(), RegexMatchLength);
  1003. RegexStr += ")";
  1004. S = S.drop_front(RegexMatchLength + 2);
  1005. } else {
  1006. size_t VerbatimMatchLength = S.find("{{");
  1007. if (VerbatimMatchLength == StringRef::npos)
  1008. VerbatimMatchLength = S.size();
  1009. // Escape and append the fixed string.
  1010. RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
  1011. S = S.drop_front(VerbatimMatchLength);
  1012. }
  1013. }
  1014. return std::make_unique<RegexDirective>(DirectiveLoc, DiagnosticLoc,
  1015. MatchAnyFileAndLine, MatchAnyLine,
  1016. Text, Min, Max, RegexStr);
  1017. }