HTMLDiagnostics.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. //===- HTMLDiagnostics.cpp - HTML Diagnostics for Paths -------------------===//
  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 file defines the HTMLDiagnostics object.
  11. //
  12. //===----------------------------------------------------------------------===//
  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/BugReporter/PathDiagnostic.h"
  27. #include "clang/StaticAnalyzer/Core/IssueHash.h"
  28. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  29. #include "llvm/ADT/ArrayRef.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/StringRef.h"
  32. #include "llvm/ADT/iterator_range.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Errc.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/FileSystem.h"
  37. #include "llvm/Support/MemoryBuffer.h"
  38. #include "llvm/Support/Path.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <map>
  43. #include <memory>
  44. #include <set>
  45. #include <sstream>
  46. #include <string>
  47. #include <system_error>
  48. #include <utility>
  49. #include <vector>
  50. using namespace clang;
  51. using namespace ento;
  52. //===----------------------------------------------------------------------===//
  53. // Boilerplate.
  54. //===----------------------------------------------------------------------===//
  55. namespace {
  56. class HTMLDiagnostics : public PathDiagnosticConsumer {
  57. std::string Directory;
  58. bool createdDir = false;
  59. bool noDir = false;
  60. const Preprocessor &PP;
  61. AnalyzerOptions &AnalyzerOpts;
  62. const bool SupportsCrossFileDiagnostics;
  63. public:
  64. HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
  65. const std::string& prefix,
  66. const Preprocessor &pp,
  67. bool supportsMultipleFiles)
  68. : Directory(prefix), PP(pp), AnalyzerOpts(AnalyzerOpts),
  69. SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
  70. ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
  71. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  72. FilesMade *filesMade) override;
  73. StringRef getName() const override {
  74. return "HTMLDiagnostics";
  75. }
  76. bool supportsCrossFileDiagnostics() const override {
  77. return SupportsCrossFileDiagnostics;
  78. }
  79. unsigned ProcessMacroPiece(raw_ostream &os,
  80. const PathDiagnosticMacroPiece& P,
  81. unsigned num);
  82. void HandlePiece(Rewriter& R, FileID BugFileID,
  83. const PathDiagnosticPiece& P, unsigned num, 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(AnalyzerOptions &AnalyzerOpts,
  114. PathDiagnosticConsumers &C,
  115. const std::string& prefix,
  116. const Preprocessor &PP) {
  117. C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, true));
  118. }
  119. void ento::createHTMLSingleFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
  120. PathDiagnosticConsumers &C,
  121. const std::string& prefix,
  122. const Preprocessor &PP) {
  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 (std::find(FileIDs.begin(), FileIDs.end(), FID) != FileIDs.end())
  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.getCheckName(), D.getBugType(), DeclWithIssue,
  467. PP.getLangOpts()) << " -->\n";
  468. os << "\n<!-- BUGLINE "
  469. << LineNumber
  470. << " -->\n";
  471. os << "\n<!-- BUGCOLUMN "
  472. << ColumnNumber
  473. << " -->\n";
  474. os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
  475. // Mark the end of the tags.
  476. os << "\n<!-- BUGMETAEND -->\n";
  477. // Insert the text.
  478. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  479. }
  480. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  481. }
  482. StringRef HTMLDiagnostics::showHelpJavascript() {
  483. return R"<<<(
  484. <script type='text/javascript'>
  485. var toggleHelp = function() {
  486. var hint = document.querySelector("#tooltiphint");
  487. var attributeName = "hidden";
  488. if (hint.hasAttribute(attributeName)) {
  489. hint.removeAttribute(attributeName);
  490. } else {
  491. hint.setAttribute("hidden", "true");
  492. }
  493. };
  494. window.addEventListener("keydown", function (event) {
  495. if (event.defaultPrevented) {
  496. return;
  497. }
  498. if (event.key == "?") {
  499. toggleHelp();
  500. } else {
  501. return;
  502. }
  503. event.preventDefault();
  504. });
  505. </script>
  506. )<<<";
  507. }
  508. void HTMLDiagnostics::RewriteFile(Rewriter &R,
  509. const PathPieces& path, FileID FID) {
  510. // Process the path.
  511. // Maintain the counts of extra note pieces separately.
  512. unsigned TotalPieces = path.size();
  513. unsigned TotalNotePieces =
  514. std::count_if(path.begin(), path.end(),
  515. [](const std::shared_ptr<PathDiagnosticPiece> &p) {
  516. return isa<PathDiagnosticNotePiece>(*p);
  517. });
  518. unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
  519. unsigned NumRegularPieces = TotalRegularPieces;
  520. unsigned NumNotePieces = TotalNotePieces;
  521. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  522. if (isa<PathDiagnosticNotePiece>(I->get())) {
  523. // This adds diagnostic bubbles, but not navigation.
  524. // Navigation through note pieces would be added later,
  525. // as a separate pass through the piece list.
  526. HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
  527. --NumNotePieces;
  528. } else {
  529. HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
  530. --NumRegularPieces;
  531. }
  532. }
  533. // Add line numbers, header, footer, etc.
  534. html::EscapeText(R, FID);
  535. html::AddLineNumbers(R, FID);
  536. // If we have a preprocessor, relex the file and syntax highlight.
  537. // We might not have a preprocessor if we come from a deserialized AST file,
  538. // for example.
  539. html::SyntaxHighlight(R, FID, PP);
  540. html::HighlightMacros(R, FID, PP);
  541. }
  542. void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
  543. const PathDiagnosticPiece& P,
  544. unsigned num, unsigned max) {
  545. // For now, just draw a box above the line in question, and emit the
  546. // warning.
  547. FullSourceLoc Pos = P.getLocation().asLocation();
  548. if (!Pos.isValid())
  549. return;
  550. SourceManager &SM = R.getSourceMgr();
  551. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  552. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  553. if (LPosInfo.first != BugFileID)
  554. return;
  555. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  556. const char* FileStart = Buf->getBufferStart();
  557. // Compute the column number. Rewind from the current position to the start
  558. // of the line.
  559. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  560. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  561. const char *LineStart = TokInstantiationPtr-ColNo;
  562. // Compute LineEnd.
  563. const char *LineEnd = TokInstantiationPtr;
  564. const char* FileEnd = Buf->getBufferEnd();
  565. while (*LineEnd != '\n' && LineEnd != FileEnd)
  566. ++LineEnd;
  567. // Compute the margin offset by counting tabs and non-tabs.
  568. unsigned PosNo = 0;
  569. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  570. PosNo += *c == '\t' ? 8 : 1;
  571. // Create the html for the message.
  572. const char *Kind = nullptr;
  573. bool IsNote = false;
  574. bool SuppressIndex = (max == 1);
  575. switch (P.getKind()) {
  576. case PathDiagnosticPiece::Call:
  577. llvm_unreachable("Calls and extra notes should already be handled");
  578. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  579. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  580. // Setting Kind to "Control" is intentional.
  581. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  582. case PathDiagnosticPiece::Note:
  583. Kind = "Note";
  584. IsNote = true;
  585. SuppressIndex = true;
  586. break;
  587. }
  588. std::string sbuf;
  589. llvm::raw_string_ostream os(sbuf);
  590. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  591. if (IsNote)
  592. os << "Note" << num;
  593. else if (num == max)
  594. os << "EndPath";
  595. else
  596. os << "Path" << num;
  597. os << "\" class=\"msg";
  598. if (Kind)
  599. os << " msg" << Kind;
  600. os << "\" style=\"margin-left:" << PosNo << "ex";
  601. // Output a maximum size.
  602. if (!isa<PathDiagnosticMacroPiece>(P)) {
  603. // Get the string and determining its maximum substring.
  604. const auto &Msg = P.getString();
  605. unsigned max_token = 0;
  606. unsigned cnt = 0;
  607. unsigned len = Msg.size();
  608. for (char C : Msg)
  609. switch (C) {
  610. default:
  611. ++cnt;
  612. continue;
  613. case ' ':
  614. case '\t':
  615. case '\n':
  616. if (cnt > max_token) max_token = cnt;
  617. cnt = 0;
  618. }
  619. if (cnt > max_token)
  620. max_token = cnt;
  621. // Determine the approximate size of the message bubble in em.
  622. unsigned em;
  623. const unsigned max_line = 120;
  624. if (max_token >= max_line)
  625. em = max_token / 2;
  626. else {
  627. unsigned characters = max_line;
  628. unsigned lines = len / max_line;
  629. if (lines > 0) {
  630. for (; characters > max_token; --characters)
  631. if (len / characters > lines) {
  632. ++characters;
  633. break;
  634. }
  635. }
  636. em = characters / 2;
  637. }
  638. if (em < max_line/2)
  639. os << "; max-width:" << em << "em";
  640. }
  641. else
  642. os << "; max-width:100em";
  643. os << "\">";
  644. if (!SuppressIndex) {
  645. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  646. os << "<div class=\"PathIndex";
  647. if (Kind) os << " PathIndex" << Kind;
  648. os << "\">" << num << "</div>";
  649. if (num > 1) {
  650. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  651. << (num - 1)
  652. << "\" title=\"Previous event ("
  653. << (num - 1)
  654. << ")\">&#x2190;</a></div></td>";
  655. }
  656. os << "</td><td>";
  657. }
  658. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  659. os << "Within the expansion of the macro '";
  660. // Get the name of the macro by relexing it.
  661. {
  662. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  663. assert(L.isFileID());
  664. StringRef BufferInfo = L.getBufferData();
  665. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  666. const char* MacroName = LocInfo.second + BufferInfo.data();
  667. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  668. BufferInfo.begin(), MacroName, BufferInfo.end());
  669. Token TheTok;
  670. rawLexer.LexFromRawLexer(TheTok);
  671. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  672. os << MacroName[i];
  673. }
  674. os << "':\n";
  675. if (!SuppressIndex) {
  676. os << "</td>";
  677. if (num < max) {
  678. os << "<td><div class=\"PathNav\"><a href=\"#";
  679. if (num == max - 1)
  680. os << "EndPath";
  681. else
  682. os << "Path" << (num + 1);
  683. os << "\" title=\"Next event ("
  684. << (num + 1)
  685. << ")\">&#x2192;</a></div></td>";
  686. }
  687. os << "</tr></table>";
  688. }
  689. // Within a macro piece. Write out each event.
  690. ProcessMacroPiece(os, *MP, 0);
  691. }
  692. else {
  693. os << html::EscapeText(P.getString());
  694. if (!SuppressIndex) {
  695. os << "</td>";
  696. if (num < max) {
  697. os << "<td><div class=\"PathNav\"><a href=\"#";
  698. if (num == max - 1)
  699. os << "EndPath";
  700. else
  701. os << "Path" << (num + 1);
  702. os << "\" title=\"Next event ("
  703. << (num + 1)
  704. << ")\">&#x2192;</a></div></td>";
  705. }
  706. os << "</tr></table>";
  707. }
  708. }
  709. os << "</div></td></tr>";
  710. // Insert the new html.
  711. unsigned DisplayPos = LineEnd - FileStart;
  712. SourceLocation Loc =
  713. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  714. R.InsertTextBefore(Loc, os.str());
  715. // Now highlight the ranges.
  716. ArrayRef<SourceRange> Ranges = P.getRanges();
  717. for (const auto &Range : Ranges)
  718. HighlightRange(R, LPosInfo.first, Range);
  719. }
  720. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  721. unsigned x = n % ('z' - 'a');
  722. n /= 'z' - 'a';
  723. if (n > 0)
  724. EmitAlphaCounter(os, n);
  725. os << char('a' + x);
  726. }
  727. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  728. const PathDiagnosticMacroPiece& P,
  729. unsigned num) {
  730. for (const auto &subPiece : P.subPieces) {
  731. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
  732. num = ProcessMacroPiece(os, *MP, num);
  733. continue;
  734. }
  735. if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
  736. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  737. "margin-left:5px\">"
  738. "<table class=\"msgT\"><tr>"
  739. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  740. EmitAlphaCounter(os, num++);
  741. os << "</div></td><td valign=\"top\">"
  742. << html::EscapeText(EP->getString())
  743. << "</td></tr></table></div>\n";
  744. }
  745. }
  746. return num;
  747. }
  748. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  749. SourceRange Range,
  750. const char *HighlightStart,
  751. const char *HighlightEnd) {
  752. SourceManager &SM = R.getSourceMgr();
  753. const LangOptions &LangOpts = R.getLangOpts();
  754. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  755. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  756. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  757. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  758. if (EndLineNo < StartLineNo)
  759. return;
  760. if (SM.getFileID(InstantiationStart) != BugFileID ||
  761. SM.getFileID(InstantiationEnd) != BugFileID)
  762. return;
  763. // Compute the column number of the end.
  764. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  765. unsigned OldEndColNo = EndColNo;
  766. if (EndColNo) {
  767. // Add in the length of the token, so that we cover multi-char tokens.
  768. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  769. }
  770. // Highlight the range. Make the span tag the outermost tag for the
  771. // selected range.
  772. SourceLocation E =
  773. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  774. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  775. }
  776. StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
  777. return R"<<<(
  778. <script type='text/javascript'>
  779. var digitMatcher = new RegExp("[0-9]+");
  780. document.addEventListener("DOMContentLoaded", function() {
  781. document.querySelectorAll(".PathNav > a").forEach(
  782. function(currentValue, currentIndex) {
  783. var hrefValue = currentValue.getAttribute("href");
  784. currentValue.onclick = function() {
  785. scrollTo(document.querySelector(hrefValue));
  786. return false;
  787. };
  788. });
  789. });
  790. var findNum = function() {
  791. var s = document.querySelector(".selected");
  792. if (!s || s.id == "EndPath") {
  793. return 0;
  794. }
  795. var out = parseInt(digitMatcher.exec(s.id)[0]);
  796. return out;
  797. };
  798. var scrollTo = function(el) {
  799. document.querySelectorAll(".selected").forEach(function(s) {
  800. s.classList.remove("selected");
  801. });
  802. el.classList.add("selected");
  803. window.scrollBy(0, el.getBoundingClientRect().top -
  804. (window.innerHeight / 2));
  805. }
  806. var move = function(num, up, numItems) {
  807. if (num == 1 && up || num == numItems - 1 && !up) {
  808. return 0;
  809. } else if (num == 0 && up) {
  810. return numItems - 1;
  811. } else if (num == 0 && !up) {
  812. return 1 % numItems;
  813. }
  814. return up ? num - 1 : num + 1;
  815. }
  816. var numToId = function(num) {
  817. if (num == 0) {
  818. return document.getElementById("EndPath")
  819. }
  820. return document.getElementById("Path" + num);
  821. };
  822. var navigateTo = function(up) {
  823. var numItems = document.querySelectorAll(
  824. ".line > .msgEvent, .line > .msgControl").length;
  825. var currentSelected = findNum();
  826. var newSelected = move(currentSelected, up, numItems);
  827. var newEl = numToId(newSelected, numItems);
  828. // Scroll element into center.
  829. scrollTo(newEl);
  830. };
  831. window.addEventListener("keydown", function (event) {
  832. if (event.defaultPrevented) {
  833. return;
  834. }
  835. if (event.key == "j") {
  836. navigateTo(/*up=*/false);
  837. } else if (event.key == "k") {
  838. navigateTo(/*up=*/true);
  839. } else {
  840. return;
  841. }
  842. event.preventDefault();
  843. }, true);
  844. </script>
  845. )<<<";
  846. }