1 //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//
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
7 //===----------------------------------------------------------------------===//
9 /// \file This file implements the html coverage renderer.
11 //===----------------------------------------------------------------------===//
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"
25 // Return a string with the special characters in \p Str escaped.
26 std::string
escape(StringRef Str
, const CoverageViewOptions
&Opts
) {
27 std::string TabExpandedResult
;
28 unsigned ColNum
= 0; // Record the column number.
31 // Replace '\t' with up to TabSize spaces.
32 unsigned NumSpaces
= Opts
.TabSize
- (ColNum
% Opts
.TabSize
);
33 for (unsigned I
= 0; I
< NumSpaces
; ++I
)
34 TabExpandedResult
+= ' ';
37 TabExpandedResult
+= C
;
38 if (C
== '\n' || C
== '\r')
44 std::string EscapedHTML
;
46 raw_string_ostream OS
{EscapedHTML
};
47 printHTMLEscaped(TabExpandedResult
, OS
);
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
+ ">";
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>";
68 const char *BeginHeader
=
70 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
71 "<meta charset='UTF-8'>";
73 const char *CSSForCoverage
=
75 background-color: #ffd0d0;
78 background-color: cyan;
81 font-family: -apple-system, sans-serif;
84 margin-top: 0px !important;
85 margin-bottom: 0px !important;
89 border-bottom: 1px solid #dbdbdb;
90 background-color: #eee;
97 border: 1px solid #dbdbdb;
101 background-color: rgba(0, 0, 0, 0);
106 border: 1px solid #dbdbdb;
110 border-collapse: collapse;
114 border: 1px solid #dbdbdb;
118 border: 1px solid #dbdbdb;
128 .column-entry-yellow {
130 background-color: #ffffd0;
132 .column-entry-yellow:hover {
133 background-color: #fffff0;
137 background-color: #ffd0d0;
139 .column-entry-red:hover {
140 background-color: #fff0f0;
142 .column-entry-green {
144 background-color: #d0ffd0;
146 .column-entry-green:hover {
147 background-color: #f0fff0;
164 background-color: #b3e6ff;
165 text-decoration: none;
167 .tooltip span.tooltip-content {
179 .tooltip span.tooltip-content:after {
186 border-top: 8px solid #000000;
187 border-right: 8px solid transparent;
188 border-left: 8px solid transparent;
190 :hover.tooltip span.tooltip-content {
200 border-collapse: collapse;
201 border-right: solid 1px #eee;
202 border-left: solid 1px #eee;
206 display: inline-block;
215 background-color: #f0f0f0;
219 const char *EndHeader
= "</head>";
221 const char *BeginCenteredDiv
= "<div class='centered'>";
223 const char *EndCenteredDiv
= "</div>";
225 const char *BeginSourceNameDiv
= "<div class='source-name-title'>";
227 const char *EndSourceNameDiv
= "</div>";
229 const char *BeginCodeTD
= "<td class='code'>";
231 const char *EndCodeTD
= "</td>";
233 const char *BeginPre
= "<pre>";
235 const char *EndPre
= "</pre>";
237 const char *BeginExpansionDiv
= "<div class='expansion-view'>";
239 const char *EndExpansionDiv
= "</div>";
241 const char *BeginTable
= "<table>";
243 const char *EndTable
= "</table>";
245 const char *ProjectTitleTag
= "h1";
247 const char *ReportTitleTag
= "h2";
249 const char *CreatedTimeTag
= "h4";
251 std::string
getPathToStyle(StringRef ViewPath
) {
252 std::string PathToStyle
= "";
253 std::string PathSep
= 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";
260 void emitPrelude(raw_ostream
&OS
, const CoverageViewOptions
&Opts
,
261 const std::string
&PathToStyle
= "") {
262 OS
<< "<!doctype html>"
266 // Link to a stylesheet if one is available. Otherwise, use the default style.
267 if (PathToStyle
.empty())
268 OS
<< "<style>" << CSSForCoverage
<< "</style>";
270 OS
<< "<link rel='stylesheet' type='text/css' href='"
271 << escape(PathToStyle
, Opts
) << "'>";
273 OS
<< EndHeader
<< "<body>";
276 void emitEpilog(raw_ostream
&OS
) {
281 } // anonymous namespace
283 Expected
<CoveragePrinter::OwnedStream
>
284 CoveragePrinterHTML::createViewFile(StringRef Path
, bool InToplevel
) {
285 auto OSOrErr
= createOutputStream(Path
, "html", InToplevel
);
289 OwnedStream OS
= std::move(OSOrErr
.get());
291 if (!Opts
.hasOutputDirectory()) {
292 emitPrelude(*OS
.get(), Opts
);
294 std::string ViewPath
= getOutputPath(Path
, "html", InToplevel
);
295 emitPrelude(*OS
.get(), Opts
, getPathToStyle(ViewPath
));
298 return std::move(OS
);
301 void CoveragePrinterHTML::closeViewFile(OwnedStream OS
) {
302 emitEpilog(*OS
.get());
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 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""));
321 CoveragePrinterHTML::buildLinkToFile(StringRef SF
,
322 const FileCoverageSummary
&FCS
) const {
323 SmallString
<128> LinkTextStr(sys::path::relative_path(FCS
.Name
));
324 sys::path::remove_dots(LinkTextStr
, /*remove_dot_dots=*/true);
325 sys::path::native(LinkTextStr
);
326 std::string LinkText
= escape(LinkTextStr
, Opts
);
327 std::string LinkTarget
=
328 escape(getOutputPath(SF
, "html", /*InToplevel=*/false), Opts
);
329 return a(LinkTarget
, LinkText
);
332 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
333 /// false, link the summary to \p SF.
334 void CoveragePrinterHTML::emitFileSummary(raw_ostream
&OS
, StringRef SF
,
335 const FileCoverageSummary
&FCS
,
336 bool IsTotals
) const {
337 SmallVector
<std::string
, 8> Columns
;
339 // Format a coverage triple and add the result to the list of columns.
340 auto AddCoverageTripleToColumn
= [&Columns
](unsigned Hit
, unsigned Total
,
344 raw_string_ostream RSO
{S
};
346 RSO
<< format("%*.2f", 7, Pctg
) << "% ";
349 RSO
<< '(' << Hit
<< '/' << Total
<< ')';
351 const char *CellClass
= "column-entry-yellow";
353 CellClass
= "column-entry-green";
354 else if (Pctg
< 80.0)
355 CellClass
= "column-entry-red";
356 Columns
.emplace_back(tag("td", tag("pre", S
), CellClass
));
359 // Simplify the display file path, and wrap it in a link if requested.
360 std::string Filename
;
364 Filename
= buildLinkToFile(SF
, FCS
);
367 Columns
.emplace_back(tag("td", tag("pre", Filename
)));
368 AddCoverageTripleToColumn(FCS
.FunctionCoverage
.getExecuted(),
369 FCS
.FunctionCoverage
.getNumFunctions(),
370 FCS
.FunctionCoverage
.getPercentCovered());
371 if (Opts
.ShowInstantiationSummary
)
372 AddCoverageTripleToColumn(FCS
.InstantiationCoverage
.getExecuted(),
373 FCS
.InstantiationCoverage
.getNumFunctions(),
374 FCS
.InstantiationCoverage
.getPercentCovered());
375 AddCoverageTripleToColumn(FCS
.LineCoverage
.getCovered(),
376 FCS
.LineCoverage
.getNumLines(),
377 FCS
.LineCoverage
.getPercentCovered());
378 if (Opts
.ShowRegionSummary
)
379 AddCoverageTripleToColumn(FCS
.RegionCoverage
.getCovered(),
380 FCS
.RegionCoverage
.getNumRegions(),
381 FCS
.RegionCoverage
.getPercentCovered());
384 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""), "light-row-bold");
386 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""), "light-row");
389 Error
CoveragePrinterHTML::createIndexFile(
390 ArrayRef
<std::string
> SourceFiles
, const CoverageMapping
&Coverage
,
391 const CoverageFiltersMatchAll
&Filters
) {
392 // Emit the default stylesheet.
393 auto CSSOrErr
= createOutputStream("style", "css", /*InToplevel=*/true);
394 if (Error E
= CSSOrErr
.takeError())
397 OwnedStream CSS
= std::move(CSSOrErr
.get());
398 CSS
->operator<<(CSSForCoverage
);
400 // Emit a file index along with some coverage statistics.
401 auto OSOrErr
= createOutputStream("index", "html", /*InToplevel=*/true);
402 if (Error E
= OSOrErr
.takeError())
404 auto OS
= std::move(OSOrErr
.get());
405 raw_ostream
&OSRef
= *OS
.get();
407 assert(Opts
.hasOutputDirectory() && "No output directory for index file");
408 emitPrelude(OSRef
, Opts
, getPathToStyle(""));
410 // Emit some basic information about the coverage report.
411 if (Opts
.hasProjectTitle())
412 OSRef
<< tag(ProjectTitleTag
, escape(Opts
.ProjectTitle
, Opts
));
413 OSRef
<< tag(ReportTitleTag
, "Coverage Report");
414 if (Opts
.hasCreatedTime())
415 OSRef
<< tag(CreatedTimeTag
, escape(Opts
.CreatedTimeStr
, Opts
));
417 // Emit a link to some documentation.
418 OSRef
<< tag("p", "Click " +
419 a("http://clang.llvm.org/docs/"
420 "SourceBasedCodeCoverage.html#interpreting-reports",
422 " for information about interpreting this report.");
424 // Emit a table containing links to reports for each file in the covmapping.
425 // Exclude files which don't contain any regions.
426 OSRef
<< BeginCenteredDiv
<< BeginTable
;
427 emitColumnLabelsForIndex(OSRef
, Opts
);
428 FileCoverageSummary
Totals("TOTALS");
429 auto FileReports
= CoverageReport::prepareFileReports(
430 Coverage
, Totals
, SourceFiles
, Opts
, Filters
);
431 bool EmptyFiles
= false;
432 for (unsigned I
= 0, E
= FileReports
.size(); I
< E
; ++I
) {
433 if (FileReports
[I
].FunctionCoverage
.getNumFunctions())
434 emitFileSummary(OSRef
, SourceFiles
[I
], FileReports
[I
]);
438 emitFileSummary(OSRef
, "Totals", Totals
, /*IsTotals=*/true);
439 OSRef
<< EndTable
<< EndCenteredDiv
;
441 // Emit links to files which don't contain any functions. These are normally
442 // not very useful, but could be relevant for code which abuses the
444 if (EmptyFiles
&& Filters
.empty()) {
445 OSRef
<< tag("p", "Files which contain no functions. (These "
446 "files contain code pulled into other files "
447 "by the preprocessor.)\n");
448 OSRef
<< BeginCenteredDiv
<< BeginTable
;
449 for (unsigned I
= 0, E
= FileReports
.size(); I
< E
; ++I
)
450 if (!FileReports
[I
].FunctionCoverage
.getNumFunctions()) {
451 std::string Link
= buildLinkToFile(SourceFiles
[I
], FileReports
[I
]);
452 OSRef
<< tag("tr", tag("td", tag("pre", Link
)), "light-row") << '\n';
454 OSRef
<< EndTable
<< EndCenteredDiv
;
457 OSRef
<< tag("h5", escape(Opts
.getLLVMVersionString(), Opts
));
460 return Error::success();
463 void SourceCoverageViewHTML::renderViewHeader(raw_ostream
&OS
) {
464 OS
<< BeginCenteredDiv
<< BeginTable
;
467 void SourceCoverageViewHTML::renderViewFooter(raw_ostream
&OS
) {
468 OS
<< EndTable
<< EndCenteredDiv
;
471 void SourceCoverageViewHTML::renderSourceName(raw_ostream
&OS
, bool WholeFile
) {
472 OS
<< BeginSourceNameDiv
<< tag("pre", escape(getSourceName(), getOptions()))
476 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream
&OS
, unsigned) {
480 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream
&OS
, unsigned) {
481 // If this view has sub-views, renderLine() cannot close the view's cell.
482 // Take care of it here, after all sub-views have been rendered.
488 void SourceCoverageViewHTML::renderViewDivider(raw_ostream
&, unsigned) {
489 // The table-based output makes view dividers unnecessary.
492 void SourceCoverageViewHTML::renderLine(raw_ostream
&OS
, LineRef L
,
493 const LineCoverageStats
&LCS
,
494 unsigned ExpansionCol
, unsigned) {
495 StringRef Line
= L
.Line
;
496 unsigned LineNo
= L
.LineNo
;
498 // Steps for handling text-escaping, highlighting, and tooltip creation:
500 // 1. Split the line into N+1 snippets, where N = |Segments|. The first
501 // snippet starts from Col=1 and ends at the start of the first segment.
502 // The last snippet starts at the last mapped column in the line and ends
503 // at the end of the line. Both are required but may be empty.
505 SmallVector
<std::string
, 8> Snippets
;
506 CoverageSegmentArray Segments
= LCS
.getLineSegments();
509 auto Snip
= [&](unsigned Start
, unsigned Len
) {
510 Snippets
.push_back(Line
.substr(Start
, Len
));
514 Snip(LCol
- 1, Segments
.empty() ? 0 : (Segments
.front()->Col
- 1));
516 for (unsigned I
= 1, E
= Segments
.size(); I
< E
; ++I
)
517 Snip(LCol
- 1, Segments
[I
]->Col
- LCol
);
519 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
520 Snip(LCol
- 1, Line
.size() + 1 - LCol
);
522 // 2. Escape all of the snippets.
524 for (unsigned I
= 0, E
= Snippets
.size(); I
< E
; ++I
)
525 Snippets
[I
] = escape(Snippets
[I
], getOptions());
527 // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
528 // 1 to set the highlight for snippet 2, segment 2 to set the highlight for
529 // snippet 3, and so on.
531 Optional
<StringRef
> Color
;
532 SmallVector
<std::pair
<unsigned, unsigned>, 2> HighlightedRanges
;
533 auto Highlight
= [&](const std::string
&Snippet
, unsigned LC
, unsigned RC
) {
534 if (getOptions().Debug
)
535 HighlightedRanges
.emplace_back(LC
, RC
);
536 return tag("span", Snippet
, Color
.getValue());
539 auto CheckIfUncovered
= [&](const CoverageSegment
*S
) {
540 return S
&& (!S
->IsGapRegion
|| (Color
&& *Color
== "red")) &&
541 S
->HasCount
&& S
->Count
== 0;
544 if (CheckIfUncovered(LCS
.getWrappedSegment())) {
546 if (!Snippets
[0].empty())
547 Snippets
[0] = Highlight(Snippets
[0], 1, 1 + Snippets
[0].size());
550 for (unsigned I
= 0, E
= Segments
.size(); I
< E
; ++I
) {
551 const auto *CurSeg
= Segments
[I
];
552 if (CheckIfUncovered(CurSeg
))
554 else if (CurSeg
->Col
== ExpansionCol
)
559 if (Color
.hasValue())
560 Snippets
[I
+ 1] = Highlight(Snippets
[I
+ 1], CurSeg
->Col
,
561 CurSeg
->Col
+ Snippets
[I
+ 1].size());
564 if (Color
.hasValue() && Segments
.empty())
565 Snippets
.back() = Highlight(Snippets
.back(), 1, 1 + Snippets
.back().size());
567 if (getOptions().Debug
) {
568 for (const auto &Range
: HighlightedRanges
) {
569 errs() << "Highlighted line " << LineNo
<< ", " << Range
.first
<< " -> ";
570 if (Range
.second
== 0)
573 errs() << Range
.second
;
578 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
579 // sub-line region count tooltips if needed.
581 if (shouldRenderRegionMarkers(LCS
)) {
582 // Just consider the segments which start *and* end on this line.
583 for (unsigned I
= 0, E
= Segments
.size() - 1; I
< E
; ++I
) {
584 const auto *CurSeg
= Segments
[I
];
585 if (!CurSeg
->IsRegionEntry
)
587 if (CurSeg
->Count
== LCS
.getExecutionCount())
591 tag("div", Snippets
[I
+ 1] + tag("span", formatCount(CurSeg
->Count
),
595 if (getOptions().Debug
)
596 errs() << "Marker at " << CurSeg
->Line
<< ":" << CurSeg
->Col
<< " = "
597 << formatCount(CurSeg
->Count
) << "\n";
603 for (const auto &Snippet
: Snippets
)
607 // If there are no sub-views left to attach to this cell, end the cell.
608 // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
613 void SourceCoverageViewHTML::renderLineCoverageColumn(
614 raw_ostream
&OS
, const LineCoverageStats
&Line
) {
615 std::string Count
= "";
617 Count
= tag("pre", formatCount(Line
.getExecutionCount()));
618 std::string CoverageClass
=
619 (Line
.getExecutionCount() > 0) ? "covered-line" : "uncovered-line";
620 OS
<< tag("td", Count
, CoverageClass
);
623 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream
&OS
,
625 std::string LineNoStr
= utostr(uint64_t(LineNo
));
626 std::string TargetName
= "L" + LineNoStr
;
627 OS
<< tag("td", a("#" + TargetName
, tag("pre", LineNoStr
), TargetName
),
631 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream
&,
632 const LineCoverageStats
&Line
,
634 // Region markers are rendered in-line using tooltips.
637 void SourceCoverageViewHTML::renderExpansionSite(raw_ostream
&OS
, LineRef L
,
638 const LineCoverageStats
&LCS
,
639 unsigned ExpansionCol
,
640 unsigned ViewDepth
) {
641 // Render the line containing the expansion site. No extra formatting needed.
642 renderLine(OS
, L
, LCS
, ExpansionCol
, ViewDepth
);
645 void SourceCoverageViewHTML::renderExpansionView(raw_ostream
&OS
,
647 unsigned ViewDepth
) {
648 OS
<< BeginExpansionDiv
;
649 ESV
.View
->print(OS
, /*WholeFile=*/false, /*ShowSourceName=*/false,
650 /*ShowTitle=*/false, ViewDepth
+ 1);
651 OS
<< EndExpansionDiv
;
654 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream
&OS
,
655 InstantiationView
&ISV
,
656 unsigned ViewDepth
) {
657 OS
<< BeginExpansionDiv
;
659 OS
<< BeginSourceNameDiv
661 escape("Unexecuted instantiation: " + ISV
.FunctionName
.str(),
665 ISV
.View
->print(OS
, /*WholeFile=*/false, /*ShowSourceName=*/true,
666 /*ShowTitle=*/false, ViewDepth
);
667 OS
<< EndExpansionDiv
;
670 void SourceCoverageViewHTML::renderTitle(raw_ostream
&OS
, StringRef Title
) {
671 if (getOptions().hasProjectTitle())
672 OS
<< tag(ProjectTitleTag
, escape(getOptions().ProjectTitle
, getOptions()));
673 OS
<< tag(ReportTitleTag
, escape(Title
, getOptions()));
674 if (getOptions().hasCreatedTime())
675 OS
<< tag(CreatedTimeTag
,
676 escape(getOptions().CreatedTimeStr
, getOptions()));
679 void SourceCoverageViewHTML::renderTableHeader(raw_ostream
&OS
,
680 unsigned FirstUncoveredLineNo
,
681 unsigned ViewDepth
) {
682 std::string SourceLabel
;
683 if (FirstUncoveredLineNo
== 0) {
684 SourceLabel
= tag("td", tag("pre", "Source"));
686 std::string LinkTarget
= "#L" + utostr(uint64_t(FirstUncoveredLineNo
));
688 tag("td", tag("pre", "Source (" +
689 a(LinkTarget
, "jump to first uncovered line") +
693 renderLinePrefix(OS
, ViewDepth
);
694 OS
<< tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
696 renderLineSuffix(OS
, ViewDepth
);