HTMLDiagnostics.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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/Analysis/IssueHash.h"
  16. #include "clang/Analysis/MacroExpansionContext.h"
  17. #include "clang/Analysis/PathDiagnostic.h"
  18. #include "clang/Basic/FileManager.h"
  19. #include "clang/Basic/LLVM.h"
  20. #include "clang/Basic/SourceLocation.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Lex/Lexer.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "clang/Lex/Token.h"
  25. #include "clang/Rewrite/Core/HTMLRewrite.h"
  26. #include "clang/Rewrite/Core/Rewriter.h"
  27. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/Sequence.h"
  31. #include "llvm/ADT/SmallString.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/ADT/iterator_range.h"
  34. #include "llvm/Support/Casting.h"
  35. #include "llvm/Support/Errc.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/MemoryBuffer.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <algorithm>
  42. #include <cassert>
  43. #include <map>
  44. #include <memory>
  45. #include <set>
  46. #include <sstream>
  47. #include <string>
  48. #include <system_error>
  49. #include <utility>
  50. #include <vector>
  51. using namespace clang;
  52. using namespace ento;
  53. //===----------------------------------------------------------------------===//
  54. // Boilerplate.
  55. //===----------------------------------------------------------------------===//
  56. namespace {
  57. class ArrowMap;
  58. class HTMLDiagnostics : public PathDiagnosticConsumer {
  59. PathDiagnosticConsumerOptions DiagOpts;
  60. std::string Directory;
  61. bool createdDir = false;
  62. bool noDir = false;
  63. const Preprocessor &PP;
  64. const bool SupportsCrossFileDiagnostics;
  65. public:
  66. HTMLDiagnostics(PathDiagnosticConsumerOptions DiagOpts,
  67. const std::string &OutputDir, const Preprocessor &pp,
  68. bool supportsMultipleFiles)
  69. : DiagOpts(std::move(DiagOpts)), Directory(OutputDir), PP(pp),
  70. SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
  71. ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
  72. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  73. FilesMade *filesMade) override;
  74. StringRef getName() const override { return "HTMLDiagnostics"; }
  75. bool supportsCrossFileDiagnostics() const override {
  76. return SupportsCrossFileDiagnostics;
  77. }
  78. unsigned ProcessMacroPiece(raw_ostream &os, const PathDiagnosticMacroPiece &P,
  79. unsigned num);
  80. unsigned ProcessControlFlowPiece(Rewriter &R, FileID BugFileID,
  81. const PathDiagnosticControlFlowPiece &P,
  82. unsigned Number);
  83. void HandlePiece(Rewriter &R, FileID BugFileID, const PathDiagnosticPiece &P,
  84. const std::vector<SourceRange> &PopUpRanges, unsigned num,
  85. unsigned max);
  86. void HighlightRange(Rewriter &R, FileID BugFileID, SourceRange Range,
  87. const char *HighlightStart = "<span class=\"mrange\">",
  88. const char *HighlightEnd = "</span>");
  89. void ReportDiag(const PathDiagnostic &D, FilesMade *filesMade);
  90. // Generate the full HTML report
  91. std::string GenerateHTML(const PathDiagnostic &D, Rewriter &R,
  92. const SourceManager &SMgr, const PathPieces &path,
  93. const char *declName);
  94. // Add HTML header/footers to file specified by FID
  95. void FinalizeHTML(const PathDiagnostic &D, Rewriter &R,
  96. const SourceManager &SMgr, const PathPieces &path,
  97. FileID FID, const FileEntry *Entry, const char *declName);
  98. // Rewrite the file specified by FID with HTML formatting.
  99. void RewriteFile(Rewriter &R, const PathPieces &path, FileID FID);
  100. PathGenerationScheme getGenerationScheme() const override {
  101. return Everything;
  102. }
  103. private:
  104. void addArrowSVGs(Rewriter &R, FileID BugFileID,
  105. const ArrowMap &ArrowIndices);
  106. /// \return Javascript for displaying shortcuts help;
  107. StringRef showHelpJavascript();
  108. /// \return Javascript for navigating the HTML report using j/k keys.
  109. StringRef generateKeyboardNavigationJavascript();
  110. /// \return Javascript for drawing control-flow arrows.
  111. StringRef generateArrowDrawingJavascript();
  112. /// \return JavaScript for an option to only show relevant lines.
  113. std::string showRelevantLinesJavascript(const PathDiagnostic &D,
  114. const PathPieces &path);
  115. /// Write executed lines from \p D in JSON format into \p os.
  116. void dumpCoverageData(const PathDiagnostic &D, const PathPieces &path,
  117. llvm::raw_string_ostream &os);
  118. };
  119. bool isArrowPiece(const PathDiagnosticPiece &P) {
  120. return isa<PathDiagnosticControlFlowPiece>(P) && P.getString().empty();
  121. }
  122. unsigned getPathSizeWithoutArrows(const PathPieces &Path) {
  123. unsigned TotalPieces = Path.size();
  124. unsigned TotalArrowPieces = llvm::count_if(
  125. Path, [](const PathDiagnosticPieceRef &P) { return isArrowPiece(*P); });
  126. return TotalPieces - TotalArrowPieces;
  127. }
  128. class ArrowMap : public std::vector<unsigned> {
  129. using Base = std::vector<unsigned>;
  130. public:
  131. ArrowMap(unsigned Size) : Base(Size, 0) {}
  132. unsigned getTotalNumberOfArrows() const { return at(0); }
  133. };
  134. llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const ArrowMap &Indices) {
  135. OS << "[ ";
  136. llvm::interleave(Indices, OS, ",");
  137. return OS << " ]";
  138. }
  139. } // namespace
  140. void ento::createHTMLDiagnosticConsumer(
  141. PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
  142. const std::string &OutputDir, const Preprocessor &PP,
  143. const cross_tu::CrossTranslationUnitContext &CTU,
  144. const MacroExpansionContext &MacroExpansions) {
  145. // FIXME: HTML is currently our default output type, but if the output
  146. // directory isn't specified, it acts like if it was in the minimal text
  147. // output mode. This doesn't make much sense, we should have the minimal text
  148. // as our default. In the case of backward compatibility concerns, this could
  149. // be preserved with -analyzer-config-compatibility-mode=true.
  150. createTextMinimalPathDiagnosticConsumer(DiagOpts, C, OutputDir, PP, CTU,
  151. MacroExpansions);
  152. // TODO: Emit an error here.
  153. if (OutputDir.empty())
  154. return;
  155. C.push_back(new HTMLDiagnostics(std::move(DiagOpts), OutputDir, PP, true));
  156. }
  157. void ento::createHTMLSingleFileDiagnosticConsumer(
  158. PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
  159. const std::string &OutputDir, const Preprocessor &PP,
  160. const cross_tu::CrossTranslationUnitContext &CTU,
  161. const clang::MacroExpansionContext &MacroExpansions) {
  162. createTextMinimalPathDiagnosticConsumer(DiagOpts, C, OutputDir, PP, CTU,
  163. MacroExpansions);
  164. // TODO: Emit an error here.
  165. if (OutputDir.empty())
  166. return;
  167. C.push_back(new HTMLDiagnostics(std::move(DiagOpts), OutputDir, PP, false));
  168. }
  169. void ento::createPlistHTMLDiagnosticConsumer(
  170. PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
  171. const std::string &prefix, const Preprocessor &PP,
  172. const cross_tu::CrossTranslationUnitContext &CTU,
  173. const MacroExpansionContext &MacroExpansions) {
  174. createHTMLDiagnosticConsumer(
  175. DiagOpts, C, std::string(llvm::sys::path::parent_path(prefix)), PP, CTU,
  176. MacroExpansions);
  177. createPlistMultiFileDiagnosticConsumer(DiagOpts, C, prefix, PP, CTU,
  178. MacroExpansions);
  179. createTextMinimalPathDiagnosticConsumer(std::move(DiagOpts), C, prefix, PP,
  180. CTU, MacroExpansions);
  181. }
  182. void ento::createSarifHTMLDiagnosticConsumer(
  183. PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
  184. const std::string &sarif_file, const Preprocessor &PP,
  185. const cross_tu::CrossTranslationUnitContext &CTU,
  186. const MacroExpansionContext &MacroExpansions) {
  187. createHTMLDiagnosticConsumer(
  188. DiagOpts, C, std::string(llvm::sys::path::parent_path(sarif_file)), PP,
  189. CTU, MacroExpansions);
  190. createSarifDiagnosticConsumer(DiagOpts, C, sarif_file, PP, CTU,
  191. MacroExpansions);
  192. createTextMinimalPathDiagnosticConsumer(std::move(DiagOpts), C, sarif_file,
  193. PP, CTU, MacroExpansions);
  194. }
  195. //===----------------------------------------------------------------------===//
  196. // Report processing.
  197. //===----------------------------------------------------------------------===//
  198. void HTMLDiagnostics::FlushDiagnosticsImpl(
  199. std::vector<const PathDiagnostic *> &Diags,
  200. FilesMade *filesMade) {
  201. for (const auto Diag : Diags)
  202. ReportDiag(*Diag, filesMade);
  203. }
  204. static llvm::SmallString<32> getIssueHash(const PathDiagnostic &D,
  205. const Preprocessor &PP) {
  206. SourceManager &SMgr = PP.getSourceManager();
  207. PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
  208. FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
  209. ? UPDLoc.asLocation()
  210. : D.getLocation().asLocation()),
  211. SMgr);
  212. return getIssueHash(L, D.getCheckerName(), D.getBugType(),
  213. D.getDeclWithIssue(), PP.getLangOpts());
  214. }
  215. void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
  216. FilesMade *filesMade) {
  217. // Create the HTML directory if it is missing.
  218. if (!createdDir) {
  219. createdDir = true;
  220. if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
  221. llvm::errs() << "warning: could not create directory '"
  222. << Directory << "': " << ec.message() << '\n';
  223. noDir = true;
  224. return;
  225. }
  226. }
  227. if (noDir)
  228. return;
  229. // First flatten out the entire path to make it easier to use.
  230. PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
  231. // The path as already been prechecked that the path is non-empty.
  232. assert(!path.empty());
  233. const SourceManager &SMgr = path.front()->getLocation().getManager();
  234. // Create a new rewriter to generate HTML.
  235. Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
  236. // Get the function/method name
  237. SmallString<128> declName("unknown");
  238. int offsetDecl = 0;
  239. if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
  240. if (const auto *ND = dyn_cast<NamedDecl>(DeclWithIssue))
  241. declName = ND->getDeclName().getAsString();
  242. if (const Stmt *Body = DeclWithIssue->getBody()) {
  243. // Retrieve the relative position of the declaration which will be used
  244. // for the file name
  245. FullSourceLoc L(
  246. SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
  247. SMgr);
  248. FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getBeginLoc()), SMgr);
  249. offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
  250. }
  251. }
  252. std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
  253. if (report.empty()) {
  254. llvm::errs() << "warning: no diagnostics generated for main file.\n";
  255. return;
  256. }
  257. // Create a path for the target HTML file.
  258. int FD;
  259. SmallString<128> FileNameStr;
  260. llvm::raw_svector_ostream FileName(FileNameStr);
  261. FileName << "report-";
  262. // Historically, neither the stable report filename nor the unstable report
  263. // filename were actually stable. That said, the stable report filename
  264. // was more stable because it was mostly composed of information
  265. // about the bug report instead of being completely random.
  266. // Now both stable and unstable report filenames are in fact stable
  267. // but the stable report filename is still more verbose.
  268. if (DiagOpts.ShouldWriteVerboseReportFilename) {
  269. // FIXME: This code relies on knowing what constitutes the issue hash.
  270. // Otherwise deduplication won't work correctly.
  271. FileID ReportFile =
  272. path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
  273. const FileEntry *Entry = SMgr.getFileEntryForID(ReportFile);
  274. FileName << llvm::sys::path::filename(Entry->getName()).str() << "-"
  275. << declName.c_str() << "-" << offsetDecl << "-";
  276. }
  277. FileName << StringRef(getIssueHash(D, PP)).substr(0, 6).str() << ".html";
  278. SmallString<128> ResultPath;
  279. llvm::sys::path::append(ResultPath, Directory, FileName.str());
  280. if (std::error_code EC = llvm::sys::fs::make_absolute(ResultPath)) {
  281. llvm::errs() << "warning: could not make '" << ResultPath
  282. << "' absolute: " << EC.message() << '\n';
  283. return;
  284. }
  285. if (std::error_code EC = llvm::sys::fs::openFileForReadWrite(
  286. ResultPath, FD, llvm::sys::fs::CD_CreateNew,
  287. llvm::sys::fs::OF_Text)) {
  288. // Existence of the file corresponds to the situation where a different
  289. // Clang instance has emitted a bug report with the same issue hash.
  290. // This is an entirely normal situation that does not deserve a warning,
  291. // as apart from hash collisions this can happen because the reports
  292. // are in fact similar enough to be considered duplicates of each other.
  293. if (EC != llvm::errc::file_exists) {
  294. llvm::errs() << "warning: could not create file in '" << Directory
  295. << "': " << EC.message() << '\n';
  296. }
  297. return;
  298. }
  299. llvm::raw_fd_ostream os(FD, true);
  300. if (filesMade)
  301. filesMade->addDiagnostic(D, getName(),
  302. llvm::sys::path::filename(ResultPath));
  303. // Emit the HTML to disk.
  304. os << report;
  305. }
  306. std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
  307. const SourceManager& SMgr, const PathPieces& path, const char *declName) {
  308. // Rewrite source files as HTML for every new file the path crosses
  309. std::vector<FileID> FileIDs;
  310. for (auto I : path) {
  311. FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
  312. if (llvm::is_contained(FileIDs, FID))
  313. continue;
  314. FileIDs.push_back(FID);
  315. RewriteFile(R, path, FID);
  316. }
  317. if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
  318. // Prefix file names, anchor tags, and nav cursors to every file
  319. for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
  320. std::string s;
  321. llvm::raw_string_ostream os(s);
  322. if (I != FileIDs.begin())
  323. os << "<hr class=divider>\n";
  324. os << "<div id=File" << I->getHashValue() << ">\n";
  325. // Left nav arrow
  326. if (I != FileIDs.begin())
  327. os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
  328. << "\">&#x2190;</a></div>";
  329. os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
  330. << "</h4>\n";
  331. // Right nav arrow
  332. if (I + 1 != E)
  333. os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
  334. << "\">&#x2192;</a></div>";
  335. os << "</div>\n";
  336. R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
  337. }
  338. // Append files to the main report file in the order they appear in the path
  339. for (auto I : llvm::drop_begin(FileIDs)) {
  340. std::string s;
  341. llvm::raw_string_ostream os(s);
  342. const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
  343. for (auto BI : *Buf)
  344. os << BI;
  345. R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
  346. }
  347. }
  348. const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
  349. if (!Buf)
  350. return {};
  351. // Add CSS, header, and footer.
  352. FileID FID =
  353. path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
  354. const FileEntry* Entry = SMgr.getFileEntryForID(FID);
  355. FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
  356. std::string file;
  357. llvm::raw_string_ostream os(file);
  358. for (auto BI : *Buf)
  359. os << BI;
  360. return file;
  361. }
  362. void HTMLDiagnostics::dumpCoverageData(
  363. const PathDiagnostic &D,
  364. const PathPieces &path,
  365. llvm::raw_string_ostream &os) {
  366. const FilesToLineNumsMap &ExecutedLines = D.getExecutedLines();
  367. os << "var relevant_lines = {";
  368. for (auto I = ExecutedLines.begin(),
  369. E = ExecutedLines.end(); I != E; ++I) {
  370. if (I != ExecutedLines.begin())
  371. os << ", ";
  372. os << "\"" << I->first.getHashValue() << "\": {";
  373. for (unsigned LineNo : I->second) {
  374. if (LineNo != *(I->second.begin()))
  375. os << ", ";
  376. os << "\"" << LineNo << "\": 1";
  377. }
  378. os << "}";
  379. }
  380. os << "};";
  381. }
  382. std::string HTMLDiagnostics::showRelevantLinesJavascript(
  383. const PathDiagnostic &D, const PathPieces &path) {
  384. std::string s;
  385. llvm::raw_string_ostream os(s);
  386. os << "<script type='text/javascript'>\n";
  387. dumpCoverageData(D, path, os);
  388. os << R"<<<(
  389. var filterCounterexample = function (hide) {
  390. var tables = document.getElementsByClassName("code");
  391. for (var t=0; t<tables.length; t++) {
  392. var table = tables[t];
  393. var file_id = table.getAttribute("data-fileid");
  394. var lines_in_fid = relevant_lines[file_id];
  395. if (!lines_in_fid) {
  396. lines_in_fid = {};
  397. }
  398. var lines = table.getElementsByClassName("codeline");
  399. for (var i=0; i<lines.length; i++) {
  400. var el = lines[i];
  401. var lineNo = el.getAttribute("data-linenumber");
  402. if (!lines_in_fid[lineNo]) {
  403. if (hide) {
  404. el.setAttribute("hidden", "");
  405. } else {
  406. el.removeAttribute("hidden");
  407. }
  408. }
  409. }
  410. }
  411. }
  412. window.addEventListener("keydown", function (event) {
  413. if (event.defaultPrevented) {
  414. return;
  415. }
  416. // SHIFT + S
  417. if (event.shiftKey && event.keyCode == 83) {
  418. var checked = document.getElementsByName("showCounterexample")[0].checked;
  419. filterCounterexample(!checked);
  420. document.getElementsByName("showCounterexample")[0].click();
  421. } else {
  422. return;
  423. }
  424. event.preventDefault();
  425. }, true);
  426. document.addEventListener("DOMContentLoaded", function() {
  427. document.querySelector('input[name="showCounterexample"]').onchange=
  428. function (event) {
  429. filterCounterexample(this.checked);
  430. };
  431. });
  432. </script>
  433. <form>
  434. <input type="checkbox" name="showCounterexample" id="showCounterexample" />
  435. <label for="showCounterexample">
  436. Show only relevant lines
  437. </label>
  438. <input type="checkbox" name="showArrows"
  439. id="showArrows" style="margin-left: 10px" />
  440. <label for="showArrows">
  441. Show control flow arrows
  442. </label>
  443. </form>
  444. )<<<";
  445. return s;
  446. }
  447. void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
  448. const SourceManager& SMgr, const PathPieces& path, FileID FID,
  449. const FileEntry *Entry, const char *declName) {
  450. // This is a cludge; basically we want to append either the full
  451. // working directory if we have no directory information. This is
  452. // a work in progress.
  453. llvm::SmallString<0> DirName;
  454. if (llvm::sys::path::is_relative(Entry->getName())) {
  455. llvm::sys::fs::current_path(DirName);
  456. DirName += '/';
  457. }
  458. int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
  459. int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
  460. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), showHelpJavascript());
  461. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
  462. generateKeyboardNavigationJavascript());
  463. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
  464. generateArrowDrawingJavascript());
  465. // Checkbox and javascript for filtering the output to the counterexample.
  466. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
  467. showRelevantLinesJavascript(D, path));
  468. // Add the name of the file as an <h1> tag.
  469. {
  470. std::string s;
  471. llvm::raw_string_ostream os(s);
  472. os << "<!-- REPORTHEADER -->\n"
  473. << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
  474. "<tr><td class=\"rowname\">File:</td><td>"
  475. << html::EscapeText(DirName)
  476. << html::EscapeText(Entry->getName())
  477. << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
  478. "<a href=\"#EndPath\">line "
  479. << LineNumber
  480. << ", column "
  481. << ColumnNumber
  482. << "</a><br />"
  483. << D.getVerboseDescription() << "</td></tr>\n";
  484. // The navigation across the extra notes pieces.
  485. unsigned NumExtraPieces = 0;
  486. for (const auto &Piece : path) {
  487. if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
  488. int LineNumber =
  489. P->getLocation().asLocation().getExpansionLineNumber();
  490. int ColumnNumber =
  491. P->getLocation().asLocation().getExpansionColumnNumber();
  492. os << "<tr><td class=\"rowname\">Note:</td><td>"
  493. << "<a href=\"#Note" << NumExtraPieces << "\">line "
  494. << LineNumber << ", column " << ColumnNumber << "</a><br />"
  495. << P->getString() << "</td></tr>";
  496. ++NumExtraPieces;
  497. }
  498. }
  499. // Output any other meta data.
  500. for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
  501. I != E; ++I) {
  502. os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
  503. }
  504. os << R"<<<(
  505. </table>
  506. <!-- REPORTSUMMARYEXTRA -->
  507. <h3>Annotated Source Code</h3>
  508. <p>Press <a href="#" onclick="toggleHelp(); return false;">'?'</a>
  509. to see keyboard shortcuts</p>
  510. <input type="checkbox" class="spoilerhider" id="showinvocation" />
  511. <label for="showinvocation" >Show analyzer invocation</label>
  512. <div class="spoiler">clang -cc1 )<<<";
  513. os << html::EscapeText(DiagOpts.ToolInvocation);
  514. os << R"<<<(
  515. </div>
  516. <div id='tooltiphint' hidden="true">
  517. <p>Keyboard shortcuts: </p>
  518. <ul>
  519. <li>Use 'j/k' keys for keyboard navigation</li>
  520. <li>Use 'Shift+S' to show/hide relevant lines</li>
  521. <li>Use '?' to toggle this window</li>
  522. </ul>
  523. <a href="#" onclick="toggleHelp(); return false;">Close</a>
  524. </div>
  525. )<<<";
  526. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  527. }
  528. // Embed meta-data tags.
  529. {
  530. std::string s;
  531. llvm::raw_string_ostream os(s);
  532. StringRef BugDesc = D.getVerboseDescription();
  533. if (!BugDesc.empty())
  534. os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
  535. StringRef BugType = D.getBugType();
  536. if (!BugType.empty())
  537. os << "\n<!-- BUGTYPE " << BugType << " -->\n";
  538. PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
  539. FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
  540. ? UPDLoc.asLocation()
  541. : D.getLocation().asLocation()),
  542. SMgr);
  543. StringRef BugCategory = D.getCategory();
  544. if (!BugCategory.empty())
  545. os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
  546. os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
  547. os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
  548. os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
  549. os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT " << getIssueHash(D, PP)
  550. << " -->\n";
  551. os << "\n<!-- BUGLINE "
  552. << LineNumber
  553. << " -->\n";
  554. os << "\n<!-- BUGCOLUMN "
  555. << ColumnNumber
  556. << " -->\n";
  557. os << "\n<!-- BUGPATHLENGTH " << getPathSizeWithoutArrows(path) << " -->\n";
  558. // Mark the end of the tags.
  559. os << "\n<!-- BUGMETAEND -->\n";
  560. // Insert the text.
  561. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  562. }
  563. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  564. }
  565. StringRef HTMLDiagnostics::showHelpJavascript() {
  566. return R"<<<(
  567. <script type='text/javascript'>
  568. var toggleHelp = function() {
  569. var hint = document.querySelector("#tooltiphint");
  570. var attributeName = "hidden";
  571. if (hint.hasAttribute(attributeName)) {
  572. hint.removeAttribute(attributeName);
  573. } else {
  574. hint.setAttribute("hidden", "true");
  575. }
  576. };
  577. window.addEventListener("keydown", function (event) {
  578. if (event.defaultPrevented) {
  579. return;
  580. }
  581. if (event.key == "?") {
  582. toggleHelp();
  583. } else {
  584. return;
  585. }
  586. event.preventDefault();
  587. });
  588. </script>
  589. )<<<";
  590. }
  591. static bool shouldDisplayPopUpRange(const SourceRange &Range) {
  592. return !(Range.getBegin().isMacroID() || Range.getEnd().isMacroID());
  593. }
  594. static void
  595. HandlePopUpPieceStartTag(Rewriter &R,
  596. const std::vector<SourceRange> &PopUpRanges) {
  597. for (const auto &Range : PopUpRanges) {
  598. if (!shouldDisplayPopUpRange(Range))
  599. continue;
  600. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "",
  601. "<table class='variable_popup'><tbody>",
  602. /*IsTokenRange=*/true);
  603. }
  604. }
  605. static void HandlePopUpPieceEndTag(Rewriter &R,
  606. const PathDiagnosticPopUpPiece &Piece,
  607. std::vector<SourceRange> &PopUpRanges,
  608. unsigned int LastReportedPieceIndex,
  609. unsigned int PopUpPieceIndex) {
  610. SmallString<256> Buf;
  611. llvm::raw_svector_ostream Out(Buf);
  612. SourceRange Range(Piece.getLocation().asRange());
  613. if (!shouldDisplayPopUpRange(Range))
  614. return;
  615. // Write out the path indices with a right arrow and the message as a row.
  616. Out << "<tr><td valign='top'><div class='PathIndex PathIndexPopUp'>"
  617. << LastReportedPieceIndex;
  618. // Also annotate the state transition with extra indices.
  619. Out << '.' << PopUpPieceIndex;
  620. Out << "</div></td><td>" << Piece.getString() << "</td></tr>";
  621. // If no report made at this range mark the variable and add the end tags.
  622. if (!llvm::is_contained(PopUpRanges, Range)) {
  623. // Store that we create a report at this range.
  624. PopUpRanges.push_back(Range);
  625. Out << "</tbody></table></span>";
  626. html::HighlightRange(R, Range.getBegin(), Range.getEnd(),
  627. "<span class='variable'>", Buf.c_str(),
  628. /*IsTokenRange=*/true);
  629. } else {
  630. // Otherwise inject just the new row at the end of the range.
  631. html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "", Buf.c_str(),
  632. /*IsTokenRange=*/true);
  633. }
  634. }
  635. void HTMLDiagnostics::RewriteFile(Rewriter &R, const PathPieces &path,
  636. FileID FID) {
  637. // Process the path.
  638. // Maintain the counts of extra note pieces separately.
  639. unsigned TotalPieces = getPathSizeWithoutArrows(path);
  640. unsigned TotalNotePieces =
  641. llvm::count_if(path, [](const PathDiagnosticPieceRef &p) {
  642. return isa<PathDiagnosticNotePiece>(*p);
  643. });
  644. unsigned PopUpPieceCount =
  645. llvm::count_if(path, [](const PathDiagnosticPieceRef &p) {
  646. return isa<PathDiagnosticPopUpPiece>(*p);
  647. });
  648. unsigned TotalRegularPieces = TotalPieces - TotalNotePieces - PopUpPieceCount;
  649. unsigned NumRegularPieces = TotalRegularPieces;
  650. unsigned NumNotePieces = TotalNotePieces;
  651. unsigned NumberOfArrows = 0;
  652. // Stores the count of the regular piece indices.
  653. std::map<int, int> IndexMap;
  654. ArrowMap ArrowIndices(TotalRegularPieces + 1);
  655. // Stores the different ranges where we have reported something.
  656. std::vector<SourceRange> PopUpRanges;
  657. for (const PathDiagnosticPieceRef &I : llvm::reverse(path)) {
  658. const auto &Piece = *I.get();
  659. if (isa<PathDiagnosticPopUpPiece>(Piece)) {
  660. ++IndexMap[NumRegularPieces];
  661. } else if (isa<PathDiagnosticNotePiece>(Piece)) {
  662. // This adds diagnostic bubbles, but not navigation.
  663. // Navigation through note pieces would be added later,
  664. // as a separate pass through the piece list.
  665. HandlePiece(R, FID, Piece, PopUpRanges, NumNotePieces, TotalNotePieces);
  666. --NumNotePieces;
  667. } else if (isArrowPiece(Piece)) {
  668. NumberOfArrows = ProcessControlFlowPiece(
  669. R, FID, cast<PathDiagnosticControlFlowPiece>(Piece), NumberOfArrows);
  670. ArrowIndices[NumRegularPieces] = NumberOfArrows;
  671. } else {
  672. HandlePiece(R, FID, Piece, PopUpRanges, NumRegularPieces,
  673. TotalRegularPieces);
  674. --NumRegularPieces;
  675. ArrowIndices[NumRegularPieces] = ArrowIndices[NumRegularPieces + 1];
  676. }
  677. }
  678. ArrowIndices[0] = NumberOfArrows;
  679. // At this point ArrowIndices represent the following data structure:
  680. // [a_0, a_1, ..., a_N]
  681. // where N is the number of events in the path.
  682. //
  683. // Then for every event with index i \in [0, N - 1], we can say that
  684. // arrows with indices \in [a_(i+1), a_i) correspond to that event.
  685. // We can say that because arrows with these indices appeared in the
  686. // path in between the i-th and the (i+1)-th events.
  687. assert(ArrowIndices.back() == 0 &&
  688. "No arrows should be after the last event");
  689. // This assertion also guarantees that all indices in are <= NumberOfArrows.
  690. assert(llvm::is_sorted(ArrowIndices, std::greater<unsigned>()) &&
  691. "Incorrect arrow indices map");
  692. // Secondary indexing if we are having multiple pop-ups between two notes.
  693. // (e.g. [(13) 'a' is 'true']; [(13.1) 'b' is 'false']; [(13.2) 'c' is...)
  694. NumRegularPieces = TotalRegularPieces;
  695. for (const PathDiagnosticPieceRef &I : llvm::reverse(path)) {
  696. const auto &Piece = *I.get();
  697. if (const auto *PopUpP = dyn_cast<PathDiagnosticPopUpPiece>(&Piece)) {
  698. int PopUpPieceIndex = IndexMap[NumRegularPieces];
  699. // Pop-up pieces needs the index of the last reported piece and its count
  700. // how many times we report to handle multiple reports on the same range.
  701. // This marks the variable, adds the </table> end tag and the message
  702. // (list element) as a row. The <table> start tag will be added after the
  703. // rows has been written out. Note: It stores every different range.
  704. HandlePopUpPieceEndTag(R, *PopUpP, PopUpRanges, NumRegularPieces,
  705. PopUpPieceIndex);
  706. if (PopUpPieceIndex > 0)
  707. --IndexMap[NumRegularPieces];
  708. } else if (!isa<PathDiagnosticNotePiece>(Piece) && !isArrowPiece(Piece)) {
  709. --NumRegularPieces;
  710. }
  711. }
  712. // Add the <table> start tag of pop-up pieces based on the stored ranges.
  713. HandlePopUpPieceStartTag(R, PopUpRanges);
  714. // Add line numbers, header, footer, etc.
  715. html::EscapeText(R, FID);
  716. html::AddLineNumbers(R, FID);
  717. addArrowSVGs(R, FID, ArrowIndices);
  718. // If we have a preprocessor, relex the file and syntax highlight.
  719. // We might not have a preprocessor if we come from a deserialized AST file,
  720. // for example.
  721. html::SyntaxHighlight(R, FID, PP);
  722. html::HighlightMacros(R, FID, PP);
  723. }
  724. void HTMLDiagnostics::HandlePiece(Rewriter &R, FileID BugFileID,
  725. const PathDiagnosticPiece &P,
  726. const std::vector<SourceRange> &PopUpRanges,
  727. unsigned num, unsigned max) {
  728. // For now, just draw a box above the line in question, and emit the
  729. // warning.
  730. FullSourceLoc Pos = P.getLocation().asLocation();
  731. if (!Pos.isValid())
  732. return;
  733. SourceManager &SM = R.getSourceMgr();
  734. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  735. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  736. if (LPosInfo.first != BugFileID)
  737. return;
  738. llvm::MemoryBufferRef Buf = SM.getBufferOrFake(LPosInfo.first);
  739. const char *FileStart = Buf.getBufferStart();
  740. // Compute the column number. Rewind from the current position to the start
  741. // of the line.
  742. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  743. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  744. const char *LineStart = TokInstantiationPtr-ColNo;
  745. // Compute LineEnd.
  746. const char *LineEnd = TokInstantiationPtr;
  747. const char *FileEnd = Buf.getBufferEnd();
  748. while (*LineEnd != '\n' && LineEnd != FileEnd)
  749. ++LineEnd;
  750. // Compute the margin offset by counting tabs and non-tabs.
  751. unsigned PosNo = 0;
  752. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  753. PosNo += *c == '\t' ? 8 : 1;
  754. // Create the html for the message.
  755. const char *Kind = nullptr;
  756. bool IsNote = false;
  757. bool SuppressIndex = (max == 1);
  758. switch (P.getKind()) {
  759. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  760. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  761. // Setting Kind to "Control" is intentional.
  762. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  763. case PathDiagnosticPiece::Note:
  764. Kind = "Note";
  765. IsNote = true;
  766. SuppressIndex = true;
  767. break;
  768. case PathDiagnosticPiece::Call:
  769. case PathDiagnosticPiece::PopUp:
  770. llvm_unreachable("Calls and extra notes should already be handled");
  771. }
  772. std::string sbuf;
  773. llvm::raw_string_ostream os(sbuf);
  774. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  775. if (IsNote)
  776. os << "Note" << num;
  777. else if (num == max)
  778. os << "EndPath";
  779. else
  780. os << "Path" << num;
  781. os << "\" class=\"msg";
  782. if (Kind)
  783. os << " msg" << Kind;
  784. os << "\" style=\"margin-left:" << PosNo << "ex";
  785. // Output a maximum size.
  786. if (!isa<PathDiagnosticMacroPiece>(P)) {
  787. // Get the string and determining its maximum substring.
  788. const auto &Msg = P.getString();
  789. unsigned max_token = 0;
  790. unsigned cnt = 0;
  791. unsigned len = Msg.size();
  792. for (char C : Msg)
  793. switch (C) {
  794. default:
  795. ++cnt;
  796. continue;
  797. case ' ':
  798. case '\t':
  799. case '\n':
  800. if (cnt > max_token) max_token = cnt;
  801. cnt = 0;
  802. }
  803. if (cnt > max_token)
  804. max_token = cnt;
  805. // Determine the approximate size of the message bubble in em.
  806. unsigned em;
  807. const unsigned max_line = 120;
  808. if (max_token >= max_line)
  809. em = max_token / 2;
  810. else {
  811. unsigned characters = max_line;
  812. unsigned lines = len / max_line;
  813. if (lines > 0) {
  814. for (; characters > max_token; --characters)
  815. if (len / characters > lines) {
  816. ++characters;
  817. break;
  818. }
  819. }
  820. em = characters / 2;
  821. }
  822. if (em < max_line/2)
  823. os << "; max-width:" << em << "em";
  824. }
  825. else
  826. os << "; max-width:100em";
  827. os << "\">";
  828. if (!SuppressIndex) {
  829. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  830. os << "<div class=\"PathIndex";
  831. if (Kind) os << " PathIndex" << Kind;
  832. os << "\">" << num << "</div>";
  833. if (num > 1) {
  834. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  835. << (num - 1)
  836. << "\" title=\"Previous event ("
  837. << (num - 1)
  838. << ")\">&#x2190;</a></div>";
  839. }
  840. os << "</td><td>";
  841. }
  842. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  843. os << "Within the expansion of the macro '";
  844. // Get the name of the macro by relexing it.
  845. {
  846. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  847. assert(L.isFileID());
  848. StringRef BufferInfo = L.getBufferData();
  849. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  850. const char* MacroName = LocInfo.second + BufferInfo.data();
  851. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  852. BufferInfo.begin(), MacroName, BufferInfo.end());
  853. Token TheTok;
  854. rawLexer.LexFromRawLexer(TheTok);
  855. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  856. os << MacroName[i];
  857. }
  858. os << "':\n";
  859. if (!SuppressIndex) {
  860. os << "</td>";
  861. if (num < max) {
  862. os << "<td><div class=\"PathNav\"><a href=\"#";
  863. if (num == max - 1)
  864. os << "EndPath";
  865. else
  866. os << "Path" << (num + 1);
  867. os << "\" title=\"Next event ("
  868. << (num + 1)
  869. << ")\">&#x2192;</a></div></td>";
  870. }
  871. os << "</tr></table>";
  872. }
  873. // Within a macro piece. Write out each event.
  874. ProcessMacroPiece(os, *MP, 0);
  875. }
  876. else {
  877. os << html::EscapeText(P.getString());
  878. if (!SuppressIndex) {
  879. os << "</td>";
  880. if (num < max) {
  881. os << "<td><div class=\"PathNav\"><a href=\"#";
  882. if (num == max - 1)
  883. os << "EndPath";
  884. else
  885. os << "Path" << (num + 1);
  886. os << "\" title=\"Next event ("
  887. << (num + 1)
  888. << ")\">&#x2192;</a></div></td>";
  889. }
  890. os << "</tr></table>";
  891. }
  892. }
  893. os << "</div></td></tr>";
  894. // Insert the new html.
  895. unsigned DisplayPos = LineEnd - FileStart;
  896. SourceLocation Loc =
  897. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  898. R.InsertTextBefore(Loc, os.str());
  899. // Now highlight the ranges.
  900. ArrayRef<SourceRange> Ranges = P.getRanges();
  901. for (const auto &Range : Ranges) {
  902. // If we have already highlighted the range as a pop-up there is no work.
  903. if (llvm::is_contained(PopUpRanges, Range))
  904. continue;
  905. HighlightRange(R, LPosInfo.first, Range);
  906. }
  907. }
  908. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  909. unsigned x = n % ('z' - 'a');
  910. n /= 'z' - 'a';
  911. if (n > 0)
  912. EmitAlphaCounter(os, n);
  913. os << char('a' + x);
  914. }
  915. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  916. const PathDiagnosticMacroPiece& P,
  917. unsigned num) {
  918. for (const auto &subPiece : P.subPieces) {
  919. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
  920. num = ProcessMacroPiece(os, *MP, num);
  921. continue;
  922. }
  923. if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
  924. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  925. "margin-left:5px\">"
  926. "<table class=\"msgT\"><tr>"
  927. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  928. EmitAlphaCounter(os, num++);
  929. os << "</div></td><td valign=\"top\">"
  930. << html::EscapeText(EP->getString())
  931. << "</td></tr></table></div>\n";
  932. }
  933. }
  934. return num;
  935. }
  936. void HTMLDiagnostics::addArrowSVGs(Rewriter &R, FileID BugFileID,
  937. const ArrowMap &ArrowIndices) {
  938. std::string S;
  939. llvm::raw_string_ostream OS(S);
  940. OS << R"<<<(
  941. <style type="text/css">
  942. svg {
  943. position:absolute;
  944. top:0;
  945. left:0;
  946. height:100%;
  947. width:100%;
  948. pointer-events: none;
  949. overflow: visible
  950. }
  951. .arrow {
  952. stroke-opacity: 0.2;
  953. stroke-width: 1;
  954. marker-end: url(#arrowhead);
  955. }
  956. .arrow.selected {
  957. stroke-opacity: 0.6;
  958. stroke-width: 2;
  959. marker-end: url(#arrowheadSelected);
  960. }
  961. .arrowhead {
  962. orient: auto;
  963. stroke: none;
  964. opacity: 0.6;
  965. fill: blue;
  966. }
  967. </style>
  968. <svg xmlns="http://www.w3.org/2000/svg">
  969. <defs>
  970. <marker id="arrowheadSelected" class="arrowhead" opacity="0.6"
  971. viewBox="0 0 10 10" refX="3" refY="5"
  972. markerWidth="4" markerHeight="4">
  973. <path d="M 0 0 L 10 5 L 0 10 z" />
  974. </marker>
  975. <marker id="arrowhead" class="arrowhead" opacity="0.2"
  976. viewBox="0 0 10 10" refX="3" refY="5"
  977. markerWidth="4" markerHeight="4">
  978. <path d="M 0 0 L 10 5 L 0 10 z" />
  979. </marker>
  980. </defs>
  981. <g id="arrows" fill="none" stroke="blue" visibility="hidden">
  982. )<<<";
  983. for (unsigned Index : llvm::seq(0u, ArrowIndices.getTotalNumberOfArrows())) {
  984. OS << " <path class=\"arrow\" id=\"arrow" << Index << "\"/>\n";
  985. }
  986. OS << R"<<<(
  987. </g>
  988. </svg>
  989. <script type='text/javascript'>
  990. const arrowIndices = )<<<";
  991. OS << ArrowIndices << "\n</script>\n";
  992. R.InsertTextBefore(R.getSourceMgr().getLocForStartOfFile(BugFileID),
  993. OS.str());
  994. }
  995. std::string getSpanBeginForControl(const char *ClassName, unsigned Index) {
  996. std::string Result;
  997. llvm::raw_string_ostream OS(Result);
  998. OS << "<span id=\"" << ClassName << Index << "\">";
  999. return Result;
  1000. }
  1001. std::string getSpanBeginForControlStart(unsigned Index) {
  1002. return getSpanBeginForControl("start", Index);
  1003. }
  1004. std::string getSpanBeginForControlEnd(unsigned Index) {
  1005. return getSpanBeginForControl("end", Index);
  1006. }
  1007. unsigned HTMLDiagnostics::ProcessControlFlowPiece(
  1008. Rewriter &R, FileID BugFileID, const PathDiagnosticControlFlowPiece &P,
  1009. unsigned Number) {
  1010. for (const PathDiagnosticLocationPair &LPair : P) {
  1011. std::string Start = getSpanBeginForControlStart(Number),
  1012. End = getSpanBeginForControlEnd(Number++);
  1013. HighlightRange(R, BugFileID, LPair.getStart().asRange().getBegin(),
  1014. Start.c_str());
  1015. HighlightRange(R, BugFileID, LPair.getEnd().asRange().getBegin(),
  1016. End.c_str());
  1017. }
  1018. return Number;
  1019. }
  1020. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  1021. SourceRange Range,
  1022. const char *HighlightStart,
  1023. const char *HighlightEnd) {
  1024. SourceManager &SM = R.getSourceMgr();
  1025. const LangOptions &LangOpts = R.getLangOpts();
  1026. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  1027. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  1028. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  1029. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  1030. if (EndLineNo < StartLineNo)
  1031. return;
  1032. if (SM.getFileID(InstantiationStart) != BugFileID ||
  1033. SM.getFileID(InstantiationEnd) != BugFileID)
  1034. return;
  1035. // Compute the column number of the end.
  1036. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  1037. unsigned OldEndColNo = EndColNo;
  1038. if (EndColNo) {
  1039. // Add in the length of the token, so that we cover multi-char tokens.
  1040. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  1041. }
  1042. // Highlight the range. Make the span tag the outermost tag for the
  1043. // selected range.
  1044. SourceLocation E =
  1045. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  1046. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  1047. }
  1048. StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
  1049. return R"<<<(
  1050. <script type='text/javascript'>
  1051. var digitMatcher = new RegExp("[0-9]+");
  1052. var querySelectorAllArray = function(selector) {
  1053. return Array.prototype.slice.call(
  1054. document.querySelectorAll(selector));
  1055. }
  1056. document.addEventListener("DOMContentLoaded", function() {
  1057. querySelectorAllArray(".PathNav > a").forEach(
  1058. function(currentValue, currentIndex) {
  1059. var hrefValue = currentValue.getAttribute("href");
  1060. currentValue.onclick = function() {
  1061. scrollTo(document.querySelector(hrefValue));
  1062. return false;
  1063. };
  1064. });
  1065. });
  1066. var findNum = function() {
  1067. var s = document.querySelector(".msg.selected");
  1068. if (!s || s.id == "EndPath") {
  1069. return 0;
  1070. }
  1071. var out = parseInt(digitMatcher.exec(s.id)[0]);
  1072. return out;
  1073. };
  1074. var classListAdd = function(el, theClass) {
  1075. if(!el.className.baseVal)
  1076. el.className += " " + theClass;
  1077. else
  1078. el.className.baseVal += " " + theClass;
  1079. };
  1080. var classListRemove = function(el, theClass) {
  1081. var className = (!el.className.baseVal) ?
  1082. el.className : el.className.baseVal;
  1083. className = className.replace(" " + theClass, "");
  1084. if(!el.className.baseVal)
  1085. el.className = className;
  1086. else
  1087. el.className.baseVal = className;
  1088. };
  1089. var scrollTo = function(el) {
  1090. querySelectorAllArray(".selected").forEach(function(s) {
  1091. classListRemove(s, "selected");
  1092. });
  1093. classListAdd(el, "selected");
  1094. window.scrollBy(0, el.getBoundingClientRect().top -
  1095. (window.innerHeight / 2));
  1096. highlightArrowsForSelectedEvent();
  1097. };
  1098. var move = function(num, up, numItems) {
  1099. if (num == 1 && up || num == numItems - 1 && !up) {
  1100. return 0;
  1101. } else if (num == 0 && up) {
  1102. return numItems - 1;
  1103. } else if (num == 0 && !up) {
  1104. return 1 % numItems;
  1105. }
  1106. return up ? num - 1 : num + 1;
  1107. }
  1108. var numToId = function(num) {
  1109. if (num == 0) {
  1110. return document.getElementById("EndPath")
  1111. }
  1112. return document.getElementById("Path" + num);
  1113. };
  1114. var navigateTo = function(up) {
  1115. var numItems = document.querySelectorAll(
  1116. ".line > .msgEvent, .line > .msgControl").length;
  1117. var currentSelected = findNum();
  1118. var newSelected = move(currentSelected, up, numItems);
  1119. var newEl = numToId(newSelected, numItems);
  1120. // Scroll element into center.
  1121. scrollTo(newEl);
  1122. };
  1123. window.addEventListener("keydown", function (event) {
  1124. if (event.defaultPrevented) {
  1125. return;
  1126. }
  1127. // key 'j'
  1128. if (event.keyCode == 74) {
  1129. navigateTo(/*up=*/false);
  1130. // key 'k'
  1131. } else if (event.keyCode == 75) {
  1132. navigateTo(/*up=*/true);
  1133. } else {
  1134. return;
  1135. }
  1136. event.preventDefault();
  1137. }, true);
  1138. </script>
  1139. )<<<";
  1140. }
  1141. StringRef HTMLDiagnostics::generateArrowDrawingJavascript() {
  1142. return R"<<<(
  1143. <script type='text/javascript'>
  1144. // Return range of numbers from a range [lower, upper).
  1145. function range(lower, upper) {
  1146. var array = [];
  1147. for (var i = lower; i <= upper; ++i) {
  1148. array.push(i);
  1149. }
  1150. return array;
  1151. }
  1152. var getRelatedArrowIndices = function(pathId) {
  1153. // HTML numeration of events is a bit different than it is in the path.
  1154. // Everything is rotated one step to the right, so the last element
  1155. // (error diagnostic) has index 0.
  1156. if (pathId == 0) {
  1157. // arrowIndices has at least 2 elements
  1158. pathId = arrowIndices.length - 1;
  1159. }
  1160. return range(arrowIndices[pathId], arrowIndices[pathId - 1]);
  1161. }
  1162. var highlightArrowsForSelectedEvent = function() {
  1163. const selectedNum = findNum();
  1164. const arrowIndicesToHighlight = getRelatedArrowIndices(selectedNum);
  1165. arrowIndicesToHighlight.forEach((index) => {
  1166. var arrow = document.querySelector("#arrow" + index);
  1167. if(arrow) {
  1168. classListAdd(arrow, "selected")
  1169. }
  1170. });
  1171. }
  1172. var getAbsoluteBoundingRect = function(element) {
  1173. const relative = element.getBoundingClientRect();
  1174. return {
  1175. left: relative.left + window.pageXOffset,
  1176. right: relative.right + window.pageXOffset,
  1177. top: relative.top + window.pageYOffset,
  1178. bottom: relative.bottom + window.pageYOffset,
  1179. height: relative.height,
  1180. width: relative.width
  1181. };
  1182. }
  1183. var drawArrow = function(index) {
  1184. // This function is based on the great answer from SO:
  1185. // https://stackoverflow.com/a/39575674/11582326
  1186. var start = document.querySelector("#start" + index);
  1187. var end = document.querySelector("#end" + index);
  1188. var arrow = document.querySelector("#arrow" + index);
  1189. var startRect = getAbsoluteBoundingRect(start);
  1190. var endRect = getAbsoluteBoundingRect(end);
  1191. // It is an arrow from a token to itself, no need to visualize it.
  1192. if (startRect.top == endRect.top &&
  1193. startRect.left == endRect.left)
  1194. return;
  1195. // Each arrow is a very simple Bézier curve, with two nodes and
  1196. // two handles. So, we need to calculate four points in the window:
  1197. // * start node
  1198. var posStart = { x: 0, y: 0 };
  1199. // * end node
  1200. var posEnd = { x: 0, y: 0 };
  1201. // * handle for the start node
  1202. var startHandle = { x: 0, y: 0 };
  1203. // * handle for the end node
  1204. var endHandle = { x: 0, y: 0 };
  1205. // One can visualize it as follows:
  1206. //
  1207. // start handle
  1208. // /
  1209. // X"""_.-""""X
  1210. // .' \
  1211. // / start node
  1212. // |
  1213. // |
  1214. // | end node
  1215. // \ /
  1216. // `->X
  1217. // X-'
  1218. // \
  1219. // end handle
  1220. //
  1221. // NOTE: (0, 0) is the top left corner of the window.
  1222. // We have 3 similar, but still different scenarios to cover:
  1223. //
  1224. // 1. Two tokens on different lines.
  1225. // -xxx
  1226. // /
  1227. // \
  1228. // -> xxx
  1229. // In this situation, we draw arrow on the left curving to the left.
  1230. // 2. Two tokens on the same line, and the destination is on the right.
  1231. // ____
  1232. // / \
  1233. // / V
  1234. // xxx xxx
  1235. // In this situation, we draw arrow above curving upwards.
  1236. // 3. Two tokens on the same line, and the destination is on the left.
  1237. // xxx xxx
  1238. // ^ /
  1239. // \____/
  1240. // In this situation, we draw arrow below curving downwards.
  1241. const onDifferentLines = startRect.top <= endRect.top - 5 ||
  1242. startRect.top >= endRect.top + 5;
  1243. const leftToRight = startRect.left < endRect.left;
  1244. // NOTE: various magic constants are chosen empirically for
  1245. // better positioning and look
  1246. if (onDifferentLines) {
  1247. // Case #1
  1248. const topToBottom = startRect.top < endRect.top;
  1249. posStart.x = startRect.left - 1;
  1250. // We don't want to start it at the top left corner of the token,
  1251. // it doesn't feel like this is where the arrow comes from.
  1252. // For this reason, we start it in the middle of the left side
  1253. // of the token.
  1254. posStart.y = startRect.top + startRect.height / 2;
  1255. // End node has arrow head and we give it a bit more space.
  1256. posEnd.x = endRect.left - 4;
  1257. posEnd.y = endRect.top;
  1258. // Utility object with x and y offsets for handles.
  1259. var curvature = {
  1260. // We want bottom-to-top arrow to curve a bit more, so it doesn't
  1261. // overlap much with top-to-bottom curves (much more frequent).
  1262. x: topToBottom ? 15 : 25,
  1263. y: Math.min((posEnd.y - posStart.y) / 3, 10)
  1264. }
  1265. // When destination is on the different line, we can make a
  1266. // curvier arrow because we have space for it.
  1267. // So, instead of using
  1268. //
  1269. // startHandle.x = posStart.x - curvature.x
  1270. // endHandle.x = posEnd.x - curvature.x
  1271. //
  1272. // We use the leftmost of these two values for both handles.
  1273. startHandle.x = Math.min(posStart.x, posEnd.x) - curvature.x;
  1274. endHandle.x = startHandle.x;
  1275. // Curving downwards from the start node...
  1276. startHandle.y = posStart.y + curvature.y;
  1277. // ... and upwards from the end node.
  1278. endHandle.y = posEnd.y - curvature.y;
  1279. } else if (leftToRight) {
  1280. // Case #2
  1281. // Starting from the top right corner...
  1282. posStart.x = startRect.right - 1;
  1283. posStart.y = startRect.top;
  1284. // ...and ending at the top left corner of the end token.
  1285. posEnd.x = endRect.left + 1;
  1286. posEnd.y = endRect.top - 1;
  1287. // Utility object with x and y offsets for handles.
  1288. var curvature = {
  1289. x: Math.min((posEnd.x - posStart.x) / 3, 15),
  1290. y: 5
  1291. }
  1292. // Curving to the right...
  1293. startHandle.x = posStart.x + curvature.x;
  1294. // ... and upwards from the start node.
  1295. startHandle.y = posStart.y - curvature.y;
  1296. // And to the left...
  1297. endHandle.x = posEnd.x - curvature.x;
  1298. // ... and upwards from the end node.
  1299. endHandle.y = posEnd.y - curvature.y;
  1300. } else {
  1301. // Case #3
  1302. // Starting from the bottom right corner...
  1303. posStart.x = startRect.right;
  1304. posStart.y = startRect.bottom;
  1305. // ...and ending also at the bottom right corner, but of the end token.
  1306. posEnd.x = endRect.right - 1;
  1307. posEnd.y = endRect.bottom + 1;
  1308. // Utility object with x and y offsets for handles.
  1309. var curvature = {
  1310. x: Math.min((posStart.x - posEnd.x) / 3, 15),
  1311. y: 5
  1312. }
  1313. // Curving to the left...
  1314. startHandle.x = posStart.x - curvature.x;
  1315. // ... and downwards from the start node.
  1316. startHandle.y = posStart.y + curvature.y;
  1317. // And to the right...
  1318. endHandle.x = posEnd.x + curvature.x;
  1319. // ... and downwards from the end node.
  1320. endHandle.y = posEnd.y + curvature.y;
  1321. }
  1322. // Put it all together into a path.
  1323. // More information on the format:
  1324. // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths
  1325. var pathStr = "M" + posStart.x + "," + posStart.y + " " +
  1326. "C" + startHandle.x + "," + startHandle.y + " " +
  1327. endHandle.x + "," + endHandle.y + " " +
  1328. posEnd.x + "," + posEnd.y;
  1329. arrow.setAttribute("d", pathStr);
  1330. };
  1331. var drawArrows = function() {
  1332. const numOfArrows = document.querySelectorAll("path[id^=arrow]").length;
  1333. for (var i = 0; i < numOfArrows; ++i) {
  1334. drawArrow(i);
  1335. }
  1336. }
  1337. var toggleArrows = function(event) {
  1338. const arrows = document.querySelector("#arrows");
  1339. if (event.target.checked) {
  1340. arrows.setAttribute("visibility", "visible");
  1341. } else {
  1342. arrows.setAttribute("visibility", "hidden");
  1343. }
  1344. }
  1345. window.addEventListener("resize", drawArrows);
  1346. document.addEventListener("DOMContentLoaded", function() {
  1347. // Whenever we show invocation, locations change, i.e. we
  1348. // need to redraw arrows.
  1349. document
  1350. .querySelector('input[id="showinvocation"]')
  1351. .addEventListener("click", drawArrows);
  1352. // Hiding irrelevant lines also should cause arrow rerender.
  1353. document
  1354. .querySelector('input[name="showCounterexample"]')
  1355. .addEventListener("change", drawArrows);
  1356. document
  1357. .querySelector('input[name="showArrows"]')
  1358. .addEventListener("change", toggleArrows);
  1359. drawArrows();
  1360. // Default highlighting for the last event.
  1361. highlightArrowsForSelectedEvent();
  1362. });
  1363. </script>
  1364. )<<<";
  1365. }