HTMLDiagnostics.cpp 32 KB

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