xref: /llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp (revision c236e5a0f1b9b8118428bec5a7adf3e3efc86cf1)
1 //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file This file implements the html coverage renderer.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "CoverageReport.h"
15 #include "SourceCoverageViewHTML.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/Path.h"
22 
23 using namespace llvm;
24 
25 namespace {
26 
27 // Return a string with the special characters in \p Str escaped.
28 std::string escape(StringRef Str, const CoverageViewOptions &Opts) {
29   std::string Result;
30   unsigned ColNum = 0; // Record the column number.
31   for (char C : Str) {
32     ++ColNum;
33     if (C == '&')
34       Result += "&";
35     else if (C == '<')
36       Result += "&lt;";
37     else if (C == '>')
38       Result += "&gt;";
39     else if (C == '\"')
40       Result += "&quot;";
41     else if (C == '\n' || C == '\r') {
42       Result += C;
43       ColNum = 0;
44     } else if (C == '\t') {
45       // Replace '\t' with TabSize spaces.
46       unsigned NumSpaces = Opts.TabSize - (--ColNum % Opts.TabSize);
47       for (unsigned I = 0; I < NumSpaces; ++I)
48         Result += "&nbsp;";
49       ColNum += NumSpaces;
50     } else
51       Result += C;
52   }
53   return Result;
54 }
55 
56 // Create a \p Name tag around \p Str, and optionally set its \p ClassName.
57 std::string tag(const std::string &Name, const std::string &Str,
58                 const std::string &ClassName = "") {
59   std::string Tag = "<" + Name;
60   if (ClassName != "")
61     Tag += " class='" + ClassName + "'";
62   return Tag + ">" + Str + "</" + Name + ">";
63 }
64 
65 // Create an anchor to \p Link with the label \p Str.
66 std::string a(const std::string &Link, const std::string &Str,
67               const std::string &TargetType = "href") {
68   return "<a " + TargetType + "='" + Link + "'>" + Str + "</a>";
69 }
70 
71 const char *BeginHeader =
72   "<head>"
73     "<meta name='viewport' content='width=device-width,initial-scale=1'>"
74     "<meta charset='UTF-8'>";
75 
76 const char *CSSForCoverage =
77     R"(.red {
78   background-color: #ffd0d0;
79 }
80 .cyan {
81   background-color: cyan;
82 }
83 body {
84   font-family: -apple-system, sans-serif;
85 }
86 pre {
87   margin-top: 0px !important;
88   margin-bottom: 0px !important;
89 }
90 .source-name-title {
91   padding: 5px 10px;
92   border-bottom: 1px solid #dbdbdb;
93   background-color: #eee;
94   line-height: 35px;
95 }
96 .centered {
97   display: table;
98   margin-left: left;
99   margin-right: auto;
100   border: 1px solid #dbdbdb;
101   border-radius: 3px;
102 }
103 .expansion-view {
104   background-color: rgba(0, 0, 0, 0);
105   margin-left: 0px;
106   margin-top: 5px;
107   margin-right: 5px;
108   margin-bottom: 5px;
109   border: 1px solid #dbdbdb;
110   border-radius: 3px;
111 }
112 table {
113   border-collapse: collapse;
114 }
115 .light-row {
116   background: #ffffff;
117   border: 1px solid #dbdbdb;
118 }
119 .column-entry {
120   text-align: right;
121 }
122 .column-entry-yellow {
123   text-align: right;
124   background-color: #ffffd0;
125 }
126 .column-entry-red {
127   text-align: right;
128   background-color: #ffd0d0;
129 }
130 .column-entry-green {
131   text-align: right;
132   background-color: #d0ffd0;
133 }
134 .line-number {
135   text-align: right;
136   color: #aaa;
137 }
138 .covered-line {
139   text-align: right;
140   color: #0080ff;
141 }
142 .uncovered-line {
143   text-align: right;
144   color: #ff3300;
145 }
146 .tooltip {
147   position: relative;
148   display: inline;
149   background-color: #b3e6ff;
150   text-decoration: none;
151 }
152 .tooltip span.tooltip-content {
153   position: absolute;
154   width: 100px;
155   margin-left: -50px;
156   color: #FFFFFF;
157   background: #000000;
158   height: 30px;
159   line-height: 30px;
160   text-align: center;
161   visibility: hidden;
162   border-radius: 6px;
163 }
164 .tooltip span.tooltip-content:after {
165   content: '';
166   position: absolute;
167   top: 100%;
168   left: 50%;
169   margin-left: -8px;
170   width: 0; height: 0;
171   border-top: 8px solid #000000;
172   border-right: 8px solid transparent;
173   border-left: 8px solid transparent;
174 }
175 :hover.tooltip span.tooltip-content {
176   visibility: visible;
177   opacity: 0.8;
178   bottom: 30px;
179   left: 50%;
180   z-index: 999;
181 }
182 th, td {
183   vertical-align: top;
184   padding: 2px 5px;
185   border-collapse: collapse;
186   border-right: solid 1px #eee;
187   border-left: solid 1px #eee;
188 }
189 td:first-child {
190   border-left: none;
191 }
192 td:last-child {
193   border-right: none;
194 }
195 .project-title {
196   font-size:36.0pt;
197   line-height:200%;
198   font-family:Calibri;
199   font-weight: bold;
200 }
201 .report-title {
202   font-size:16.0pt;
203   line-height:120%;
204   font-family:Arial;
205   font-weight: bold;
206 }
207 .created-time {
208   font-size:14.0pt;
209   line-height:120%;
210   font-family:Arial;
211 }
212 )";
213 
214 const char *EndHeader = "</head>";
215 
216 const char *BeginCenteredDiv = "<div class='centered'>";
217 
218 const char *EndCenteredDiv = "</div>";
219 
220 const char *BeginSourceNameDiv = "<div class='source-name-title'>";
221 
222 const char *EndSourceNameDiv = "</div>";
223 
224 const char *BeginCodeTD = "<td class='code'>";
225 
226 const char *EndCodeTD = "</td>";
227 
228 const char *BeginPre = "<pre>";
229 
230 const char *EndPre = "</pre>";
231 
232 const char *BeginExpansionDiv = "<div class='expansion-view'>";
233 
234 const char *EndExpansionDiv = "</div>";
235 
236 const char *BeginTable = "<table>";
237 
238 const char *EndTable = "</table>";
239 
240 const char *BeginProjectTitleDiv = "<div class='project-title'>";
241 
242 const char *EndProjectTitleDiv = "</div>";
243 
244 const char *BeginReportTitleDiv = "<div class='report-title'>";
245 
246 const char *EndReportTitleDiv = "</div>";
247 
248 const char *BeginCreatedTimeDiv = "<div class='created-time'>";
249 
250 const char *EndCreatedTimeDiv = "</div>";
251 
252 const char *LineBreak = "<br>";
253 
254 std::string getPathToStyle(StringRef ViewPath) {
255   std::string PathToStyle = "";
256   std::string PathSep = sys::path::get_separator();
257   unsigned NumSeps = ViewPath.count(PathSep);
258   for (unsigned I = 0, E = NumSeps; I < E; ++I)
259     PathToStyle += ".." + PathSep;
260   return PathToStyle + "style.css";
261 }
262 
263 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
264                  const std::string &PathToStyle = "") {
265   OS << "<!doctype html>"
266         "<html>"
267      << BeginHeader;
268 
269   // Link to a stylesheet if one is available. Otherwise, use the default style.
270   if (PathToStyle.empty())
271     OS << "<style>" << CSSForCoverage << "</style>";
272   else
273     OS << "<link rel='stylesheet' type='text/css' href='"
274        << escape(PathToStyle, Opts) << "'>";
275 
276   OS << EndHeader << "<body>";
277 }
278 
279 void emitEpilog(raw_ostream &OS) {
280   OS << "</body>"
281      << "</html>";
282 }
283 
284 } // anonymous namespace
285 
286 Expected<CoveragePrinter::OwnedStream>
287 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
288   auto OSOrErr = createOutputStream(Path, "html", InToplevel);
289   if (!OSOrErr)
290     return OSOrErr;
291 
292   OwnedStream OS = std::move(OSOrErr.get());
293 
294   if (!Opts.hasOutputDirectory()) {
295     emitPrelude(*OS.get(), Opts);
296   } else {
297     std::string ViewPath = getOutputPath(Path, "html", InToplevel);
298     emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
299   }
300 
301   return std::move(OS);
302 }
303 
304 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
305   emitEpilog(*OS.get());
306 }
307 
308 /// Emit column labels for the table in the index.
309 static void emitColumnLabelsForIndex(raw_ostream &OS) {
310   SmallVector<std::string, 4> Columns;
311   for (const char *Label :
312        {"Filename", "Region Coverage", "Function Coverage", "Line Coverage"})
313     Columns.emplace_back(tag("td", Label, "column-entry"));
314   OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
315 }
316 
317 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
318 /// false, link the summary to \p SF.
319 void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
320                                           const FileCoverageSummary &FCS,
321                                           bool IsTotals) const {
322   SmallVector<std::string, 4> Columns;
323 
324   // Format a coverage triple and add the result to the list of columns.
325   auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
326                                               float Pctg) {
327     std::string S;
328     {
329       raw_string_ostream RSO{S};
330       RSO << format("%*.2f", 7, Pctg) << "% (" << Hit << '/' << Total << ')';
331     }
332     const char *CellClass = "column-entry-yellow";
333     if (Pctg < 80.0)
334       CellClass = "column-entry-red";
335     else if (Hit == Total)
336       CellClass = "column-entry-green";
337     Columns.emplace_back(tag("td", tag("pre", S, "code"), CellClass));
338   };
339 
340   // Simplify the display file path, and wrap it in a link if requested.
341   std::string Filename;
342   SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
343   sys::path::remove_dots(LinkTextStr, /*remove_dot_dots=*/true);
344   sys::path::native(LinkTextStr);
345   std::string LinkText = escape(LinkTextStr, Opts);
346   if (IsTotals) {
347     Filename = LinkText;
348   } else {
349     std::string LinkTarget =
350         escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
351     Filename = a(LinkTarget, LinkText);
352   }
353 
354   Columns.emplace_back(tag("td", tag("pre", Filename, "code")));
355   AddCoverageTripleToColumn(
356       FCS.RegionCoverage.NumRegions - FCS.RegionCoverage.NotCovered,
357       FCS.RegionCoverage.NumRegions, FCS.RegionCoverage.getPercentCovered());
358   AddCoverageTripleToColumn(FCS.FunctionCoverage.Executed,
359                             FCS.FunctionCoverage.NumFunctions,
360                             FCS.FunctionCoverage.getPercentCovered());
361   AddCoverageTripleToColumn(
362       FCS.LineCoverage.NumLines - FCS.LineCoverage.NotCovered,
363       FCS.LineCoverage.NumLines, FCS.LineCoverage.getPercentCovered());
364 
365   OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
366 }
367 
368 Error CoveragePrinterHTML::createIndexFile(
369     ArrayRef<StringRef> SourceFiles,
370     const coverage::CoverageMapping &Coverage) {
371   // Emit the default stylesheet.
372   auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
373   if (Error E = CSSOrErr.takeError())
374     return E;
375 
376   OwnedStream CSS = std::move(CSSOrErr.get());
377   CSS->operator<<(CSSForCoverage);
378 
379   // Emit a file index along with some coverage statistics.
380   auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
381   if (Error E = OSOrErr.takeError())
382     return E;
383   auto OS = std::move(OSOrErr.get());
384   raw_ostream &OSRef = *OS.get();
385 
386   assert(Opts.hasOutputDirectory() && "No output directory for index file");
387   emitPrelude(OSRef, Opts, getPathToStyle(""));
388 
389   // Emit some basic information about the coverage report.
390   if (Opts.hasProjectTitle())
391     OSRef << BeginProjectTitleDiv
392           << tag("span", escape(Opts.ProjectTitle, Opts)) << EndProjectTitleDiv;
393   OSRef << BeginReportTitleDiv
394         << tag("span", escape("Code Coverage Report", Opts))
395         << EndReportTitleDiv;
396   if (Opts.hasCreatedTime())
397     OSRef << BeginCreatedTimeDiv
398           << tag("span", escape(Opts.CreatedTimeStr, Opts))
399           << EndCreatedTimeDiv;
400   OSRef << LineBreak;
401 
402   // Emit a table containing links to reports for each file in the covmapping.
403   CoverageReport Report(Opts, Coverage);
404   OSRef << BeginCenteredDiv << BeginTable;
405   emitColumnLabelsForIndex(OSRef);
406   FileCoverageSummary Totals("TOTALS");
407   auto FileReports = Report.prepareFileReports(Totals, SourceFiles);
408   for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
409     emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
410   emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
411   OSRef << EndTable << EndCenteredDiv;
412   emitEpilog(OSRef);
413 
414   return Error::success();
415 }
416 
417 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
418   OS << LineBreak << BeginCenteredDiv << BeginTable;
419 }
420 
421 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
422   OS << EndTable << EndCenteredDiv;
423 }
424 
425 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile,
426                                               unsigned FirstUncoveredLineNo) {
427   OS << BeginSourceNameDiv;
428   std::string ViewInfo = escape(
429       WholeFile ? getVerboseSourceName() : getSourceName(), getOptions());
430   OS << tag("pre", ViewInfo);
431   if (WholeFile) {
432     // Render the "Go to first unexecuted line" link for the view.
433     if (FirstUncoveredLineNo != 0) { // The file is not fully covered
434       std::string LinkText =
435           escape("Go to first unexecuted line", getOptions());
436       std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
437       OS << tag("pre", a(LinkTarget, LinkText));
438     }
439   }
440   OS << EndSourceNameDiv;
441 }
442 
443 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
444   OS << "<tr>";
445 }
446 
447 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
448   // If this view has sub-views, renderLine() cannot close the view's cell.
449   // Take care of it here, after all sub-views have been rendered.
450   if (hasSubViews())
451     OS << EndCodeTD;
452   OS << "</tr>";
453 }
454 
455 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
456   // The table-based output makes view dividers unnecessary.
457 }
458 
459 void SourceCoverageViewHTML::renderLine(
460     raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
461     CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned) {
462   StringRef Line = L.Line;
463   unsigned LineNo = L.LineNo;
464 
465   // Steps for handling text-escaping, highlighting, and tooltip creation:
466   //
467   // 1. Split the line into N+1 snippets, where N = |Segments|. The first
468   //    snippet starts from Col=1 and ends at the start of the first segment.
469   //    The last snippet starts at the last mapped column in the line and ends
470   //    at the end of the line. Both are required but may be empty.
471 
472   SmallVector<std::string, 8> Snippets;
473 
474   unsigned LCol = 1;
475   auto Snip = [&](unsigned Start, unsigned Len) {
476     Snippets.push_back(Line.substr(Start, Len));
477     LCol += Len;
478   };
479 
480   Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
481 
482   for (unsigned I = 1, E = Segments.size(); I < E; ++I)
483     Snip(LCol - 1, Segments[I]->Col - LCol);
484 
485   // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
486   Snip(LCol - 1, Line.size() + 1 - LCol);
487 
488   // 2. Escape all of the snippets.
489 
490   for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
491     Snippets[I] = escape(Snippets[I], getOptions());
492 
493   // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
494   //    1 to set the highlight for snippet 2, segment 2 to set the highlight for
495   //    snippet 3, and so on.
496 
497   Optional<std::string> Color;
498   SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
499   auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
500     if (getOptions().Debug)
501       HighlightedRanges.emplace_back(LC, RC);
502     return tag("span", Snippet, Color.getValue());
503   };
504 
505   auto CheckIfUncovered = [](const coverage::CoverageSegment *S) {
506     return S && S->HasCount && S->Count == 0;
507   };
508 
509   if (CheckIfUncovered(WrappedSegment)) {
510     Color = "red";
511     if (!Snippets[0].empty())
512       Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
513   }
514 
515   for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
516     const auto *CurSeg = Segments[I];
517     if (CurSeg->Col == ExpansionCol)
518       Color = "cyan";
519     else if (CheckIfUncovered(CurSeg))
520       Color = "red";
521     else
522       Color = None;
523 
524     if (Color.hasValue())
525       Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
526                                   CurSeg->Col + Snippets[I + 1].size());
527   }
528 
529   if (Color.hasValue() && Segments.empty())
530     Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
531 
532   if (getOptions().Debug) {
533     for (const auto &Range : HighlightedRanges) {
534       errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
535       if (Range.second == 0)
536         errs() << "?";
537       else
538         errs() << Range.second;
539       errs() << "\n";
540     }
541   }
542 
543   // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
544   //    sub-line region count tooltips if needed.
545 
546   bool HasMultipleRegions = [&] {
547     unsigned RegionCount = 0;
548     for (const auto *S : Segments)
549       if (S->HasCount && S->IsRegionEntry)
550         if (++RegionCount > 1)
551           return true;
552     return false;
553   }();
554 
555   if (shouldRenderRegionMarkers(HasMultipleRegions)) {
556     for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
557       const auto *CurSeg = Segments[I];
558       if (!CurSeg->IsRegionEntry || !CurSeg->HasCount)
559         continue;
560 
561       Snippets[I + 1] =
562           tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
563                                            "tooltip-content"),
564               "tooltip");
565     }
566   }
567 
568   OS << BeginCodeTD;
569   OS << BeginPre;
570   for (const auto &Snippet : Snippets)
571     OS << Snippet;
572   OS << EndPre;
573 
574   // If there are no sub-views left to attach to this cell, end the cell.
575   // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
576   if (!hasSubViews())
577     OS << EndCodeTD;
578 }
579 
580 void SourceCoverageViewHTML::renderLineCoverageColumn(
581     raw_ostream &OS, const LineCoverageStats &Line) {
582   std::string Count = "";
583   if (Line.isMapped())
584     Count = tag("pre", formatCount(Line.ExecutionCount));
585   std::string CoverageClass =
586       (Line.ExecutionCount > 0) ? "covered-line" : "uncovered-line";
587   OS << tag("td", Count, CoverageClass);
588 }
589 
590 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
591                                                     unsigned LineNo) {
592   std::string LineNoStr = utostr(uint64_t(LineNo));
593   OS << tag("td", a("L" + LineNoStr, tag("pre", LineNoStr), "name"),
594             "line-number");
595 }
596 
597 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
598                                                  CoverageSegmentArray,
599                                                  unsigned) {
600   // Region markers are rendered in-line using tooltips.
601 }
602 
603 void SourceCoverageViewHTML::renderExpansionSite(
604     raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
605     CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned ViewDepth) {
606   // Render the line containing the expansion site. No extra formatting needed.
607   renderLine(OS, L, WrappedSegment, Segments, ExpansionCol, ViewDepth);
608 }
609 
610 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
611                                                  ExpansionView &ESV,
612                                                  unsigned ViewDepth) {
613   OS << BeginExpansionDiv;
614   ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
615                   ViewDepth + 1);
616   OS << EndExpansionDiv;
617 }
618 
619 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
620                                                      InstantiationView &ISV,
621                                                      unsigned ViewDepth) {
622   OS << BeginExpansionDiv;
623   ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true, ViewDepth);
624   OS << EndExpansionDiv;
625 }
626 
627 void SourceCoverageViewHTML::renderCellInTitle(raw_ostream &OS,
628                                                StringRef CellText) {
629   if (getOptions().hasProjectTitle())
630     OS << BeginProjectTitleDiv
631        << tag("span", escape(getOptions().ProjectTitle, getOptions()))
632        << EndProjectTitleDiv;
633 
634   OS << BeginReportTitleDiv << tag("span", escape(CellText, getOptions()))
635      << EndReportTitleDiv;
636 
637   if (getOptions().hasCreatedTime())
638     OS << BeginCreatedTimeDiv
639        << tag("span", escape(getOptions().CreatedTimeStr, getOptions()))
640        << EndCreatedTimeDiv;
641 }
642 
643 void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
644                                                unsigned ViewDepth) {
645   renderLinePrefix(OS, ViewDepth);
646   OS << tag("td", tag("span", tag("pre", escape("Line No.", getOptions()))))
647      << tag("td", tag("span", tag("pre", escape("Count", getOptions()))))
648      << tag("td", tag("span", tag("pre", escape("Source", getOptions()))));
649   renderLineSuffix(OS, ViewDepth);
650 }
651