Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
Line
Count
Source (jump to first uncovered line)
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/Analysis/PathDiagnostic.h"
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/IssueHash.h"
28
#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
29
#include "llvm/ADT/ArrayRef.h"
30
#include "llvm/ADT/SmallString.h"
31
#include "llvm/ADT/StringRef.h"
32
#include "llvm/ADT/iterator_range.h"
33
#include "llvm/Support/Casting.h"
34
#include "llvm/Support/Errc.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/FileSystem.h"
37
#include "llvm/Support/MemoryBuffer.h"
38
#include "llvm/Support/Path.h"
39
#include "llvm/Support/raw_ostream.h"
40
#include <algorithm>
41
#include <cassert>
42
#include <map>
43
#include <memory>
44
#include <set>
45
#include <sstream>
46
#include <string>
47
#include <system_error>
48
#include <utility>
49
#include <vector>
50
51
using namespace clang;
52
using namespace ento;
53
54
//===----------------------------------------------------------------------===//
55
// Boilerplate.
56
//===----------------------------------------------------------------------===//
57
58
namespace {
59
60
class HTMLDiagnostics : public PathDiagnosticConsumer {
61
  std::string Directory;
62
  bool createdDir = false;
63
  bool noDir = false;
64
  const Preprocessor &PP;
65
  AnalyzerOptions &AnalyzerOpts;
66
  const bool SupportsCrossFileDiagnostics;
67
68
public:
69
  HTMLDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string &OutputDir,
70
                  const Preprocessor &pp, bool supportsMultipleFiles)
71
      : Directory(OutputDir), PP(pp), AnalyzerOpts(AnalyzerOpts),
72
45
        SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
73
74
45
  ~HTMLDiagnostics() override { FlushDiagnostics(nullptr); }
75
76
  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
77
                            FilesMade *filesMade) override;
78
79
94
  StringRef getName() const override {
80
94
    return "HTMLDiagnostics";
81
94
  }
82
83
101
  bool supportsCrossFileDiagnostics() const override {
84
101
    return SupportsCrossFileDiagnostics;
85
101
  }
86
87
  unsigned ProcessMacroPiece(raw_ostream &os,
88
                             const PathDiagnosticMacroPiece& P,
89
                             unsigned num);
90
91
  void HandlePiece(Rewriter &R, FileID BugFileID, const PathDiagnosticPiece &P,
92
                   const std::vector<SourceRange> &PopUpRanges, unsigned num,
93
                   unsigned max);
94
95
  void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
96
                      const char *HighlightStart = "<span class=\"mrange\">",
97
                      const char *HighlightEnd = "</span>");
98
99
  void ReportDiag(const PathDiagnostic& D,
100
                  FilesMade *filesMade);
101
102
  // Generate the full HTML report
103
  std::string GenerateHTML(const PathDiagnostic& D, Rewriter &R,
104
                           const SourceManager& SMgr, const PathPieces& path,
105
                           const char *declName);
106
107
  // Add HTML header/footers to file specified by FID
108
  void FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
109
                    const SourceManager& SMgr, const PathPieces& path,
110
                    FileID FID, const FileEntry *Entry, const char *declName);
111
112
  // Rewrite the file specified by FID with HTML formatting.
113
  void RewriteFile(Rewriter &R, const PathPieces& path, FileID FID);
114
115
116
private:
117
  /// \return Javascript for displaying shortcuts help;
118
  StringRef showHelpJavascript();
119
120
  /// \return Javascript for navigating the HTML report using j/k keys.
121
  StringRef generateKeyboardNavigationJavascript();
122
123
  /// \return JavaScript for an option to only show relevant lines.
124
  std::string showRelevantLinesJavascript(
125
    const PathDiagnostic &D, const PathPieces &path);
126
127
  /// Write executed lines from \p D in JSON format into \p os.
128
  void dumpCoverageData(const PathDiagnostic &D,
129
                        const PathPieces &path,
130
                        llvm::raw_string_ostream &os);
131
};
132
133
} // namespace
134
135
void ento::createHTMLDiagnosticConsumer(
136
    AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
137
    const std::string &OutputDir, const Preprocessor &PP,
138
1.14k
    const cross_tu::CrossTranslationUnitContext &CTU) {
139
140
  // FIXME: HTML is currently our default output type, but if the output
141
  // directory isn't specified, it acts like if it was in the minimal text
142
  // output mode. This doesn't make much sense, we should have the minimal text
143
  // as our default. In the case of backward compatibility concerns, this could
144
  // be preserved with -analyzer-config-compatibility-mode=true.
145
1.14k
  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
146
147
  // TODO: Emit an error here.
148
1.14k
  if (OutputDir.empty())
149
1.09k
    return;
150
151
42
  C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, true));
152
42
}
153
154
void ento::createHTMLSingleFileDiagnosticConsumer(
155
    AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
156
    const std::string &OutputDir, const Preprocessor &PP,
157
3
    const cross_tu::CrossTranslationUnitContext &CTU) {
158
159
  // TODO: Emit an error here.
160
3
  if (OutputDir.empty())
161
0
    return;
162
163
3
  C.push_back(new HTMLDiagnostics(AnalyzerOpts, OutputDir, PP, false));
164
3
  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, OutputDir, PP, CTU);
165
3
}
166
167
void ento::createPlistHTMLDiagnosticConsumer(
168
    AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
169
    const std::string &prefix, const Preprocessor &PP,
170
2
    const cross_tu::CrossTranslationUnitContext &CTU) {
171
2
  createHTMLDiagnosticConsumer(
172
2
      AnalyzerOpts, C, std::string(llvm::sys::path::parent_path(prefix)), PP,
173
2
      CTU);
174
2
  createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP, CTU);
175
2
  createTextMinimalPathDiagnosticConsumer(AnalyzerOpts, C, prefix, PP, CTU);
176
2
}
177
178
//===----------------------------------------------------------------------===//
179
// Report processing.
180
//===----------------------------------------------------------------------===//
181
182
void HTMLDiagnostics::FlushDiagnosticsImpl(
183
  std::vector<const PathDiagnostic *> &Diags,
184
45
  FilesMade *filesMade) {
185
45
  for (const auto Diag : Diags)
186
97
    ReportDiag(*Diag, filesMade);
187
45
}
188
189
void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
190
97
                                 FilesMade *filesMade) {
191
  // Create the HTML directory if it is missing.
192
97
  if (!createdDir) {
193
41
    createdDir = true;
194
41
    if (std::error_code ec = llvm::sys::fs::create_directories(Directory)) {
195
0
      llvm::errs() << "warning: could not create directory '"
196
0
                   << Directory << "': " << ec.message() << '\n';
197
0
      noDir = true;
198
0
      return;
199
0
    }
200
97
  }
201
202
97
  if (noDir)
203
0
    return;
204
205
  // First flatten out the entire path to make it easier to use.
206
97
  PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
207
208
  // The path as already been prechecked that the path is non-empty.
209
97
  assert(!path.empty());
210
97
  const SourceManager &SMgr = path.front()->getLocation().getManager();
211
212
  // Create a new rewriter to generate HTML.
213
97
  Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
214
215
  // The file for the first path element is considered the main report file, it
216
  // will usually be equivalent to SMgr.getMainFileID(); however, it might be a
217
  // header when -analyzer-opt-analyze-headers is used.
218
97
  FileID ReportFile = path.front()->getLocation().asLocation().getExpansionLoc().getFileID();
219
220
  // Get the function/method name
221
97
  SmallString<128> declName("unknown");
222
97
  int offsetDecl = 0;
223
97
  if (const Decl *DeclWithIssue = D.getDeclWithIssue()) {
224
97
      if (const auto *ND = dyn_cast<NamedDecl>(DeclWithIssue))
225
95
          declName = ND->getDeclName().getAsString();
226
227
97
      if (const Stmt *Body = DeclWithIssue->getBody()) {
228
          // Retrieve the relative position of the declaration which will be used
229
          // for the file name
230
97
          FullSourceLoc L(
231
97
              SMgr.getExpansionLoc(path.back()->getLocation().asLocation()),
232
97
              SMgr);
233
97
          FullSourceLoc FunL(SMgr.getExpansionLoc(Body->getBeginLoc()), SMgr);
234
97
          offsetDecl = L.getExpansionLineNumber() - FunL.getExpansionLineNumber();
235
97
      }
236
97
  }
237
238
97
  std::string report = GenerateHTML(D, R, SMgr, path, declName.c_str());
239
97
  if (report.empty()) {
240
0
    llvm::errs() << "warning: no diagnostics generated for main file.\n";
241
0
    return;
242
0
  }
243
244
  // Create a path for the target HTML file.
245
97
  int FD;
246
97
  SmallString<128> Model, ResultPath;
247
248
97
  if (!AnalyzerOpts.ShouldWriteStableReportFilename) {
249
97
      llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
250
97
      if (std::error_code EC =
251
0
          llvm::sys::fs::make_absolute(Model)) {
252
0
          llvm::errs() << "warning: could not make '" << Model
253
0
                       << "' absolute: " << EC.message() << '\n';
254
0
        return;
255
0
      }
256
97
      if (std::error_code EC =
257
3
          llvm::sys::fs::createUniqueFile(Model, FD, ResultPath)) {
258
3
          llvm::errs() << "warning: could not create file in '" << Directory
259
3
                       << "': " << EC.message() << '\n';
260
3
          return;
261
3
      }
262
0
  } else {
263
0
      int i = 1;
264
0
      std::error_code EC;
265
0
      do {
266
          // Find a filename which is not already used
267
0
          const FileEntry* Entry = SMgr.getFileEntryForID(ReportFile);
268
0
          std::stringstream filename;
269
0
          Model = "";
270
0
          filename << "report-"
271
0
                   << llvm::sys::path::filename(Entry->getName()).str()
272
0
                   << "-" << declName.c_str()
273
0
                   << "-" << offsetDecl
274
0
                   << "-" << i << ".html";
275
0
          llvm::sys::path::append(Model, Directory,
276
0
                                  filename.str());
277
0
          EC = llvm::sys::fs::openFileForReadWrite(
278
0
              Model, FD, llvm::sys::fs::CD_CreateNew, llvm::sys::fs::OF_None);
279
0
          if (EC && EC != llvm::errc::file_exists) {
280
0
              llvm::errs() << "warning: could not create file '" << Model
281
0
                           << "': " << EC.message() << '\n';
282
0
              return;
283
0
          }
284
0
          i++;
285
0
      } while (EC);
286
0
  }
287
288
94
  llvm::raw_fd_ostream os(FD, true);
289
290
94
  if (filesMade)
291
94
    filesMade->addDiagnostic(D, getName(),
292
94
                             llvm::sys::path::filename(ResultPath));
293
294
  // Emit the HTML to disk.
295
94
  os << report;
296
94
}
297
298
std::string HTMLDiagnostics::GenerateHTML(const PathDiagnostic& D, Rewriter &R,
299
97
    const SourceManager& SMgr, const PathPieces& path, const char *declName) {
300
  // Rewrite source files as HTML for every new file the path crosses
301
97
  std::vector<FileID> FileIDs;
302
251
  for (auto I : path) {
303
251
    FileID FID = I->getLocation().asLocation().getExpansionLoc().getFileID();
304
251
    if (llvm::is_contained(FileIDs, FID))
305
150
      continue;
306
307
101
    FileIDs.push_back(FID);
308
101
    RewriteFile(R, path, FID);
309
101
  }
310
311
97
  if (SupportsCrossFileDiagnostics && 
FileIDs.size() > 195
) {
312
    // Prefix file names, anchor tags, and nav cursors to every file
313
12
    for (auto I = FileIDs.begin(), E = FileIDs.end(); I != E; 
I++8
) {
314
8
      std::string s;
315
8
      llvm::raw_string_ostream os(s);
316
317
8
      if (I != FileIDs.begin())
318
4
        os << "<hr class=divider>\n";
319
320
8
      os << "<div id=File" << I->getHashValue() << ">\n";
321
322
      // Left nav arrow
323
8
      if (I != FileIDs.begin())
324
4
        os << "<div class=FileNav><a href=\"#File" << (I - 1)->getHashValue()
325
4
           << "\">&#x2190;</a></div>";
326
327
8
      os << "<h4 class=FileName>" << SMgr.getFileEntryForID(*I)->getName()
328
8
         << "</h4>\n";
329
330
      // Right nav arrow
331
8
      if (I + 1 != E)
332
4
        os << "<div class=FileNav><a href=\"#File" << (I + 1)->getHashValue()
333
4
           << "\">&#x2192;</a></div>";
334
335
8
      os << "</div>\n";
336
337
8
      R.InsertTextBefore(SMgr.getLocForStartOfFile(*I), os.str());
338
8
    }
339
340
    // Append files to the main report file in the order they appear in the path
341
4
    for (auto I : llvm::make_range(FileIDs.begin() + 1, FileIDs.end())) {
342
4
      std::string s;
343
4
      llvm::raw_string_ostream os(s);
344
345
4
      const RewriteBuffer *Buf = R.getRewriteBufferFor(I);
346
4
      for (auto BI : *Buf)
347
7.12k
        os << BI;
348
349
4
      R.InsertTextAfter(SMgr.getLocForEndOfFile(FileIDs[0]), os.str());
350
4
    }
351
4
  }
352
353
97
  const RewriteBuffer *Buf = R.getRewriteBufferFor(FileIDs[0]);
354
97
  if (!Buf)
355
0
    return {};
356
357
  // Add CSS, header, and footer.
358
97
  FileID FID =
359
97
      path.back()->getLocation().asLocation().getExpansionLoc().getFileID();
360
97
  const FileEntry* Entry = SMgr.getFileEntryForID(FID);
361
97
  FinalizeHTML(D, R, SMgr, path, FileIDs[0], Entry, declName);
362
363
97
  std::string file;
364
97
  llvm::raw_string_ostream os(file);
365
97
  for (auto BI : *Buf)
366
4.46M
    os << BI;
367
368
97
  return os.str();
369
97
}
370
371
void HTMLDiagnostics::dumpCoverageData(
372
    const PathDiagnostic &D,
373
    const PathPieces &path,
374
97
    llvm::raw_string_ostream &os) {
375
376
97
  const FilesToLineNumsMap &ExecutedLines = D.getExecutedLines();
377
378
97
  os << "var relevant_lines = {";
379
97
  for (auto I = ExecutedLines.begin(),
380
198
            E = ExecutedLines.end(); I != E; 
++I101
) {
381
101
    if (I != ExecutedLines.begin())
382
4
      os << ", ";
383
384
101
    os << "\"" << I->first.getHashValue() << "\": {";
385
608
    for (unsigned LineNo : I->second) {
386
608
      if (LineNo != *(I->second.begin()))
387
507
        os << ", ";
388
389
608
      os << "\"" << LineNo << "\": 1";
390
608
    }
391
101
    os << "}";
392
101
  }
393
394
97
  os << "};";
395
97
}
396
397
std::string HTMLDiagnostics::showRelevantLinesJavascript(
398
97
      const PathDiagnostic &D, const PathPieces &path) {
399
97
  std::string s;
400
97
  llvm::raw_string_ostream os(s);
401
97
  os << "<script type='text/javascript'>\n";
402
97
  dumpCoverageData(D, path, os);
403
97
  os << R"<<<(
404
97
405
97
var filterCounterexample = function (hide) {
406
97
  var tables = document.getElementsByClassName("code");
407
97
  for (var t=0; t<tables.length; t++) {
408
97
    var table = tables[t];
409
97
    var file_id = table.getAttribute("data-fileid");
410
97
    var lines_in_fid = relevant_lines[file_id];
411
97
    if (!lines_in_fid) {
412
97
      lines_in_fid = {};
413
97
    }
414
97
    var lines = table.getElementsByClassName("codeline");
415
97
    for (var i=0; i<lines.length; i++) {
416
97
        var el = lines[i];
417
97
        var lineNo = el.getAttribute("data-linenumber");
418
97
        if (!lines_in_fid[lineNo]) {
419
97
          if (hide) {
420
97
            el.setAttribute("hidden", "");
421
97
          } else {
422
97
            el.removeAttribute("hidden");
423
97
          }
424
97
        }
425
97
    }
426
97
  }
427
97
}
428
97
429
97
window.addEventListener("keydown", function (event) {
430
97
  if (event.defaultPrevented) {
431
97
    return;
432
97
  }
433
97
  if (event.key == "S") {
434
97
    var checked = document.getElementsByName("showCounterexample")[0].checked;
435
97
    filterCounterexample(!checked);
436
97
    document.getElementsByName("showCounterexample")[0].checked = !checked;
437
97
  } else {
438
97
    return;
439
97
  }
440
97
  event.preventDefault();
441
97
}, true);
442
97
443
97
document.addEventListener("DOMContentLoaded", function() {
444
97
    document.querySelector('input[name="showCounterexample"]').onchange=
445
97
        function (event) {
446
97
      filterCounterexample(this.checked);
447
97
    };
448
97
});
449
97
</script>
450
97
451
97
<form>
452
97
    <input type="checkbox" name="showCounterexample" id="showCounterexample" />
453
97
    <label for="showCounterexample">
454
97
       Show only relevant lines
455
97
    </label>
456
97
</form>
457
97
)<<<";
458
459
97
  return os.str();
460
97
}
461
462
void HTMLDiagnostics::FinalizeHTML(const PathDiagnostic& D, Rewriter &R,
463
    const SourceManager& SMgr, const PathPieces& path, FileID FID,
464
97
    const FileEntry *Entry, const char *declName) {
465
  // This is a cludge; basically we want to append either the full
466
  // working directory if we have no directory information.  This is
467
  // a work in progress.
468
469
97
  llvm::SmallString<0> DirName;
470
471
97
  if (llvm::sys::path::is_relative(Entry->getName())) {
472
0
    llvm::sys::fs::current_path(DirName);
473
0
    DirName += '/';
474
0
  }
475
476
97
  int LineNumber = path.back()->getLocation().asLocation().getExpansionLineNumber();
477
97
  int ColumnNumber = path.back()->getLocation().asLocation().getExpansionColumnNumber();
478
479
97
  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), showHelpJavascript());
480
481
97
  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
482
97
                     generateKeyboardNavigationJavascript());
483
484
  // Checkbox and javascript for filtering the output to the counterexample.
485
97
  R.InsertTextBefore(SMgr.getLocForStartOfFile(FID),
486
97
                     showRelevantLinesJavascript(D, path));
487
488
  // Add the name of the file as an <h1> tag.
489
97
  {
490
97
    std::string s;
491
97
    llvm::raw_string_ostream os(s);
492
493
97
    os << "<!-- REPORTHEADER -->\n"
494
97
       << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
495
97
          "<tr><td class=\"rowname\">File:</td><td>"
496
97
       << html::EscapeText(DirName)
497
97
       << html::EscapeText(Entry->getName())
498
97
       << "</td></tr>\n<tr><td class=\"rowname\">Warning:</td><td>"
499
97
          "<a href=\"#EndPath\">line "
500
97
       << LineNumber
501
97
       << ", column "
502
97
       << ColumnNumber
503
97
       << "</a><br />"
504
97
       << D.getVerboseDescription() << "</td></tr>\n";
505
506
    // The navigation across the extra notes pieces.
507
97
    unsigned NumExtraPieces = 0;
508
251
    for (const auto &Piece : path) {
509
251
      if (const auto *P = dyn_cast<PathDiagnosticNotePiece>(Piece.get())) {
510
0
        int LineNumber =
511
0
            P->getLocation().asLocation().getExpansionLineNumber();
512
0
        int ColumnNumber =
513
0
            P->getLocation().asLocation().getExpansionColumnNumber();
514
0
        os << "<tr><td class=\"rowname\">Note:</td><td>"
515
0
           << "<a href=\"#Note" << NumExtraPieces << "\">line "
516
0
           << LineNumber << ", column " << ColumnNumber << "</a><br />"
517
0
           << P->getString() << "</td></tr>";
518
0
        ++NumExtraPieces;
519
0
      }
520
251
    }
521
522
    // Output any other meta data.
523
524
97
    for (PathDiagnostic::meta_iterator I = D.meta_begin(), E = D.meta_end();
525
97
         I != E; 
++I0
) {
526
0
      os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
527
0
    }
528
529
97
    os << R"<<<(
530
97
</table>
531
97
<!-- REPORTSUMMARYEXTRA -->
532
97
<h3>Annotated Source Code</h3>
533
97
<p>Press <a href="#" onclick="toggleHelp(); return false;">'?'</a>
534
97
   to see keyboard shortcuts</p>
535
97
<input type="checkbox" class="spoilerhider" id="showinvocation" />
536
97
<label for="showinvocation" >Show analyzer invocation</label>
537
97
<div class="spoiler">clang -cc1 )<<<";
538
97
    os << html::EscapeText(AnalyzerOpts.FullCompilerInvocation);
539
97
    os << R"<<<(
540
97
</div>
541
97
<div id='tooltiphint' hidden="true">
542
97
  <p>Keyboard shortcuts: </p>
543
97
  <ul>
544
97
    <li>Use 'j/k' keys for keyboard navigation</li>
545
97
    <li>Use 'Shift+S' to show/hide relevant lines</li>
546
97
    <li>Use '?' to toggle this window</li>
547
97
  </ul>
548
97
  <a href="#" onclick="toggleHelp(); return false;">Close</a>
549
97
</div>
550
97
)<<<";
551
97
    R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
552
97
  }
553
554
  // Embed meta-data tags.
555
97
  {
556
97
    std::string s;
557
97
    llvm::raw_string_ostream os(s);
558
559
97
    StringRef BugDesc = D.getVerboseDescription();
560
97
    if (!BugDesc.empty())
561
97
      os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
562
563
97
    StringRef BugType = D.getBugType();
564
97
    if (!BugType.empty())
565
97
      os << "\n<!-- BUGTYPE " << BugType << " -->\n";
566
567
97
    PathDiagnosticLocation UPDLoc = D.getUniqueingLoc();
568
97
    FullSourceLoc L(SMgr.getExpansionLoc(UPDLoc.isValid()
569
1
                                             ? UPDLoc.asLocation()
570
96
                                             : D.getLocation().asLocation()),
571
97
                    SMgr);
572
97
    const Decl *DeclWithIssue = D.getDeclWithIssue();
573
574
97
    StringRef BugCategory = D.getCategory();
575
97
    if (!BugCategory.empty())
576
97
      os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
577
578
97
    os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
579
580
97
    os << "\n<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
581
582
97
    os  << "\n<!-- FUNCTIONNAME " <<  declName << " -->\n";
583
584
97
    os << "\n<!-- ISSUEHASHCONTENTOFLINEINCONTEXT "
585
97
       << GetIssueHash(SMgr, L, D.getCheckerName(), D.getBugType(),
586
97
                       DeclWithIssue, PP.getLangOpts())
587
97
       << " -->\n";
588
589
97
    os << "\n<!-- BUGLINE "
590
97
       << LineNumber
591
97
       << " -->\n";
592
593
97
    os << "\n<!-- BUGCOLUMN "
594
97
      << ColumnNumber
595
97
      << " -->\n";
596
597
97
    os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
598
599
    // Mark the end of the tags.
600
97
    os << "\n<!-- BUGMETAEND -->\n";
601
602
    // Insert the text.
603
97
    R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
604
97
  }
605
606
97
  html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
607
97
}
608
609
97
StringRef HTMLDiagnostics::showHelpJavascript() {
610
97
  return R"<<<(
611
97
<script type='text/javascript'>
612
97
613
97
var toggleHelp = function() {
614
97
    var hint = document.querySelector("#tooltiphint");
615
97
    var attributeName = "hidden";
616
97
    if (hint.hasAttribute(attributeName)) {
617
97
      hint.removeAttribute(attributeName);
618
97
    } else {
619
97
      hint.setAttribute("hidden", "true");
620
97
    }
621
97
};
622
97
window.addEventListener("keydown", function (event) {
623
97
  if (event.defaultPrevented) {
624
97
    return;
625
97
  }
626
97
  if (event.key == "?") {
627
97
    toggleHelp();
628
97
  } else {
629
97
    return;
630
97
  }
631
97
  event.preventDefault();
632
97
});
633
97
</script>
634
97
)<<<";
635
97
}
636
637
10
static bool shouldDisplayPopUpRange(const SourceRange &Range) {
638
10
  return !(Range.getBegin().isMacroID() || 
Range.getEnd().isMacroID()9
);
639
10
}
640
641
static void
642
HandlePopUpPieceStartTag(Rewriter &R,
643
101
                         const std::vector<SourceRange> &PopUpRanges) {
644
4
  for (const auto &Range : PopUpRanges) {
645
4
    if (!shouldDisplayPopUpRange(Range))
646
0
      continue;
647
648
4
    html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "",
649
4
                         "<table class='variable_popup'><tbody>",
650
4
                         /*IsTokenRange=*/true);
651
4
  }
652
101
}
653
654
static void HandlePopUpPieceEndTag(Rewriter &R,
655
                                   const PathDiagnosticPopUpPiece &Piece,
656
                                   std::vector<SourceRange> &PopUpRanges,
657
                                   unsigned int LastReportedPieceIndex,
658
6
                                   unsigned int PopUpPieceIndex) {
659
6
  SmallString<256> Buf;
660
6
  llvm::raw_svector_ostream Out(Buf);
661
662
6
  SourceRange Range(Piece.getLocation().asRange());
663
6
  if (!shouldDisplayPopUpRange(Range))
664
1
    return;
665
666
  // Write out the path indices with a right arrow and the message as a row.
667
5
  Out << "<tr><td valign='top'><div class='PathIndex PathIndexPopUp'>"
668
5
      << LastReportedPieceIndex;
669
670
  // Also annotate the state transition with extra indices.
671
5
  Out << '.' << PopUpPieceIndex;
672
673
5
  Out << "</div></td><td>" << Piece.getString() << "</td></tr>";
674
675
  // If no report made at this range mark the variable and add the end tags.
676
5
  if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) ==
677
4
      PopUpRanges.end()) {
678
    // Store that we create a report at this range.
679
4
    PopUpRanges.push_back(Range);
680
681
4
    Out << "</tbody></table></span>";
682
4
    html::HighlightRange(R, Range.getBegin(), Range.getEnd(),
683
4
                         "<span class='variable'>", Buf.c_str(),
684
4
                         /*IsTokenRange=*/true);
685
1
  } else {
686
    // Otherwise inject just the new row at the end of the range.
687
1
    html::HighlightRange(R, Range.getBegin(), Range.getEnd(), "", Buf.c_str(),
688
1
                         /*IsTokenRange=*/true);
689
1
  }
690
5
}
691
692
void HTMLDiagnostics::RewriteFile(Rewriter &R,
693
101
                                  const PathPieces& path, FileID FID) {
694
  // Process the path.
695
  // Maintain the counts of extra note pieces separately.
696
101
  unsigned TotalPieces = path.size();
697
101
  unsigned TotalNotePieces = std::count_if(
698
268
      path.begin(), path.end(), [](const PathDiagnosticPieceRef &p) {
699
268
        return isa<PathDiagnosticNotePiece>(*p);
700
268
      });
701
101
  unsigned PopUpPieceCount = std::count_if(
702
268
      path.begin(), path.end(), [](const PathDiagnosticPieceRef &p) {
703
268
        return isa<PathDiagnosticPopUpPiece>(*p);
704
268
      });
705
706
101
  unsigned TotalRegularPieces = TotalPieces - TotalNotePieces - PopUpPieceCount;
707
101
  unsigned NumRegularPieces = TotalRegularPieces;
708
101
  unsigned NumNotePieces = TotalNotePieces;
709
  // Stores the count of the regular piece indices.
710
101
  std::map<int, int> IndexMap;
711
712
  // Stores the different ranges where we have reported something.
713
101
  std::vector<SourceRange> PopUpRanges;
714
369
  for (auto I = path.rbegin(), E = path.rend(); I != E; 
++I268
) {
715
268
    const auto &Piece = *I->get();
716
717
268
    if (isa<PathDiagnosticPopUpPiece>(Piece)) {
718
6
      ++IndexMap[NumRegularPieces];
719
262
    } else if (isa<PathDiagnosticNotePiece>(Piece)) {
720
      // This adds diagnostic bubbles, but not navigation.
721
      // Navigation through note pieces would be added later,
722
      // as a separate pass through the piece list.
723
0
      HandlePiece(R, FID, Piece, PopUpRanges, NumNotePieces, TotalNotePieces);
724
0
      --NumNotePieces;
725
262
    } else {
726
262
      HandlePiece(R, FID, Piece, PopUpRanges, NumRegularPieces,
727
262
                  TotalRegularPieces);
728
262
      --NumRegularPieces;
729
262
    }
730
268
  }
731
732
  // Secondary indexing if we are having multiple pop-ups between two notes.
733
  // (e.g. [(13) 'a' is 'true'];  [(13.1) 'b' is 'false'];  [(13.2) 'c' is...)
734
101
  NumRegularPieces = TotalRegularPieces;
735
369
  for (auto I = path.rbegin(), E = path.rend(); I != E; 
++I268
) {
736
268
    const auto &Piece = *I->get();
737
738
268
    if (const auto *PopUpP = dyn_cast<PathDiagnosticPopUpPiece>(&Piece)) {
739
6
      int PopUpPieceIndex = IndexMap[NumRegularPieces];
740
741
      // Pop-up pieces needs the index of the last reported piece and its count
742
      // how many times we report to handle multiple reports on the same range.
743
      // This marks the variable, adds the </table> end tag and the message
744
      // (list element) as a row. The <table> start tag will be added after the
745
      // rows has been written out. Note: It stores every different range.
746
6
      HandlePopUpPieceEndTag(R, *PopUpP, PopUpRanges, NumRegularPieces,
747
6
                             PopUpPieceIndex);
748
749
6
      if (PopUpPieceIndex > 0)
750
6
        --IndexMap[NumRegularPieces];
751
752
262
    } else if (!isa<PathDiagnosticNotePiece>(Piece)) {
753
262
      --NumRegularPieces;
754
262
    }
755
268
  }
756
757
  // Add the <table> start tag of pop-up pieces based on the stored ranges.
758
101
  HandlePopUpPieceStartTag(R, PopUpRanges);
759
760
  // Add line numbers, header, footer, etc.
761
101
  html::EscapeText(R, FID);
762
101
  html::AddLineNumbers(R, FID);
763
764
  // If we have a preprocessor, relex the file and syntax highlight.
765
  // We might not have a preprocessor if we come from a deserialized AST file,
766
  // for example.
767
101
  html::SyntaxHighlight(R, FID, PP);
768
101
  html::HighlightMacros(R, FID, PP);
769
101
}
770
771
void HTMLDiagnostics::HandlePiece(Rewriter &R, FileID BugFileID,
772
                                  const PathDiagnosticPiece &P,
773
                                  const std::vector<SourceRange> &PopUpRanges,
774
262
                                  unsigned num, unsigned max) {
775
  // For now, just draw a box above the line in question, and emit the
776
  // warning.
777
262
  FullSourceLoc Pos = P.getLocation().asLocation();
778
779
262
  if (!Pos.isValid())
780
0
    return;
781
782
262
  SourceManager &SM = R.getSourceMgr();
783
262
  assert(&Pos.getManager() == &SM && "SourceManagers are different!");
784
262
  std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
785
786
262
  if (LPosInfo.first != BugFileID)
787
16
    return;
788
789
246
  const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
790
246
  const char* FileStart = Buf->getBufferStart();
791
792
  // Compute the column number.  Rewind from the current position to the start
793
  // of the line.
794
246
  unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
795
246
  const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
796
246
  const char *LineStart = TokInstantiationPtr-ColNo;
797
798
  // Compute LineEnd.
799
246
  const char *LineEnd = TokInstantiationPtr;
800
246
  const char* FileEnd = Buf->getBufferEnd();
801
8.31k
  while (*LineEnd != '\n' && 
LineEnd != FileEnd8.06k
)
802
8.06k
    ++LineEnd;
803
804
  // Compute the margin offset by counting tabs and non-tabs.
805
246
  unsigned PosNo = 0;
806
1.72k
  for (const char* c = LineStart; c != TokInstantiationPtr; 
++c1.47k
)
807
1.47k
    PosNo += *c == '\t' ? 
85
:
11.47k
;
808
809
  // Create the html for the message.
810
811
246
  const char *Kind = nullptr;
812
246
  bool IsNote = false;
813
246
  bool SuppressIndex = (max == 1);
814
246
  switch (P.getKind()) {
815
209
  case PathDiagnosticPiece::Event: Kind = "Event"; break;
816
37
  case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
817
    // Setting Kind to "Control" is intentional.
818
0
  case PathDiagnosticPiece::Macro: Kind = "Control"; break;
819
0
  case PathDiagnosticPiece::Note:
820
0
    Kind = "Note";
821
0
    IsNote = true;
822
0
    SuppressIndex = true;
823
0
    break;
824
0
  case PathDiagnosticPiece::Call:
825
0
  case PathDiagnosticPiece::PopUp:
826
0
    llvm_unreachable("Calls and extra notes should already be handled");
827
246
  }
828
829
246
  std::string sbuf;
830
246
  llvm::raw_string_ostream os(sbuf);
831
832
246
  os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
833
834
246
  if (IsNote)
835
0
    os << "Note" << num;
836
246
  else if (num == max)
837
97
    os << "EndPath";
838
149
  else
839
149
    os << "Path" << num;
840
841
246
  os << "\" class=\"msg";
842
246
  if (Kind)
843
246
    os << " msg" << Kind;
844
246
  os << "\" style=\"margin-left:" << PosNo << "ex";
845
846
  // Output a maximum size.
847
246
  if (!isa<PathDiagnosticMacroPiece>(P)) {
848
    // Get the string and determining its maximum substring.
849
246
    const auto &Msg = P.getString();
850
246
    unsigned max_token = 0;
851
246
    unsigned cnt = 0;
852
246
    unsigned len = Msg.size();
853
854
246
    for (char C : Msg)
855
9.42k
      switch (C) {
856
8.31k
      default:
857
8.31k
        ++cnt;
858
8.31k
        continue;
859
1.10k
      case ' ':
860
1.10k
      case '\t':
861
1.10k
      case '\n':
862
1.10k
        if (cnt > max_token) 
max_token = cnt319
;
863
1.10k
        cnt = 0;
864
9.42k
      }
865
866
246
    if (cnt > max_token)
867
56
      max_token = cnt;
868
869
    // Determine the approximate size of the message bubble in em.
870
246
    unsigned em;
871
246
    const unsigned max_line = 120;
872
873
246
    if (max_token >= max_line)
874
0
      em = max_token / 2;
875
246
    else {
876
246
      unsigned characters = max_line;
877
246
      unsigned lines = len / max_line;
878
879
246
      if (lines > 0) {
880
298
        for (; characters > max_token; 
--characters283
)
881
286
          if (len / characters > lines) {
882
3
            ++characters;
883
3
            break;
884
3
          }
885
15
      }
886
887
246
      em = characters / 2;
888
246
    }
889
890
246
    if (em < max_line/2)
891
15
      os << "; max-width:" << em << "em";
892
246
  }
893
0
  else
894
0
    os << "; max-width:100em";
895
896
246
  os << "\">";
897
898
246
  if (!SuppressIndex) {
899
201
    os << "<table class=\"msgT\"><tr><td valign=\"top\">";
900
201
    os << "<div class=\"PathIndex";
901
201
    if (Kind) os << " PathIndex" << Kind;
902
201
    os << "\">" << num << "</div>";
903
904
201
    if (num > 1) {
905
149
      os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
906
149
         << (num - 1)
907
149
         << "\" title=\"Previous event ("
908
149
         << (num - 1)
909
149
         << ")\">&#x2190;</a></div>";
910
149
    }
911
912
201
    os << "</td><td>";
913
201
  }
914
915
246
  if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(&P)) {
916
0
    os << "Within the expansion of the macro '";
917
918
    // Get the name of the macro by relexing it.
919
0
    {
920
0
      FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
921
0
      assert(L.isFileID());
922
0
      StringRef BufferInfo = L.getBufferData();
923
0
      std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
924
0
      const char* MacroName = LocInfo.second + BufferInfo.data();
925
0
      Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
926
0
                     BufferInfo.begin(), MacroName, BufferInfo.end());
927
928
0
      Token TheTok;
929
0
      rawLexer.LexFromRawLexer(TheTok);
930
0
      for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
931
0
        os << MacroName[i];
932
0
    }
933
934
0
    os << "':\n";
935
936
0
    if (!SuppressIndex) {
937
0
      os << "</td>";
938
0
      if (num < max) {
939
0
        os << "<td><div class=\"PathNav\"><a href=\"#";
940
0
        if (num == max - 1)
941
0
          os << "EndPath";
942
0
        else
943
0
          os << "Path" << (num + 1);
944
0
        os << "\" title=\"Next event ("
945
0
        << (num + 1)
946
0
        << ")\">&#x2192;</a></div></td>";
947
0
      }
948
949
0
      os << "</tr></table>";
950
0
    }
951
952
    // Within a macro piece.  Write out each event.
953
0
    ProcessMacroPiece(os, *MP, 0);
954
0
  }
955
246
  else {
956
246
    os << html::EscapeText(P.getString());
957
958
246
    if (!SuppressIndex) {
959
201
      os << "</td>";
960
201
      if (num < max) {
961
149
        os << "<td><div class=\"PathNav\"><a href=\"#";
962
149
        if (num == max - 1)
963
52
          os << "EndPath";
964
97
        else
965
97
          os << "Path" << (num + 1);
966
149
        os << "\" title=\"Next event ("
967
149
           << (num + 1)
968
149
           << ")\">&#x2192;</a></div></td>";
969
149
      }
970
971
201
      os << "</tr></table>";
972
201
    }
973
246
  }
974
975
246
  os << "</div></td></tr>";
976
977
  // Insert the new html.
978
246
  unsigned DisplayPos = LineEnd - FileStart;
979
246
  SourceLocation Loc =
980
246
    SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
981
982
246
  R.InsertTextBefore(Loc, os.str());
983
984
  // Now highlight the ranges.
985
246
  ArrayRef<SourceRange> Ranges = P.getRanges();
986
199
  for (const auto &Range : Ranges) {
987
    // If we have already highlighted the range as a pop-up there is no work.
988
199
    if (std::find(PopUpRanges.begin(), PopUpRanges.end(), Range) !=
989
199
        PopUpRanges.end())
990
0
      continue;
991
992
199
    HighlightRange(R, LPosInfo.first, Range);
993
199
  }
994
246
}
995
996
0
static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
997
0
  unsigned x = n % ('z' - 'a');
998
0
  n /= 'z' - 'a';
999
1000
0
  if (n > 0)
1001
0
    EmitAlphaCounter(os, n);
1002
1003
0
  os << char('a' + x);
1004
0
}
1005
1006
unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
1007
                                            const PathDiagnosticMacroPiece& P,
1008
0
                                            unsigned num) {
1009
0
  for (const auto &subPiece : P.subPieces) {
1010
0
    if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(subPiece.get())) {
1011
0
      num = ProcessMacroPiece(os, *MP, num);
1012
0
      continue;
1013
0
    }
1014
1015
0
    if (const auto *EP = dyn_cast<PathDiagnosticEventPiece>(subPiece.get())) {
1016
0
      os << "<div class=\"msg msgEvent\" style=\"width:94%; "
1017
0
            "margin-left:5px\">"
1018
0
            "<table class=\"msgT\"><tr>"
1019
0
            "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
1020
0
      EmitAlphaCounter(os, num++);
1021
0
      os << "</div></td><td valign=\"top\">"
1022
0
         << html::EscapeText(EP->getString())
1023
0
         << "</td></tr></table></div>\n";
1024
0
    }
1025
0
  }
1026
1027
0
  return num;
1028
0
}
1029
1030
void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
1031
                                     SourceRange Range,
1032
                                     const char *HighlightStart,
1033
199
                                     const char *HighlightEnd) {
1034
199
  SourceManager &SM = R.getSourceMgr();
1035
199
  const LangOptions &LangOpts = R.getLangOpts();
1036
1037
199
  SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
1038
199
  unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
1039
1040
199
  SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
1041
199
  unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
1042
1043
199
  if (EndLineNo < StartLineNo)
1044
0
    return;
1045
1046
199
  if (SM.getFileID(InstantiationStart) != BugFileID ||
1047
199
      SM.getFileID(InstantiationEnd) != BugFileID)
1048
0
    return;
1049
1050
  // Compute the column number of the end.
1051
199
  unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
1052
199
  unsigned OldEndColNo = EndColNo;
1053
1054
199
  if (EndColNo) {
1055
    // Add in the length of the token, so that we cover multi-char tokens.
1056
199
    EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
1057
199
  }
1058
1059
  // Highlight the range.  Make the span tag the outermost tag for the
1060
  // selected range.
1061
1062
199
  SourceLocation E =
1063
199
    InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
1064
1065
199
  html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
1066
199
}
1067
1068
97
StringRef HTMLDiagnostics::generateKeyboardNavigationJavascript() {
1069
97
  return R"<<<(
1070
97
<script type='text/javascript'>
1071
97
var digitMatcher = new RegExp("[0-9]+");
1072
97
1073
97
var querySelectorAllArray = function(selector) {
1074
97
  return Array.prototype.slice.call(
1075
97
    document.querySelectorAll(selector));
1076
97
}
1077
97
1078
97
document.addEventListener("DOMContentLoaded", function() {
1079
97
    querySelectorAllArray(".PathNav > a").forEach(
1080
97
        function(currentValue, currentIndex) {
1081
97
            var hrefValue = currentValue.getAttribute("href");
1082
97
            currentValue.onclick = function() {
1083
97
                scrollTo(document.querySelector(hrefValue));
1084
97
                return false;
1085
97
            };
1086
97
        });
1087
97
});
1088
97
1089
97
var findNum = function() {
1090
97
    var s = document.querySelector(".selected");
1091
97
    if (!s || s.id == "EndPath") {
1092
97
        return 0;
1093
97
    }
1094
97
    var out = parseInt(digitMatcher.exec(s.id)[0]);
1095
97
    return out;
1096
97
};
1097
97
1098
97
var scrollTo = function(el) {
1099
97
    querySelectorAllArray(".selected").forEach(function(s) {
1100
97
        s.classList.remove("selected");
1101
97
    });
1102
97
    el.classList.add("selected");
1103
97
    window.scrollBy(0, el.getBoundingClientRect().top -
1104
97
        (window.innerHeight / 2));
1105
97
}
1106
97
1107
97
var move = function(num, up, numItems) {
1108
97
  if (num == 1 && up || num == numItems - 1 && !up) {
1109
97
    return 0;
1110
97
  } else if (num == 0 && up) {
1111
97
    return numItems - 1;
1112
97
  } else if (num == 0 && !up) {
1113
97
    return 1 % numItems;
1114
97
  }
1115
97
  return up ? num - 1 : num + 1;
1116
97
}
1117
97
1118
97
var numToId = function(num) {
1119
97
  if (num == 0) {
1120
97
    return document.getElementById("EndPath")
1121
97
  }
1122
97
  return document.getElementById("Path" + num);
1123
97
};
1124
97
1125
97
var navigateTo = function(up) {
1126
97
  var numItems = document.querySelectorAll(
1127
97
      ".line > .msgEvent, .line > .msgControl").length;
1128
97
  var currentSelected = findNum();
1129
97
  var newSelected = move(currentSelected, up, numItems);
1130
97
  var newEl = numToId(newSelected, numItems);
1131
97
1132
97
  // Scroll element into center.
1133
97
  scrollTo(newEl);
1134
97
};
1135
97
1136
97
window.addEventListener("keydown", function (event) {
1137
97
  if (event.defaultPrevented) {
1138
97
    return;
1139
97
  }
1140
97
  if (event.key == "j") {
1141
97
    navigateTo(/*up=*/false);
1142
97
  } else if (event.key == "k") {
1143
97
    navigateTo(/*up=*/true);
1144
97
  } else {
1145
97
    return;
1146
97
  }
1147
97
  event.preventDefault();
1148
97
}, true);
1149
97
</script>
1150
97
  )<<<";
1151
97
}