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