xref: /llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp (revision 163cb1fc2fe4caa8306a18abdb0516870e4d7f3d)
1 //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//
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 /// \file This file implements the html coverage renderer.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "SourceCoverageViewHTML.h"
14 #include "CoverageReport.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/ThreadPool.h"
20 #include <optional>
21 
22 using namespace llvm;
23 
24 namespace {
25 
26 // Return a string with the special characters in \p Str escaped.
27 std::string escape(StringRef Str, const CoverageViewOptions &Opts) {
28   std::string TabExpandedResult;
29   unsigned ColNum = 0; // Record the column number.
30   for (char C : Str) {
31     if (C == '\t') {
32       // Replace '\t' with up to TabSize spaces.
33       unsigned NumSpaces = Opts.TabSize - (ColNum % Opts.TabSize);
34       TabExpandedResult.append(NumSpaces, ' ');
35       ColNum += NumSpaces;
36     } else {
37       TabExpandedResult += C;
38       if (C == '\n' || C == '\r')
39         ColNum = 0;
40       else
41         ++ColNum;
42     }
43   }
44   std::string EscapedHTML;
45   {
46     raw_string_ostream OS{EscapedHTML};
47     printHTMLEscaped(TabExpandedResult, OS);
48   }
49   return EscapedHTML;
50 }
51 
52 // Create a \p Name tag around \p Str, and optionally set its \p ClassName.
53 std::string tag(StringRef Name, StringRef Str, StringRef ClassName = "") {
54   std::string Tag = "<";
55   Tag += Name;
56   if (!ClassName.empty()) {
57     Tag += " class='";
58     Tag += ClassName;
59     Tag += "'";
60   }
61   Tag += ">";
62   Tag += Str;
63   Tag += "</";
64   Tag += Name;
65   Tag += ">";
66   return Tag;
67 }
68 
69 // Create an anchor to \p Link with the label \p Str.
70 std::string a(StringRef Link, StringRef Str, StringRef TargetName = "") {
71   std::string Tag;
72   Tag += "<a ";
73   if (!TargetName.empty()) {
74     Tag += "name='";
75     Tag += TargetName;
76     Tag += "' ";
77   }
78   Tag += "href='";
79   Tag += Link;
80   Tag += "'>";
81   Tag += Str;
82   Tag += "</a>";
83   return Tag;
84 }
85 
86 const char *BeginHeader =
87     "<head>"
88     "<meta name='viewport' content='width=device-width,initial-scale=1'>"
89     "<meta charset='UTF-8'>";
90 
91 const char *CSSForCoverage =
92     R"(.red {
93   background-color: #f004;
94 }
95 .cyan {
96   background-color: cyan;
97 }
98 body {
99   font-family: -apple-system, sans-serif;
100 }
101 pre {
102   margin-top: 0px !important;
103   margin-bottom: 0px !important;
104 }
105 .source-name-title {
106   padding: 5px 10px;
107   border-bottom: 1px solid #8888;
108   background-color: #0002;
109   line-height: 35px;
110 }
111 .centered {
112   display: table;
113   margin-left: left;
114   margin-right: auto;
115   border: 1px solid #8888;
116   border-radius: 3px;
117 }
118 .expansion-view {
119   margin-left: 0px;
120   margin-top: 5px;
121   margin-right: 5px;
122   margin-bottom: 5px;
123   border: 1px solid #8888;
124   border-radius: 3px;
125 }
126 table {
127   border-collapse: collapse;
128 }
129 .light-row {
130   border: 1px solid #8888;
131   border-left: none;
132   border-right: none;
133 }
134 .light-row-bold {
135   border: 1px solid #8888;
136   border-left: none;
137   border-right: none;
138   font-weight: bold;
139 }
140 .column-entry {
141   text-align: left;
142 }
143 .column-entry-bold {
144   font-weight: bold;
145   text-align: left;
146 }
147 .column-entry-yellow {
148   text-align: left;
149   background-color: #ff06;
150 }
151 .column-entry-red {
152   text-align: left;
153   background-color: #f004;
154 }
155 .column-entry-gray {
156   text-align: left;
157   background-color: #fff4;
158 }
159 .column-entry-green {
160   text-align: left;
161   background-color: #0f04;
162 }
163 .line-number {
164   text-align: right;
165 }
166 .covered-line {
167   text-align: right;
168   color: #06d;
169 }
170 .uncovered-line {
171   text-align: right;
172   color: #d00;
173 }
174 .tooltip {
175   position: relative;
176   display: inline;
177   background-color: #bef;
178   text-decoration: none;
179 }
180 .tooltip span.tooltip-content {
181   position: absolute;
182   width: 100px;
183   margin-left: -50px;
184   color: #FFFFFF;
185   background: #000000;
186   height: 30px;
187   line-height: 30px;
188   text-align: center;
189   visibility: hidden;
190   border-radius: 6px;
191 }
192 .tooltip span.tooltip-content:after {
193   content: '';
194   position: absolute;
195   top: 100%;
196   left: 50%;
197   margin-left: -8px;
198   width: 0; height: 0;
199   border-top: 8px solid #000000;
200   border-right: 8px solid transparent;
201   border-left: 8px solid transparent;
202 }
203 :hover.tooltip span.tooltip-content {
204   visibility: visible;
205   opacity: 0.8;
206   bottom: 30px;
207   left: 50%;
208   z-index: 999;
209 }
210 th, td {
211   vertical-align: top;
212   padding: 2px 8px;
213   border-collapse: collapse;
214   border-right: 1px solid #8888;
215   border-left: 1px solid #8888;
216   text-align: left;
217 }
218 td pre {
219   display: inline-block;
220   text-decoration: inherit;
221 }
222 td:first-child {
223   border-left: none;
224 }
225 td:last-child {
226   border-right: none;
227 }
228 tr:hover {
229   background-color: #eee;
230 }
231 tr:last-child {
232   border-bottom: none;
233 }
234 tr:has(> td >a:target) {
235   background-color: #50f6;
236 }
237 a {
238   color: inherit;
239 }
240 @media (prefers-color-scheme: dark) {
241   body {
242     background-color: #222;
243     color: whitesmoke;
244   }
245   tr:hover {
246     background-color: #111;
247   }
248   .covered-line {
249     color: #39f;
250   }
251   .uncovered-line {
252     color: #f55;
253   }
254   .tooltip {
255     background-color: #068;
256   }
257 }
258 )";
259 
260 const char *EndHeader = "</head>";
261 
262 const char *BeginCenteredDiv = "<div class='centered'>";
263 
264 const char *EndCenteredDiv = "</div>";
265 
266 const char *BeginSourceNameDiv = "<div class='source-name-title'>";
267 
268 const char *EndSourceNameDiv = "</div>";
269 
270 const char *BeginCodeTD = "<td class='code'>";
271 
272 const char *EndCodeTD = "</td>";
273 
274 const char *BeginPre = "<pre>";
275 
276 const char *EndPre = "</pre>";
277 
278 const char *BeginExpansionDiv = "<div class='expansion-view'>";
279 
280 const char *EndExpansionDiv = "</div>";
281 
282 const char *BeginTable = "<table>";
283 
284 const char *EndTable = "</table>";
285 
286 const char *ProjectTitleTag = "h1";
287 
288 const char *ReportTitleTag = "h2";
289 
290 const char *CreatedTimeTag = "h4";
291 
292 std::string getPathToStyle(StringRef ViewPath) {
293   std::string PathToStyle;
294   std::string PathSep = std::string(sys::path::get_separator());
295   unsigned NumSeps = ViewPath.count(PathSep);
296   for (unsigned I = 0, E = NumSeps; I < E; ++I)
297     PathToStyle += ".." + PathSep;
298   return PathToStyle + "style.css";
299 }
300 
301 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
302                  const std::string &PathToStyle = "") {
303   OS << "<!doctype html>"
304         "<html>"
305      << BeginHeader;
306 
307   // Link to a stylesheet if one is available. Otherwise, use the default style.
308   if (PathToStyle.empty())
309     OS << "<style>" << CSSForCoverage << "</style>";
310   else
311     OS << "<link rel='stylesheet' type='text/css' href='"
312        << escape(PathToStyle, Opts) << "'>";
313 
314   OS << EndHeader << "<body>";
315 }
316 
317 void emitTableRow(raw_ostream &OS, const CoverageViewOptions &Opts,
318                   const std::string &FirstCol, const FileCoverageSummary &FCS,
319                   bool IsTotals) {
320   SmallVector<std::string, 8> Columns;
321 
322   // Format a coverage triple and add the result to the list of columns.
323   auto AddCoverageTripleToColumn =
324       [&Columns, &Opts](unsigned Hit, unsigned Total, float Pctg) {
325         std::string S;
326         {
327           raw_string_ostream RSO{S};
328           if (Total)
329             RSO << format("%*.2f", 7, Pctg) << "% ";
330           else
331             RSO << "- ";
332           RSO << '(' << Hit << '/' << Total << ')';
333         }
334         const char *CellClass = "column-entry-yellow";
335         if (!Total)
336           CellClass = "column-entry-gray";
337         else if (Pctg >= Opts.HighCovWatermark)
338           CellClass = "column-entry-green";
339         else if (Pctg < Opts.LowCovWatermark)
340           CellClass = "column-entry-red";
341         Columns.emplace_back(tag("td", tag("pre", S), CellClass));
342       };
343 
344   Columns.emplace_back(tag("td", tag("pre", FirstCol)));
345   AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),
346                             FCS.FunctionCoverage.getNumFunctions(),
347                             FCS.FunctionCoverage.getPercentCovered());
348   if (Opts.ShowInstantiationSummary)
349     AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),
350                               FCS.InstantiationCoverage.getNumFunctions(),
351                               FCS.InstantiationCoverage.getPercentCovered());
352   AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),
353                             FCS.LineCoverage.getNumLines(),
354                             FCS.LineCoverage.getPercentCovered());
355   if (Opts.ShowRegionSummary)
356     AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),
357                               FCS.RegionCoverage.getNumRegions(),
358                               FCS.RegionCoverage.getPercentCovered());
359   if (Opts.ShowBranchSummary)
360     AddCoverageTripleToColumn(FCS.BranchCoverage.getCovered(),
361                               FCS.BranchCoverage.getNumBranches(),
362                               FCS.BranchCoverage.getPercentCovered());
363   if (Opts.ShowMCDCSummary)
364     AddCoverageTripleToColumn(FCS.MCDCCoverage.getCoveredPairs(),
365                               FCS.MCDCCoverage.getNumPairs(),
366                               FCS.MCDCCoverage.getPercentCovered());
367 
368   if (IsTotals)
369     OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row-bold");
370   else
371     OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
372 }
373 
374 void emitEpilog(raw_ostream &OS) {
375   OS << "</body>"
376      << "</html>";
377 }
378 
379 } // anonymous namespace
380 
381 Expected<CoveragePrinter::OwnedStream>
382 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
383   auto OSOrErr = createOutputStream(Path, "html", InToplevel);
384   if (!OSOrErr)
385     return OSOrErr;
386 
387   OwnedStream OS = std::move(OSOrErr.get());
388 
389   if (!Opts.hasOutputDirectory()) {
390     emitPrelude(*OS.get(), Opts);
391   } else {
392     std::string ViewPath = getOutputPath(Path, "html", InToplevel);
393     emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
394   }
395 
396   return std::move(OS);
397 }
398 
399 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
400   emitEpilog(*OS.get());
401 }
402 
403 /// Emit column labels for the table in the index.
404 static void emitColumnLabelsForIndex(raw_ostream &OS,
405                                      const CoverageViewOptions &Opts) {
406   SmallVector<std::string, 4> Columns;
407   Columns.emplace_back(tag("td", "Filename", "column-entry-bold"));
408   Columns.emplace_back(tag("td", "Function Coverage", "column-entry-bold"));
409   if (Opts.ShowInstantiationSummary)
410     Columns.emplace_back(
411         tag("td", "Instantiation Coverage", "column-entry-bold"));
412   Columns.emplace_back(tag("td", "Line Coverage", "column-entry-bold"));
413   if (Opts.ShowRegionSummary)
414     Columns.emplace_back(tag("td", "Region Coverage", "column-entry-bold"));
415   if (Opts.ShowBranchSummary)
416     Columns.emplace_back(tag("td", "Branch Coverage", "column-entry-bold"));
417   if (Opts.ShowMCDCSummary)
418     Columns.emplace_back(tag("td", "MC/DC", "column-entry-bold"));
419   OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
420 }
421 
422 std::string
423 CoveragePrinterHTML::buildLinkToFile(StringRef SF,
424                                      const FileCoverageSummary &FCS) const {
425   SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
426   sys::path::remove_dots(LinkTextStr, /*remove_dot_dot=*/true);
427   sys::path::native(LinkTextStr);
428   std::string LinkText = escape(LinkTextStr, Opts);
429   std::string LinkTarget =
430       escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
431   return a(LinkTarget, LinkText);
432 }
433 
434 Error CoveragePrinterHTML::emitStyleSheet() {
435   auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
436   if (Error E = CSSOrErr.takeError())
437     return E;
438 
439   OwnedStream CSS = std::move(CSSOrErr.get());
440   CSS->operator<<(CSSForCoverage);
441 
442   return Error::success();
443 }
444 
445 void CoveragePrinterHTML::emitReportHeader(raw_ostream &OSRef,
446                                            const std::string &Title) {
447   // Emit some basic information about the coverage report.
448   if (Opts.hasProjectTitle())
449     OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));
450   OSRef << tag(ReportTitleTag, Title);
451   if (Opts.hasCreatedTime())
452     OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));
453 
454   // Emit a link to some documentation.
455   OSRef << tag("p", "Click " +
456                         a("http://clang.llvm.org/docs/"
457                           "SourceBasedCodeCoverage.html#interpreting-reports",
458                           "here") +
459                         " for information about interpreting this report.");
460 
461   // Emit a table containing links to reports for each file in the covmapping.
462   // Exclude files which don't contain any regions.
463   OSRef << BeginCenteredDiv << BeginTable;
464   emitColumnLabelsForIndex(OSRef, Opts);
465 }
466 
467 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
468 /// false, link the summary to \p SF.
469 void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
470                                           const FileCoverageSummary &FCS,
471                                           bool IsTotals) const {
472   // Simplify the display file path, and wrap it in a link if requested.
473   std::string Filename;
474   if (IsTotals) {
475     Filename = std::string(SF);
476   } else {
477     Filename = buildLinkToFile(SF, FCS);
478   }
479 
480   emitTableRow(OS, Opts, Filename, FCS, IsTotals);
481 }
482 
483 Error CoveragePrinterHTML::createIndexFile(
484     ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,
485     const CoverageFiltersMatchAll &Filters) {
486   // Emit the default stylesheet.
487   if (Error E = emitStyleSheet())
488     return E;
489 
490   // Emit a file index along with some coverage statistics.
491   auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
492   if (Error E = OSOrErr.takeError())
493     return E;
494   auto OS = std::move(OSOrErr.get());
495   raw_ostream &OSRef = *OS.get();
496 
497   assert(Opts.hasOutputDirectory() && "No output directory for index file");
498   emitPrelude(OSRef, Opts, getPathToStyle(""));
499 
500   emitReportHeader(OSRef, "Coverage Report");
501 
502   FileCoverageSummary Totals("TOTALS");
503   auto FileReports = CoverageReport::prepareFileReports(
504       Coverage, Totals, SourceFiles, Opts, Filters);
505   bool EmptyFiles = false;
506   for (unsigned I = 0, E = FileReports.size(); I < E; ++I) {
507     if (FileReports[I].FunctionCoverage.getNumFunctions())
508       emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
509     else
510       EmptyFiles = true;
511   }
512   emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
513   OSRef << EndTable << EndCenteredDiv;
514 
515   // Emit links to files which don't contain any functions. These are normally
516   // not very useful, but could be relevant for code which abuses the
517   // preprocessor.
518   if (EmptyFiles && Filters.empty()) {
519     OSRef << tag("p", "Files which contain no functions. (These "
520                       "files contain code pulled into other files "
521                       "by the preprocessor.)\n");
522     OSRef << BeginCenteredDiv << BeginTable;
523     for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
524       if (!FileReports[I].FunctionCoverage.getNumFunctions()) {
525         std::string Link = buildLinkToFile(SourceFiles[I], FileReports[I]);
526         OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';
527       }
528     OSRef << EndTable << EndCenteredDiv;
529   }
530 
531   OSRef << tag("h5", escape(Opts.getLLVMVersionString(), Opts));
532   emitEpilog(OSRef);
533 
534   return Error::success();
535 }
536 
537 struct CoveragePrinterHTMLDirectory::Reporter : public DirectoryCoverageReport {
538   CoveragePrinterHTMLDirectory &Printer;
539 
540   Reporter(CoveragePrinterHTMLDirectory &Printer,
541            const coverage::CoverageMapping &Coverage,
542            const CoverageFiltersMatchAll &Filters)
543       : DirectoryCoverageReport(Printer.Opts, Coverage, Filters),
544         Printer(Printer) {}
545 
546   Error generateSubDirectoryReport(SubFileReports &&SubFiles,
547                                    SubDirReports &&SubDirs,
548                                    FileCoverageSummary &&SubTotals) override {
549     auto &LCPath = SubTotals.Name;
550     assert(Options.hasOutputDirectory() &&
551            "No output directory for index file");
552 
553     SmallString<128> OSPath = LCPath;
554     sys::path::append(OSPath, "index");
555     auto OSOrErr = Printer.createOutputStream(OSPath, "html",
556                                               /*InToplevel=*/false);
557     if (auto E = OSOrErr.takeError())
558       return E;
559     auto OS = std::move(OSOrErr.get());
560     raw_ostream &OSRef = *OS.get();
561 
562     auto IndexHtmlPath = Printer.getOutputPath((LCPath + "index").str(), "html",
563                                                /*InToplevel=*/false);
564     emitPrelude(OSRef, Options, getPathToStyle(IndexHtmlPath));
565 
566     auto NavLink = buildTitleLinks(LCPath);
567     Printer.emitReportHeader(OSRef, "Coverage Report (" + NavLink + ")");
568 
569     std::vector<const FileCoverageSummary *> EmptyFiles;
570 
571     // Make directories at the top of the table.
572     for (auto &&SubDir : SubDirs) {
573       auto &Report = SubDir.second.first;
574       if (!Report.FunctionCoverage.getNumFunctions())
575         EmptyFiles.push_back(&Report);
576       else
577         emitTableRow(OSRef, Options, buildRelLinkToFile(Report.Name), Report,
578                      /*IsTotals=*/false);
579     }
580 
581     for (auto &&SubFile : SubFiles) {
582       auto &Report = SubFile.second;
583       if (!Report.FunctionCoverage.getNumFunctions())
584         EmptyFiles.push_back(&Report);
585       else
586         emitTableRow(OSRef, Options, buildRelLinkToFile(Report.Name), Report,
587                      /*IsTotals=*/false);
588     }
589 
590     // Emit the totals row.
591     emitTableRow(OSRef, Options, "Totals", SubTotals, /*IsTotals=*/false);
592     OSRef << EndTable << EndCenteredDiv;
593 
594     // Emit links to files which don't contain any functions. These are normally
595     // not very useful, but could be relevant for code which abuses the
596     // preprocessor.
597     if (!EmptyFiles.empty()) {
598       OSRef << tag("p", "Files which contain no functions. (These "
599                         "files contain code pulled into other files "
600                         "by the preprocessor.)\n");
601       OSRef << BeginCenteredDiv << BeginTable;
602       for (auto FCS : EmptyFiles) {
603         auto Link = buildRelLinkToFile(FCS->Name);
604         OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';
605       }
606       OSRef << EndTable << EndCenteredDiv;
607     }
608 
609     // Emit epilog.
610     OSRef << tag("h5", escape(Options.getLLVMVersionString(), Options));
611     emitEpilog(OSRef);
612 
613     return Error::success();
614   }
615 
616   /// Make a title with hyperlinks to the index.html files of each hierarchy
617   /// of the report.
618   std::string buildTitleLinks(StringRef LCPath) const {
619     // For each report level in LCPStack, extract the path component and
620     // calculate the number of "../" relative to current LCPath.
621     SmallVector<std::pair<SmallString<128>, unsigned>, 16> Components;
622 
623     auto Iter = LCPStack.begin(), IterE = LCPStack.end();
624     SmallString<128> RootPath;
625     if (*Iter == 0) {
626       // If llvm-cov works on relative coverage mapping data, the LCP of
627       // all source file paths can be 0, which makes the title path empty.
628       // As we like adding a slash at the back of the path to indicate a
629       // directory, in this case, we use "." as the root path to make it
630       // not be confused with the root path "/".
631       RootPath = ".";
632     } else {
633       RootPath = LCPath.substr(0, *Iter);
634       sys::path::native(RootPath);
635       sys::path::remove_dots(RootPath, /*remove_dot_dot=*/true);
636     }
637     Components.emplace_back(std::move(RootPath), 0);
638 
639     for (auto Last = *Iter; ++Iter != IterE; Last = *Iter) {
640       SmallString<128> SubPath = LCPath.substr(Last, *Iter - Last);
641       sys::path::native(SubPath);
642       sys::path::remove_dots(SubPath, /*remove_dot_dot=*/true);
643       auto Level = unsigned(SubPath.count(sys::path::get_separator())) + 1;
644       Components.back().second += Level;
645       Components.emplace_back(std::move(SubPath), Level);
646     }
647 
648     // Then we make the title accroding to Components.
649     std::string S;
650     for (auto I = Components.begin(), E = Components.end();;) {
651       auto &Name = I->first;
652       if (++I == E) {
653         S += a("./index.html", Name);
654         S += sys::path::get_separator();
655         break;
656       }
657 
658       SmallString<128> Link;
659       for (unsigned J = I->second; J > 0; --J)
660         Link += "../";
661       Link += "index.html";
662       S += a(Link, Name);
663       S += sys::path::get_separator();
664     }
665     return S;
666   }
667 
668   std::string buildRelLinkToFile(StringRef RelPath) const {
669     SmallString<128> LinkTextStr(RelPath);
670     sys::path::native(LinkTextStr);
671 
672     // remove_dots will remove trailing slash, so we need to check before it.
673     auto IsDir = LinkTextStr.ends_with(sys::path::get_separator());
674     sys::path::remove_dots(LinkTextStr, /*remove_dot_dot=*/true);
675 
676     SmallString<128> LinkTargetStr(LinkTextStr);
677     if (IsDir) {
678       LinkTextStr += sys::path::get_separator();
679       sys::path::append(LinkTargetStr, "index.html");
680     } else {
681       LinkTargetStr += ".html";
682     }
683 
684     auto LinkText = escape(LinkTextStr, Options);
685     auto LinkTarget = escape(LinkTargetStr, Options);
686     return a(LinkTarget, LinkText);
687   }
688 };
689 
690 Error CoveragePrinterHTMLDirectory::createIndexFile(
691     ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,
692     const CoverageFiltersMatchAll &Filters) {
693   // The createSubIndexFile function only works when SourceFiles is
694   // more than one. So we fallback to CoveragePrinterHTML when it is.
695   if (SourceFiles.size() <= 1)
696     return CoveragePrinterHTML::createIndexFile(SourceFiles, Coverage, Filters);
697 
698   // Emit the default stylesheet.
699   if (Error E = emitStyleSheet())
700     return E;
701 
702   // Emit index files in every subdirectory.
703   Reporter Report(*this, Coverage, Filters);
704   auto TotalsOrErr = Report.prepareDirectoryReports(SourceFiles);
705   if (auto E = TotalsOrErr.takeError())
706     return E;
707   auto &LCPath = TotalsOrErr->Name;
708 
709   // Emit the top level index file. Top level index file is just a redirection
710   // to the index file in the LCP directory.
711   auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
712   if (auto E = OSOrErr.takeError())
713     return E;
714   auto OS = std::move(OSOrErr.get());
715   auto LCPIndexFilePath =
716       getOutputPath((LCPath + "index").str(), "html", /*InToplevel=*/false);
717   *OS.get() << R"(<!DOCTYPE html>
718   <html>
719     <head>
720       <meta http-equiv="Refresh" content="0; url=')"
721             << LCPIndexFilePath << R"('" />
722     </head>
723     <body></body>
724   </html>
725   )";
726 
727   return Error::success();
728 }
729 
730 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
731   OS << BeginCenteredDiv << BeginTable;
732 }
733 
734 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
735   OS << EndTable << EndCenteredDiv;
736 }
737 
738 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {
739   OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))
740      << EndSourceNameDiv;
741 }
742 
743 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
744   OS << "<tr>";
745 }
746 
747 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
748   // If this view has sub-views, renderLine() cannot close the view's cell.
749   // Take care of it here, after all sub-views have been rendered.
750   if (hasSubViews())
751     OS << EndCodeTD;
752   OS << "</tr>";
753 }
754 
755 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
756   // The table-based output makes view dividers unnecessary.
757 }
758 
759 void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L,
760                                         const LineCoverageStats &LCS,
761                                         unsigned ExpansionCol, unsigned) {
762   StringRef Line = L.Line;
763   unsigned LineNo = L.LineNo;
764 
765   // Steps for handling text-escaping, highlighting, and tooltip creation:
766   //
767   // 1. Split the line into N+1 snippets, where N = |Segments|. The first
768   //    snippet starts from Col=1 and ends at the start of the first segment.
769   //    The last snippet starts at the last mapped column in the line and ends
770   //    at the end of the line. Both are required but may be empty.
771 
772   SmallVector<std::string, 8> Snippets;
773   CoverageSegmentArray Segments = LCS.getLineSegments();
774 
775   unsigned LCol = 1;
776   auto Snip = [&](unsigned Start, unsigned Len) {
777     Snippets.push_back(std::string(Line.substr(Start, Len)));
778     LCol += Len;
779   };
780 
781   Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
782 
783   for (unsigned I = 1, E = Segments.size(); I < E; ++I)
784     Snip(LCol - 1, Segments[I]->Col - LCol);
785 
786   // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
787   Snip(LCol - 1, Line.size() + 1 - LCol);
788 
789   // 2. Escape all of the snippets.
790 
791   for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
792     Snippets[I] = escape(Snippets[I], getOptions());
793 
794   // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
795   //    1 to set the highlight for snippet 2, segment 2 to set the highlight for
796   //    snippet 3, and so on.
797 
798   std::optional<StringRef> Color;
799   SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
800   auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
801     if (getOptions().Debug)
802       HighlightedRanges.emplace_back(LC, RC);
803     return tag("span", Snippet, std::string(*Color));
804   };
805 
806   auto CheckIfUncovered = [&](const CoverageSegment *S) {
807     return S && (!S->IsGapRegion || (Color && *Color == "red")) &&
808            S->HasCount && S->Count == 0;
809   };
810 
811   if (CheckIfUncovered(LCS.getWrappedSegment())) {
812     Color = "red";
813     if (!Snippets[0].empty())
814       Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
815   }
816 
817   for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
818     const auto *CurSeg = Segments[I];
819     if (CheckIfUncovered(CurSeg))
820       Color = "red";
821     else if (CurSeg->Col == ExpansionCol)
822       Color = "cyan";
823     else
824       Color = std::nullopt;
825 
826     if (Color)
827       Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
828                                   CurSeg->Col + Snippets[I + 1].size());
829   }
830 
831   if (Color && Segments.empty())
832     Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
833 
834   if (getOptions().Debug) {
835     for (const auto &Range : HighlightedRanges) {
836       errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
837       if (Range.second == 0)
838         errs() << "?";
839       else
840         errs() << Range.second;
841       errs() << "\n";
842     }
843   }
844 
845   // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
846   //    sub-line region count tooltips if needed.
847 
848   if (shouldRenderRegionMarkers(LCS)) {
849     // Just consider the segments which start *and* end on this line.
850     for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
851       const auto *CurSeg = Segments[I];
852       if (!CurSeg->IsRegionEntry)
853         continue;
854       if (CurSeg->Count == LCS.getExecutionCount())
855         continue;
856 
857       Snippets[I + 1] =
858           tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
859                                            "tooltip-content"),
860               "tooltip");
861 
862       if (getOptions().Debug)
863         errs() << "Marker at " << CurSeg->Line << ":" << CurSeg->Col << " = "
864                << formatCount(CurSeg->Count) << "\n";
865     }
866   }
867 
868   OS << BeginCodeTD;
869   OS << BeginPre;
870   for (const auto &Snippet : Snippets)
871     OS << Snippet;
872   OS << EndPre;
873 
874   // If there are no sub-views left to attach to this cell, end the cell.
875   // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
876   if (!hasSubViews())
877     OS << EndCodeTD;
878 }
879 
880 void SourceCoverageViewHTML::renderLineCoverageColumn(
881     raw_ostream &OS, const LineCoverageStats &Line) {
882   std::string Count;
883   if (Line.isMapped())
884     Count = tag("pre", formatCount(Line.getExecutionCount()));
885   std::string CoverageClass =
886       (Line.getExecutionCount() > 0) ? "covered-line" : "uncovered-line";
887   OS << tag("td", Count, CoverageClass);
888 }
889 
890 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
891                                                     unsigned LineNo) {
892   std::string LineNoStr = utostr(uint64_t(LineNo));
893   std::string TargetName = "L" + LineNoStr;
894   OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),
895             "line-number");
896 }
897 
898 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
899                                                  const LineCoverageStats &Line,
900                                                  unsigned) {
901   // Region markers are rendered in-line using tooltips.
902 }
903 
904 void SourceCoverageViewHTML::renderExpansionSite(raw_ostream &OS, LineRef L,
905                                                  const LineCoverageStats &LCS,
906                                                  unsigned ExpansionCol,
907                                                  unsigned ViewDepth) {
908   // Render the line containing the expansion site. No extra formatting needed.
909   renderLine(OS, L, LCS, ExpansionCol, ViewDepth);
910 }
911 
912 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
913                                                  ExpansionView &ESV,
914                                                  unsigned ViewDepth) {
915   OS << BeginExpansionDiv;
916   ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
917                   /*ShowTitle=*/false, ViewDepth + 1);
918   OS << EndExpansionDiv;
919 }
920 
921 void SourceCoverageViewHTML::renderBranchView(raw_ostream &OS, BranchView &BRV,
922                                               unsigned ViewDepth) {
923   // Render the child subview.
924   if (getOptions().Debug)
925     errs() << "Branch at line " << BRV.getLine() << '\n';
926 
927   OS << BeginExpansionDiv;
928   OS << BeginPre;
929   for (const auto &R : BRV.Regions) {
930     // Calculate TruePercent and False Percent.
931     double TruePercent = 0.0;
932     double FalsePercent = 0.0;
933     // FIXME: It may overflow when the data is too large, but I have not
934     // encountered it in actual use, and not sure whether to use __uint128_t.
935     uint64_t Total = R.ExecutionCount + R.FalseExecutionCount;
936 
937     if (!getOptions().ShowBranchCounts && Total != 0) {
938       TruePercent = ((double)(R.ExecutionCount) / (double)Total) * 100.0;
939       FalsePercent = ((double)(R.FalseExecutionCount) / (double)Total) * 100.0;
940     }
941 
942     // Display Line + Column.
943     std::string LineNoStr = utostr(uint64_t(R.LineStart));
944     std::string ColNoStr = utostr(uint64_t(R.ColumnStart));
945     std::string TargetName = "L" + LineNoStr;
946 
947     OS << "  Branch (";
948     OS << tag("span",
949               a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr),
950                 TargetName),
951               "line-number") +
952               "): [";
953 
954     if (R.Folded) {
955       OS << "Folded - Ignored]\n";
956       continue;
957     }
958 
959     // Display TrueCount or TruePercent.
960     std::string TrueColor = R.ExecutionCount ? "None" : "red";
961     std::string TrueCovClass =
962         (R.ExecutionCount > 0) ? "covered-line" : "uncovered-line";
963 
964     OS << tag("span", "True", TrueColor);
965     OS << ": ";
966     if (getOptions().ShowBranchCounts)
967       OS << tag("span", formatCount(R.ExecutionCount), TrueCovClass) << ", ";
968     else
969       OS << format("%0.2f", TruePercent) << "%, ";
970 
971     // Display FalseCount or FalsePercent.
972     std::string FalseColor = R.FalseExecutionCount ? "None" : "red";
973     std::string FalseCovClass =
974         (R.FalseExecutionCount > 0) ? "covered-line" : "uncovered-line";
975 
976     OS << tag("span", "False", FalseColor);
977     OS << ": ";
978     if (getOptions().ShowBranchCounts)
979       OS << tag("span", formatCount(R.FalseExecutionCount), FalseCovClass);
980     else
981       OS << format("%0.2f", FalsePercent) << "%";
982 
983     OS << "]\n";
984   }
985   OS << EndPre;
986   OS << EndExpansionDiv;
987 }
988 
989 void SourceCoverageViewHTML::renderMCDCView(raw_ostream &OS, MCDCView &MRV,
990                                             unsigned ViewDepth) {
991   for (auto &Record : MRV.Records) {
992     OS << BeginExpansionDiv;
993     OS << BeginPre;
994     OS << "  MC/DC Decision Region (";
995 
996     // Display Line + Column information.
997     const CounterMappingRegion &DecisionRegion = Record.getDecisionRegion();
998     std::string LineNoStr = Twine(DecisionRegion.LineStart).str();
999     std::string ColNoStr = Twine(DecisionRegion.ColumnStart).str();
1000     std::string TargetName = "L" + LineNoStr;
1001     OS << tag("span",
1002               a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr)),
1003               "line-number") +
1004               ") to (";
1005     LineNoStr = utostr(uint64_t(DecisionRegion.LineEnd));
1006     ColNoStr = utostr(uint64_t(DecisionRegion.ColumnEnd));
1007     OS << tag("span",
1008               a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr)),
1009               "line-number") +
1010               ")\n\n";
1011 
1012     // Display MC/DC Information.
1013     OS << "  Number of Conditions: " << Record.getNumConditions() << "\n";
1014     for (unsigned i = 0; i < Record.getNumConditions(); i++) {
1015       OS << "     " << Record.getConditionHeaderString(i);
1016     }
1017     OS << "\n";
1018     OS << "  Executed MC/DC Test Vectors:\n\n     ";
1019     OS << Record.getTestVectorHeaderString();
1020     for (unsigned i = 0; i < Record.getNumTestVectors(); i++)
1021       OS << Record.getTestVectorString(i);
1022     OS << "\n";
1023     for (unsigned i = 0; i < Record.getNumConditions(); i++)
1024       OS << Record.getConditionCoverageString(i);
1025     OS << "  MC/DC Coverage for Expression: ";
1026     OS << format("%0.2f", Record.getPercentCovered()) << "%\n";
1027     OS << EndPre;
1028     OS << EndExpansionDiv;
1029   }
1030   return;
1031 }
1032 
1033 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
1034                                                      InstantiationView &ISV,
1035                                                      unsigned ViewDepth) {
1036   OS << BeginExpansionDiv;
1037   if (!ISV.View)
1038     OS << BeginSourceNameDiv
1039        << tag("pre",
1040               escape("Unexecuted instantiation: " + ISV.FunctionName.str(),
1041                      getOptions()))
1042        << EndSourceNameDiv;
1043   else
1044     ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,
1045                     /*ShowTitle=*/false, ViewDepth);
1046   OS << EndExpansionDiv;
1047 }
1048 
1049 void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {
1050   if (getOptions().hasProjectTitle())
1051     OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));
1052   OS << tag(ReportTitleTag, escape(Title, getOptions()));
1053   if (getOptions().hasCreatedTime())
1054     OS << tag(CreatedTimeTag,
1055               escape(getOptions().CreatedTimeStr, getOptions()));
1056 }
1057 
1058 void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
1059                                                unsigned FirstUncoveredLineNo,
1060                                                unsigned ViewDepth) {
1061   std::string SourceLabel;
1062   if (FirstUncoveredLineNo == 0) {
1063     SourceLabel = tag("td", tag("pre", "Source"));
1064   } else {
1065     std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
1066     SourceLabel =
1067         tag("td", tag("pre", "Source (" +
1068                                  a(LinkTarget, "jump to first uncovered line") +
1069                                  ")"));
1070   }
1071 
1072   renderLinePrefix(OS, ViewDepth);
1073   OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
1074      << SourceLabel;
1075   renderLineSuffix(OS, ViewDepth);
1076 }
1077