HTMLDiagnostics.cpp 31 KB

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