HTMLDiagnostics.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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/AST/Decl.h"
  13. #include "clang/AST/DeclBase.h"
  14. #include "clang/AST/Stmt.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/LLVM.h"
  17. #include "clang/Basic/SourceLocation.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/Lex/Lexer.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Lex/Token.h"
  22. #include "clang/Rewrite/Core/HTMLRewrite.h"
  23. #include "clang/Rewrite/Core/Rewriter.h"
  24. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.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(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 (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.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. static void
  509. HandlePopUpPieceStartTag(Rewriter &R,
  510. const std::vector<SourceRange> &PopUpRanges) {
  511. for (const auto &Range : PopUpRanges) {
  512. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "",
  513. "<table class='variable_popup'><tbody>",
  514. /*IsTokenRange=*/true);
  515. }
  516. }
  517. static void HandlePopUpPieceEndTag(Rewriter &R,
  518. const PathDiagnosticPopUpPiece &Piece,
  519. std::vector<SourceRange> &PopUpRanges,
  520. unsigned int LastReportedPieceIndex,
  521. unsigned int PopUpPieceIndex) {
  522. SmallString<256> Buf;
  523. llvm::raw_svector_ostream Out(Buf);
  524. SourceRange Range(Piece.getLocation().asRange());
  525. // Write out the path indices with a right arrow and the message as a row.
  526. Out << "<tr><td valign='top'><div class='PathIndex PathIndexPopUp'>"
  527. << LastReportedPieceIndex;
  528. // Also annotate the state transition with extra indices.
  529. Out << '.' << PopUpPieceIndex;
  530. Out << "</div></td><td>" << Piece.getString() << "</td></tr>";
  531. // If no report made at this range mark the variable and add the end tags.
  532. if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) ==
  533. PopUpRanges.end()) {
  534. // Store that we create a report at this range.
  535. PopUpRanges.push_back(Range);
  536. Out << "</tbody></table></span>";
  537. html::HighlightRange(R, Range.getBegin(), Range.getEnd(),
  538. "<span class='variable'>", Buf.c_str(),
  539. /*IsTokenRange=*/true);
  540. // Otherwise inject just the new row at the end of the range.
  541. } else {
  542. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "", Buf.c_str(),
  543. /*IsTokenRange=*/true);
  544. }
  545. }
  546. void HTMLDiagnostics::RewriteFile(Rewriter &R,
  547. const PathPieces& path, FileID FID) {
  548. // Process the path.
  549. // Maintain the counts of extra note pieces separately.
  550. unsigned TotalPieces = path.size();
  551. unsigned TotalNotePieces =
  552. std::count_if(path.begin(), path.end(),
  553. [](const std::shared_ptr<PathDiagnosticPiece> &p) {
  554. return isa<PathDiagnosticNotePiece>(*p);
  555. });
  556. unsigned PopUpPieceCount =
  557. std::count_if(path.begin(), path.end(),
  558. [](const std::shared_ptr<PathDiagnosticPiece> &p) {
  559. return isa<PathDiagnosticPopUpPiece>(*p);
  560. });
  561. unsigned TotalRegularPieces = TotalPieces - TotalNotePieces - PopUpPieceCount;
  562. unsigned NumRegularPieces = TotalRegularPieces;
  563. unsigned NumNotePieces = TotalNotePieces;
  564. // Stores the count of the regular piece indices.
  565. std::map<int, int> IndexMap;
  566. // Stores the different ranges where we have reported something.
  567. std::vector<SourceRange> PopUpRanges;
  568. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  569. const auto &Piece = *I->get();
  570. if (isa<PathDiagnosticPopUpPiece>(Piece)) {
  571. ++IndexMap[NumRegularPieces];
  572. } else if (isa<PathDiagnosticNotePiece>(Piece)) {
  573. // This adds diagnostic bubbles, but not navigation.
  574. // Navigation through note pieces would be added later,
  575. // as a separate pass through the piece list.
  576. HandlePiece(R, FID, Piece, PopUpRanges, NumNotePieces, TotalNotePieces);
  577. --NumNotePieces;
  578. } else {
  579. HandlePiece(R, FID, Piece, PopUpRanges, NumRegularPieces,
  580. TotalRegularPieces);
  581. --NumRegularPieces;
  582. }
  583. }
  584. // Secondary indexing if we are having multiple pop-ups between two notes.
  585. // (e.g. [(13) 'a' is 'true']; [(13.1) 'b' is 'false']; [(13.2) 'c' is...)
  586. NumRegularPieces = TotalRegularPieces;
  587. for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
  588. const auto &Piece = *I->get();
  589. if (const auto *PopUpP = dyn_cast<PathDiagnosticPopUpPiece>(&Piece)) {
  590. int PopUpPieceIndex = IndexMap[NumRegularPieces];
  591. // Pop-up pieces needs the index of the last reported piece and its count
  592. // how many times we report to handle multiple reports on the same range.
  593. // This marks the variable, adds the </table> end tag and the message
  594. // (list element) as a row. The <table> start tag will be added after the
  595. // rows has been written out. Note: It stores every different range.
  596. HandlePopUpPieceEndTag(R, *PopUpP, PopUpRanges, NumRegularPieces,
  597. PopUpPieceIndex);
  598. if (PopUpPieceIndex > 0)
  599. --IndexMap[NumRegularPieces];
  600. } else if (!isa<PathDiagnosticNotePiece>(Piece)) {
  601. --NumRegularPieces;
  602. }
  603. }
  604. // Add the <table> start tag of pop-up pieces based on the stored ranges.
  605. HandlePopUpPieceStartTag(R, PopUpRanges);
  606. // Add line numbers, header, footer, etc.
  607. html::EscapeText(R, FID);
  608. html::AddLineNumbers(R, FID);
  609. // If we have a preprocessor, relex the file and syntax highlight.
  610. // We might not have a preprocessor if we come from a deserialized AST file,
  611. // for example.
  612. html::SyntaxHighlight(R, FID, PP);
  613. html::HighlightMacros(R, FID, PP);
  614. }
  615. void HTMLDiagnostics::HandlePiece(Rewriter &R, FileID BugFileID,
  616. const PathDiagnosticPiece &P,
  617. const std::vector<SourceRange> &PopUpRanges,
  618. unsigned num, unsigned max) {
  619. // For now, just draw a box above the line in question, and emit the
  620. // warning.
  621. FullSourceLoc Pos = P.getLocation().asLocation();
  622. if (!Pos.isValid())
  623. return;
  624. SourceManager &SM = R.getSourceMgr();
  625. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  626. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  627. if (LPosInfo.first != BugFileID)
  628. return;
  629. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  630. const char* FileStart = Buf->getBufferStart();
  631. // Compute the column number. Rewind from the current position to the start
  632. // of the line.
  633. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  634. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  635. const char *LineStart = TokInstantiationPtr-ColNo;
  636. // Compute LineEnd.
  637. const char *LineEnd = TokInstantiationPtr;
  638. const char* FileEnd = Buf->getBufferEnd();
  639. while (*LineEnd != '\n' && LineEnd != FileEnd)
  640. ++LineEnd;
  641. // Compute the margin offset by counting tabs and non-tabs.
  642. unsigned PosNo = 0;
  643. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  644. PosNo += *c == '\t' ? 8 : 1;
  645. // Create the html for the message.
  646. const char *Kind = nullptr;
  647. bool IsNote = false;
  648. bool SuppressIndex = (max == 1);
  649. switch (P.getKind()) {
  650. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  651. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  652. // Setting Kind to "Control" is intentional.
  653. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  654. case PathDiagnosticPiece::Note:
  655. Kind = "Note";
  656. IsNote = true;
  657. SuppressIndex = true;
  658. break;
  659. case PathDiagnosticPiece::Call:
  660. case PathDiagnosticPiece::PopUp:
  661. llvm_unreachable("Calls and extra notes should already be handled");
  662. }
  663. std::string sbuf;
  664. llvm::raw_string_ostream os(sbuf);
  665. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  666. if (IsNote)
  667. os << "Note" << num;
  668. else if (num == max)
  669. os << "EndPath";
  670. else
  671. os << "Path" << num;
  672. os << "\" class=\"msg";
  673. if (Kind)
  674. os << " msg" << Kind;
  675. os << "\" style=\"margin-left:" << PosNo << "ex";
  676. // Output a maximum size.
  677. if (!isa<PathDiagnosticMacroPiece>(P)) {
  678. // Get the string and determining its maximum substring.
  679. const auto &Msg = P.getString();
  680. unsigned max_token = 0;
  681. unsigned cnt = 0;
  682. unsigned len = Msg.size();
  683. for (char C : Msg)
  684. switch (C) {
  685. default:
  686. ++cnt;
  687. continue;
  688. case ' ':
  689. case '\t':
  690. case '\n':
  691. if (cnt > max_token) max_token = cnt;
  692. cnt = 0;
  693. }
  694. if (cnt > max_token)
  695. max_token = cnt;
  696. // Determine the approximate size of the message bubble in em.
  697. unsigned em;
  698. const unsigned max_line = 120;
  699. if (max_token >= max_line)
  700. em = max_token / 2;
  701. else {
  702. unsigned characters = max_line;
  703. unsigned lines = len / max_line;
  704. if (lines > 0) {
  705. for (; characters > max_token; --characters)
  706. if (len / characters > lines) {
  707. ++characters;
  708. break;
  709. }
  710. }
  711. em = characters / 2;
  712. }
  713. if (em < max_line/2)
  714. os << "; max-width:" << em << "em";
  715. }
  716. else
  717. os << "; max-width:100em";
  718. os << "\">";
  719. if (!SuppressIndex) {
  720. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  721. os << "<div class=\"PathIndex";
  722. if (Kind) os << " PathIndex" << Kind;
  723. os << "\">" << num << "</div>";
  724. if (num > 1) {
  725. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  726. << (num - 1)
  727. << "\" title=\"Previous event ("
  728. << (num - 1)
  729. << ")\">&#x2190;</a></div></td>";
  730. }
  731. os << "</td><td>";
  732. }
  733. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  734. os << "Within the expansion of the macro '";
  735. // Get the name of the macro by relexing it.
  736. {
  737. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  738. assert(L.isFileID());
  739. StringRef BufferInfo = L.getBufferData();
  740. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  741. const char* MacroName = LocInfo.second + BufferInfo.data();
  742. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  743. BufferInfo.begin(), MacroName, BufferInfo.end());
  744. Token TheTok;
  745. rawLexer.LexFromRawLexer(TheTok);
  746. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  747. os << MacroName[i];
  748. }
  749. os << "':\n";
  750. if (!SuppressIndex) {
  751. os << "</td>";
  752. if (num < max) {
  753. os << "<td><div class=\"PathNav\"><a href=\"#";
  754. if (num == max - 1)
  755. os << "EndPath";
  756. else
  757. os << "Path" << (num + 1);
  758. os << "\" title=\"Next event ("
  759. << (num + 1)
  760. << ")\">&#x2192;</a></div></td>";
  761. }
  762. os << "</tr></table>";
  763. }
  764. // Within a macro piece. Write out each event.
  765. ProcessMacroPiece(os, *MP, 0);
  766. }
  767. else {
  768. os << html::EscapeText(P.getString());
  769. if (!SuppressIndex) {
  770. os << "</td>";
  771. if (num < max) {
  772. os << "<td><div class=\"PathNav\"><a href=\"#";
  773. if (num == max - 1)
  774. os << "EndPath";
  775. else
  776. os << "Path" << (num + 1);
  777. os << "\" title=\"Next event ("
  778. << (num + 1)
  779. << ")\">&#x2192;</a></div></td>";
  780. }
  781. os << "</tr></table>";
  782. }
  783. }
  784. os << "</div></td></tr>";
  785. // Insert the new html.
  786. unsigned DisplayPos = LineEnd - FileStart;
  787. SourceLocation Loc =
  788. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  789. R.InsertTextBefore(Loc, os.str());
  790. // Now highlight the ranges.
  791. ArrayRef<SourceRange> Ranges = P.getRanges();
  792. for (const auto &Range : Ranges) {
  793. // If we have already highlighted the range as a pop-up there is no work.
  794. if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) !=
  795. PopUpRanges.end())
  796. continue;
  797. HighlightRange(R, LPosInfo.first, Range);
  798. }
  799. }
  800. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  801. unsigned x = n % ('z' - 'a');
  802. n /= 'z' - 'a';
  803. if (n > 0)
  804. EmitAlphaCounter(os, n);
  805. os << char('a' + x);
  806. }
  807. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  808. const PathDiagnosticMacroPiece& P,
  809. unsigned num) {
  810. for (const auto &subPiece : P.subPieces) {
  811. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
  812. num = ProcessMacroPiece(os, *MP, num);
  813. continue;
  814. }
  815. if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
  816. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  817. "margin-left:5px\">"
  818. "<table class=\"msgT\"><tr>"
  819. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  820. EmitAlphaCounter(os, num++);
  821. os << "</div></td><td valign=\"top\">"
  822. << html::EscapeText(EP->getString())
  823. << "</td></tr></table></div>\n";
  824. }
  825. }
  826. return num;
  827. }
  828. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  829. SourceRange Range,
  830. const char *HighlightStart,
  831. const char *HighlightEnd) {
  832. SourceManager &SM = R.getSourceMgr();
  833. const LangOptions &LangOpts = R.getLangOpts();
  834. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  835. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  836. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  837. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  838. if (EndLineNo < StartLineNo)
  839. return;
  840. if (SM.getFileID(InstantiationStart) != BugFileID ||
  841. SM.getFileID(InstantiationEnd) != BugFileID)
  842. return;
  843. // Compute the column number of the end.
  844. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  845. unsigned OldEndColNo = EndColNo;
  846. if (EndColNo) {
  847. // Add in the length of the token, so that we cover multi-char tokens.
  848. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  849. }
  850. // Highlight the range. Make the span tag the outermost tag for the
  851. // selected range.
  852. SourceLocation E =
  853. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  854. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  855. }
  856. StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
  857. return R"<<<(
  858. <script type='text/javascript'>
  859. var digitMatcher = new RegExp("[0-9]+");
  860. document.addEventListener("DOMContentLoaded", function() {
  861. document.querySelectorAll(".PathNav > a").forEach(
  862. function(currentValue, currentIndex) {
  863. var hrefValue = currentValue.getAttribute("href");
  864. currentValue.onclick = function() {
  865. scrollTo(document.querySelector(hrefValue));
  866. return false;
  867. };
  868. });
  869. });
  870. var findNum = function() {
  871. var s = document.querySelector(".selected");
  872. if (!s || s.id == "EndPath") {
  873. return 0;
  874. }
  875. var out = parseInt(digitMatcher.exec(s.id)[0]);
  876. return out;
  877. };
  878. var scrollTo = function(el) {
  879. document.querySelectorAll(".selected").forEach(function(s) {
  880. s.classList.remove("selected");
  881. });
  882. el.classList.add("selected");
  883. window.scrollBy(0, el.getBoundingClientRect().top -
  884. (window.innerHeight / 2));
  885. }
  886. var move = function(num, up, numItems) {
  887. if (num == 1 && up || num == numItems - 1 && !up) {
  888. return 0;
  889. } else if (num == 0 && up) {
  890. return numItems - 1;
  891. } else if (num == 0 && !up) {
  892. return 1 % numItems;
  893. }
  894. return up ? num - 1 : num + 1;
  895. }
  896. var numToId = function(num) {
  897. if (num == 0) {
  898. return document.getElementById("EndPath")
  899. }
  900. return document.getElementById("Path" + num);
  901. };
  902. var navigateTo = function(up) {
  903. var numItems = document.querySelectorAll(
  904. ".line > .msgEvent, .line > .msgControl").length;
  905. var currentSelected = findNum();
  906. var newSelected = move(currentSelected, up, numItems);
  907. var newEl = numToId(newSelected, numItems);
  908. // Scroll element into center.
  909. scrollTo(newEl);
  910. };
  911. window.addEventListener("keydown", function (event) {
  912. if (event.defaultPrevented) {
  913. return;
  914. }
  915. if (event.key == "j") {
  916. navigateTo(/*up=*/false);
  917. } else if (event.key == "k") {
  918. navigateTo(/*up=*/true);
  919. } else {
  920. return;
  921. }
  922. event.preventDefault();
  923. }, true);
  924. </script>
  925. )<<<";
  926. }