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/FileSystem.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/Path.h"
27 // Return a string with the special characters in \p Str escaped.
28 std::string escape(StringRef Str, const CoverageViewOptions &Opts) {
30 unsigned ColNum = 0; // Record the column number.
41 else if (C == '\n' || C == '\r') {
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)
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;
61 Tag += " class='" + ClassName + "'";
62 return Tag + ">" + Str + "</" + Name + ">";
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 &TargetName = "") {
68 std::string Name = TargetName.empty() ? "" : ("name='" + TargetName + "' ");
69 return "<a " + Name + "href='" + Link + "'>" + Str + "</a>";
72 const char *BeginHeader =
74 "<meta name='viewport' content='width=device-width,initial-scale=1'>"
75 "<meta charset='UTF-8'>";
77 const char *CSSForCoverage =
79 background-color: #ffd0d0;
82 background-color: cyan;
85 font-family: -apple-system, sans-serif;
88 margin-top: 0px !important;
89 margin-bottom: 0px !important;
93 border-bottom: 1px solid #dbdbdb;
94 background-color: #eee;
101 border: 1px solid #dbdbdb;
105 background-color: rgba(0, 0, 0, 0);
110 border: 1px solid #dbdbdb;
114 border-collapse: collapse;
118 border: 1px solid #dbdbdb;
126 .column-entry-yellow {
128 background-color: #ffffd0;
132 background-color: #ffd0d0;
134 .column-entry-green {
136 background-color: #d0ffd0;
153 background-color: #b3e6ff;
154 text-decoration: none;
156 .tooltip span.tooltip-content {
168 .tooltip span.tooltip-content:after {
175 border-top: 8px solid #000000;
176 border-right: 8px solid transparent;
177 border-left: 8px solid transparent;
179 :hover.tooltip span.tooltip-content {
189 border-collapse: collapse;
190 border-right: solid 1px #eee;
191 border-left: solid 1px #eee;
201 const char *EndHeader = "</head>";
203 const char *BeginCenteredDiv = "<div class='centered'>";
205 const char *EndCenteredDiv = "</div>";
207 const char *BeginSourceNameDiv = "<div class='source-name-title'>";
209 const char *EndSourceNameDiv = "</div>";
211 const char *BeginCodeTD = "<td class='code'>";
213 const char *EndCodeTD = "</td>";
215 const char *BeginPre = "<pre>";
217 const char *EndPre = "</pre>";
219 const char *BeginExpansionDiv = "<div class='expansion-view'>";
221 const char *EndExpansionDiv = "</div>";
223 const char *BeginTable = "<table>";
225 const char *EndTable = "</table>";
227 const char *ProjectTitleTag = "h1";
229 const char *ReportTitleTag = "h2";
231 const char *CreatedTimeTag = "h4";
233 std::string getPathToStyle(StringRef ViewPath) {
234 std::string PathToStyle = "";
235 std::string PathSep = sys::path::get_separator();
236 unsigned NumSeps = ViewPath.count(PathSep);
237 for (unsigned I = 0, E = NumSeps; I < E; ++I)
238 PathToStyle += ".." + PathSep;
239 return PathToStyle + "style.css";
242 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
243 const std::string &PathToStyle = "") {
244 OS << "<!doctype html>"
248 // Link to a stylesheet if one is available. Otherwise, use the default style.
249 if (PathToStyle.empty())
250 OS << "<style>" << CSSForCoverage << "</style>";
252 OS << "<link rel='stylesheet' type='text/css' href='"
253 << escape(PathToStyle, Opts) << "'>";
255 OS << EndHeader << "<body>";
258 void emitEpilog(raw_ostream &OS) {
263 } // anonymous namespace
265 Expected<CoveragePrinter::OwnedStream>
266 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
267 auto OSOrErr = createOutputStream(Path, "html", InToplevel);
271 OwnedStream OS = std::move(OSOrErr.get());
273 if (!Opts.hasOutputDirectory()) {
274 emitPrelude(*OS.get(), Opts);
276 std::string ViewPath = getOutputPath(Path, "html", InToplevel);
277 emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
280 return std::move(OS);
283 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
284 emitEpilog(*OS.get());
287 /// Emit column labels for the table in the index.
288 static void emitColumnLabelsForIndex(raw_ostream &OS) {
289 SmallVector<std::string, 4> Columns;
290 Columns.emplace_back(tag("td", "Filename", "column-entry-left"));
291 for (const char *Label : {"Function Coverage", "Instantiation Coverage",
292 "Line Coverage", "Region Coverage"})
293 Columns.emplace_back(tag("td", Label, "column-entry"));
294 OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
297 /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
298 /// false, link the summary to \p SF.
299 void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
300 const FileCoverageSummary &FCS,
301 bool IsTotals) const {
302 SmallVector<std::string, 8> Columns;
304 // Format a coverage triple and add the result to the list of columns.
305 auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
309 raw_string_ostream RSO{S};
311 RSO << format("%*.2f", 7, Pctg) << "% ";
314 RSO << '(' << Hit << '/' << Total << ')';
316 const char *CellClass = "column-entry-yellow";
318 CellClass = "column-entry-green";
319 else if (Pctg < 80.0)
320 CellClass = "column-entry-red";
321 Columns.emplace_back(tag("td", tag("pre", S), CellClass));
324 // Simplify the display file path, and wrap it in a link if requested.
325 std::string Filename;
329 SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
330 sys::path::remove_dots(LinkTextStr, /*remove_dot_dots=*/true);
331 sys::path::native(LinkTextStr);
332 std::string LinkText = escape(LinkTextStr, Opts);
333 std::string LinkTarget =
334 escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
335 Filename = a(LinkTarget, LinkText);
338 Columns.emplace_back(tag("td", tag("pre", Filename)));
339 AddCoverageTripleToColumn(FCS.FunctionCoverage.Executed,
340 FCS.FunctionCoverage.NumFunctions,
341 FCS.FunctionCoverage.getPercentCovered());
342 AddCoverageTripleToColumn(FCS.InstantiationCoverage.Executed,
343 FCS.InstantiationCoverage.NumFunctions,
344 FCS.InstantiationCoverage.getPercentCovered());
345 AddCoverageTripleToColumn(FCS.LineCoverage.Covered, FCS.LineCoverage.NumLines,
346 FCS.LineCoverage.getPercentCovered());
347 AddCoverageTripleToColumn(FCS.RegionCoverage.Covered,
348 FCS.RegionCoverage.NumRegions,
349 FCS.RegionCoverage.getPercentCovered());
351 OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
354 Error CoveragePrinterHTML::createIndexFile(
355 ArrayRef<std::string> SourceFiles,
356 const coverage::CoverageMapping &Coverage) {
357 // Emit the default stylesheet.
358 auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
359 if (Error E = CSSOrErr.takeError())
362 OwnedStream CSS = std::move(CSSOrErr.get());
363 CSS->operator<<(CSSForCoverage);
365 // Emit a file index along with some coverage statistics.
366 auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
367 if (Error E = OSOrErr.takeError())
369 auto OS = std::move(OSOrErr.get());
370 raw_ostream &OSRef = *OS.get();
372 assert(Opts.hasOutputDirectory() && "No output directory for index file");
373 emitPrelude(OSRef, Opts, getPathToStyle(""));
375 // Emit some basic information about the coverage report.
376 if (Opts.hasProjectTitle())
377 OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));
378 OSRef << tag(ReportTitleTag, "Coverage Report");
379 if (Opts.hasCreatedTime())
380 OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));
382 // Emit a link to some documentation.
383 OSRef << tag("p", "Click " +
384 a("http://clang.llvm.org/docs/"
385 "SourceBasedCodeCoverage.html#interpreting-reports",
387 " for information about interpreting this report.");
389 // Emit a table containing links to reports for each file in the covmapping.
390 OSRef << BeginCenteredDiv << BeginTable;
391 emitColumnLabelsForIndex(OSRef);
392 FileCoverageSummary Totals("TOTALS");
394 CoverageReport::prepareFileReports(Coverage, Totals, SourceFiles);
395 for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
396 emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
397 emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
398 OSRef << EndTable << EndCenteredDiv
399 << tag("h5", escape(Opts.getLLVMVersionString(), Opts));
402 return Error::success();
405 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
406 OS << BeginCenteredDiv << BeginTable;
409 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
410 OS << EndTable << EndCenteredDiv;
413 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {
414 OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))
418 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
422 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
423 // If this view has sub-views, renderLine() cannot close the view's cell.
424 // Take care of it here, after all sub-views have been rendered.
430 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
431 // The table-based output makes view dividers unnecessary.
434 void SourceCoverageViewHTML::renderLine(
435 raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
436 CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned) {
437 StringRef Line = L.Line;
438 unsigned LineNo = L.LineNo;
440 // Steps for handling text-escaping, highlighting, and tooltip creation:
442 // 1. Split the line into N+1 snippets, where N = |Segments|. The first
443 // snippet starts from Col=1 and ends at the start of the first segment.
444 // The last snippet starts at the last mapped column in the line and ends
445 // at the end of the line. Both are required but may be empty.
447 SmallVector<std::string, 8> Snippets;
450 auto Snip = [&](unsigned Start, unsigned Len) {
451 Snippets.push_back(Line.substr(Start, Len));
455 Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
457 for (unsigned I = 1, E = Segments.size(); I < E; ++I)
458 Snip(LCol - 1, Segments[I]->Col - LCol);
460 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
461 Snip(LCol - 1, Line.size() + 1 - LCol);
463 // 2. Escape all of the snippets.
465 for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
466 Snippets[I] = escape(Snippets[I], getOptions());
468 // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
469 // 1 to set the highlight for snippet 2, segment 2 to set the highlight for
470 // snippet 3, and so on.
472 Optional<std::string> Color;
473 SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
474 auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
475 if (getOptions().Debug)
476 HighlightedRanges.emplace_back(LC, RC);
477 return tag("span", Snippet, Color.getValue());
480 auto CheckIfUncovered = [](const coverage::CoverageSegment *S) {
481 return S && S->HasCount && S->Count == 0;
484 if (CheckIfUncovered(WrappedSegment)) {
486 if (!Snippets[0].empty())
487 Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
490 for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
491 const auto *CurSeg = Segments[I];
492 if (CurSeg->Col == ExpansionCol)
494 else if (CheckIfUncovered(CurSeg))
499 if (Color.hasValue())
500 Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
501 CurSeg->Col + Snippets[I + 1].size());
504 if (Color.hasValue() && Segments.empty())
505 Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
507 if (getOptions().Debug) {
508 for (const auto &Range : HighlightedRanges) {
509 errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
510 if (Range.second == 0)
513 errs() << Range.second;
518 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
519 // sub-line region count tooltips if needed.
521 bool HasMultipleRegions = [&] {
522 unsigned RegionCount = 0;
523 for (const auto *S : Segments)
524 if (S->HasCount && S->IsRegionEntry)
525 if (++RegionCount > 1)
530 if (shouldRenderRegionMarkers(HasMultipleRegions)) {
531 for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
532 const auto *CurSeg = Segments[I];
533 if (!CurSeg->IsRegionEntry || !CurSeg->HasCount)
537 tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
545 for (const auto &Snippet : Snippets)
549 // If there are no sub-views left to attach to this cell, end the cell.
550 // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
555 void SourceCoverageViewHTML::renderLineCoverageColumn(
556 raw_ostream &OS, const LineCoverageStats &Line) {
557 std::string Count = "";
559 Count = tag("pre", formatCount(Line.ExecutionCount));
560 std::string CoverageClass =
561 (Line.ExecutionCount > 0) ? "covered-line" : "uncovered-line";
562 OS << tag("td", Count, CoverageClass);
565 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
567 std::string LineNoStr = utostr(uint64_t(LineNo));
568 std::string TargetName = "L" + LineNoStr;
569 OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),
573 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
574 CoverageSegmentArray,
576 // Region markers are rendered in-line using tooltips.
579 void SourceCoverageViewHTML::renderExpansionSite(
580 raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
581 CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned ViewDepth) {
582 // Render the line containing the expansion site. No extra formatting needed.
583 renderLine(OS, L, WrappedSegment, Segments, ExpansionCol, ViewDepth);
586 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
588 unsigned ViewDepth) {
589 OS << BeginExpansionDiv;
590 ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
592 OS << EndExpansionDiv;
595 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
596 InstantiationView &ISV,
597 unsigned ViewDepth) {
598 OS << BeginExpansionDiv;
600 OS << BeginSourceNameDiv
602 escape("Unexecuted instantiation: " + ISV.FunctionName.str(),
606 ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,
608 OS << EndExpansionDiv;
611 void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {
612 if (getOptions().hasProjectTitle())
613 OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));
614 OS << tag(ReportTitleTag, escape(Title, getOptions()));
615 if (getOptions().hasCreatedTime())
616 OS << tag(CreatedTimeTag,
617 escape(getOptions().CreatedTimeStr, getOptions()));
620 void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
621 unsigned FirstUncoveredLineNo,
622 unsigned ViewDepth) {
623 std::string SourceLabel;
624 if (FirstUncoveredLineNo == 0) {
625 SourceLabel = tag("td", tag("pre", "Source"));
627 std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
629 tag("td", tag("pre", "Source (" +
630 a(LinkTarget, "jump to first uncovered line") +
634 renderLinePrefix(OS, ViewDepth);
635 OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
637 renderLineSuffix(OS, ViewDepth);