xref: /llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp (revision 4bb5141a371048a2e4befb5d76ce6aa032875032)
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 "CoverageReport.h"
14 #include "SourceCoverageViewHTML.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/Path.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(const std::string &Name, const std::string &Str,
54                 const std::string &ClassName = "") {
55   std::string Tag = "<" + Name;
56   if (!ClassName.empty())
57     Tag += " class='" + ClassName + "'";
58   return Tag + ">" + Str + "</" + Name + ">";
59 }
60 
61 // Create an anchor to \p Link with the label \p Str.
62 std::string a(const std::string &Link, const std::string &Str,
63               const std::string &TargetName = "") {
64   std::string Name = TargetName.empty() ? "" : ("name='" + TargetName + "' ");
65   return "<a " + Name + "href='" + Link + "'>" + Str + "</a>";
66 }
67 
68 const char *BeginHeader =
69   "<head>"
70     "<meta name='viewport' content='width=device-width,initial-scale=1'>"
71     "<meta charset='UTF-8'>";
72 
73 const char *CSSForCoverage =
74     R"(.red {
75   background-color: #ffd0d0;
76 }
77 .cyan {
78   background-color: cyan;
79 }
80 body {
81   font-family: -apple-system, sans-serif;
82 }
83 pre {
84   margin-top: 0px !important;
85   margin-bottom: 0px !important;
86 }
87 .source-name-title {
88   padding: 5px 10px;
89   border-bottom: 1px solid #dbdbdb;
90   background-color: #eee;
91   line-height: 35px;
92 }
93 .centered {
94   display: table;
95   margin-left: left;
96   margin-right: auto;
97   border: 1px solid #dbdbdb;
98   border-radius: 3px;
99 }
100 .expansion-view {
101   background-color: rgba(0, 0, 0, 0);
102   margin-left: 0px;
103   margin-top: 5px;
104   margin-right: 5px;
105   margin-bottom: 5px;
106   border: 1px solid #dbdbdb;
107   border-radius: 3px;
108 }
109 table {
110   border-collapse: collapse;
111 }
112 .light-row {
113   background: #ffffff;
114   border: 1px solid #dbdbdb;
115 }
116 .light-row-bold {
117   background: #ffffff;
118   border: 1px solid #dbdbdb;
119   font-weight: bold;
120 }
121 .column-entry {
122   text-align: left;
123 }
124 .column-entry-bold {
125   font-weight: bold;
126   text-align: left;
127 }
128 .column-entry-yellow {
129   text-align: left;
130   background-color: #ffffd0;
131 }
132 .column-entry-yellow:hover {
133   background-color: #fffff0;
134 }
135 .column-entry-red {
136   text-align: left;
137   background-color: #ffd0d0;
138 }
139 .column-entry-red:hover {
140   background-color: #fff0f0;
141 }
142 .column-entry-green {
143   text-align: left;
144   background-color: #d0ffd0;
145 }
146 .column-entry-green:hover {
147   background-color: #f0fff0;
148 }
149 .line-number {
150   text-align: right;
151   color: #aaa;
152 }
153 .covered-line {
154   text-align: right;
155   color: #0080ff;
156 }
157 .uncovered-line {
158   text-align: right;
159   color: #ff3300;
160 }
161 .tooltip {
162   position: relative;
163   display: inline;
164   background-color: #b3e6ff;
165   text-decoration: none;
166 }
167 .tooltip span.tooltip-content {
168   position: absolute;
169   width: 100px;
170   margin-left: -50px;
171   color: #FFFFFF;
172   background: #000000;
173   height: 30px;
174   line-height: 30px;
175   text-align: center;
176   visibility: hidden;
177   border-radius: 6px;
178 }
179 .tooltip span.tooltip-content:after {
180   content: '';
181   position: absolute;
182   top: 100%;
183   left: 50%;
184   margin-left: -8px;
185   width: 0; height: 0;
186   border-top: 8px solid #000000;
187   border-right: 8px solid transparent;
188   border-left: 8px solid transparent;
189 }
190 :hover.tooltip span.tooltip-content {
191   visibility: visible;
192   opacity: 0.8;
193   bottom: 30px;
194   left: 50%;
195   z-index: 999;
196 }
197 th, td {
198   vertical-align: top;
199   padding: 2px 8px;
200   border-collapse: collapse;
201   border-right: solid 1px #eee;
202   border-left: solid 1px #eee;
203   text-align: left;
204 }
205 td pre {
206   display: inline-block;
207 }
208 td:first-child {
209   border-left: none;
210 }
211 td:last-child {
212   border-right: none;
213 }
214 tr:hover {
215   background-color: #f0f0f0;
216 }
217 )";
218 
219 const char *EndHeader = "</head>";
220 
221 const char *BeginCenteredDiv = "<div class='centered'>";
222 
223 const char *EndCenteredDiv = "</div>";
224 
225 const char *BeginSourceNameDiv = "<div class='source-name-title'>";
226 
227 const char *EndSourceNameDiv = "</div>";
228 
229 const char *BeginCodeTD = "<td class='code'>";
230 
231 const char *EndCodeTD = "</td>";
232 
233 const char *BeginPre = "<pre>";
234 
235 const char *EndPre = "</pre>";
236 
237 const char *BeginExpansionDiv = "<div class='expansion-view'>";
238 
239 const char *EndExpansionDiv = "</div>";
240 
241 const char *BeginTable = "<table>";
242 
243 const char *EndTable = "</table>";
244 
245 const char *ProjectTitleTag = "h1";
246 
247 const char *ReportTitleTag = "h2";
248 
249 const char *CreatedTimeTag = "h4";
250 
251 std::string getPathToStyle(StringRef ViewPath) {
252   std::string PathToStyle;
253   std::string PathSep = std::string(sys::path::get_separator());
254   unsigned NumSeps = ViewPath.count(PathSep);
255   for (unsigned I = 0, E = NumSeps; I < E; ++I)
256     PathToStyle += ".." + PathSep;
257   return PathToStyle + "style.css";
258 }
259 
260 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
261                  const std::string &PathToStyle = "") {
262   OS << "<!doctype html>"
263         "<html>"
264      << BeginHeader;
265 
266   // Link to a stylesheet if one is available. Otherwise, use the default style.
267   if (PathToStyle.empty())
268     OS << "<style>" << CSSForCoverage << "</style>";
269   else
270     OS << "<link rel='stylesheet' type='text/css' href='"
271        << escape(PathToStyle, Opts) << "'>";
272 
273   OS << EndHeader << "<body>";
274 }
275 
276 void emitEpilog(raw_ostream &OS) {
277   OS << "</body>"
278      << "</html>";
279 }
280 
281 } // anonymous namespace
282 
283 Expected<CoveragePrinter::OwnedStream>
284 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
285   auto OSOrErr = createOutputStream(Path, "html", InToplevel);
286   if (!OSOrErr)
287     return OSOrErr;
288 
289   OwnedStream OS = std::move(OSOrErr.get());
290 
291   if (!Opts.hasOutputDirectory()) {
292     emitPrelude(*OS.get(), Opts);
293   } else {
294     std::string ViewPath = getOutputPath(Path, "html", InToplevel);
295     emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
296   }
297 
298   return std::move(OS);
299 }
300 
301 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
302   emitEpilog(*OS.get());
303 }
304 
305 /// Emit column labels for the table in the index.
306 static void emitColumnLabelsForIndex(raw_ostream &OS,
307                                      const CoverageViewOptions &Opts) {
308   SmallVector<std::string, 4> Columns;
309   Columns.emplace_back(tag("td", "Filename", "column-entry-bold"));
310   Columns.emplace_back(tag("td", "Function Coverage", "column-entry-bold"));
311   if (Opts.ShowInstantiationSummary)
312     Columns.emplace_back(
313         tag("td", "Instantiation Coverage", "column-entry-bold"));
314   Columns.emplace_back(tag("td", "Line Coverage", "column-entry-bold"));
315   if (Opts.ShowRegionSummary)
316     Columns.emplace_back(tag("td", "Region Coverage", "column-entry-bold"));
317   if (Opts.ShowBranchSummary)
318     Columns.emplace_back(tag("td", "Branch Coverage", "column-entry-bold"));
319   OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
320 }
321 
322 std::string
323 CoveragePrinterHTML::buildLinkToFile(StringRef SF,
324                                      const FileCoverageSummary &FCS) const {
325   SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
326   sys::path::remove_dots(LinkTextStr, /*remove_dot_dot=*/true);
327   sys::path::native(LinkTextStr);
328   std::string LinkText = escape(LinkTextStr, Opts);
329   std::string LinkTarget =
330       escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
331   return a(LinkTarget, LinkText);
332 }
333 
334 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
335 /// false, link the summary to \p SF.
336 void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
337                                           const FileCoverageSummary &FCS,
338                                           bool IsTotals) const {
339   SmallVector<std::string, 8> Columns;
340 
341   // Format a coverage triple and add the result to the list of columns.
342   auto AddCoverageTripleToColumn =
343       [&Columns, this](unsigned Hit, unsigned Total, float Pctg) {
344         std::string S;
345         {
346           raw_string_ostream RSO{S};
347           if (Total)
348             RSO << format("%*.2f", 7, Pctg) << "% ";
349           else
350             RSO << "- ";
351           RSO << '(' << Hit << '/' << Total << ')';
352         }
353         const char *CellClass = "column-entry-yellow";
354         if (Pctg >= Opts.HighCovWatermark)
355           CellClass = "column-entry-green";
356         else if (Pctg < Opts.LowCovWatermark)
357           CellClass = "column-entry-red";
358         Columns.emplace_back(tag("td", tag("pre", S), CellClass));
359       };
360 
361   // Simplify the display file path, and wrap it in a link if requested.
362   std::string Filename;
363   if (IsTotals) {
364     Filename = std::string(SF);
365   } else {
366     Filename = buildLinkToFile(SF, FCS);
367   }
368 
369   Columns.emplace_back(tag("td", tag("pre", Filename)));
370   AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),
371                             FCS.FunctionCoverage.getNumFunctions(),
372                             FCS.FunctionCoverage.getPercentCovered());
373   if (Opts.ShowInstantiationSummary)
374     AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),
375                               FCS.InstantiationCoverage.getNumFunctions(),
376                               FCS.InstantiationCoverage.getPercentCovered());
377   AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),
378                             FCS.LineCoverage.getNumLines(),
379                             FCS.LineCoverage.getPercentCovered());
380   if (Opts.ShowRegionSummary)
381     AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),
382                               FCS.RegionCoverage.getNumRegions(),
383                               FCS.RegionCoverage.getPercentCovered());
384   if (Opts.ShowBranchSummary)
385     AddCoverageTripleToColumn(FCS.BranchCoverage.getCovered(),
386                               FCS.BranchCoverage.getNumBranches(),
387                               FCS.BranchCoverage.getPercentCovered());
388 
389   if (IsTotals)
390     OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row-bold");
391   else
392     OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
393 }
394 
395 Error CoveragePrinterHTML::createIndexFile(
396     ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,
397     const CoverageFiltersMatchAll &Filters) {
398   // Emit the default stylesheet.
399   auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
400   if (Error E = CSSOrErr.takeError())
401     return E;
402 
403   OwnedStream CSS = std::move(CSSOrErr.get());
404   CSS->operator<<(CSSForCoverage);
405 
406   // Emit a file index along with some coverage statistics.
407   auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
408   if (Error E = OSOrErr.takeError())
409     return E;
410   auto OS = std::move(OSOrErr.get());
411   raw_ostream &OSRef = *OS.get();
412 
413   assert(Opts.hasOutputDirectory() && "No output directory for index file");
414   emitPrelude(OSRef, Opts, getPathToStyle(""));
415 
416   // Emit some basic information about the coverage report.
417   if (Opts.hasProjectTitle())
418     OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));
419   OSRef << tag(ReportTitleTag, "Coverage Report");
420   if (Opts.hasCreatedTime())
421     OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));
422 
423   // Emit a link to some documentation.
424   OSRef << tag("p", "Click " +
425                         a("http://clang.llvm.org/docs/"
426                           "SourceBasedCodeCoverage.html#interpreting-reports",
427                           "here") +
428                         " for information about interpreting this report.");
429 
430   // Emit a table containing links to reports for each file in the covmapping.
431   // Exclude files which don't contain any regions.
432   OSRef << BeginCenteredDiv << BeginTable;
433   emitColumnLabelsForIndex(OSRef, Opts);
434   FileCoverageSummary Totals("TOTALS");
435   auto FileReports = CoverageReport::prepareFileReports(
436       Coverage, Totals, SourceFiles, Opts, Filters);
437   bool EmptyFiles = false;
438   for (unsigned I = 0, E = FileReports.size(); I < E; ++I) {
439     if (FileReports[I].FunctionCoverage.getNumFunctions())
440       emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
441     else
442       EmptyFiles = true;
443   }
444   emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
445   OSRef << EndTable << EndCenteredDiv;
446 
447   // Emit links to files which don't contain any functions. These are normally
448   // not very useful, but could be relevant for code which abuses the
449   // preprocessor.
450   if (EmptyFiles && Filters.empty()) {
451     OSRef << tag("p", "Files which contain no functions. (These "
452                       "files contain code pulled into other files "
453                       "by the preprocessor.)\n");
454     OSRef << BeginCenteredDiv << BeginTable;
455     for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
456       if (!FileReports[I].FunctionCoverage.getNumFunctions()) {
457         std::string Link = buildLinkToFile(SourceFiles[I], FileReports[I]);
458         OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';
459       }
460     OSRef << EndTable << EndCenteredDiv;
461   }
462 
463   OSRef << tag("h5", escape(Opts.getLLVMVersionString(), Opts));
464   emitEpilog(OSRef);
465 
466   return Error::success();
467 }
468 
469 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
470   OS << BeginCenteredDiv << BeginTable;
471 }
472 
473 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
474   OS << EndTable << EndCenteredDiv;
475 }
476 
477 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {
478   OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))
479      << EndSourceNameDiv;
480 }
481 
482 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
483   OS << "<tr>";
484 }
485 
486 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
487   // If this view has sub-views, renderLine() cannot close the view's cell.
488   // Take care of it here, after all sub-views have been rendered.
489   if (hasSubViews())
490     OS << EndCodeTD;
491   OS << "</tr>";
492 }
493 
494 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
495   // The table-based output makes view dividers unnecessary.
496 }
497 
498 void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L,
499                                         const LineCoverageStats &LCS,
500                                         unsigned ExpansionCol, unsigned) {
501   StringRef Line = L.Line;
502   unsigned LineNo = L.LineNo;
503 
504   // Steps for handling text-escaping, highlighting, and tooltip creation:
505   //
506   // 1. Split the line into N+1 snippets, where N = |Segments|. The first
507   //    snippet starts from Col=1 and ends at the start of the first segment.
508   //    The last snippet starts at the last mapped column in the line and ends
509   //    at the end of the line. Both are required but may be empty.
510 
511   SmallVector<std::string, 8> Snippets;
512   CoverageSegmentArray Segments = LCS.getLineSegments();
513 
514   unsigned LCol = 1;
515   auto Snip = [&](unsigned Start, unsigned Len) {
516     Snippets.push_back(std::string(Line.substr(Start, Len)));
517     LCol += Len;
518   };
519 
520   Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
521 
522   for (unsigned I = 1, E = Segments.size(); I < E; ++I)
523     Snip(LCol - 1, Segments[I]->Col - LCol);
524 
525   // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
526   Snip(LCol - 1, Line.size() + 1 - LCol);
527 
528   // 2. Escape all of the snippets.
529 
530   for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
531     Snippets[I] = escape(Snippets[I], getOptions());
532 
533   // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
534   //    1 to set the highlight for snippet 2, segment 2 to set the highlight for
535   //    snippet 3, and so on.
536 
537   std::optional<StringRef> Color;
538   SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
539   auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
540     if (getOptions().Debug)
541       HighlightedRanges.emplace_back(LC, RC);
542     return tag("span", Snippet, std::string(*Color));
543   };
544 
545   auto CheckIfUncovered = [&](const CoverageSegment *S) {
546     return S && (!S->IsGapRegion || (Color && *Color == "red")) &&
547            S->HasCount && S->Count == 0;
548   };
549 
550   if (CheckIfUncovered(LCS.getWrappedSegment())) {
551     Color = "red";
552     if (!Snippets[0].empty())
553       Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
554   }
555 
556   for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
557     const auto *CurSeg = Segments[I];
558     if (CheckIfUncovered(CurSeg))
559       Color = "red";
560     else if (CurSeg->Col == ExpansionCol)
561       Color = "cyan";
562     else
563       Color = None;
564 
565     if (Color)
566       Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
567                                   CurSeg->Col + Snippets[I + 1].size());
568   }
569 
570   if (Color && Segments.empty())
571     Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
572 
573   if (getOptions().Debug) {
574     for (const auto &Range : HighlightedRanges) {
575       errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
576       if (Range.second == 0)
577         errs() << "?";
578       else
579         errs() << Range.second;
580       errs() << "\n";
581     }
582   }
583 
584   // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
585   //    sub-line region count tooltips if needed.
586 
587   if (shouldRenderRegionMarkers(LCS)) {
588     // Just consider the segments which start *and* end on this line.
589     for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
590       const auto *CurSeg = Segments[I];
591       if (!CurSeg->IsRegionEntry)
592         continue;
593       if (CurSeg->Count == LCS.getExecutionCount())
594         continue;
595 
596       Snippets[I + 1] =
597           tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
598                                            "tooltip-content"),
599               "tooltip");
600 
601       if (getOptions().Debug)
602         errs() << "Marker at " << CurSeg->Line << ":" << CurSeg->Col << " = "
603                << formatCount(CurSeg->Count) << "\n";
604     }
605   }
606 
607   OS << BeginCodeTD;
608   OS << BeginPre;
609   for (const auto &Snippet : Snippets)
610     OS << Snippet;
611   OS << EndPre;
612 
613   // If there are no sub-views left to attach to this cell, end the cell.
614   // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
615   if (!hasSubViews())
616     OS << EndCodeTD;
617 }
618 
619 void SourceCoverageViewHTML::renderLineCoverageColumn(
620     raw_ostream &OS, const LineCoverageStats &Line) {
621   std::string Count;
622   if (Line.isMapped())
623     Count = tag("pre", formatCount(Line.getExecutionCount()));
624   std::string CoverageClass =
625       (Line.getExecutionCount() > 0) ? "covered-line" : "uncovered-line";
626   OS << tag("td", Count, CoverageClass);
627 }
628 
629 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
630                                                     unsigned LineNo) {
631   std::string LineNoStr = utostr(uint64_t(LineNo));
632   std::string TargetName = "L" + LineNoStr;
633   OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),
634             "line-number");
635 }
636 
637 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
638                                                  const LineCoverageStats &Line,
639                                                  unsigned) {
640   // Region markers are rendered in-line using tooltips.
641 }
642 
643 void SourceCoverageViewHTML::renderExpansionSite(raw_ostream &OS, LineRef L,
644                                                  const LineCoverageStats &LCS,
645                                                  unsigned ExpansionCol,
646                                                  unsigned ViewDepth) {
647   // Render the line containing the expansion site. No extra formatting needed.
648   renderLine(OS, L, LCS, ExpansionCol, ViewDepth);
649 }
650 
651 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
652                                                  ExpansionView &ESV,
653                                                  unsigned ViewDepth) {
654   OS << BeginExpansionDiv;
655   ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
656                   /*ShowTitle=*/false, ViewDepth + 1);
657   OS << EndExpansionDiv;
658 }
659 
660 void SourceCoverageViewHTML::renderBranchView(raw_ostream &OS, BranchView &BRV,
661                                               unsigned ViewDepth) {
662   // Render the child subview.
663   if (getOptions().Debug)
664     errs() << "Branch at line " << BRV.getLine() << '\n';
665 
666   OS << BeginExpansionDiv;
667   OS << BeginPre;
668   for (const auto &R : BRV.Regions) {
669     // Calculate TruePercent and False Percent.
670     double TruePercent = 0.0;
671     double FalsePercent = 0.0;
672     unsigned Total = R.ExecutionCount + R.FalseExecutionCount;
673 
674     if (!getOptions().ShowBranchCounts && Total != 0) {
675       TruePercent = ((double)(R.ExecutionCount) / (double)Total) * 100.0;
676       FalsePercent = ((double)(R.FalseExecutionCount) / (double)Total) * 100.0;
677     }
678 
679     // Display Line + Column.
680     std::string LineNoStr = utostr(uint64_t(R.LineStart));
681     std::string ColNoStr = utostr(uint64_t(R.ColumnStart));
682     std::string TargetName = "L" + LineNoStr;
683 
684     OS << "  Branch (";
685     OS << tag("span",
686               a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr),
687                 TargetName),
688               "line-number") +
689               "): [";
690 
691     if (R.Folded) {
692       OS << "Folded - Ignored]\n";
693       continue;
694     }
695 
696     // Display TrueCount or TruePercent.
697     std::string TrueColor = R.ExecutionCount ? "None" : "red";
698     std::string TrueCovClass =
699         (R.ExecutionCount > 0) ? "covered-line" : "uncovered-line";
700 
701     OS << tag("span", "True", TrueColor);
702     OS << ": ";
703     if (getOptions().ShowBranchCounts)
704       OS << tag("span", formatCount(R.ExecutionCount), TrueCovClass) << ", ";
705     else
706       OS << format("%0.2f", TruePercent) << "%, ";
707 
708     // Display FalseCount or FalsePercent.
709     std::string FalseColor = R.FalseExecutionCount ? "None" : "red";
710     std::string FalseCovClass =
711         (R.FalseExecutionCount > 0) ? "covered-line" : "uncovered-line";
712 
713     OS << tag("span", "False", FalseColor);
714     OS << ": ";
715     if (getOptions().ShowBranchCounts)
716       OS << tag("span", formatCount(R.FalseExecutionCount), FalseCovClass);
717     else
718       OS << format("%0.2f", FalsePercent) << "%";
719 
720     OS << "]\n";
721   }
722   OS << EndPre;
723   OS << EndExpansionDiv;
724 }
725 
726 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
727                                                      InstantiationView &ISV,
728                                                      unsigned ViewDepth) {
729   OS << BeginExpansionDiv;
730   if (!ISV.View)
731     OS << BeginSourceNameDiv
732        << tag("pre",
733               escape("Unexecuted instantiation: " + ISV.FunctionName.str(),
734                      getOptions()))
735        << EndSourceNameDiv;
736   else
737     ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,
738                     /*ShowTitle=*/false, ViewDepth);
739   OS << EndExpansionDiv;
740 }
741 
742 void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {
743   if (getOptions().hasProjectTitle())
744     OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));
745   OS << tag(ReportTitleTag, escape(Title, getOptions()));
746   if (getOptions().hasCreatedTime())
747     OS << tag(CreatedTimeTag,
748               escape(getOptions().CreatedTimeStr, getOptions()));
749 }
750 
751 void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
752                                                unsigned FirstUncoveredLineNo,
753                                                unsigned ViewDepth) {
754   std::string SourceLabel;
755   if (FirstUncoveredLineNo == 0) {
756     SourceLabel = tag("td", tag("pre", "Source"));
757   } else {
758     std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
759     SourceLabel =
760         tag("td", tag("pre", "Source (" +
761                                  a(LinkTarget, "jump to first uncovered line") +
762                                  ")"));
763   }
764 
765   renderLinePrefix(OS, ViewDepth);
766   OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
767      << SourceLabel;
768   renderLineSuffix(OS, ViewDepth);
769 }
770