HTMLDiagnostics.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. //===- HTMLDiagnostics.cpp - HTML Diagnostics for Paths -------------------===//
  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 file defines the HTMLDiagnostics object.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Analysis/PathDiagnostic.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclBase.h"
  15. #include "clang/AST/Stmt.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/Lex/Lexer.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Lex/Token.h"
  23. #include "clang/Rewrite/Core/HTMLRewrite.h"
  24. #include "clang/Rewrite/Core/Rewriter.h"
  25. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  26. #include "clang/StaticAnalyzer/Core/IssueHash.h"
  27. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/ADT/iterator_range.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/Errc.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <map>
  42. #include <memory>
  43. #include <set>
  44. #include <sstream>
  45. #include <string>
  46. #include <system_error>
  47. #include <utility>
  48. #include <vector>
  49. using namespace clang;
  50. using namespace ento;
  51. //===----------------------------------------------------------------------===//
  52. // Boilerplate.
  53. //===----------------------------------------------------------------------===//
  54. namespace {
  55. class HTMLDiagnostics : public PathDiagnosticConsumer {
  56. std::string Directory;
  57. bool createdDir = false;
  58. bool noDir = false;
  59. const Preprocessor &PP;
  60. AnalyzerOptions &AnalyzerOpts;
  61. const bool SupportsCrossFileDiagnostics;
  62. public:
  63. HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
  64. const std::string& prefix,
  65. const Preprocessor &pp,
  66. bool supportsMultipleFiles)
  67. : Directory(prefix), PP(pp), AnalyzerOpts(AnalyzerOpts),
  68. SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
  69. ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
  70. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  71. FilesMade *filesMade) override;
  72. StringRef getName() const override {
  73. return "HTMLDiagnostics";
  74. }
  75. bool supportsCrossFileDiagnostics() const override {
  76. return SupportsCrossFileDiagnostics;
  77. }
  78. unsigned ProcessMacroPiece(raw_ostream &os,
  79. const PathDiagnosticMacroPiece& P,
  80. unsigned num);
  81. void HandlePiece(Rewriter &R, FileID BugFileID, const PathDiagnosticPiece &P,
  82. const std::vector<SourceRange> &PopUpRanges, unsigned num,
  83. unsigned max);
  84. void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
  85. const char *HighlightStart = "<span class=\"mrange\">",
  86. const char *HighlightEnd = "</span>");
  87. void ReportDiag(const PathDiagnostic& D,
  88. FilesMade *filesMade);
  89. // Generate the full HTML report
  90. std::string GenerateHTML(const PathDiagnostic& D, Rewriter &R,
  91. const SourceManager& SMgr, const PathPieces& path,
  92. const char *declName);
  93. // Add HTML header/footers to file specified by FID
  94. void FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
  95. const SourceManager& SMgr, const PathPieces& path,
  96. FileID FID, const FileEntry *Entry, const char *declName);
  97. // Rewrite the file specified by FID with HTML formatting.
  98. void RewriteFile(Rewriter &R, const PathPieces& path, FileID FID);
  99. private:
  100. /// \return Javascript for displaying shortcuts help;
  101. StringRef showHelpJavascript();
  102. /// \return Javascript for navigating the HTML report using j/k keys.
  103. StringRef generateKeyboardNavigationJavascript();
  104. /// \return JavaScript for an option to only show relevant lines.
  105. std::string showRelevantLinesJavascript(
  106. const PathDiagnostic &D, const PathPieces &path);
  107. /// Write executed lines from \p D in JSON format into \p os.
  108. void dumpCoverageData(const PathDiagnostic &D,
  109. const PathPieces &path,
  110. llvm::raw_string_ostream &os);
  111. };
  112. } // namespace
  113. void ento::createHTMLDiagnosticConsumer(
  114. AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
  115. const std::string &prefix, const Preprocessor &PP,
  116. const cross_tu::CrossTranslationUnitContext &) {
  117. C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, true));
  118. }
  119. void ento::createHTMLSingleFileDiagnosticConsumer(
  120. AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
  121. const std::string &prefix, const Preprocessor &PP,
  122. const cross_tu::CrossTranslationUnitContext &) {
  123. C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, false));
  124. }
  125. //===----------------------------------------------------------------------===//
  126. // Report processing.
  127. //===----------------------------------------------------------------------===//
  128. void HTMLDiagnostics::FlushDiagnosticsImpl(
  129. std::vector<const PathDiagnostic *> &Diags,
  130. FilesMade *filesMade) {
  131. for (const auto Diag : Diags)
  132. ReportDiag(*Diag, filesMade);
  133. }
  134. void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
  135. FilesMade *filesMade) {
  136. // Create the HTML directory if it is missing.
  137. if (!createdDir) {
  138. createdDir = true;
  139. if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
  140. llvm::errs() << "warning: could not create directory '"
  141. << Directory << "': " << ec.message() << '\n';
  142. noDir = true;
  143. return;
  144. }
  145. }
  146. if (noDir)
  147. return;
  148. // First flatten out the entire path to make it easier to use.
  149. PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
  150. // The path as already been prechecked that the path is non-empty.
  151. assert(!path.empty());
  152. const SourceManager &SMgr = path.front()->getLocation().getManager();
  153. // Create a new rewriter to generate HTML.
  154. Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
  155. // The file for the first path element is considered the main report file, it
  156. // will usually be equivalent to SMgr.getMainFileID(); however, it might be a
  157. // header when -analyzer-opt-analyze-headers is used.
  158. FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
  159. // Get the function/method name
  160. SmallString<128> declName("unknown");
  161. int offsetDecl = 0;
  162. if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
  163. if (const auto *ND = dyn_cast<NamedDecl>(DeclWithIssue))
  164. declName = ND->getDeclName().getAsString();
  165. if (const Stmt *Body = DeclWithIssue->getBody()) {
  166. // Retrieve the relative position of the declaration which will be used
  167. // for the file name
  168. FullSourceLoc L(
  169. SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
  170. SMgr);
  171. FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getBeginLoc()), SMgr);
  172. offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
  173. }
  174. }
  175. std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
  176. if (report.empty()) {
  177. llvm::errs() << "warning: no diagnostics generated for main file.\n";
  178. return;
  179. }
  180. // Create a path for the target HTML file.
  181. int FD;
  182. SmallString<128> Model, ResultPath;
  183. if (!AnalyzerOpts.ShouldWriteStableReportFilename) {
  184. llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
  185. if (std::error_code EC =
  186. llvm::sys::fs::make_absolute(Model)) {
  187. llvm::errs() << "warning: could not make '" << Model
  188. << "' absolute: " << EC.message() << '\n';
  189. return;
  190. }
  191. if (std::error_code EC =
  192. llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
  193. llvm::errs() << "warning: could not create file in '" << Directory
  194. << "': " << EC.message() << '\n';
  195. return;
  196. }
  197. } else {
  198. int i = 1;
  199. std::error_code EC;
  200. do {
  201. // Find a filename which is not already used
  202. const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
  203. std::stringstream filename;
  204. Model = "";
  205. filename << "report-"
  206. << llvm::sys::path::filename(Entry->getName()).str()
  207. << "-" << declName.c_str()
  208. << "-" << offsetDecl
  209. << "-" << i << ".html";
  210. llvm::sys::path::append(Model, Directory,
  211. filename.str());
  212. EC = llvm::sys::fs::openFileForReadWrite(
  213. Model, FD, llvm::sys::fs::CD_CreateNew, llvm::sys::fs::OF_None);
  214. if (EC && EC != llvm::errc::file_exists) {
  215. llvm::errs() << "warning: could not create file '" << Model
  216. << "': " << EC.message() << '\n';
  217. return;
  218. }
  219. i++;
  220. } while (EC);
  221. }
  222. llvm::raw_fd_ostream os(FD, true);
  223. if (filesMade)
  224. filesMade->addDiagnostic(D, getName(),
  225. llvm::sys::path::filename(ResultPath));
  226. // Emit the HTML to disk.
  227. os << report;
  228. }
  229. std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
  230. const SourceManager& SMgr, const PathPieces& path, const char *declName) {
  231. // Rewrite source files as HTML for every new file the path crosses
  232. std::vector<FileID> FileIDs;
  233. for (auto I : path) {
  234. FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
  235. if (llvm::is_contained(FileIDs, FID))
  236. continue;
  237. FileIDs.push_back(FID);
  238. RewriteFile(R, path, FID);
  239. }
  240. if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
  241. // Prefix file names, anchor tags, and nav cursors to every file
  242. for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
  243. std::string s;
  244. llvm::raw_string_ostream os(s);
  245. if (I != FileIDs.begin())
  246. os << "<hr class=divider>\n";
  247. os << "<div id=File" << I->getHashValue() << ">\n";
  248. // Left nav arrow
  249. if (I != FileIDs.begin())
  250. os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
  251. << "\">&#x2190;</a></div>";
  252. os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
  253. << "</h4>\n";
  254. // Right nav arrow
  255. if (I + 1 != E)
  256. os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
  257. << "\">&#x2192;</a></div>";
  258. os << "</div>\n";
  259. R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
  260. }
  261. // Append files to the main report file in the order they appear in the path
  262. for (auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
  263. std::string s;
  264. llvm::raw_string_ostream os(s);
  265. const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
  266. for (auto BI : *Buf)
  267. os << BI;
  268. R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
  269. }
  270. }
  271. const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
  272. if (!Buf)
  273. return {};
  274. // Add CSS, header, and footer.
  275. FileID FID =
  276. path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
  277. const FileEntry* Entry = SMgr.getFileEntryForID(FID);
  278. FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
  279. std::string file;
  280. llvm::raw_string_ostream os(file);
  281. for (auto BI : *Buf)
  282. os << BI;
  283. return os.str();
  284. }
  285. void HTMLDiagnostics::dumpCoverageData(
  286. const PathDiagnostic &D,
  287. const PathPieces &path,
  288. llvm::raw_string_ostream &os) {
  289. const FilesToLineNumsMap &ExecutedLines = D.getExecutedLines();
  290. os << "var relevant_lines = {";
  291. for (auto I = ExecutedLines.begin(),
  292. E = ExecutedLines.end(); I != E; ++I) {
  293. if (I != ExecutedLines.begin())
  294. os << ", ";
  295. os << "\"" << I->first.getHashValue() << "\": {";
  296. for (unsigned LineNo : I->second) {
  297. if (LineNo != *(I->second.begin()))
  298. os << ", ";
  299. os << "\"" << LineNo << "\": 1";
  300. }
  301. os << "}";
  302. }
  303. os << "};";
  304. }
  305. std::string HTMLDiagnostics::showRelevantLinesJavascript(
  306. const PathDiagnostic &D, const PathPieces &path) {
  307. std::string s;
  308. llvm::raw_string_ostream os(s);
  309. os << "<script type='text/javascript'>\n";
  310. dumpCoverageData(D, path, os);
  311. os << R"<<<(
  312. var filterCounterexample = function (hide) {
  313. var tables = document.getElementsByClassName("code");
  314. for (var t=0; t<tables.length; t++) {
  315. var table = tables[t];
  316. var file_id = table.getAttribute("data-fileid");
  317. var lines_in_fid = relevant_lines[file_id];
  318. if (!lines_in_fid) {
  319. lines_in_fid = {};
  320. }
  321. var lines = table.getElementsByClassName("codeline");
  322. for (var i=0; i<lines.length; i++) {
  323. var el = lines[i];
  324. var lineNo = el.getAttribute("data-linenumber");
  325. if (!lines_in_fid[lineNo]) {
  326. if (hide) {
  327. el.setAttribute("hidden", "");
  328. } else {
  329. el.removeAttribute("hidden");
  330. }
  331. }
  332. }
  333. }
  334. }
  335. window.addEventListener("keydown", function (event) {
  336. if (event.defaultPrevented) {
  337. return;
  338. }
  339. if (event.key == "S") {
  340. var checked = document.getElementsByName("showCounterexample")[0].checked;
  341. filterCounterexample(!checked);
  342. document.getElementsByName("showCounterexample")[0].checked = !checked;
  343. } else {
  344. return;
  345. }
  346. event.preventDefault();
  347. }, true);
  348. document.addEventListener("DOMContentLoaded", function() {
  349. document.querySelector('input[name="showCounterexample"]').onchange=
  350. function (event) {
  351. filterCounterexample(this.checked);
  352. };
  353. });
  354. </script>
  355. <form>
  356. <input type="checkbox" name="showCounterexample" id="showCounterexample" />
  357. <label for="showCounterexample">
  358. Show only relevant lines
  359. </label>
  360. </form>
  361. )<<<";
  362. return os.str();
  363. }
  364. void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
  365. const SourceManager& SMgr, const PathPieces& path, FileID FID,
  366. const FileEntry *Entry, const char *declName) {
  367. // This is a cludge; basically we want to append either the full
  368. // working directory if we have no directory information. This is
  369. // a work in progress.
  370. llvm::SmallString<0> DirName;
  371. if (llvm::sys::path::is_relative(Entry->getName())) {
  372. llvm::sys::fs::current_path(DirName);
  373. DirName += '/';
  374. }
  375. int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
  376. int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
  377. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), showHelpJavascript());
  378. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
  379. generateKeyboardNavigationJavascript());
  380. // Checkbox and javascript for filtering the output to the counterexample.
  381. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
  382. showRelevantLinesJavascript(D, path));
  383. // Add the name of the file as an <h1> tag.
  384. {
  385. std::string s;
  386. llvm::raw_string_ostream os(s);
  387. os << "<!-- REPORTHEADER -->\n"
  388. << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
  389. "<tr><td class=\"rowname\">File:</td><td>"
  390. << html::EscapeText(DirName)
  391. << html::EscapeText(Entry->getName())
  392. << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
  393. "<a href=\"#EndPath\">line "
  394. << LineNumber
  395. << ", column "
  396. << ColumnNumber
  397. << "</a><br />"
  398. << D.getVerboseDescription() << "</td></tr>\n";
  399. // The navigation across the extra notes pieces.
  400. unsigned NumExtraPieces = 0;
  401. for (const auto &Piece : path) {
  402. if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
  403. int LineNumber =
  404. P->getLocation().asLocation().getExpansionLineNumber();
  405. int ColumnNumber =
  406. P->getLocation().asLocation().getExpansionColumnNumber();
  407. os << "<tr><td class=\"rowname\">Note:</td><td>"
  408. << "<a href=\"#Note" << NumExtraPieces << "\">line "
  409. << LineNumber << ", column " << ColumnNumber << "</a><br />"
  410. << P->getString() << "</td></tr>";
  411. ++NumExtraPieces;
  412. }
  413. }
  414. // Output any other meta data.
  415. for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
  416. I != E; ++I) {
  417. os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
  418. }
  419. os << R"<<<(
  420. </table>
  421. <!-- REPORTSUMMARYEXTRA -->
  422. <h3>Annotated Source Code</h3>
  423. <p>Press <a href="#" onclick="toggleHelp(); return false;">'?'</a>
  424. to see keyboard shortcuts</p>
  425. <input type="checkbox" class="spoilerhider" id="showinvocation" />
  426. <label for="showinvocation" >Show analyzer invocation</label>
  427. <div class="spoiler">clang -cc1 )<<<";
  428. os << html::EscapeText(AnalyzerOpts.FullCompilerInvocation);
  429. os << R"<<<(
  430. </div>
  431. <div id='tooltiphint' hidden="true">
  432. <p>Keyboard shortcuts: </p>
  433. <ul>
  434. <li>Use 'j/k' keys for keyboard navigation</li>
  435. <li>Use 'Shift+S' to show/hide relevant lines</li>
  436. <li>Use '?' to toggle this window</li>
  437. </ul>
  438. <a href="#" onclick="toggleHelp(); return false;">Close</a>
  439. </div>
  440. )<<<";
  441. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  442. }
  443. // Embed meta-data tags.
  444. {
  445. std::string s;
  446. llvm::raw_string_ostream os(s);
  447. StringRef BugDesc = D.getVerboseDescription();
  448. if (!BugDesc.empty())
  449. os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
  450. StringRef BugType = D.getBugType();
  451. if (!BugType.empty())
  452. os << "\n<!-- BUGTYPE " << BugType << " -->\n";
  453. PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
  454. FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
  455. ? UPDLoc.asLocation()
  456. : D.getLocation().asLocation()),
  457. SMgr);
  458. const Decl *DeclWithIssue = D.getDeclWithIssue();
  459. StringRef BugCategory = D.getCategory();
  460. if (!BugCategory.empty())
  461. os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
  462. os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
  463. os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
  464. os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
  465. os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
  466. << GetIssueHash(SMgr, L, D.getCheckerName(), D.getBugType(),
  467. DeclWithIssue, PP.getLangOpts())
  468. << " -->\n";
  469. os << "\n<!-- BUGLINE "
  470. << LineNumber
  471. << " -->\n";
  472. os << "\n<!-- BUGCOLUMN "
  473. << ColumnNumber
  474. << " -->\n";
  475. os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
  476. // Mark the end of the tags.
  477. os << "\n<!-- BUGMETAEND -->\n";
  478. // Insert the text.
  479. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  480. }
  481. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  482. }
  483. StringRef HTMLDiagnostics::showHelpJavascript() {
  484. return R"<<<(
  485. <script type='text/javascript'>
  486. var toggleHelp = function() {
  487. var hint = document.querySelector("#tooltiphint");
  488. var attributeName = "hidden";
  489. if (hint.hasAttribute(attributeName)) {
  490. hint.removeAttribute(attributeName);
  491. } else {
  492. hint.setAttribute("hidden", "true");
  493. }
  494. };
  495. window.addEventListener("keydown", function (event) {
  496. if (event.defaultPrevented) {
  497. return;
  498. }
  499. if (event.key == "?") {
  500. toggleHelp();
  501. } else {
  502. return;
  503. }
  504. event.preventDefault();
  505. });
  506. </script>
  507. )<<<";
  508. }
  509. static void
  510. HandlePopUpPieceStartTag(Rewriter &R,
  511. const std::vector<SourceRange> &PopUpRanges) {
  512. for (const auto &Range : PopUpRanges) {
  513. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "",
  514. "<table class='variable_popup'><tbody>",
  515. /*IsTokenRange=*/true);
  516. }
  517. }
  518. static void HandlePopUpPieceEndTag(Rewriter &R,
  519. const PathDiagnosticPopUpPiece &Piece,
  520. std::vector<SourceRange> &PopUpRanges,
  521. unsigned int LastReportedPieceIndex,
  522. unsigned int PopUpPieceIndex) {
  523. SmallString<256> Buf;
  524. llvm::raw_svector_ostream Out(Buf);
  525. SourceRange Range(Piece.getLocation().asRange());
  526. // Write out the path indices with a right arrow and the message as a row.
  527. Out << "<tr><td valign='top'><div class='PathIndex PathIndexPopUp'>"
  528. << LastReportedPieceIndex;
  529. // Also annotate the state transition with extra indices.
  530. Out << '.' << PopUpPieceIndex;
  531. Out << "</div></td><td>" << Piece.getString() << "</td></tr>";
  532. // If no report made at this range mark the variable and add the end tags.
  533. if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) ==
  534. PopUpRanges.end()) {
  535. // Store that we create a report at this range.
  536. PopUpRanges.push_back(Range);
  537. Out << "</tbody></table></span>";
  538. html::HighlightRange(R, Range.getBegin(), Range.getEnd(),
  539. "<span class='variable'>", Buf.c_str(),
  540. /*IsTokenRange=*/true);
  541. } else {
  542. // Otherwise inject just the new row at the end of the range.
  543. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "", Buf.c_str(),
  544. /*IsTokenRange=*/true);
  545. }
  546. }
  547. void HTMLDiagnostics::RewriteFile(Rewriter &R,
  548. const PathPieces& path, FileID FID) {
  549. // Process the path.
  550. // Maintain the counts of extra note pieces separately.
  551. unsigned TotalPieces = path.size();
  552. unsigned TotalNotePieces = std::count_if(
  553. path.begin(), path.end(), [](const PathDiagnosticPieceRef &p) {
  554. return isa<PathDiagnosticNotePiece>(*p);
  555. });
  556. unsigned PopUpPieceCount = std::count_if(
  557. path.begin(), path.end(), [](const PathDiagnosticPieceRef &p) {
  558. return isa<PathDiagnosticPopUpPiece>(*p);
  559. });
  560. unsigned TotalRegularPieces = TotalPieces - TotalNotePieces - PopUpPieceCount;
  561. unsigned NumRegularPieces = TotalRegularPieces;
  562. unsigned NumNotePieces = TotalNotePieces;
  563. // Stores the count of the regular piece indices.
  564. std::map<int, int> IndexMap;
  565. // Stores the different ranges where we have reported something.
  566. std::vector<SourceRange> PopUpRanges;
  567. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  568. const auto &Piece = *I->get();
  569. if (isa<PathDiagnosticPopUpPiece>(Piece)) {
  570. ++IndexMap[NumRegularPieces];
  571. } else if (isa<PathDiagnosticNotePiece>(Piece)) {
  572. // This adds diagnostic bubbles, but not navigation.
  573. // Navigation through note pieces would be added later,
  574. // as a separate pass through the piece list.
  575. HandlePiece(R, FID, Piece, PopUpRanges, NumNotePieces, TotalNotePieces);
  576. --NumNotePieces;
  577. } else {
  578. HandlePiece(R, FID, Piece, PopUpRanges, NumRegularPieces,
  579. TotalRegularPieces);
  580. --NumRegularPieces;
  581. }
  582. }
  583. // Secondary indexing if we are having multiple pop-ups between two notes.
  584. // (e.g. [(13) 'a' is 'true']; [(13.1) 'b' is 'false']; [(13.2) 'c' is...)
  585. NumRegularPieces = TotalRegularPieces;
  586. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  587. const auto &Piece = *I->get();
  588. if (const auto *PopUpP = dyn_cast<PathDiagnosticPopUpPiece>(&Piece)) {
  589. int PopUpPieceIndex = IndexMap[NumRegularPieces];
  590. // Pop-up pieces needs the index of the last reported piece and its count
  591. // how many times we report to handle multiple reports on the same range.
  592. // This marks the variable, adds the </table> end tag and the message
  593. // (list element) as a row. The <table> start tag will be added after the
  594. // rows has been written out. Note: It stores every different range.
  595. HandlePopUpPieceEndTag(R, *PopUpP, PopUpRanges, NumRegularPieces,
  596. PopUpPieceIndex);
  597. if (PopUpPieceIndex > 0)
  598. --IndexMap[NumRegularPieces];
  599. } else if (!isa<PathDiagnosticNotePiece>(Piece)) {
  600. --NumRegularPieces;
  601. }
  602. }
  603. // Add the <table> start tag of pop-up pieces based on the stored ranges.
  604. HandlePopUpPieceStartTag(R, PopUpRanges);
  605. // Add line numbers, header, footer, etc.
  606. html::EscapeText(R, FID);
  607. html::AddLineNumbers(R, FID);
  608. // If we have a preprocessor, relex the file and syntax highlight.
  609. // We might not have a preprocessor if we come from a deserialized AST file,
  610. // for example.
  611. html::SyntaxHighlight(R, FID, PP);
  612. html::HighlightMacros(R, FID, PP);
  613. }
  614. void HTMLDiagnostics::HandlePiece(Rewriter &R, FileID BugFileID,
  615. const PathDiagnosticPiece &P,
  616. const std::vector<SourceRange> &PopUpRanges,
  617. unsigned num, unsigned max) {
  618. // For now, just draw a box above the line in question, and emit the
  619. // warning.
  620. FullSourceLoc Pos = P.getLocation().asLocation();
  621. if (!Pos.isValid())
  622. return;
  623. SourceManager &SM = R.getSourceMgr();
  624. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  625. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  626. if (LPosInfo.first != BugFileID)
  627. return;
  628. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  629. const char* FileStart = Buf->getBufferStart();
  630. // Compute the column number. Rewind from the current position to the start
  631. // of the line.
  632. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  633. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  634. const char *LineStart = TokInstantiationPtr-ColNo;
  635. // Compute LineEnd.
  636. const char *LineEnd = TokInstantiationPtr;
  637. const char* FileEnd = Buf->getBufferEnd();
  638. while (*LineEnd != '\n' && LineEnd != FileEnd)
  639. ++LineEnd;
  640. // Compute the margin offset by counting tabs and non-tabs.
  641. unsigned PosNo = 0;
  642. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  643. PosNo += *c == '\t' ? 8 : 1;
  644. // Create the html for the message.
  645. const char *Kind = nullptr;
  646. bool IsNote = false;
  647. bool SuppressIndex = (max == 1);
  648. switch (P.getKind()) {
  649. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  650. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  651. // Setting Kind to "Control" is intentional.
  652. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  653. case PathDiagnosticPiece::Note:
  654. Kind = "Note";
  655. IsNote = true;
  656. SuppressIndex = true;
  657. break;
  658. case PathDiagnosticPiece::Call:
  659. case PathDiagnosticPiece::PopUp:
  660. llvm_unreachable("Calls and extra notes should already be handled");
  661. }
  662. std::string sbuf;
  663. llvm::raw_string_ostream os(sbuf);
  664. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  665. if (IsNote)
  666. os << "Note" << num;
  667. else if (num == max)
  668. os << "EndPath";
  669. else
  670. os << "Path" << num;
  671. os << "\" class=\"msg";
  672. if (Kind)
  673. os << " msg" << Kind;
  674. os << "\" style=\"margin-left:" << PosNo << "ex";
  675. // Output a maximum size.
  676. if (!isa<PathDiagnosticMacroPiece>(P)) {
  677. // Get the string and determining its maximum substring.
  678. const auto &Msg = P.getString();
  679. unsigned max_token = 0;
  680. unsigned cnt = 0;
  681. unsigned len = Msg.size();
  682. for (char C : Msg)
  683. switch (C) {
  684. default:
  685. ++cnt;
  686. continue;
  687. case ' ':
  688. case '\t':
  689. case '\n':
  690. if (cnt > max_token) max_token = cnt;
  691. cnt = 0;
  692. }
  693. if (cnt > max_token)
  694. max_token = cnt;
  695. // Determine the approximate size of the message bubble in em.
  696. unsigned em;
  697. const unsigned max_line = 120;
  698. if (max_token >= max_line)
  699. em = max_token / 2;
  700. else {
  701. unsigned characters = max_line;
  702. unsigned lines = len / max_line;
  703. if (lines > 0) {
  704. for (; characters > max_token; --characters)
  705. if (len / characters > lines) {
  706. ++characters;
  707. break;
  708. }
  709. }
  710. em = characters / 2;
  711. }
  712. if (em < max_line/2)
  713. os << "; max-width:" << em << "em";
  714. }
  715. else
  716. os << "; max-width:100em";
  717. os << "\">";
  718. if (!SuppressIndex) {
  719. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  720. os << "<div class=\"PathIndex";
  721. if (Kind) os << " PathIndex" << Kind;
  722. os << "\">" << num << "</div>";
  723. if (num > 1) {
  724. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  725. << (num - 1)
  726. << "\" title=\"Previous event ("
  727. << (num - 1)
  728. << ")\">&#x2190;</a></div></td>";
  729. }
  730. os << "</td><td>";
  731. }
  732. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  733. os << "Within the expansion of the macro '";
  734. // Get the name of the macro by relexing it.
  735. {
  736. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  737. assert(L.isFileID());
  738. StringRef BufferInfo = L.getBufferData();
  739. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  740. const char* MacroName = LocInfo.second + BufferInfo.data();
  741. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  742. BufferInfo.begin(), MacroName, BufferInfo.end());
  743. Token TheTok;
  744. rawLexer.LexFromRawLexer(TheTok);
  745. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  746. os << MacroName[i];
  747. }
  748. os << "':\n";
  749. if (!SuppressIndex) {
  750. os << "</td>";
  751. if (num < max) {
  752. os << "<td><div class=\"PathNav\"><a href=\"#";
  753. if (num == max - 1)
  754. os << "EndPath";
  755. else
  756. os << "Path" << (num + 1);
  757. os << "\" title=\"Next event ("
  758. << (num + 1)
  759. << ")\">&#x2192;</a></div></td>";
  760. }
  761. os << "</tr></table>";
  762. }
  763. // Within a macro piece. Write out each event.
  764. ProcessMacroPiece(os, *MP, 0);
  765. }
  766. else {
  767. os << html::EscapeText(P.getString());
  768. if (!SuppressIndex) {
  769. os << "</td>";
  770. if (num < max) {
  771. os << "<td><div class=\"PathNav\"><a href=\"#";
  772. if (num == max - 1)
  773. os << "EndPath";
  774. else
  775. os << "Path" << (num + 1);
  776. os << "\" title=\"Next event ("
  777. << (num + 1)
  778. << ")\">&#x2192;</a></div></td>";
  779. }
  780. os << "</tr></table>";
  781. }
  782. }
  783. os << "</div></td></tr>";
  784. // Insert the new html.
  785. unsigned DisplayPos = LineEnd - FileStart;
  786. SourceLocation Loc =
  787. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  788. R.InsertTextBefore(Loc, os.str());
  789. // Now highlight the ranges.
  790. ArrayRef<SourceRange> Ranges = P.getRanges();
  791. for (const auto &Range : Ranges) {
  792. // If we have already highlighted the range as a pop-up there is no work.
  793. if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) !=
  794. PopUpRanges.end())
  795. continue;
  796. HighlightRange(R, LPosInfo.first, Range);
  797. }
  798. }
  799. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  800. unsigned x = n % ('z' - 'a');
  801. n /= 'z' - 'a';
  802. if (n > 0)
  803. EmitAlphaCounter(os, n);
  804. os << char('a' + x);
  805. }
  806. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  807. const PathDiagnosticMacroPiece& P,
  808. unsigned num) {
  809. for (const auto &subPiece : P.subPieces) {
  810. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
  811. num = ProcessMacroPiece(os, *MP, num);
  812. continue;
  813. }
  814. if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
  815. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  816. "margin-left:5px\">"
  817. "<table class=\"msgT\"><tr>"
  818. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  819. EmitAlphaCounter(os, num++);
  820. os << "</div></td><td valign=\"top\">"
  821. << html::EscapeText(EP->getString())
  822. << "</td></tr></table></div>\n";
  823. }
  824. }
  825. return num;
  826. }
  827. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  828. SourceRange Range,
  829. const char *HighlightStart,
  830. const char *HighlightEnd) {
  831. SourceManager &SM = R.getSourceMgr();
  832. const LangOptions &LangOpts = R.getLangOpts();
  833. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  834. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  835. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  836. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  837. if (EndLineNo < StartLineNo)
  838. return;
  839. if (SM.getFileID(InstantiationStart) != BugFileID ||
  840. SM.getFileID(InstantiationEnd) != BugFileID)
  841. return;
  842. // Compute the column number of the end.
  843. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  844. unsigned OldEndColNo = EndColNo;
  845. if (EndColNo) {
  846. // Add in the length of the token, so that we cover multi-char tokens.
  847. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  848. }
  849. // Highlight the range. Make the span tag the outermost tag for the
  850. // selected range.
  851. SourceLocation E =
  852. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  853. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  854. }
  855. StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
  856. return R"<<<(
  857. <script type='text/javascript'>
  858. var digitMatcher = new RegExp("[0-9]+");
  859. document.addEventListener("DOMContentLoaded", function() {
  860. document.querySelectorAll(".PathNav > a").forEach(
  861. function(currentValue, currentIndex) {
  862. var hrefValue = currentValue.getAttribute("href");
  863. currentValue.onclick = function() {
  864. scrollTo(document.querySelector(hrefValue));
  865. return false;
  866. };
  867. });
  868. });
  869. var findNum = function() {
  870. var s = document.querySelector(".selected");
  871. if (!s || s.id == "EndPath") {
  872. return 0;
  873. }
  874. var out = parseInt(digitMatcher.exec(s.id)[0]);
  875. return out;
  876. };
  877. var scrollTo = function(el) {
  878. document.querySelectorAll(".selected").forEach(function(s) {
  879. s.classList.remove("selected");
  880. });
  881. el.classList.add("selected");
  882. window.scrollBy(0, el.getBoundingClientRect().top -
  883. (window.innerHeight / 2));
  884. }
  885. var move = function(num, up, numItems) {
  886. if (num == 1 && up || num == numItems - 1 && !up) {
  887. return 0;
  888. } else if (num == 0 && up) {
  889. return numItems - 1;
  890. } else if (num == 0 && !up) {
  891. return 1 % numItems;
  892. }
  893. return up ? num - 1 : num + 1;
  894. }
  895. var numToId = function(num) {
  896. if (num == 0) {
  897. return document.getElementById("EndPath")
  898. }
  899. return document.getElementById("Path" + num);
  900. };
  901. var navigateTo = function(up) {
  902. var numItems = document.querySelectorAll(
  903. ".line > .msgEvent, .line > .msgControl").length;
  904. var currentSelected = findNum();
  905. var newSelected = move(currentSelected, up, numItems);
  906. var newEl = numToId(newSelected, numItems);
  907. // Scroll element into center.
  908. scrollTo(newEl);
  909. };
  910. window.addEventListener("keydown", function (event) {
  911. if (event.defaultPrevented) {
  912. return;
  913. }
  914. if (event.key == "j") {
  915. navigateTo(/*up=*/false);
  916. } else if (event.key == "k") {
  917. navigateTo(/*up=*/true);
  918. } else {
  919. return;
  920. }
  921. event.preventDefault();
  922. }, true);
  923. </script>
  924. )<<<";
  925. }