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
) {
28 std::string TabExpandedResult
;
29 unsigned ColNum
= 0; // Record the column number.
32 // Replace '\t' with up to TabSize spaces.
33 unsigned NumSpaces
= Opts
.TabSize
- (ColNum
% Opts
.TabSize
);
34 for (unsigned I
= 0; I
< NumSpaces
; ++I
)
35 TabExpandedResult
+= ' ';
38 TabExpandedResult
+= C
;
39 if (C
== '\n' || C
== '\r')
45 std::string EscapedHTML
;
47 raw_string_ostream OS
{EscapedHTML
};
48 printHTMLEscaped(TabExpandedResult
, OS
);
53 // Create a \p Name tag around \p Str, and optionally set its \p ClassName.
54 std::string
tag(const std::string
&Name
, const std::string
&Str
,
55 const std::string
&ClassName
= "") {
56 std::string Tag
= "<" + Name
;
57 if (!ClassName
.empty())
58 Tag
+= " class='" + ClassName
+ "'";
59 return Tag
+ ">" + Str
+ "</" + Name
+ ">";
62 // Create an anchor to \p Link with the label \p Str.
63 std::string
a(const std::string
&Link
, const std::string
&Str
,
64 const std::string
&TargetName
= "") {
65 std::string Name
= TargetName
.empty() ? "" : ("name='" + TargetName
+ "' ");
66 return "<a " + Name
+ "href='" + Link
+ "'>" + Str
+ "</a>";
69 const char *BeginHeader
=
71 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
72 "<meta charset='UTF-8'>";
74 const char *CSSForCoverage
=
76 background-color: #ffd0d0;
79 background-color: cyan;
82 font-family: -apple-system, sans-serif;
85 margin-top: 0px !important;
86 margin-bottom: 0px !important;
90 border-bottom: 1px solid #dbdbdb;
91 background-color: #eee;
98 border: 1px solid #dbdbdb;
102 background-color: rgba(0, 0, 0, 0);
107 border: 1px solid #dbdbdb;
111 border-collapse: collapse;
115 border: 1px solid #dbdbdb;
119 border: 1px solid #dbdbdb;
129 .column-entry-yellow {
131 background-color: #ffffd0;
133 .column-entry-yellow:hover {
134 background-color: #fffff0;
138 background-color: #ffd0d0;
140 .column-entry-red:hover {
141 background-color: #fff0f0;
143 .column-entry-green {
145 background-color: #d0ffd0;
147 .column-entry-green:hover {
148 background-color: #f0fff0;
165 background-color: #b3e6ff;
166 text-decoration: none;
168 .tooltip span.tooltip-content {
180 .tooltip span.tooltip-content:after {
187 border-top: 8px solid #000000;
188 border-right: 8px solid transparent;
189 border-left: 8px solid transparent;
191 :hover.tooltip span.tooltip-content {
201 border-collapse: collapse;
202 border-right: solid 1px #eee;
203 border-left: solid 1px #eee;
207 display: inline-block;
216 background-color: #f0f0f0;
220 const char *EndHeader
= "</head>";
222 const char *BeginCenteredDiv
= "<div class='centered'>";
224 const char *EndCenteredDiv
= "</div>";
226 const char *BeginSourceNameDiv
= "<div class='source-name-title'>";
228 const char *EndSourceNameDiv
= "</div>";
230 const char *BeginCodeTD
= "<td class='code'>";
232 const char *EndCodeTD
= "</td>";
234 const char *BeginPre
= "<pre>";
236 const char *EndPre
= "</pre>";
238 const char *BeginExpansionDiv
= "<div class='expansion-view'>";
240 const char *EndExpansionDiv
= "</div>";
242 const char *BeginTable
= "<table>";
244 const char *EndTable
= "</table>";
246 const char *ProjectTitleTag
= "h1";
248 const char *ReportTitleTag
= "h2";
250 const char *CreatedTimeTag
= "h4";
252 std::string
getPathToStyle(StringRef ViewPath
) {
253 std::string PathToStyle
= "";
254 std::string PathSep
= sys::path::get_separator();
255 unsigned NumSeps
= ViewPath
.count(PathSep
);
256 for (unsigned I
= 0, E
= NumSeps
; I
< E
; ++I
)
257 PathToStyle
+= ".." + PathSep
;
258 return PathToStyle
+ "style.css";
261 void emitPrelude(raw_ostream
&OS
, const CoverageViewOptions
&Opts
,
262 const std::string
&PathToStyle
= "") {
263 OS
<< "<!doctype html>"
267 // Link to a stylesheet if one is available. Otherwise, use the default style.
268 if (PathToStyle
.empty())
269 OS
<< "<style>" << CSSForCoverage
<< "</style>";
271 OS
<< "<link rel='stylesheet' type='text/css' href='"
272 << escape(PathToStyle
, Opts
) << "'>";
274 OS
<< EndHeader
<< "<body>";
277 void emitEpilog(raw_ostream
&OS
) {
282 } // anonymous namespace
284 Expected
<CoveragePrinter::OwnedStream
>
285 CoveragePrinterHTML::createViewFile(StringRef Path
, bool InToplevel
) {
286 auto OSOrErr
= createOutputStream(Path
, "html", InToplevel
);
290 OwnedStream OS
= std::move(OSOrErr
.get());
292 if (!Opts
.hasOutputDirectory()) {
293 emitPrelude(*OS
.get(), Opts
);
295 std::string ViewPath
= getOutputPath(Path
, "html", InToplevel
);
296 emitPrelude(*OS
.get(), Opts
, getPathToStyle(ViewPath
));
299 return std::move(OS
);
302 void CoveragePrinterHTML::closeViewFile(OwnedStream OS
) {
303 emitEpilog(*OS
.get());
306 /// Emit column labels for the table in the index.
307 static void emitColumnLabelsForIndex(raw_ostream
&OS
,
308 const CoverageViewOptions
&Opts
) {
309 SmallVector
<std::string
, 4> Columns
;
310 Columns
.emplace_back(tag("td", "Filename", "column-entry-bold"));
311 Columns
.emplace_back(tag("td", "Function Coverage", "column-entry-bold"));
312 if (Opts
.ShowInstantiationSummary
)
313 Columns
.emplace_back(
314 tag("td", "Instantiation Coverage", "column-entry-bold"));
315 Columns
.emplace_back(tag("td", "Line Coverage", "column-entry-bold"));
316 if (Opts
.ShowRegionSummary
)
317 Columns
.emplace_back(tag("td", "Region Coverage", "column-entry-bold"));
318 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""));
322 CoveragePrinterHTML::buildLinkToFile(StringRef SF
,
323 const FileCoverageSummary
&FCS
) const {
324 SmallString
<128> LinkTextStr(sys::path::relative_path(FCS
.Name
));
325 sys::path::remove_dots(LinkTextStr
, /*remove_dot_dots=*/true);
326 sys::path::native(LinkTextStr
);
327 std::string LinkText
= escape(LinkTextStr
, Opts
);
328 std::string LinkTarget
=
329 escape(getOutputPath(SF
, "html", /*InToplevel=*/false), Opts
);
330 return a(LinkTarget
, LinkText
);
333 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
334 /// false, link the summary to \p SF.
335 void CoveragePrinterHTML::emitFileSummary(raw_ostream
&OS
, StringRef SF
,
336 const FileCoverageSummary
&FCS
,
337 bool IsTotals
) const {
338 SmallVector
<std::string
, 8> Columns
;
340 // Format a coverage triple and add the result to the list of columns.
341 auto AddCoverageTripleToColumn
= [&Columns
](unsigned Hit
, unsigned Total
,
345 raw_string_ostream RSO
{S
};
347 RSO
<< format("%*.2f", 7, Pctg
) << "% ";
350 RSO
<< '(' << Hit
<< '/' << Total
<< ')';
352 const char *CellClass
= "column-entry-yellow";
354 CellClass
= "column-entry-green";
355 else if (Pctg
< 80.0)
356 CellClass
= "column-entry-red";
357 Columns
.emplace_back(tag("td", tag("pre", S
), CellClass
));
360 // Simplify the display file path, and wrap it in a link if requested.
361 std::string Filename
;
365 Filename
= buildLinkToFile(SF
, FCS
);
368 Columns
.emplace_back(tag("td", tag("pre", Filename
)));
369 AddCoverageTripleToColumn(FCS
.FunctionCoverage
.getExecuted(),
370 FCS
.FunctionCoverage
.getNumFunctions(),
371 FCS
.FunctionCoverage
.getPercentCovered());
372 if (Opts
.ShowInstantiationSummary
)
373 AddCoverageTripleToColumn(FCS
.InstantiationCoverage
.getExecuted(),
374 FCS
.InstantiationCoverage
.getNumFunctions(),
375 FCS
.InstantiationCoverage
.getPercentCovered());
376 AddCoverageTripleToColumn(FCS
.LineCoverage
.getCovered(),
377 FCS
.LineCoverage
.getNumLines(),
378 FCS
.LineCoverage
.getPercentCovered());
379 if (Opts
.ShowRegionSummary
)
380 AddCoverageTripleToColumn(FCS
.RegionCoverage
.getCovered(),
381 FCS
.RegionCoverage
.getNumRegions(),
382 FCS
.RegionCoverage
.getPercentCovered());
385 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""), "light-row-bold");
387 OS
<< tag("tr", join(Columns
.begin(), Columns
.end(), ""), "light-row");
390 Error
CoveragePrinterHTML::createIndexFile(
391 ArrayRef
<std::string
> SourceFiles
, const CoverageMapping
&Coverage
,
392 const CoverageFiltersMatchAll
&Filters
) {
393 // Emit the default stylesheet.
394 auto CSSOrErr
= createOutputStream("style", "css", /*InToplevel=*/true);
395 if (Error E
= CSSOrErr
.takeError())
398 OwnedStream CSS
= std::move(CSSOrErr
.get());
399 CSS
->operator<<(CSSForCoverage
);
401 // Emit a file index along with some coverage statistics.
402 auto OSOrErr
= createOutputStream("index", "html", /*InToplevel=*/true);
403 if (Error E
= OSOrErr
.takeError())
405 auto OS
= std::move(OSOrErr
.get());
406 raw_ostream
&OSRef
= *OS
.get();
408 assert(Opts
.hasOutputDirectory() && "No output directory for index file");
409 emitPrelude(OSRef
, Opts
, getPathToStyle(""));
411 // Emit some basic information about the coverage report.
412 if (Opts
.hasProjectTitle())
413 OSRef
<< tag(ProjectTitleTag
, escape(Opts
.ProjectTitle
, Opts
));
414 OSRef
<< tag(ReportTitleTag
, "Coverage Report");
415 if (Opts
.hasCreatedTime())
416 OSRef
<< tag(CreatedTimeTag
, escape(Opts
.CreatedTimeStr
, Opts
));
418 // Emit a link to some documentation.
419 OSRef
<< tag("p", "Click " +
420 a("http://clang.llvm.org/docs/"
421 "SourceBasedCodeCoverage.html#interpreting-reports",
423 " for information about interpreting this report.");
425 // Emit a table containing links to reports for each file in the covmapping.
426 // Exclude files which don't contain any regions.
427 OSRef
<< BeginCenteredDiv
<< BeginTable
;
428 emitColumnLabelsForIndex(OSRef
, Opts
);
429 FileCoverageSummary
Totals("TOTALS");
430 auto FileReports
= CoverageReport::prepareFileReports(
431 Coverage
, Totals
, SourceFiles
, Opts
, Filters
);
432 bool EmptyFiles
= false;
433 for (unsigned I
= 0, E
= FileReports
.size(); I
< E
; ++I
) {
434 if (FileReports
[I
].FunctionCoverage
.getNumFunctions())
435 emitFileSummary(OSRef
, SourceFiles
[I
], FileReports
[I
]);
439 emitFileSummary(OSRef
, "Totals", Totals
, /*IsTotals=*/true);
440 OSRef
<< EndTable
<< EndCenteredDiv
;
442 // Emit links to files which don't contain any functions. These are normally
443 // not very useful, but could be relevant for code which abuses the
445 if (EmptyFiles
&& Filters
.empty()) {
446 OSRef
<< tag("p", "Files which contain no functions. (These "
447 "files contain code pulled into other files "
448 "by the preprocessor.)\n");
449 OSRef
<< BeginCenteredDiv
<< BeginTable
;
450 for (unsigned I
= 0, E
= FileReports
.size(); I
< E
; ++I
)
451 if (!FileReports
[I
].FunctionCoverage
.getNumFunctions()) {
452 std::string Link
= buildLinkToFile(SourceFiles
[I
], FileReports
[I
]);
453 OSRef
<< tag("tr", tag("td", tag("pre", Link
)), "light-row") << '\n';
455 OSRef
<< EndTable
<< EndCenteredDiv
;
458 OSRef
<< tag("h5", escape(Opts
.getLLVMVersionString(), Opts
));
461 return Error::success();
464 void SourceCoverageViewHTML::renderViewHeader(raw_ostream
&OS
) {
465 OS
<< BeginCenteredDiv
<< BeginTable
;
468 void SourceCoverageViewHTML::renderViewFooter(raw_ostream
&OS
) {
469 OS
<< EndTable
<< EndCenteredDiv
;
472 void SourceCoverageViewHTML::renderSourceName(raw_ostream
&OS
, bool WholeFile
) {
473 OS
<< BeginSourceNameDiv
<< tag("pre", escape(getSourceName(), getOptions()))
477 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream
&OS
, unsigned) {
481 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream
&OS
, unsigned) {
482 // If this view has sub-views, renderLine() cannot close the view's cell.
483 // Take care of it here, after all sub-views have been rendered.
489 void SourceCoverageViewHTML::renderViewDivider(raw_ostream
&, unsigned) {
490 // The table-based output makes view dividers unnecessary.
493 void SourceCoverageViewHTML::renderLine(raw_ostream
&OS
, LineRef L
,
494 const LineCoverageStats
&LCS
,
495 unsigned ExpansionCol
, unsigned) {
496 StringRef Line
= L
.Line
;
497 unsigned LineNo
= L
.LineNo
;
499 // Steps for handling text-escaping, highlighting, and tooltip creation:
501 // 1. Split the line into N+1 snippets, where N = |Segments|. The first
502 // snippet starts from Col=1 and ends at the start of the first segment.
503 // The last snippet starts at the last mapped column in the line and ends
504 // at the end of the line. Both are required but may be empty.
506 SmallVector
<std::string
, 8> Snippets
;
507 CoverageSegmentArray Segments
= LCS
.getLineSegments();
510 auto Snip
= [&](unsigned Start
, unsigned Len
) {
511 Snippets
.push_back(Line
.substr(Start
, Len
));
515 Snip(LCol
- 1, Segments
.empty() ? 0 : (Segments
.front()->Col
- 1));
517 for (unsigned I
= 1, E
= Segments
.size(); I
< E
; ++I
)
518 Snip(LCol
- 1, Segments
[I
]->Col
- LCol
);
520 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
521 Snip(LCol
- 1, Line
.size() + 1 - LCol
);
523 // 2. Escape all of the snippets.
525 for (unsigned I
= 0, E
= Snippets
.size(); I
< E
; ++I
)
526 Snippets
[I
] = escape(Snippets
[I
], getOptions());
528 // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
529 // 1 to set the highlight for snippet 2, segment 2 to set the highlight for
530 // snippet 3, and so on.
532 Optional
<StringRef
> Color
;
533 SmallVector
<std::pair
<unsigned, unsigned>, 2> HighlightedRanges
;
534 auto Highlight
= [&](const std::string
&Snippet
, unsigned LC
, unsigned RC
) {
535 if (getOptions().Debug
)
536 HighlightedRanges
.emplace_back(LC
, RC
);
537 return tag("span", Snippet
, Color
.getValue());
540 auto CheckIfUncovered
= [&](const CoverageSegment
*S
) {
541 return S
&& (!S
->IsGapRegion
|| (Color
&& *Color
== "red")) &&
542 S
->HasCount
&& S
->Count
== 0;
545 if (CheckIfUncovered(LCS
.getWrappedSegment())) {
547 if (!Snippets
[0].empty())
548 Snippets
[0] = Highlight(Snippets
[0], 1, 1 + Snippets
[0].size());
551 for (unsigned I
= 0, E
= Segments
.size(); I
< E
; ++I
) {
552 const auto *CurSeg
= Segments
[I
];
553 if (CheckIfUncovered(CurSeg
))
555 else if (CurSeg
->Col
== ExpansionCol
)
560 if (Color
.hasValue())
561 Snippets
[I
+ 1] = Highlight(Snippets
[I
+ 1], CurSeg
->Col
,
562 CurSeg
->Col
+ Snippets
[I
+ 1].size());
565 if (Color
.hasValue() && Segments
.empty())
566 Snippets
.back() = Highlight(Snippets
.back(), 1, 1 + Snippets
.back().size());
568 if (getOptions().Debug
) {
569 for (const auto &Range
: HighlightedRanges
) {
570 errs() << "Highlighted line " << LineNo
<< ", " << Range
.first
<< " -> ";
571 if (Range
.second
== 0)
574 errs() << Range
.second
;
579 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
580 // sub-line region count tooltips if needed.
582 if (shouldRenderRegionMarkers(LCS
)) {
583 // Just consider the segments which start *and* end on this line.
584 for (unsigned I
= 0, E
= Segments
.size() - 1; I
< E
; ++I
) {
585 const auto *CurSeg
= Segments
[I
];
586 if (!CurSeg
->IsRegionEntry
)
588 if (CurSeg
->Count
== LCS
.getExecutionCount())
592 tag("div", Snippets
[I
+ 1] + tag("span", formatCount(CurSeg
->Count
),
596 if (getOptions().Debug
)
597 errs() << "Marker at " << CurSeg
->Line
<< ":" << CurSeg
->Col
<< " = "
598 << formatCount(CurSeg
->Count
) << "\n";
604 for (const auto &Snippet
: Snippets
)
608 // If there are no sub-views left to attach to this cell, end the cell.
609 // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
614 void SourceCoverageViewHTML::renderLineCoverageColumn(
615 raw_ostream
&OS
, const LineCoverageStats
&Line
) {
616 std::string Count
= "";
618 Count
= tag("pre", formatCount(Line
.getExecutionCount()));
619 std::string CoverageClass
=
620 (Line
.getExecutionCount() > 0) ? "covered-line" : "uncovered-line";
621 OS
<< tag("td", Count
, CoverageClass
);
624 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream
&OS
,
626 std::string LineNoStr
= utostr(uint64_t(LineNo
));
627 std::string TargetName
= "L" + LineNoStr
;
628 OS
<< tag("td", a("#" + TargetName
, tag("pre", LineNoStr
), TargetName
),
632 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream
&,
633 const LineCoverageStats
&Line
,
635 // Region markers are rendered in-line using tooltips.
638 void SourceCoverageViewHTML::renderExpansionSite(raw_ostream
&OS
, LineRef L
,
639 const LineCoverageStats
&LCS
,
640 unsigned ExpansionCol
,
641 unsigned ViewDepth
) {
642 // Render the line containing the expansion site. No extra formatting needed.
643 renderLine(OS
, L
, LCS
, ExpansionCol
, ViewDepth
);
646 void SourceCoverageViewHTML::renderExpansionView(raw_ostream
&OS
,
648 unsigned ViewDepth
) {
649 OS
<< BeginExpansionDiv
;
650 ESV
.View
->print(OS
, /*WholeFile=*/false, /*ShowSourceName=*/false,
651 /*ShowTitle=*/false, ViewDepth
+ 1);
652 OS
<< EndExpansionDiv
;
655 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream
&OS
,
656 InstantiationView
&ISV
,
657 unsigned ViewDepth
) {
658 OS
<< BeginExpansionDiv
;
660 OS
<< BeginSourceNameDiv
662 escape("Unexecuted instantiation: " + ISV
.FunctionName
.str(),
666 ISV
.View
->print(OS
, /*WholeFile=*/false, /*ShowSourceName=*/true,
667 /*ShowTitle=*/false, ViewDepth
);
668 OS
<< EndExpansionDiv
;
671 void SourceCoverageViewHTML::renderTitle(raw_ostream
&OS
, StringRef Title
) {
672 if (getOptions().hasProjectTitle())
673 OS
<< tag(ProjectTitleTag
, escape(getOptions().ProjectTitle
, getOptions()));
674 OS
<< tag(ReportTitleTag
, escape(Title
, getOptions()));
675 if (getOptions().hasCreatedTime())
676 OS
<< tag(CreatedTimeTag
,
677 escape(getOptions().CreatedTimeStr
, getOptions()));
680 void SourceCoverageViewHTML::renderTableHeader(raw_ostream
&OS
,
681 unsigned FirstUncoveredLineNo
,
682 unsigned ViewDepth
) {
683 std::string SourceLabel
;
684 if (FirstUncoveredLineNo
== 0) {
685 SourceLabel
= tag("td", tag("pre", "Source"));
687 std::string LinkTarget
= "#L" + utostr(uint64_t(FirstUncoveredLineNo
));
689 tag("td", tag("pre", "Source (" +
690 a(LinkTarget
, "jump to first uncovered line") +
694 renderLinePrefix(OS
, ViewDepth
);
695 OS
<< tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
697 renderLineSuffix(OS
, ViewDepth
);