Coverage Report

Created: 2023-09-21 18:56

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