1 //===- HTMLDiagnostics.cpp - HTML Diagnostics for Paths -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the HTMLDiagnostics object.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/AST/Stmt.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/Token.h"
24 #include "clang/Rewrite/Core/HTMLRewrite.h"
25 #include "clang/Rewrite/Core/Rewriter.h"
26 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
27 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
28 #include "clang/StaticAnalyzer/Core/IssueHash.h"
29 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
30 #include "llvm/ADT/ArrayRef.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"
48 #include <system_error>
52 using namespace clang;
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
61 class HTMLDiagnostics : public PathDiagnosticConsumer {
62 std::string Directory;
63 bool createdDir = false;
65 const Preprocessor &PP;
66 AnalyzerOptions &AnalyzerOpts;
67 const bool SupportsCrossFileDiagnostics;
70 HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts,
71 const std::string& prefix,
72 const Preprocessor &pp,
73 bool supportsMultipleFiles)
74 : Directory(prefix), PP(pp), AnalyzerOpts(AnalyzerOpts),
75 SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
77 ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
79 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
80 FilesMade *filesMade) override;
82 StringRef getName() const override {
83 return "HTMLDiagnostics";
86 bool supportsCrossFileDiagnostics() const override {
87 return SupportsCrossFileDiagnostics;
90 unsigned ProcessMacroPiece(raw_ostream &os,
91 const PathDiagnosticMacroPiece& P,
94 void HandlePiece(Rewriter& R, FileID BugFileID,
95 const PathDiagnosticPiece& P, unsigned num, unsigned max);
97 void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
98 const char *HighlightStart = "<span class=\"mrange\">",
99 const char *HighlightEnd = "</span>");
101 void ReportDiag(const PathDiagnostic& D,
102 FilesMade *filesMade);
104 // Generate the full HTML report
105 std::string GenerateHTML(const PathDiagnostic& D, Rewriter &R,
106 const SourceManager& SMgr, const PathPieces& path,
107 const char *declName);
109 // Add HTML header/footers to file specified by FID
110 void FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
111 const SourceManager& SMgr, const PathPieces& path,
112 FileID FID, const FileEntry *Entry, const char *declName);
114 // Rewrite the file specified by FID with HTML formatting.
115 void RewriteFile(Rewriter &R, const SourceManager& SMgr,
116 const PathPieces& path, FileID FID);
118 /// \return Javascript for navigating the HTML report using j/k keys.
119 std::string generateKeyboardNavigationJavascript();
122 /// \return Javascript for displaying shortcuts help;
123 std::string showHelpJavascript();
128 void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
129 PathDiagnosticConsumers &C,
130 const std::string& prefix,
131 const Preprocessor &PP) {
132 C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, true));
135 void ento::createHTMLSingleFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
136 PathDiagnosticConsumers &C,
137 const std::string& prefix,
138 const Preprocessor &PP) {
139 C.push_back(new HTMLDiagnostics(AnalyzerOpts, prefix, PP, false));
142 //===----------------------------------------------------------------------===//
143 // Report processing.
144 //===----------------------------------------------------------------------===//
146 void HTMLDiagnostics::FlushDiagnosticsImpl(
147 std::vector<const PathDiagnostic *> &Diags,
148 FilesMade *filesMade) {
149 for (const auto Diag : Diags)
150 ReportDiag(*Diag, filesMade);
153 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
154 FilesMade *filesMade) {
155 // Create the HTML directory if it is missing.
158 if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
159 llvm::errs() << "warning: could not create directory '"
160 << Directory << "': " << ec.message() << '\n';
169 // First flatten out the entire path to make it easier to use.
170 PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
172 // The path as already been prechecked that the path is non-empty.
173 assert(!path.empty());
174 const SourceManager &SMgr = path.front()->getLocation().getManager();
176 // Create a new rewriter to generate HTML.
177 Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
179 // The file for the first path element is considered the main report file, it
180 // will usually be equivalent to SMgr.getMainFileID(); however, it might be a
181 // header when -analyzer-opt-analyze-headers is used.
182 FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
184 // Get the function/method name
185 SmallString<128> declName("unknown");
187 if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
188 if (const auto *ND = dyn_cast<NamedDecl>(DeclWithIssue))
189 declName = ND->getDeclName().getAsString();
191 if (const Stmt *Body = DeclWithIssue->getBody()) {
192 // Retrieve the relative position of the declaration which will be used
195 SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
197 FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getLocStart()), SMgr);
198 offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
202 std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
203 if (report.empty()) {
204 llvm::errs() << "warning: no diagnostics generated for main file.\n";
208 // Create a path for the target HTML file.
210 SmallString<128> Model, ResultPath;
212 if (!AnalyzerOpts.shouldWriteStableReportFilename()) {
213 llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
214 if (std::error_code EC =
215 llvm::sys::fs::make_absolute(Model)) {
216 llvm::errs() << "warning: could not make '" << Model
217 << "' absolute: " << EC.message() << '\n';
220 if (std::error_code EC =
221 llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
222 llvm::errs() << "warning: could not create file in '" << Directory
223 << "': " << EC.message() << '\n';
230 // Find a filename which is not already used
231 const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
232 std::stringstream filename;
234 filename << "report-"
235 << llvm::sys::path::filename(Entry->getName()).str()
236 << "-" << declName.c_str()
238 << "-" << i << ".html";
239 llvm::sys::path::append(Model, Directory,
241 EC = llvm::sys::fs::openFileForReadWrite(
242 Model, FD, llvm::sys::fs::CD_CreateNew, llvm::sys::fs::OF_None);
243 if (EC && EC != llvm::errc::file_exists) {
244 llvm::errs() << "warning: could not create file '" << Model
245 << "': " << EC.message() << '\n';
252 llvm::raw_fd_ostream os(FD, true);
255 filesMade->addDiagnostic(D, getName(),
256 llvm::sys::path::filename(ResultPath));
258 // Emit the HTML to disk.
262 std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
263 const SourceManager& SMgr, const PathPieces& path, const char *declName) {
264 // Rewrite source files as HTML for every new file the path crosses
265 std::vector<FileID> FileIDs;
266 for (auto I : path) {
267 FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
268 if (std::find(FileIDs.begin(), FileIDs.end(), FID) != FileIDs.end())
271 FileIDs.push_back(FID);
272 RewriteFile(R, SMgr, path, FID);
275 if (SupportsCrossFileDiagnostics && FileIDs.size() > 1) {
276 // Prefix file names, anchor tags, and nav cursors to every file
277 for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; I++) {
279 llvm::raw_string_ostream os(s);
281 if (I != FileIDs.begin())
282 os << "<hr class=divider>\n";
284 os << "<div id=File" << I->getHashValue() << ">\n";
287 if (I != FileIDs.begin())
288 os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
289 << "\">←</a></div>";
291 os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
296 os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
297 << "\">→</a></div>";
301 R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
304 // Append files to the main report file in the order they appear in the path
305 for (auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
307 llvm::raw_string_ostream os(s);
309 const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
313 R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
317 const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
321 // Add CSS, header, and footer.
323 path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
324 const FileEntry* Entry = SMgr.getFileEntryForID(FID);
325 FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
328 llvm::raw_string_ostream os(file);
335 /// Write executed lines from \p D in JSON format into \p os.
336 static void serializeExecutedLines(
337 const PathDiagnostic &D,
338 const PathPieces &path,
339 llvm::raw_string_ostream &os) {
340 // Copy executed lines from path diagnostics.
341 std::map<unsigned, std::set<unsigned>> ExecutedLines;
342 for (auto I = D.executedLines_begin(),
343 E = D.executedLines_end(); I != E; ++I) {
344 std::set<unsigned> &LinesInFile = ExecutedLines[I->first];
345 for (unsigned LineNo : I->second) {
346 LinesInFile.insert(LineNo);
350 // We need to include all lines for which any kind of diagnostics appears.
351 for (const auto &P : path) {
352 FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
353 FileID FID = Loc.getFileID();
354 unsigned LineNo = Loc.getLineNumber();
355 ExecutedLines[FID.getHashValue()].insert(LineNo);
358 os << "var relevant_lines = {";
359 for (auto I = ExecutedLines.begin(),
360 E = ExecutedLines.end(); I != E; ++I) {
361 if (I != ExecutedLines.begin())
364 os << "\"" << I->first << "\": {";
365 for (unsigned LineNo : I->second) {
366 if (LineNo != *(I->second.begin()))
369 os << "\"" << LineNo << "\": 1";
377 /// \return JavaScript for an option to only show relevant lines.
378 static std::string showRelevantLinesJavascript(
379 const PathDiagnostic &D, const PathPieces &path) {
381 llvm::raw_string_ostream os(s);
382 os << "<script type='text/javascript'>\n";
383 serializeExecutedLines(D, path, os);
386 var filterCounterexample = function (hide) {
387 var tables = document.getElementsByClassName("code");
388 for (var t=0; t<tables.length; t++) {
389 var table = tables[t];
390 var file_id = table.getAttribute("data-fileid");
391 var lines_in_fid = relevant_lines[file_id];
395 var lines = table.getElementsByClassName("codeline");
396 for (var i=0; i<lines.length; i++) {
398 var lineNo = el.getAttribute("data-linenumber");
399 if (!lines_in_fid[lineNo]) {
401 el.setAttribute("hidden", "");
403 el.removeAttribute("hidden");
410 window.addEventListener("keydown", function (event) {
411 if (event.defaultPrevented) {
414 if (event.key == "S") {
415 var checked = document.getElementsByName("showCounterexample")[0].checked;
416 filterCounterexample(!checked);
417 document.getElementsByName("showCounterexample")[0].checked = !checked;
421 event.preventDefault();
424 document.addEventListener("DOMContentLoaded", function() {
425 document.querySelector('input[name="showCounterexample"]').onchange=
427 filterCounterexample(this.checked);
433 <input type="checkbox" name="showCounterexample" id="showCounterexample" />
434 <label for="showCounterexample">
435 Show only relevant lines
443 void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
444 const SourceManager& SMgr, const PathPieces& path, FileID FID,
445 const FileEntry *Entry, const char *declName) {
446 // This is a cludge; basically we want to append either the full
447 // working directory if we have no directory information. This is
448 // a work in progress.
450 llvm::SmallString<0> DirName;
452 if (llvm::sys::path::is_relative(Entry->getName())) {
453 llvm::sys::fs::current_path(DirName);
457 int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
458 int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
460 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), showHelpJavascript());
462 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
463 generateKeyboardNavigationJavascript());
465 // Checkbox and javascript for filtering the output to the counterexample.
466 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
467 showRelevantLinesJavascript(D, path));
469 // Add the name of the file as an <h1> tag.
472 llvm::raw_string_ostream os(s);
474 os << "<!-- REPORTHEADER -->\n"
475 << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
476 "<tr><td class=\"rowname\">File:</td><td>"
477 << html::EscapeText(DirName)
478 << html::EscapeText(Entry->getName())
479 << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
480 "<a href=\"#EndPath\">line "
485 << D.getVerboseDescription() << "</td></tr>\n";
487 // The navigation across the extra notes pieces.
488 unsigned NumExtraPieces = 0;
489 for (const auto &Piece : path) {
490 if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
492 P->getLocation().asLocation().getExpansionLineNumber();
494 P->getLocation().asLocation().getExpansionColumnNumber();
495 os << "<tr><td class=\"rowname\">Note:</td><td>"
496 << "<a href=\"#Note" << NumExtraPieces << "\">line "
497 << LineNumber << ", column " << ColumnNumber << "</a><br />"
498 << P->getString() << "</td></tr>";
503 // Output any other meta data.
505 for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
507 os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
512 <!-- REPORTSUMMARYEXTRA -->
513 <h3>Annotated Source Code</h3>
514 <p>Press <a href="#" onclick="toggleHelp(); return false;">'?'</a>
515 to see keyboard shortcuts</p>
516 <input type="checkbox" class="spoilerhider" id="showinvocation" />
517 <label for="showinvocation" >Show analyzer invocation</label>
518 <div class="spoiler">clang -cc1 )<<<";
519 os << html::EscapeText(AnalyzerOpts.FullCompilerInvocation);
522 <div id='tooltiphint' hidden="true">
523 <p>Keyboard shortcuts: </p>
525 <li>Use 'j/k' keys for keyboard navigation</li>
526 <li>Use 'Shift+S' to show/hide relevant lines</li>
527 <li>Use '?' to toggle this window</li>
529 <a href="#" onclick="toggleHelp(); return false;">Close</a>
532 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
535 // Embed meta-data tags.
538 llvm::raw_string_ostream os(s);
540 StringRef BugDesc = D.getVerboseDescription();
541 if (!BugDesc.empty())
542 os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
544 StringRef BugType = D.getBugType();
545 if (!BugType.empty())
546 os << "\n<!-- BUGTYPE " << BugType << " -->\n";
548 PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
549 FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
550 ? UPDLoc.asLocation()
551 : D.getLocation().asLocation()),
553 const Decl *DeclWithIssue = D.getDeclWithIssue();
555 StringRef BugCategory = D.getCategory();
556 if (!BugCategory.empty())
557 os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
559 os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
561 os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
563 os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
565 os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
566 << GetIssueHash(SMgr, L, D.getCheckName(), D.getBugType(), DeclWithIssue,
567 PP.getLangOpts()) << " -->\n";
569 os << "\n<!-- BUGLINE "
573 os << "\n<!-- BUGCOLUMN "
577 os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
579 // Mark the end of the tags.
580 os << "\n<!-- BUGMETAEND -->\n";
583 R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
586 html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
589 std::string HTMLDiagnostics::showHelpJavascript() {
591 <script type='text/javascript'>
593 var toggleHelp = function() {
594 var hint = document.querySelector("#tooltiphint");
595 var attributeName = "hidden";
596 if (hint.hasAttribute(attributeName)) {
597 hint.removeAttribute(attributeName);
599 hint.setAttribute("hidden", "true");
602 window.addEventListener("keydown", function (event) {
603 if (event.defaultPrevented) {
606 if (event.key == "?") {
611 event.preventDefault();
617 void HTMLDiagnostics::RewriteFile(Rewriter &R, const SourceManager& SMgr,
618 const PathPieces& path, FileID FID) {
620 // Maintain the counts of extra note pieces separately.
621 unsigned TotalPieces = path.size();
622 unsigned TotalNotePieces =
623 std::count_if(path.begin(), path.end(),
624 [](const std::shared_ptr<PathDiagnosticPiece> &p) {
625 return isa<PathDiagnosticNotePiece>(*p);
628 unsigned TotalRegularPieces = TotalPieces - TotalNotePieces;
629 unsigned NumRegularPieces = TotalRegularPieces;
630 unsigned NumNotePieces = TotalNotePieces;
632 for (auto I = path.rbegin(), E = path.rend(); I != E; ++I) {
633 if (isa<PathDiagnosticNotePiece>(I->get())) {
634 // This adds diagnostic bubbles, but not navigation.
635 // Navigation through note pieces would be added later,
636 // as a separate pass through the piece list.
637 HandlePiece(R, FID, **I, NumNotePieces, TotalNotePieces);
640 HandlePiece(R, FID, **I, NumRegularPieces, TotalRegularPieces);
645 // Add line numbers, header, footer, etc.
647 html::EscapeText(R, FID);
648 html::AddLineNumbers(R, FID);
650 // If we have a preprocessor, relex the file and syntax highlight.
651 // We might not have a preprocessor if we come from a deserialized AST file,
654 html::SyntaxHighlight(R, FID, PP);
655 html::HighlightMacros(R, FID, PP);
658 void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
659 const PathDiagnosticPiece& P,
660 unsigned num, unsigned max) {
661 // For now, just draw a box above the line in question, and emit the
663 FullSourceLoc Pos = P.getLocation().asLocation();
668 SourceManager &SM = R.getSourceMgr();
669 assert(&Pos.getManager() == &SM && "SourceManagers are different!");
670 std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
672 if (LPosInfo.first != BugFileID)
675 const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
676 const char* FileStart = Buf->getBufferStart();
678 // Compute the column number. Rewind from the current position to the start
680 unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
681 const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
682 const char *LineStart = TokInstantiationPtr-ColNo;
685 const char *LineEnd = TokInstantiationPtr;
686 const char* FileEnd = Buf->getBufferEnd();
687 while (*LineEnd != '\n' && LineEnd != FileEnd)
690 // Compute the margin offset by counting tabs and non-tabs.
692 for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
693 PosNo += *c == '\t' ? 8 : 1;
695 // Create the html for the message.
697 const char *Kind = nullptr;
699 bool SuppressIndex = (max == 1);
700 switch (P.getKind()) {
701 case PathDiagnosticPiece::Call:
702 llvm_unreachable("Calls and extra notes should already be handled");
703 case PathDiagnosticPiece::Event: Kind = "Event"; break;
704 case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
705 // Setting Kind to "Control" is intentional.
706 case PathDiagnosticPiece::Macro: Kind = "Control"; break;
707 case PathDiagnosticPiece::Note:
710 SuppressIndex = true;
715 llvm::raw_string_ostream os(sbuf);
717 os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
726 os << "\" class=\"msg";
728 os << " msg" << Kind;
729 os << "\" style=\"margin-left:" << PosNo << "ex";
731 // Output a maximum size.
732 if (!isa<PathDiagnosticMacroPiece>(P)) {
733 // Get the string and determining its maximum substring.
734 const auto &Msg = P.getString();
735 unsigned max_token = 0;
737 unsigned len = Msg.size();
747 if (cnt > max_token) max_token = cnt;
754 // Determine the approximate size of the message bubble in em.
756 const unsigned max_line = 120;
758 if (max_token >= max_line)
761 unsigned characters = max_line;
762 unsigned lines = len / max_line;
765 for (; characters > max_token; --characters)
766 if (len / characters > lines) {
776 os << "; max-width:" << em << "em";
779 os << "; max-width:100em";
783 if (!SuppressIndex) {
784 os << "<table class=\"msgT\"><tr><td valign=\"top\">";
785 os << "<div class=\"PathIndex";
786 if (Kind) os << " PathIndex" << Kind;
787 os << "\">" << num << "</div>";
790 os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
792 << "\" title=\"Previous event ("
794 << ")\">←</a></div></td>";
800 if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
801 os << "Within the expansion of the macro '";
803 // Get the name of the macro by relexing it.
805 FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
806 assert(L.isFileID());
807 StringRef BufferInfo = L.getBufferData();
808 std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
809 const char* MacroName = LocInfo.second + BufferInfo.data();
810 Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
811 BufferInfo.begin(), MacroName, BufferInfo.end());
814 rawLexer.LexFromRawLexer(TheTok);
815 for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
821 if (!SuppressIndex) {
824 os << "<td><div class=\"PathNav\"><a href=\"#";
828 os << "Path" << (num + 1);
829 os << "\" title=\"Next event ("
831 << ")\">→</a></div></td>";
834 os << "</tr></table>";
837 // Within a macro piece. Write out each event.
838 ProcessMacroPiece(os, *MP, 0);
841 os << html::EscapeText(P.getString());
843 if (!SuppressIndex) {
846 os << "<td><div class=\"PathNav\"><a href=\"#";
850 os << "Path" << (num + 1);
851 os << "\" title=\"Next event ("
853 << ")\">→</a></div></td>";
856 os << "</tr></table>";
860 os << "</div></td></tr>";
862 // Insert the new html.
863 unsigned DisplayPos = LineEnd - FileStart;
865 SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
867 R.InsertTextBefore(Loc, os.str());
869 // Now highlight the ranges.
870 ArrayRef<SourceRange> Ranges = P.getRanges();
871 for (const auto &Range : Ranges)
872 HighlightRange(R, LPosInfo.first, Range);
875 static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
876 unsigned x = n % ('z' - 'a');
880 EmitAlphaCounter(os, n);
885 unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
886 const PathDiagnosticMacroPiece& P,
888 for (const auto &subPiece : P.subPieces) {
889 if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
890 num = ProcessMacroPiece(os, *MP, num);
894 if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
895 os << "<div class=\"msg msgEvent\" style=\"width:94%; "
897 "<table class=\"msgT\"><tr>"
898 "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
899 EmitAlphaCounter(os, num++);
900 os << "</div></td><td valign=\"top\">"
901 << html::EscapeText(EP->getString())
902 << "</td></tr></table></div>\n";
909 void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
911 const char *HighlightStart,
912 const char *HighlightEnd) {
913 SourceManager &SM = R.getSourceMgr();
914 const LangOptions &LangOpts = R.getLangOpts();
916 SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
917 unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
919 SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
920 unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
922 if (EndLineNo < StartLineNo)
925 if (SM.getFileID(InstantiationStart) != BugFileID ||
926 SM.getFileID(InstantiationEnd) != BugFileID)
929 // Compute the column number of the end.
930 unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
931 unsigned OldEndColNo = EndColNo;
934 // Add in the length of the token, so that we cover multi-char tokens.
935 EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
938 // Highlight the range. Make the span tag the outermost tag for the
942 InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
944 html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
947 std::string HTMLDiagnostics::generateKeyboardNavigationJavascript() {
949 <script type='text/javascript'>
950 var digitMatcher = new RegExp("[0-9]+");
952 document.addEventListener("DOMContentLoaded", function() {
953 document.querySelectorAll(".PathNav > a").forEach(
954 function(currentValue, currentIndex) {
955 var hrefValue = currentValue.getAttribute("href");
956 currentValue.onclick = function() {
957 scrollTo(document.querySelector(hrefValue));
963 var findNum = function() {
964 var s = document.querySelector(".selected");
965 if (!s || s.id == "EndPath") {
968 var out = parseInt(digitMatcher.exec(s.id)[0]);
972 var scrollTo = function(el) {
973 document.querySelectorAll(".selected").forEach(function(s) {
974 s.classList.remove("selected");
976 el.classList.add("selected");
977 window.scrollBy(0, el.getBoundingClientRect().top -
978 (window.innerHeight / 2));
981 var move = function(num, up, numItems) {
982 if (num == 1 && up || num == numItems - 1 && !up) {
984 } else if (num == 0 && up) {
986 } else if (num == 0 && !up) {
989 return up ? num - 1 : num + 1;
992 var numToId = function(num) {
994 return document.getElementById("EndPath")
996 return document.getElementById("Path" + num);
999 var navigateTo = function(up) {
1000 var numItems = document.querySelectorAll(".line > .msg").length;
1001 var currentSelected = findNum();
1002 var newSelected = move(currentSelected, up, numItems);
1003 var newEl = numToId(newSelected, numItems);
1005 // Scroll element into center.
1009 window.addEventListener("keydown", function (event) {
1010 if (event.defaultPrevented) {
1013 if (event.key == "j") {
1014 navigateTo(/*up=*/false);
1015 } else if (event.key == "k") {
1016 navigateTo(/*up=*/true);
1020 event.preventDefault();