VerifyDiagnosticConsumer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. //===---- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is a concrete diagnostic client, which buffers the diagnostic messages.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/TextDiagnosticBuffer.h"
  18. #include "clang/Lex/HeaderSearch.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/Support/Regex.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. typedef VerifyDiagnosticConsumer::Directive Directive;
  25. typedef VerifyDiagnosticConsumer::DirectiveList DirectiveList;
  26. typedef VerifyDiagnosticConsumer::ExpectedData ExpectedData;
  27. VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
  28. : Diags(_Diags),
  29. PrimaryClient(Diags.getClient()), OwnsPrimaryClient(Diags.ownsClient()),
  30. Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(nullptr),
  31. LangOpts(nullptr), SrcManager(nullptr), ActiveSourceFiles(0),
  32. Status(HasNoDirectives)
  33. {
  34. Diags.takeClient();
  35. if (Diags.hasSourceManager())
  36. setSourceManager(Diags.getSourceManager());
  37. }
  38. VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
  39. assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
  40. assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
  41. SrcManager = nullptr;
  42. CheckDiagnostics();
  43. Diags.takeClient();
  44. if (OwnsPrimaryClient)
  45. delete PrimaryClient;
  46. }
  47. #ifndef NDEBUG
  48. namespace {
  49. class VerifyFileTracker : public PPCallbacks {
  50. VerifyDiagnosticConsumer &Verify;
  51. SourceManager &SM;
  52. public:
  53. VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
  54. : Verify(Verify), SM(SM) { }
  55. /// \brief Hook into the preprocessor and update the list of parsed
  56. /// files when the preprocessor indicates a new file is entered.
  57. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  58. SrcMgr::CharacteristicKind FileType,
  59. FileID PrevFID) {
  60. Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
  61. VerifyDiagnosticConsumer::IsParsed);
  62. }
  63. };
  64. } // End anonymous namespace.
  65. #endif
  66. // DiagnosticConsumer interface.
  67. void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
  68. const Preprocessor *PP) {
  69. // Attach comment handler on first invocation.
  70. if (++ActiveSourceFiles == 1) {
  71. if (PP) {
  72. CurrentPreprocessor = PP;
  73. this->LangOpts = &LangOpts;
  74. setSourceManager(PP->getSourceManager());
  75. const_cast<Preprocessor*>(PP)->addCommentHandler(this);
  76. #ifndef NDEBUG
  77. // Debug build tracks parsed files.
  78. VerifyFileTracker *V = new VerifyFileTracker(*this, *SrcManager);
  79. const_cast<Preprocessor*>(PP)->addPPCallbacks(V);
  80. #endif
  81. }
  82. }
  83. assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
  84. PrimaryClient->BeginSourceFile(LangOpts, PP);
  85. }
  86. void VerifyDiagnosticConsumer::EndSourceFile() {
  87. assert(ActiveSourceFiles && "No active source files!");
  88. PrimaryClient->EndSourceFile();
  89. // Detach comment handler once last active source file completed.
  90. if (--ActiveSourceFiles == 0) {
  91. if (CurrentPreprocessor)
  92. const_cast<Preprocessor*>(CurrentPreprocessor)->removeCommentHandler(this);
  93. // Check diagnostics once last file completed.
  94. CheckDiagnostics();
  95. CurrentPreprocessor = nullptr;
  96. LangOpts = nullptr;
  97. }
  98. }
  99. void VerifyDiagnosticConsumer::HandleDiagnostic(
  100. DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
  101. if (Info.hasSourceManager()) {
  102. // If this diagnostic is for a different source manager, ignore it.
  103. if (SrcManager && &Info.getSourceManager() != SrcManager)
  104. return;
  105. setSourceManager(Info.getSourceManager());
  106. }
  107. #ifndef NDEBUG
  108. // Debug build tracks unparsed files for possible
  109. // unparsed expected-* directives.
  110. if (SrcManager) {
  111. SourceLocation Loc = Info.getLocation();
  112. if (Loc.isValid()) {
  113. ParsedStatus PS = IsUnparsed;
  114. Loc = SrcManager->getExpansionLoc(Loc);
  115. FileID FID = SrcManager->getFileID(Loc);
  116. const FileEntry *FE = SrcManager->getFileEntryForID(FID);
  117. if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
  118. // If the file is a modules header file it shall not be parsed
  119. // for expected-* directives.
  120. HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
  121. if (HS.findModuleForHeader(FE))
  122. PS = IsUnparsedNoDirectives;
  123. }
  124. UpdateParsedFileStatus(*SrcManager, FID, PS);
  125. }
  126. }
  127. #endif
  128. // Send the diagnostic to the buffer, we will check it once we reach the end
  129. // of the source file (or are destructed).
  130. Buffer->HandleDiagnostic(DiagLevel, Info);
  131. }
  132. //===----------------------------------------------------------------------===//
  133. // Checking diagnostics implementation.
  134. //===----------------------------------------------------------------------===//
  135. typedef TextDiagnosticBuffer::DiagList DiagList;
  136. typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
  137. namespace {
  138. /// StandardDirective - Directive with string matching.
  139. ///
  140. class StandardDirective : public Directive {
  141. public:
  142. StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
  143. bool MatchAnyLine, StringRef Text, unsigned Min,
  144. unsigned Max)
  145. : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max) { }
  146. bool isValid(std::string &Error) override {
  147. // all strings are considered valid; even empty ones
  148. return true;
  149. }
  150. bool match(StringRef S) override {
  151. return S.find(Text) != StringRef::npos;
  152. }
  153. };
  154. /// RegexDirective - Directive with regular-expression matching.
  155. ///
  156. class RegexDirective : public Directive {
  157. public:
  158. RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
  159. bool MatchAnyLine, StringRef Text, unsigned Min, unsigned Max,
  160. StringRef RegexStr)
  161. : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text, Min, Max),
  162. Regex(RegexStr) { }
  163. bool isValid(std::string &Error) override {
  164. if (Regex.isValid(Error))
  165. return true;
  166. return false;
  167. }
  168. bool match(StringRef S) override {
  169. return Regex.match(S);
  170. }
  171. private:
  172. llvm::Regex Regex;
  173. };
  174. class ParseHelper
  175. {
  176. public:
  177. ParseHelper(StringRef S)
  178. : Begin(S.begin()), End(S.end()), C(Begin), P(Begin), PEnd(nullptr) {}
  179. // Return true if string literal is next.
  180. bool Next(StringRef S) {
  181. P = C;
  182. PEnd = C + S.size();
  183. if (PEnd > End)
  184. return false;
  185. return !memcmp(P, S.data(), S.size());
  186. }
  187. // Return true if number is next.
  188. // Output N only if number is next.
  189. bool Next(unsigned &N) {
  190. unsigned TMP = 0;
  191. P = C;
  192. for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
  193. TMP *= 10;
  194. TMP += P[0] - '0';
  195. }
  196. if (P == C)
  197. return false;
  198. PEnd = P;
  199. N = TMP;
  200. return true;
  201. }
  202. // Return true if string literal is found.
  203. // When true, P marks begin-position of S in content.
  204. bool Search(StringRef S, bool EnsureStartOfWord = false) {
  205. do {
  206. P = std::search(C, End, S.begin(), S.end());
  207. PEnd = P + S.size();
  208. if (P == End)
  209. break;
  210. if (!EnsureStartOfWord
  211. // Check if string literal starts a new word.
  212. || P == Begin || isWhitespace(P[-1])
  213. // Or it could be preceded by the start of a comment.
  214. || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
  215. && P[-2] == '/'))
  216. return true;
  217. // Otherwise, skip and search again.
  218. } while (Advance());
  219. return false;
  220. }
  221. // Return true if a CloseBrace that closes the OpenBrace at the current nest
  222. // level is found. When true, P marks begin-position of CloseBrace.
  223. bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
  224. unsigned Depth = 1;
  225. P = C;
  226. while (P < End) {
  227. StringRef S(P, End - P);
  228. if (S.startswith(OpenBrace)) {
  229. ++Depth;
  230. P += OpenBrace.size();
  231. } else if (S.startswith(CloseBrace)) {
  232. --Depth;
  233. if (Depth == 0) {
  234. PEnd = P + CloseBrace.size();
  235. return true;
  236. }
  237. P += CloseBrace.size();
  238. } else {
  239. ++P;
  240. }
  241. }
  242. return false;
  243. }
  244. // Advance 1-past previous next/search.
  245. // Behavior is undefined if previous next/search failed.
  246. bool Advance() {
  247. C = PEnd;
  248. return C < End;
  249. }
  250. // Skip zero or more whitespace.
  251. void SkipWhitespace() {
  252. for (; C < End && isWhitespace(*C); ++C)
  253. ;
  254. }
  255. // Return true if EOF reached.
  256. bool Done() {
  257. return !(C < End);
  258. }
  259. const char * const Begin; // beginning of expected content
  260. const char * const End; // end of expected content (1-past)
  261. const char *C; // position of next char in content
  262. const char *P;
  263. private:
  264. const char *PEnd; // previous next/search subject end (1-past)
  265. };
  266. } // namespace anonymous
  267. /// ParseDirective - Go through the comment and see if it indicates expected
  268. /// diagnostics. If so, then put them in the appropriate directive list.
  269. ///
  270. /// Returns true if any valid directives were found.
  271. static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
  272. Preprocessor *PP, SourceLocation Pos,
  273. VerifyDiagnosticConsumer::DirectiveStatus &Status) {
  274. DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics();
  275. // A single comment may contain multiple directives.
  276. bool FoundDirective = false;
  277. for (ParseHelper PH(S); !PH.Done();) {
  278. // Search for token: expected
  279. if (!PH.Search("expected", true))
  280. break;
  281. PH.Advance();
  282. // Next token: -
  283. if (!PH.Next("-"))
  284. continue;
  285. PH.Advance();
  286. // Next token: { error | warning | note }
  287. DirectiveList *DL = nullptr;
  288. if (PH.Next("error"))
  289. DL = ED ? &ED->Errors : nullptr;
  290. else if (PH.Next("warning"))
  291. DL = ED ? &ED->Warnings : nullptr;
  292. else if (PH.Next("remark"))
  293. DL = ED ? &ED->Remarks : nullptr;
  294. else if (PH.Next("note"))
  295. DL = ED ? &ED->Notes : nullptr;
  296. else if (PH.Next("no-diagnostics")) {
  297. if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
  298. Diags.Report(Pos, diag::err_verify_invalid_no_diags)
  299. << /*IsExpectedNoDiagnostics=*/true;
  300. else
  301. Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
  302. continue;
  303. } else
  304. continue;
  305. PH.Advance();
  306. if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
  307. Diags.Report(Pos, diag::err_verify_invalid_no_diags)
  308. << /*IsExpectedNoDiagnostics=*/false;
  309. continue;
  310. }
  311. Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
  312. // If a directive has been found but we're not interested
  313. // in storing the directive information, return now.
  314. if (!DL)
  315. return true;
  316. // Default directive kind.
  317. bool RegexKind = false;
  318. const char* KindStr = "string";
  319. // Next optional token: -
  320. if (PH.Next("-re")) {
  321. PH.Advance();
  322. RegexKind = true;
  323. KindStr = "regex";
  324. }
  325. // Next optional token: @
  326. SourceLocation ExpectedLoc;
  327. bool MatchAnyLine = false;
  328. if (!PH.Next("@")) {
  329. ExpectedLoc = Pos;
  330. } else {
  331. PH.Advance();
  332. unsigned Line = 0;
  333. bool FoundPlus = PH.Next("+");
  334. if (FoundPlus || PH.Next("-")) {
  335. // Relative to current line.
  336. PH.Advance();
  337. bool Invalid = false;
  338. unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
  339. if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
  340. if (FoundPlus) ExpectedLine += Line;
  341. else ExpectedLine -= Line;
  342. ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
  343. }
  344. } else if (PH.Next(Line)) {
  345. // Absolute line number.
  346. if (Line > 0)
  347. ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
  348. } else if (PP && PH.Search(":")) {
  349. // Specific source file.
  350. StringRef Filename(PH.C, PH.P-PH.C);
  351. PH.Advance();
  352. // Lookup file via Preprocessor, like a #include.
  353. const DirectoryLookup *CurDir;
  354. const FileEntry *FE = PP->LookupFile(Pos, Filename, false, nullptr,
  355. CurDir, nullptr, nullptr, nullptr);
  356. if (!FE) {
  357. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  358. diag::err_verify_missing_file) << Filename << KindStr;
  359. continue;
  360. }
  361. if (SM.translateFile(FE).isInvalid())
  362. SM.createFileID(FE, Pos, SrcMgr::C_User);
  363. if (PH.Next(Line) && Line > 0)
  364. ExpectedLoc = SM.translateFileLineCol(FE, Line, 1);
  365. else if (PH.Next("*")) {
  366. MatchAnyLine = true;
  367. ExpectedLoc = SM.translateFileLineCol(FE, 1, 1);
  368. }
  369. }
  370. if (ExpectedLoc.isInvalid()) {
  371. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  372. diag::err_verify_missing_line) << KindStr;
  373. continue;
  374. }
  375. PH.Advance();
  376. }
  377. // Skip optional whitespace.
  378. PH.SkipWhitespace();
  379. // Next optional token: positive integer or a '+'.
  380. unsigned Min = 1;
  381. unsigned Max = 1;
  382. if (PH.Next(Min)) {
  383. PH.Advance();
  384. // A positive integer can be followed by a '+' meaning min
  385. // or more, or by a '-' meaning a range from min to max.
  386. if (PH.Next("+")) {
  387. Max = Directive::MaxCount;
  388. PH.Advance();
  389. } else if (PH.Next("-")) {
  390. PH.Advance();
  391. if (!PH.Next(Max) || Max < Min) {
  392. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  393. diag::err_verify_invalid_range) << KindStr;
  394. continue;
  395. }
  396. PH.Advance();
  397. } else {
  398. Max = Min;
  399. }
  400. } else if (PH.Next("+")) {
  401. // '+' on its own means "1 or more".
  402. Max = Directive::MaxCount;
  403. PH.Advance();
  404. }
  405. // Skip optional whitespace.
  406. PH.SkipWhitespace();
  407. // Next token: {{
  408. if (!PH.Next("{{")) {
  409. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  410. diag::err_verify_missing_start) << KindStr;
  411. continue;
  412. }
  413. PH.Advance();
  414. const char* const ContentBegin = PH.C; // mark content begin
  415. // Search for token: }}
  416. if (!PH.SearchClosingBrace("{{", "}}")) {
  417. Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
  418. diag::err_verify_missing_end) << KindStr;
  419. continue;
  420. }
  421. const char* const ContentEnd = PH.P; // mark content end
  422. PH.Advance();
  423. // Build directive text; convert \n to newlines.
  424. std::string Text;
  425. StringRef NewlineStr = "\\n";
  426. StringRef Content(ContentBegin, ContentEnd-ContentBegin);
  427. size_t CPos = 0;
  428. size_t FPos;
  429. while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
  430. Text += Content.substr(CPos, FPos-CPos);
  431. Text += '\n';
  432. CPos = FPos + NewlineStr.size();
  433. }
  434. if (Text.empty())
  435. Text.assign(ContentBegin, ContentEnd);
  436. // Check that regex directives contain at least one regex.
  437. if (RegexKind && Text.find("{{") == StringRef::npos) {
  438. Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
  439. diag::err_verify_missing_regex) << Text;
  440. return false;
  441. }
  442. // Construct new directive.
  443. std::unique_ptr<Directive> D(
  444. Directive::create(RegexKind, Pos, ExpectedLoc, MatchAnyLine, Text,
  445. Min, Max));
  446. std::string Error;
  447. if (D->isValid(Error)) {
  448. DL->push_back(D.release());
  449. FoundDirective = true;
  450. } else {
  451. Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
  452. diag::err_verify_invalid_content)
  453. << KindStr << Error;
  454. }
  455. }
  456. return FoundDirective;
  457. }
  458. /// HandleComment - Hook into the preprocessor and extract comments containing
  459. /// expected errors and warnings.
  460. bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
  461. SourceRange Comment) {
  462. SourceManager &SM = PP.getSourceManager();
  463. // If this comment is for a different source manager, ignore it.
  464. if (SrcManager && &SM != SrcManager)
  465. return false;
  466. SourceLocation CommentBegin = Comment.getBegin();
  467. const char *CommentRaw = SM.getCharacterData(CommentBegin);
  468. StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
  469. if (C.empty())
  470. return false;
  471. // Fold any "\<EOL>" sequences
  472. size_t loc = C.find('\\');
  473. if (loc == StringRef::npos) {
  474. ParseDirective(C, &ED, SM, &PP, CommentBegin, Status);
  475. return false;
  476. }
  477. std::string C2;
  478. C2.reserve(C.size());
  479. for (size_t last = 0;; loc = C.find('\\', last)) {
  480. if (loc == StringRef::npos || loc == C.size()) {
  481. C2 += C.substr(last);
  482. break;
  483. }
  484. C2 += C.substr(last, loc-last);
  485. last = loc + 1;
  486. if (C[last] == '\n' || C[last] == '\r') {
  487. ++last;
  488. // Escape \r\n or \n\r, but not \n\n.
  489. if (last < C.size())
  490. if (C[last] == '\n' || C[last] == '\r')
  491. if (C[last] != C[last-1])
  492. ++last;
  493. } else {
  494. // This was just a normal backslash.
  495. C2 += '\\';
  496. }
  497. }
  498. if (!C2.empty())
  499. ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status);
  500. return false;
  501. }
  502. #ifndef NDEBUG
  503. /// \brief Lex the specified source file to determine whether it contains
  504. /// any expected-* directives. As a Lexer is used rather than a full-blown
  505. /// Preprocessor, directives inside skipped #if blocks will still be found.
  506. ///
  507. /// \return true if any directives were found.
  508. static bool findDirectives(SourceManager &SM, FileID FID,
  509. const LangOptions &LangOpts) {
  510. // Create a raw lexer to pull all the comments out of FID.
  511. if (FID.isInvalid())
  512. return false;
  513. // Create a lexer to lex all the tokens of the main file in raw mode.
  514. const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
  515. Lexer RawLex(FID, FromFile, SM, LangOpts);
  516. // Return comments as tokens, this is how we find expected diagnostics.
  517. RawLex.SetCommentRetentionState(true);
  518. Token Tok;
  519. Tok.setKind(tok::comment);
  520. VerifyDiagnosticConsumer::DirectiveStatus Status =
  521. VerifyDiagnosticConsumer::HasNoDirectives;
  522. while (Tok.isNot(tok::eof)) {
  523. RawLex.LexFromRawLexer(Tok);
  524. if (!Tok.is(tok::comment)) continue;
  525. std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
  526. if (Comment.empty()) continue;
  527. // Find first directive.
  528. if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
  529. Status))
  530. return true;
  531. }
  532. return false;
  533. }
  534. #endif // !NDEBUG
  535. /// \brief Takes a list of diagnostics that have been generated but not matched
  536. /// by an expected-* directive and produces a diagnostic to the user from this.
  537. static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
  538. const_diag_iterator diag_begin,
  539. const_diag_iterator diag_end,
  540. const char *Kind) {
  541. if (diag_begin == diag_end) return 0;
  542. SmallString<256> Fmt;
  543. llvm::raw_svector_ostream OS(Fmt);
  544. for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
  545. if (I->first.isInvalid() || !SourceMgr)
  546. OS << "\n (frontend)";
  547. else {
  548. OS << "\n ";
  549. if (const FileEntry *File = SourceMgr->getFileEntryForID(
  550. SourceMgr->getFileID(I->first)))
  551. OS << " File " << File->getName();
  552. OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
  553. }
  554. OS << ": " << I->second;
  555. }
  556. Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
  557. << Kind << /*Unexpected=*/true << OS.str();
  558. return std::distance(diag_begin, diag_end);
  559. }
  560. /// \brief Takes a list of diagnostics that were expected to have been generated
  561. /// but were not and produces a diagnostic to the user from this.
  562. static unsigned PrintExpected(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  563. DirectiveList &DL, const char *Kind) {
  564. if (DL.empty())
  565. return 0;
  566. SmallString<256> Fmt;
  567. llvm::raw_svector_ostream OS(Fmt);
  568. for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
  569. Directive &D = **I;
  570. OS << "\n File " << SourceMgr.getFilename(D.DiagnosticLoc);
  571. if (D.MatchAnyLine)
  572. OS << " Line *";
  573. else
  574. OS << " Line " << SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
  575. if (D.DirectiveLoc != D.DiagnosticLoc)
  576. OS << " (directive at "
  577. << SourceMgr.getFilename(D.DirectiveLoc) << ':'
  578. << SourceMgr.getPresumedLineNumber(D.DirectiveLoc) << ')';
  579. OS << ": " << D.Text;
  580. }
  581. Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
  582. << Kind << /*Unexpected=*/false << OS.str();
  583. return DL.size();
  584. }
  585. /// \brief Determine whether two source locations come from the same file.
  586. static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
  587. SourceLocation DiagnosticLoc) {
  588. while (DiagnosticLoc.isMacroID())
  589. DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
  590. if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
  591. return true;
  592. const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
  593. if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc))
  594. return true;
  595. return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
  596. }
  597. /// CheckLists - Compare expected to seen diagnostic lists and return the
  598. /// the difference between them.
  599. ///
  600. static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  601. const char *Label,
  602. DirectiveList &Left,
  603. const_diag_iterator d2_begin,
  604. const_diag_iterator d2_end) {
  605. DirectiveList LeftOnly;
  606. DiagList Right(d2_begin, d2_end);
  607. for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
  608. Directive& D = **I;
  609. unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
  610. for (unsigned i = 0; i < D.Max; ++i) {
  611. DiagList::iterator II, IE;
  612. for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
  613. if (!D.MatchAnyLine) {
  614. unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
  615. if (LineNo1 != LineNo2)
  616. continue;
  617. }
  618. if (!IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
  619. continue;
  620. const std::string &RightText = II->second;
  621. if (D.match(RightText))
  622. break;
  623. }
  624. if (II == IE) {
  625. // Not found.
  626. if (i >= D.Min) break;
  627. LeftOnly.push_back(*I);
  628. } else {
  629. // Found. The same cannot be found twice.
  630. Right.erase(II);
  631. }
  632. }
  633. }
  634. // Now all that's left in Right are those that were not matched.
  635. unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
  636. num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
  637. return num;
  638. }
  639. /// CheckResults - This compares the expected results to those that
  640. /// were actually reported. It emits any discrepencies. Return "true" if there
  641. /// were problems. Return "false" otherwise.
  642. ///
  643. static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  644. const TextDiagnosticBuffer &Buffer,
  645. ExpectedData &ED) {
  646. // We want to capture the delta between what was expected and what was
  647. // seen.
  648. //
  649. // Expected \ Seen - set expected but not seen
  650. // Seen \ Expected - set seen but not expected
  651. unsigned NumProblems = 0;
  652. // See if there are error mismatches.
  653. NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
  654. Buffer.err_begin(), Buffer.err_end());
  655. // See if there are warning mismatches.
  656. NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
  657. Buffer.warn_begin(), Buffer.warn_end());
  658. // See if there are remark mismatches.
  659. NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
  660. Buffer.remark_begin(), Buffer.remark_end());
  661. // See if there are note mismatches.
  662. NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
  663. Buffer.note_begin(), Buffer.note_end());
  664. return NumProblems;
  665. }
  666. void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
  667. FileID FID,
  668. ParsedStatus PS) {
  669. // Check SourceManager hasn't changed.
  670. setSourceManager(SM);
  671. #ifndef NDEBUG
  672. if (FID.isInvalid())
  673. return;
  674. const FileEntry *FE = SM.getFileEntryForID(FID);
  675. if (PS == IsParsed) {
  676. // Move the FileID from the unparsed set to the parsed set.
  677. UnparsedFiles.erase(FID);
  678. ParsedFiles.insert(std::make_pair(FID, FE));
  679. } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
  680. // Add the FileID to the unparsed set if we haven't seen it before.
  681. // Check for directives.
  682. bool FoundDirectives;
  683. if (PS == IsUnparsedNoDirectives)
  684. FoundDirectives = false;
  685. else
  686. FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
  687. // Add the FileID to the unparsed set.
  688. UnparsedFiles.insert(std::make_pair(FID,
  689. UnparsedFileStatus(FE, FoundDirectives)));
  690. }
  691. #endif
  692. }
  693. void VerifyDiagnosticConsumer::CheckDiagnostics() {
  694. // Ensure any diagnostics go to the primary client.
  695. bool OwnsCurClient = Diags.ownsClient();
  696. DiagnosticConsumer *CurClient = Diags.takeClient();
  697. Diags.setClient(PrimaryClient, false);
  698. #ifndef NDEBUG
  699. // In a debug build, scan through any files that may have been missed
  700. // during parsing and issue a fatal error if directives are contained
  701. // within these files. If a fatal error occurs, this suggests that
  702. // this file is being parsed separately from the main file, in which
  703. // case consider moving the directives to the correct place, if this
  704. // is applicable.
  705. if (UnparsedFiles.size() > 0) {
  706. // Generate a cache of parsed FileEntry pointers for alias lookups.
  707. llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
  708. for (ParsedFilesMap::iterator I = ParsedFiles.begin(),
  709. End = ParsedFiles.end(); I != End; ++I) {
  710. if (const FileEntry *FE = I->second)
  711. ParsedFileCache.insert(FE);
  712. }
  713. // Iterate through list of unparsed files.
  714. for (UnparsedFilesMap::iterator I = UnparsedFiles.begin(),
  715. End = UnparsedFiles.end(); I != End; ++I) {
  716. const UnparsedFileStatus &Status = I->second;
  717. const FileEntry *FE = Status.getFile();
  718. // Skip files that have been parsed via an alias.
  719. if (FE && ParsedFileCache.count(FE))
  720. continue;
  721. // Report a fatal error if this file contained directives.
  722. if (Status.foundDirectives()) {
  723. llvm::report_fatal_error(Twine("-verify directives found after rather"
  724. " than during normal parsing of ",
  725. StringRef(FE ? FE->getName() : "(unknown)")));
  726. }
  727. }
  728. // UnparsedFiles has been processed now, so clear it.
  729. UnparsedFiles.clear();
  730. }
  731. #endif // !NDEBUG
  732. if (SrcManager) {
  733. // Produce an error if no expected-* directives could be found in the
  734. // source file(s) processed.
  735. if (Status == HasNoDirectives) {
  736. Diags.Report(diag::err_verify_no_directives).setForceEmit();
  737. ++NumErrors;
  738. Status = HasNoDirectivesReported;
  739. }
  740. // Check that the expected diagnostics occurred.
  741. NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
  742. } else {
  743. NumErrors += (PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
  744. Buffer->err_end(), "error") +
  745. PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
  746. Buffer->warn_end(), "warn") +
  747. PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
  748. Buffer->note_end(), "note"));
  749. }
  750. Diags.takeClient();
  751. Diags.setClient(CurClient, OwnsCurClient);
  752. // Reset the buffer, we have processed all the diagnostics in it.
  753. Buffer.reset(new TextDiagnosticBuffer());
  754. ED.Reset();
  755. }
  756. Directive *Directive::create(bool RegexKind, SourceLocation DirectiveLoc,
  757. SourceLocation DiagnosticLoc, bool MatchAnyLine,
  758. StringRef Text, unsigned Min, unsigned Max) {
  759. if (!RegexKind)
  760. return new StandardDirective(DirectiveLoc, DiagnosticLoc, MatchAnyLine,
  761. Text, Min, Max);
  762. // Parse the directive into a regular expression.
  763. std::string RegexStr;
  764. StringRef S = Text;
  765. while (!S.empty()) {
  766. if (S.startswith("{{")) {
  767. S = S.drop_front(2);
  768. size_t RegexMatchLength = S.find("}}");
  769. assert(RegexMatchLength != StringRef::npos);
  770. // Append the regex, enclosed in parentheses.
  771. RegexStr += "(";
  772. RegexStr.append(S.data(), RegexMatchLength);
  773. RegexStr += ")";
  774. S = S.drop_front(RegexMatchLength + 2);
  775. } else {
  776. size_t VerbatimMatchLength = S.find("{{");
  777. if (VerbatimMatchLength == StringRef::npos)
  778. VerbatimMatchLength = S.size();
  779. // Escape and append the fixed string.
  780. RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
  781. S = S.drop_front(VerbatimMatchLength);
  782. }
  783. }
  784. return new RegexDirective(DirectiveLoc, DiagnosticLoc, MatchAnyLine, Text,
  785. Min, Max, RegexStr);
  786. }