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