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