VerifyDiagnosticConsumer.cpp 31 KB

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