1 //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \file This file implements the html coverage renderer.
12 //===----------------------------------------------------------------------===//
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/Format.h"
20 #include "llvm/Support/Path.h"
26 // Return a string with the special characters in \p Str escaped.
27 std::string escape(StringRef Str, const CoverageViewOptions &Opts) {
29 unsigned ColNum = 0; // Record the column number.
40 else if (C == '\n' || C == '\r') {
43 } else if (C == '\t') {
44 // Replace '\t' with TabSize spaces.
45 unsigned NumSpaces = Opts.TabSize - (--ColNum % Opts.TabSize);
46 for (unsigned I = 0; I < NumSpaces; ++I)
55 // Create a \p Name tag around \p Str, and optionally set its \p ClassName.
56 std::string tag(const std::string &Name, const std::string &Str,
57 const std::string &ClassName = "") {
58 std::string Tag = "<" + Name;
60 Tag += " class='" + ClassName + "'";
61 return Tag + ">" + Str + "</" + Name + ">";
64 // Create an anchor to \p Link with the label \p Str.
65 std::string a(const std::string &Link, const std::string &Str,
66 const std::string &TargetName = "") {
67 std::string Name = TargetName.empty() ? "" : ("name='" + TargetName + "' ");
68 return "<a " + Name + "href='" + Link + "'>" + Str + "</a>";
71 const char *BeginHeader =
73 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
74 "<meta charset='UTF-8'>";
76 const char *CSSForCoverage =
78 background-color: #ffd0d0;
81 background-color: cyan;
84 font-family: -apple-system, sans-serif;
87 margin-top: 0px !important;
88 margin-bottom: 0px !important;
92 border-bottom: 1px solid #dbdbdb;
93 background-color: #eee;
100 border: 1px solid #dbdbdb;
104 background-color: rgba(0, 0, 0, 0);
109 border: 1px solid #dbdbdb;
113 border-collapse: collapse;
117 border: 1px solid #dbdbdb;
125 .column-entry-yellow {
127 background-color: #ffffd0;
131 background-color: #ffd0d0;
133 .column-entry-green {
135 background-color: #d0ffd0;
152 background-color: #b3e6ff;
153 text-decoration: none;
155 .tooltip span.tooltip-content {
167 .tooltip span.tooltip-content:after {
174 border-top: 8px solid #000000;
175 border-right: 8px solid transparent;
176 border-left: 8px solid transparent;
178 :hover.tooltip span.tooltip-content {
188 border-collapse: collapse;
189 border-right: solid 1px #eee;
190 border-left: solid 1px #eee;
200 const char *EndHeader = "</head>";
202 const char *BeginCenteredDiv = "<div class='centered'>";
204 const char *EndCenteredDiv = "</div>";
206 const char *BeginSourceNameDiv = "<div class='source-name-title'>";
208 const char *EndSourceNameDiv = "</div>";
210 const char *BeginCodeTD = "<td class='code'>";
212 const char *EndCodeTD = "</td>";
214 const char *BeginPre = "<pre>";
216 const char *EndPre = "</pre>";
218 const char *BeginExpansionDiv = "<div class='expansion-view'>";
220 const char *EndExpansionDiv = "</div>";
222 const char *BeginTable = "<table>";
224 const char *EndTable = "</table>";
226 const char *ProjectTitleTag = "h1";
228 const char *ReportTitleTag = "h2";
230 const char *CreatedTimeTag = "h4";
232 std::string getPathToStyle(StringRef ViewPath) {
233 std::string PathToStyle = "";
234 std::string PathSep = sys::path::get_separator();
235 unsigned NumSeps = ViewPath.count(PathSep);
236 for (unsigned I = 0, E = NumSeps; I < E; ++I)
237 PathToStyle += ".." + PathSep;
238 return PathToStyle + "style.css";
241 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
242 const std::string &PathToStyle = "") {
243 OS << "<!doctype html>"
247 // Link to a stylesheet if one is available. Otherwise, use the default style.
248 if (PathToStyle.empty())
249 OS << "<style>" << CSSForCoverage << "</style>";
251 OS << "<link rel='stylesheet' type='text/css' href='"
252 << escape(PathToStyle, Opts) << "'>";
254 OS << EndHeader << "<body>";
257 void emitEpilog(raw_ostream &OS) {
262 } // anonymous namespace
264 Expected<CoveragePrinter::OwnedStream>
265 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
266 auto OSOrErr = createOutputStream(Path, "html", InToplevel);
270 OwnedStream OS = std::move(OSOrErr.get());
272 if (!Opts.hasOutputDirectory()) {
273 emitPrelude(*OS.get(), Opts);
275 std::string ViewPath = getOutputPath(Path, "html", InToplevel);
276 emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
279 return std::move(OS);
282 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
283 emitEpilog(*OS.get());
286 /// Emit column labels for the table in the index.
287 static void emitColumnLabelsForIndex(raw_ostream &OS,
288 const CoverageViewOptions &Opts) {
289 SmallVector<std::string, 4> Columns;
290 Columns.emplace_back(tag("td", "Filename", "column-entry-left"));
291 Columns.emplace_back(tag("td", "Function Coverage", "column-entry"));
292 if (Opts.ShowInstantiationSummary)
293 Columns.emplace_back(tag("td", "Instantiation Coverage", "column-entry"));
294 Columns.emplace_back(tag("td", "Line Coverage", "column-entry"));
295 if (Opts.ShowRegionSummary)
296 Columns.emplace_back(tag("td", "Region Coverage", "column-entry"));
297 OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
301 CoveragePrinterHTML::buildLinkToFile(StringRef SF,
302 const FileCoverageSummary &FCS) const {
303 SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
304 sys::path::remove_dots(LinkTextStr, /*remove_dot_dots=*/true);
305 sys::path::native(LinkTextStr);
306 std::string LinkText = escape(LinkTextStr, Opts);
307 std::string LinkTarget =
308 escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
309 return a(LinkTarget, LinkText);
312 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
313 /// false, link the summary to \p SF.
314 void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
315 const FileCoverageSummary &FCS,
316 bool IsTotals) const {
317 SmallVector<std::string, 8> Columns;
319 // Format a coverage triple and add the result to the list of columns.
320 auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
324 raw_string_ostream RSO{S};
326 RSO << format("%*.2f", 7, Pctg) << "% ";
329 RSO << '(' << Hit << '/' << Total << ')';
331 const char *CellClass = "column-entry-yellow";
333 CellClass = "column-entry-green";
334 else if (Pctg < 80.0)
335 CellClass = "column-entry-red";
336 Columns.emplace_back(tag("td", tag("pre", S), CellClass));
339 // Simplify the display file path, and wrap it in a link if requested.
340 std::string Filename;
344 Filename = buildLinkToFile(SF, FCS);
347 Columns.emplace_back(tag("td", tag("pre", Filename)));
348 AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),
349 FCS.FunctionCoverage.getNumFunctions(),
350 FCS.FunctionCoverage.getPercentCovered());
351 if (Opts.ShowInstantiationSummary)
352 AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),
353 FCS.InstantiationCoverage.getNumFunctions(),
354 FCS.InstantiationCoverage.getPercentCovered());
355 AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),
356 FCS.LineCoverage.getNumLines(),
357 FCS.LineCoverage.getPercentCovered());
358 if (Opts.ShowRegionSummary)
359 AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),
360 FCS.RegionCoverage.getNumRegions(),
361 FCS.RegionCoverage.getPercentCovered());
363 OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
366 Error CoveragePrinterHTML::createIndexFile(
367 ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,
368 const CoverageFiltersMatchAll &Filters) {
369 // Emit the default stylesheet.
370 auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
371 if (Error E = CSSOrErr.takeError())
374 OwnedStream CSS = std::move(CSSOrErr.get());
375 CSS->operator<<(CSSForCoverage);
377 // Emit a file index along with some coverage statistics.
378 auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
379 if (Error E = OSOrErr.takeError())
381 auto OS = std::move(OSOrErr.get());
382 raw_ostream &OSRef = *OS.get();
384 assert(Opts.hasOutputDirectory() && "No output directory for index file");
385 emitPrelude(OSRef, Opts, getPathToStyle(""));
387 // Emit some basic information about the coverage report.
388 if (Opts.hasProjectTitle())
389 OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));
390 OSRef << tag(ReportTitleTag, "Coverage Report");
391 if (Opts.hasCreatedTime())
392 OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));
394 // Emit a link to some documentation.
395 OSRef << tag("p", "Click " +
396 a("http://clang.llvm.org/docs/"
397 "SourceBasedCodeCoverage.html#interpreting-reports",
399 " for information about interpreting this report.");
401 // Emit a table containing links to reports for each file in the covmapping.
402 // Exclude files which don't contain any regions.
403 OSRef << BeginCenteredDiv << BeginTable;
404 emitColumnLabelsForIndex(OSRef, Opts);
405 FileCoverageSummary Totals("TOTALS");
406 auto FileReports = CoverageReport::prepareFileReports(
407 Coverage, Totals, SourceFiles, Opts, Filters);
408 bool EmptyFiles = false;
409 for (unsigned I = 0, E = FileReports.size(); I < E; ++I) {
410 if (FileReports[I].FunctionCoverage.getNumFunctions())
411 emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
415 emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
416 OSRef << EndTable << EndCenteredDiv;
418 // Emit links to files which don't contain any functions. These are normally
419 // not very useful, but could be relevant for code which abuses the
421 if (EmptyFiles && Filters.empty()) {
422 OSRef << tag("p", "Files which contain no functions. (These "
423 "files contain code pulled into other files "
424 "by the preprocessor.)\n");
425 OSRef << BeginCenteredDiv << BeginTable;
426 for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
427 if (!FileReports[I].FunctionCoverage.getNumFunctions()) {
428 std::string Link = buildLinkToFile(SourceFiles[I], FileReports[I]);
429 OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';
431 OSRef << EndTable << EndCenteredDiv;
434 OSRef << tag("h5", escape(Opts.getLLVMVersionString(), Opts));
437 return Error::success();
440 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
441 OS << BeginCenteredDiv << BeginTable;
444 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
445 OS << EndTable << EndCenteredDiv;
448 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {
449 OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))
453 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
457 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
458 // If this view has sub-views, renderLine() cannot close the view's cell.
459 // Take care of it here, after all sub-views have been rendered.
465 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
466 // The table-based output makes view dividers unnecessary.
469 void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L,
470 const LineCoverageStats &LCS,
471 unsigned ExpansionCol, unsigned) {
472 StringRef Line = L.Line;
473 unsigned LineNo = L.LineNo;
475 // Steps for handling text-escaping, highlighting, and tooltip creation:
477 // 1. Split the line into N+1 snippets, where N = |Segments|. The first
478 // snippet starts from Col=1 and ends at the start of the first segment.
479 // The last snippet starts at the last mapped column in the line and ends
480 // at the end of the line. Both are required but may be empty.
482 SmallVector<std::string, 8> Snippets;
483 CoverageSegmentArray Segments = LCS.getLineSegments();
486 auto Snip = [&](unsigned Start, unsigned Len) {
487 Snippets.push_back(Line.substr(Start, Len));
491 Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
493 for (unsigned I = 1, E = Segments.size(); I < E; ++I)
494 Snip(LCol - 1, Segments[I]->Col - LCol);
496 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
497 Snip(LCol - 1, Line.size() + 1 - LCol);
499 // 2. Escape all of the snippets.
501 for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
502 Snippets[I] = escape(Snippets[I], getOptions());
504 // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
505 // 1 to set the highlight for snippet 2, segment 2 to set the highlight for
506 // snippet 3, and so on.
508 Optional<StringRef> Color;
509 SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
510 auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
511 if (getOptions().Debug)
512 HighlightedRanges.emplace_back(LC, RC);
513 return tag("span", Snippet, Color.getValue());
516 auto CheckIfUncovered = [&](const CoverageSegment *S) {
517 return S && (!S->IsGapRegion || (Color && *Color == "red")) &&
518 S->HasCount && S->Count == 0;
521 if (CheckIfUncovered(LCS.getWrappedSegment())) {
523 if (!Snippets[0].empty())
524 Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
527 for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
528 const auto *CurSeg = Segments[I];
529 if (CheckIfUncovered(CurSeg))
531 else if (CurSeg->Col == ExpansionCol)
536 if (Color.hasValue())
537 Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
538 CurSeg->Col + Snippets[I + 1].size());
541 if (Color.hasValue() && Segments.empty())
542 Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
544 if (getOptions().Debug) {
545 for (const auto &Range : HighlightedRanges) {
546 errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
547 if (Range.second == 0)
550 errs() << Range.second;
555 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
556 // sub-line region count tooltips if needed.
558 if (shouldRenderRegionMarkers(LCS)) {
559 // Just consider the segments which start *and* end on this line.
560 for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
561 const auto *CurSeg = Segments[I];
562 if (!CurSeg->IsRegionEntry)
564 if (CurSeg->Count == LCS.getExecutionCount())
568 tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
572 if (getOptions().Debug)
573 errs() << "Marker at " << CurSeg->Line << ":" << CurSeg->Col << " = "
574 << formatCount(CurSeg->Count) << "\n";
580 for (const auto &Snippet : Snippets)
584 // If there are no sub-views left to attach to this cell, end the cell.
585 // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
590 void SourceCoverageViewHTML::renderLineCoverageColumn(
591 raw_ostream &OS, const LineCoverageStats &Line) {
592 std::string Count = "";
594 Count = tag("pre", formatCount(Line.getExecutionCount()));
595 std::string CoverageClass =
596 (Line.getExecutionCount() > 0) ? "covered-line" : "uncovered-line";
597 OS << tag("td", Count, CoverageClass);
600 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
602 std::string LineNoStr = utostr(uint64_t(LineNo));
603 std::string TargetName = "L" + LineNoStr;
604 OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),
608 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
609 const LineCoverageStats &Line,
611 // Region markers are rendered in-line using tooltips.
614 void SourceCoverageViewHTML::renderExpansionSite(raw_ostream &OS, LineRef L,
615 const LineCoverageStats &LCS,
616 unsigned ExpansionCol,
617 unsigned ViewDepth) {
618 // Render the line containing the expansion site. No extra formatting needed.
619 renderLine(OS, L, LCS, ExpansionCol, ViewDepth);
622 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
624 unsigned ViewDepth) {
625 OS << BeginExpansionDiv;
626 ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
627 /*ShowTitle=*/false, ViewDepth + 1);
628 OS << EndExpansionDiv;
631 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
632 InstantiationView &ISV,
633 unsigned ViewDepth) {
634 OS << BeginExpansionDiv;
636 OS << BeginSourceNameDiv
638 escape("Unexecuted instantiation: " + ISV.FunctionName.str(),
642 ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,
643 /*ShowTitle=*/false, ViewDepth);
644 OS << EndExpansionDiv;
647 void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {
648 if (getOptions().hasProjectTitle())
649 OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));
650 OS << tag(ReportTitleTag, escape(Title, getOptions()));
651 if (getOptions().hasCreatedTime())
652 OS << tag(CreatedTimeTag,
653 escape(getOptions().CreatedTimeStr, getOptions()));
656 void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
657 unsigned FirstUncoveredLineNo,
658 unsigned ViewDepth) {
659 std::string SourceLabel;
660 if (FirstUncoveredLineNo == 0) {
661 SourceLabel = tag("td", tag("pre", "Source"));
663 std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
665 tag("td", tag("pre", "Source (" +
666 a(LinkTarget, "jump to first uncovered line") +
670 renderLinePrefix(OS, ViewDepth);
671 OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
673 renderLineSuffix(OS, ViewDepth);