Path: blob/main/contrib/llvm-project/llvm/tools/llvm-cov/SourceCoverageViewHTML.cpp
35231 views
//===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file This file implements the html coverage renderer.9///10//===----------------------------------------------------------------------===//1112#include "SourceCoverageViewHTML.h"13#include "CoverageReport.h"14#include "llvm/ADT/SmallString.h"15#include "llvm/ADT/StringExtras.h"16#include "llvm/Support/Format.h"17#include "llvm/Support/Path.h"18#include "llvm/Support/ThreadPool.h"19#include <optional>2021using namespace llvm;2223namespace {2425// Return a string with the special characters in \p Str escaped.26std::string escape(StringRef Str, const CoverageViewOptions &Opts) {27std::string TabExpandedResult;28unsigned ColNum = 0; // Record the column number.29for (char C : Str) {30if (C == '\t') {31// Replace '\t' with up to TabSize spaces.32unsigned NumSpaces = Opts.TabSize - (ColNum % Opts.TabSize);33TabExpandedResult.append(NumSpaces, ' ');34ColNum += NumSpaces;35} else {36TabExpandedResult += C;37if (C == '\n' || C == '\r')38ColNum = 0;39else40++ColNum;41}42}43std::string EscapedHTML;44{45raw_string_ostream OS{EscapedHTML};46printHTMLEscaped(TabExpandedResult, OS);47}48return EscapedHTML;49}5051// Create a \p Name tag around \p Str, and optionally set its \p ClassName.52std::string tag(StringRef Name, StringRef Str, StringRef ClassName = "") {53std::string Tag = "<";54Tag += Name;55if (!ClassName.empty()) {56Tag += " class='";57Tag += ClassName;58Tag += "'";59}60Tag += ">";61Tag += Str;62Tag += "</";63Tag += Name;64Tag += ">";65return Tag;66}6768// Create an anchor to \p Link with the label \p Str.69std::string a(StringRef Link, StringRef Str, StringRef TargetName = "") {70std::string Tag;71Tag += "<a ";72if (!TargetName.empty()) {73Tag += "name='";74Tag += TargetName;75Tag += "' ";76}77Tag += "href='";78Tag += Link;79Tag += "'>";80Tag += Str;81Tag += "</a>";82return Tag;83}8485const char *BeginHeader =86"<head>"87"<meta name='viewport' content='width=device-width,initial-scale=1'>"88"<meta charset='UTF-8'>";8990const char *JSForCoverage =91R"javascript(9293function next_uncovered(selector, reverse, scroll_selector) {94function visit_element(element) {95element.classList.add("seen");96element.classList.add("selected");9798if (!scroll_selector) {99scroll_selector = "tr:has(.selected) td.line-number"100}101102const scroll_to = document.querySelector(scroll_selector);103if (scroll_to) {104scroll_to.scrollIntoView({behavior: "smooth", block: "center", inline: "end"});105}106107}108109function select_one() {110if (!reverse) {111const previously_selected = document.querySelector(".selected");112113if (previously_selected) {114previously_selected.classList.remove("selected");115}116117return document.querySelector(selector + ":not(.seen)");118} else {119const previously_selected = document.querySelector(".selected");120121if (previously_selected) {122previously_selected.classList.remove("selected");123previously_selected.classList.remove("seen");124}125126const nodes = document.querySelectorAll(selector + ".seen");127if (nodes) {128const last = nodes[nodes.length - 1]; // last129return last;130} else {131return undefined;132}133}134}135136function reset_all() {137if (!reverse) {138const all_seen = document.querySelectorAll(selector + ".seen");139140if (all_seen) {141all_seen.forEach(e => e.classList.remove("seen"));142}143} else {144const all_seen = document.querySelectorAll(selector + ":not(.seen)");145146if (all_seen) {147all_seen.forEach(e => e.classList.add("seen"));148}149}150151}152153const uncovered = select_one();154155if (uncovered) {156visit_element(uncovered);157} else {158reset_all();159160161const uncovered = select_one();162163if (uncovered) {164visit_element(uncovered);165}166}167}168169function next_line(reverse) {170next_uncovered("td.uncovered-line", reverse)171}172173function next_region(reverse) {174next_uncovered("span.red.region", reverse);175}176177function next_branch(reverse) {178next_uncovered("span.red.branch", reverse);179}180181document.addEventListener("keypress", function(event) {182console.log(event);183const reverse = event.shiftKey;184if (event.code == "KeyL") {185next_line(reverse);186}187if (event.code == "KeyB") {188next_branch(reverse);189}190if (event.code == "KeyR") {191next_region(reverse);192}193194});195)javascript";196197const char *CSSForCoverage =198R"(.red {199background-color: #f004;200}201.cyan {202background-color: cyan;203}204html {205scroll-behavior: smooth;206}207body {208font-family: -apple-system, sans-serif;209}210pre {211margin-top: 0px !important;212margin-bottom: 0px !important;213}214.source-name-title {215padding: 5px 10px;216border-bottom: 1px solid #8888;217background-color: #0002;218line-height: 35px;219}220.centered {221display: table;222margin-left: left;223margin-right: auto;224border: 1px solid #8888;225border-radius: 3px;226}227.expansion-view {228margin-left: 0px;229margin-top: 5px;230margin-right: 5px;231margin-bottom: 5px;232border: 1px solid #8888;233border-radius: 3px;234}235table {236border-collapse: collapse;237}238.light-row {239border: 1px solid #8888;240border-left: none;241border-right: none;242}243.light-row-bold {244border: 1px solid #8888;245border-left: none;246border-right: none;247font-weight: bold;248}249.column-entry {250text-align: left;251}252.column-entry-bold {253font-weight: bold;254text-align: left;255}256.column-entry-yellow {257text-align: left;258background-color: #ff06;259}260.column-entry-red {261text-align: left;262background-color: #f004;263}264.column-entry-gray {265text-align: left;266background-color: #fff4;267}268.column-entry-green {269text-align: left;270background-color: #0f04;271}272.line-number {273text-align: right;274}275.covered-line {276text-align: right;277color: #06d;278}279.uncovered-line {280text-align: right;281color: #d00;282}283.uncovered-line.selected {284color: #f00;285font-weight: bold;286}287.region.red.selected {288background-color: #f008;289font-weight: bold;290}291.branch.red.selected {292background-color: #f008;293font-weight: bold;294}295.tooltip {296position: relative;297display: inline;298background-color: #bef;299text-decoration: none;300}301.tooltip span.tooltip-content {302position: absolute;303width: 100px;304margin-left: -50px;305color: #FFFFFF;306background: #000000;307height: 30px;308line-height: 30px;309text-align: center;310visibility: hidden;311border-radius: 6px;312}313.tooltip span.tooltip-content:after {314content: '';315position: absolute;316top: 100%;317left: 50%;318margin-left: -8px;319width: 0; height: 0;320border-top: 8px solid #000000;321border-right: 8px solid transparent;322border-left: 8px solid transparent;323}324:hover.tooltip span.tooltip-content {325visibility: visible;326opacity: 0.8;327bottom: 30px;328left: 50%;329z-index: 999;330}331th, td {332vertical-align: top;333padding: 2px 8px;334border-collapse: collapse;335border-right: 1px solid #8888;336border-left: 1px solid #8888;337text-align: left;338}339td pre {340display: inline-block;341text-decoration: inherit;342}343td:first-child {344border-left: none;345}346td:last-child {347border-right: none;348}349tr:hover {350background-color: #eee;351}352tr:last-child {353border-bottom: none;354}355tr:has(> td >a:target), tr:has(> td.uncovered-line.selected) {356background-color: #8884;357}358a {359color: inherit;360}361.control {362position: fixed;363top: 0em;364right: 0em;365padding: 1em;366background: #FFF8;367}368@media (prefers-color-scheme: dark) {369body {370background-color: #222;371color: whitesmoke;372}373tr:hover {374background-color: #111;375}376.covered-line {377color: #39f;378}379.uncovered-line {380color: #f55;381}382.tooltip {383background-color: #068;384}385.control {386background: #2228;387}388tr:has(> td >a:target), tr:has(> td.uncovered-line.selected) {389background-color: #8884;390}391}392)";393394const char *EndHeader = "</head>";395396const char *BeginCenteredDiv = "<div class='centered'>";397398const char *EndCenteredDiv = "</div>";399400const char *BeginSourceNameDiv = "<div class='source-name-title'>";401402const char *EndSourceNameDiv = "</div>";403404const char *BeginCodeTD = "<td class='code'>";405406const char *EndCodeTD = "</td>";407408const char *BeginPre = "<pre>";409410const char *EndPre = "</pre>";411412const char *BeginExpansionDiv = "<div class='expansion-view'>";413414const char *EndExpansionDiv = "</div>";415416const char *BeginTable = "<table>";417418const char *EndTable = "</table>";419420const char *ProjectTitleTag = "h1";421422const char *ReportTitleTag = "h2";423424const char *CreatedTimeTag = "h4";425426std::string getPathToStyle(StringRef ViewPath) {427std::string PathToStyle;428std::string PathSep = std::string(sys::path::get_separator());429unsigned NumSeps = ViewPath.count(PathSep);430for (unsigned I = 0, E = NumSeps; I < E; ++I)431PathToStyle += ".." + PathSep;432return PathToStyle + "style.css";433}434435std::string getPathToJavaScript(StringRef ViewPath) {436std::string PathToJavaScript;437std::string PathSep = std::string(sys::path::get_separator());438unsigned NumSeps = ViewPath.count(PathSep);439for (unsigned I = 0, E = NumSeps; I < E; ++I)440PathToJavaScript += ".." + PathSep;441return PathToJavaScript + "control.js";442}443444void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,445const std::string &PathToStyle = "",446const std::string &PathToJavaScript = "") {447OS << "<!doctype html>"448"<html>"449<< BeginHeader;450451// Link to a stylesheet if one is available. Otherwise, use the default style.452if (PathToStyle.empty())453OS << "<style>" << CSSForCoverage << "</style>";454else455OS << "<link rel='stylesheet' type='text/css' href='"456<< escape(PathToStyle, Opts) << "'>";457458// Link to a JavaScript if one is available459if (PathToJavaScript.empty())460OS << "<script>" << JSForCoverage << "</script>";461else462OS << "<script src='" << escape(PathToJavaScript, Opts) << "'></script>";463464OS << EndHeader << "<body>";465}466467void emitTableRow(raw_ostream &OS, const CoverageViewOptions &Opts,468const std::string &FirstCol, const FileCoverageSummary &FCS,469bool IsTotals) {470SmallVector<std::string, 8> Columns;471472// Format a coverage triple and add the result to the list of columns.473auto AddCoverageTripleToColumn =474[&Columns, &Opts](unsigned Hit, unsigned Total, float Pctg) {475std::string S;476{477raw_string_ostream RSO{S};478if (Total)479RSO << format("%*.2f", 7, Pctg) << "% ";480else481RSO << "- ";482RSO << '(' << Hit << '/' << Total << ')';483}484const char *CellClass = "column-entry-yellow";485if (!Total)486CellClass = "column-entry-gray";487else if (Pctg >= Opts.HighCovWatermark)488CellClass = "column-entry-green";489else if (Pctg < Opts.LowCovWatermark)490CellClass = "column-entry-red";491Columns.emplace_back(tag("td", tag("pre", S), CellClass));492};493494Columns.emplace_back(tag("td", tag("pre", FirstCol)));495AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),496FCS.FunctionCoverage.getNumFunctions(),497FCS.FunctionCoverage.getPercentCovered());498if (Opts.ShowInstantiationSummary)499AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),500FCS.InstantiationCoverage.getNumFunctions(),501FCS.InstantiationCoverage.getPercentCovered());502AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),503FCS.LineCoverage.getNumLines(),504FCS.LineCoverage.getPercentCovered());505if (Opts.ShowRegionSummary)506AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),507FCS.RegionCoverage.getNumRegions(),508FCS.RegionCoverage.getPercentCovered());509if (Opts.ShowBranchSummary)510AddCoverageTripleToColumn(FCS.BranchCoverage.getCovered(),511FCS.BranchCoverage.getNumBranches(),512FCS.BranchCoverage.getPercentCovered());513if (Opts.ShowMCDCSummary)514AddCoverageTripleToColumn(FCS.MCDCCoverage.getCoveredPairs(),515FCS.MCDCCoverage.getNumPairs(),516FCS.MCDCCoverage.getPercentCovered());517518if (IsTotals)519OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row-bold");520else521OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");522}523524void emitEpilog(raw_ostream &OS) {525OS << "</body>"526<< "</html>";527}528529} // anonymous namespace530531Expected<CoveragePrinter::OwnedStream>532CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {533auto OSOrErr = createOutputStream(Path, "html", InToplevel);534if (!OSOrErr)535return OSOrErr;536537OwnedStream OS = std::move(OSOrErr.get());538539if (!Opts.hasOutputDirectory()) {540emitPrelude(*OS.get(), Opts);541} else {542std::string ViewPath = getOutputPath(Path, "html", InToplevel);543emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath),544getPathToJavaScript(ViewPath));545}546547return std::move(OS);548}549550void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {551emitEpilog(*OS.get());552}553554/// Emit column labels for the table in the index.555static void emitColumnLabelsForIndex(raw_ostream &OS,556const CoverageViewOptions &Opts) {557SmallVector<std::string, 4> Columns;558Columns.emplace_back(tag("td", "Filename", "column-entry-bold"));559Columns.emplace_back(tag("td", "Function Coverage", "column-entry-bold"));560if (Opts.ShowInstantiationSummary)561Columns.emplace_back(562tag("td", "Instantiation Coverage", "column-entry-bold"));563Columns.emplace_back(tag("td", "Line Coverage", "column-entry-bold"));564if (Opts.ShowRegionSummary)565Columns.emplace_back(tag("td", "Region Coverage", "column-entry-bold"));566if (Opts.ShowBranchSummary)567Columns.emplace_back(tag("td", "Branch Coverage", "column-entry-bold"));568if (Opts.ShowMCDCSummary)569Columns.emplace_back(tag("td", "MC/DC", "column-entry-bold"));570OS << tag("tr", join(Columns.begin(), Columns.end(), ""));571}572573std::string574CoveragePrinterHTML::buildLinkToFile(StringRef SF,575const FileCoverageSummary &FCS) const {576SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));577sys::path::remove_dots(LinkTextStr, /*remove_dot_dot=*/true);578sys::path::native(LinkTextStr);579std::string LinkText = escape(LinkTextStr, Opts);580std::string LinkTarget =581escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);582return a(LinkTarget, LinkText);583}584585Error CoveragePrinterHTML::emitStyleSheet() {586auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);587if (Error E = CSSOrErr.takeError())588return E;589590OwnedStream CSS = std::move(CSSOrErr.get());591CSS->operator<<(CSSForCoverage);592593return Error::success();594}595596Error CoveragePrinterHTML::emitJavaScript() {597auto JSOrErr = createOutputStream("control", "js", /*InToplevel=*/true);598if (Error E = JSOrErr.takeError())599return E;600601OwnedStream JS = std::move(JSOrErr.get());602JS->operator<<(JSForCoverage);603604return Error::success();605}606607void CoveragePrinterHTML::emitReportHeader(raw_ostream &OSRef,608const std::string &Title) {609// Emit some basic information about the coverage report.610if (Opts.hasProjectTitle())611OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));612OSRef << tag(ReportTitleTag, Title);613if (Opts.hasCreatedTime())614OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));615616// Emit a link to some documentation.617OSRef << tag("p", "Click " +618a("http://clang.llvm.org/docs/"619"SourceBasedCodeCoverage.html#interpreting-reports",620"here") +621" for information about interpreting this report.");622623// Emit a table containing links to reports for each file in the covmapping.624// Exclude files which don't contain any regions.625OSRef << BeginCenteredDiv << BeginTable;626emitColumnLabelsForIndex(OSRef, Opts);627}628629/// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is630/// false, link the summary to \p SF.631void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,632const FileCoverageSummary &FCS,633bool IsTotals) const {634// Simplify the display file path, and wrap it in a link if requested.635std::string Filename;636if (IsTotals) {637Filename = std::string(SF);638} else {639Filename = buildLinkToFile(SF, FCS);640}641642emitTableRow(OS, Opts, Filename, FCS, IsTotals);643}644645Error CoveragePrinterHTML::createIndexFile(646ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,647const CoverageFiltersMatchAll &Filters) {648// Emit the default stylesheet.649if (Error E = emitStyleSheet())650return E;651652// Emit the JavaScript UI implementation653if (Error E = emitJavaScript())654return E;655656// Emit a file index along with some coverage statistics.657auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);658if (Error E = OSOrErr.takeError())659return E;660auto OS = std::move(OSOrErr.get());661raw_ostream &OSRef = *OS.get();662663assert(Opts.hasOutputDirectory() && "No output directory for index file");664emitPrelude(OSRef, Opts, getPathToStyle(""), getPathToJavaScript(""));665666emitReportHeader(OSRef, "Coverage Report");667668FileCoverageSummary Totals("TOTALS");669auto FileReports = CoverageReport::prepareFileReports(670Coverage, Totals, SourceFiles, Opts, Filters);671bool EmptyFiles = false;672for (unsigned I = 0, E = FileReports.size(); I < E; ++I) {673if (FileReports[I].FunctionCoverage.getNumFunctions())674emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);675else676EmptyFiles = true;677}678emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);679OSRef << EndTable << EndCenteredDiv;680681// Emit links to files which don't contain any functions. These are normally682// not very useful, but could be relevant for code which abuses the683// preprocessor.684if (EmptyFiles && Filters.empty()) {685OSRef << tag("p", "Files which contain no functions. (These "686"files contain code pulled into other files "687"by the preprocessor.)\n");688OSRef << BeginCenteredDiv << BeginTable;689for (unsigned I = 0, E = FileReports.size(); I < E; ++I)690if (!FileReports[I].FunctionCoverage.getNumFunctions()) {691std::string Link = buildLinkToFile(SourceFiles[I], FileReports[I]);692OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';693}694OSRef << EndTable << EndCenteredDiv;695}696697OSRef << tag("h5", escape(Opts.getLLVMVersionString(), Opts));698emitEpilog(OSRef);699700return Error::success();701}702703struct CoveragePrinterHTMLDirectory::Reporter : public DirectoryCoverageReport {704CoveragePrinterHTMLDirectory &Printer;705706Reporter(CoveragePrinterHTMLDirectory &Printer,707const coverage::CoverageMapping &Coverage,708const CoverageFiltersMatchAll &Filters)709: DirectoryCoverageReport(Printer.Opts, Coverage, Filters),710Printer(Printer) {}711712Error generateSubDirectoryReport(SubFileReports &&SubFiles,713SubDirReports &&SubDirs,714FileCoverageSummary &&SubTotals) override {715auto &LCPath = SubTotals.Name;716assert(Options.hasOutputDirectory() &&717"No output directory for index file");718719SmallString<128> OSPath = LCPath;720sys::path::append(OSPath, "index");721auto OSOrErr = Printer.createOutputStream(OSPath, "html",722/*InToplevel=*/false);723if (auto E = OSOrErr.takeError())724return E;725auto OS = std::move(OSOrErr.get());726raw_ostream &OSRef = *OS.get();727728auto IndexHtmlPath = Printer.getOutputPath((LCPath + "index").str(), "html",729/*InToplevel=*/false);730emitPrelude(OSRef, Options, getPathToStyle(IndexHtmlPath),731getPathToJavaScript(IndexHtmlPath));732733auto NavLink = buildTitleLinks(LCPath);734Printer.emitReportHeader(OSRef, "Coverage Report (" + NavLink + ")");735736std::vector<const FileCoverageSummary *> EmptyFiles;737738// Make directories at the top of the table.739for (auto &&SubDir : SubDirs) {740auto &Report = SubDir.second.first;741if (!Report.FunctionCoverage.getNumFunctions())742EmptyFiles.push_back(&Report);743else744emitTableRow(OSRef, Options, buildRelLinkToFile(Report.Name), Report,745/*IsTotals=*/false);746}747748for (auto &&SubFile : SubFiles) {749auto &Report = SubFile.second;750if (!Report.FunctionCoverage.getNumFunctions())751EmptyFiles.push_back(&Report);752else753emitTableRow(OSRef, Options, buildRelLinkToFile(Report.Name), Report,754/*IsTotals=*/false);755}756757// Emit the totals row.758emitTableRow(OSRef, Options, "Totals", SubTotals, /*IsTotals=*/false);759OSRef << EndTable << EndCenteredDiv;760761// Emit links to files which don't contain any functions. These are normally762// not very useful, but could be relevant for code which abuses the763// preprocessor.764if (!EmptyFiles.empty()) {765OSRef << tag("p", "Files which contain no functions. (These "766"files contain code pulled into other files "767"by the preprocessor.)\n");768OSRef << BeginCenteredDiv << BeginTable;769for (auto FCS : EmptyFiles) {770auto Link = buildRelLinkToFile(FCS->Name);771OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';772}773OSRef << EndTable << EndCenteredDiv;774}775776// Emit epilog.777OSRef << tag("h5", escape(Options.getLLVMVersionString(), Options));778emitEpilog(OSRef);779780return Error::success();781}782783/// Make a title with hyperlinks to the index.html files of each hierarchy784/// of the report.785std::string buildTitleLinks(StringRef LCPath) const {786// For each report level in LCPStack, extract the path component and787// calculate the number of "../" relative to current LCPath.788SmallVector<std::pair<SmallString<128>, unsigned>, 16> Components;789790auto Iter = LCPStack.begin(), IterE = LCPStack.end();791SmallString<128> RootPath;792if (*Iter == 0) {793// If llvm-cov works on relative coverage mapping data, the LCP of794// all source file paths can be 0, which makes the title path empty.795// As we like adding a slash at the back of the path to indicate a796// directory, in this case, we use "." as the root path to make it797// not be confused with the root path "/".798RootPath = ".";799} else {800RootPath = LCPath.substr(0, *Iter);801sys::path::native(RootPath);802sys::path::remove_dots(RootPath, /*remove_dot_dot=*/true);803}804Components.emplace_back(std::move(RootPath), 0);805806for (auto Last = *Iter; ++Iter != IterE; Last = *Iter) {807SmallString<128> SubPath = LCPath.substr(Last, *Iter - Last);808sys::path::native(SubPath);809sys::path::remove_dots(SubPath, /*remove_dot_dot=*/true);810auto Level = unsigned(SubPath.count(sys::path::get_separator())) + 1;811Components.back().second += Level;812Components.emplace_back(std::move(SubPath), Level);813}814815// Then we make the title accroding to Components.816std::string S;817for (auto I = Components.begin(), E = Components.end();;) {818auto &Name = I->first;819if (++I == E) {820S += a("./index.html", Name);821S += sys::path::get_separator();822break;823}824825SmallString<128> Link;826for (unsigned J = I->second; J > 0; --J)827Link += "../";828Link += "index.html";829S += a(Link, Name);830S += sys::path::get_separator();831}832return S;833}834835std::string buildRelLinkToFile(StringRef RelPath) const {836SmallString<128> LinkTextStr(RelPath);837sys::path::native(LinkTextStr);838839// remove_dots will remove trailing slash, so we need to check before it.840auto IsDir = LinkTextStr.ends_with(sys::path::get_separator());841sys::path::remove_dots(LinkTextStr, /*remove_dot_dot=*/true);842843SmallString<128> LinkTargetStr(LinkTextStr);844if (IsDir) {845LinkTextStr += sys::path::get_separator();846sys::path::append(LinkTargetStr, "index.html");847} else {848LinkTargetStr += ".html";849}850851auto LinkText = escape(LinkTextStr, Options);852auto LinkTarget = escape(LinkTargetStr, Options);853return a(LinkTarget, LinkText);854}855};856857Error CoveragePrinterHTMLDirectory::createIndexFile(858ArrayRef<std::string> SourceFiles, const CoverageMapping &Coverage,859const CoverageFiltersMatchAll &Filters) {860// The createSubIndexFile function only works when SourceFiles is861// more than one. So we fallback to CoveragePrinterHTML when it is.862if (SourceFiles.size() <= 1)863return CoveragePrinterHTML::createIndexFile(SourceFiles, Coverage, Filters);864865// Emit the default stylesheet.866if (Error E = emitStyleSheet())867return E;868869// Emit the JavaScript UI implementation870if (Error E = emitJavaScript())871return E;872873// Emit index files in every subdirectory.874Reporter Report(*this, Coverage, Filters);875auto TotalsOrErr = Report.prepareDirectoryReports(SourceFiles);876if (auto E = TotalsOrErr.takeError())877return E;878auto &LCPath = TotalsOrErr->Name;879880// Emit the top level index file. Top level index file is just a redirection881// to the index file in the LCP directory.882auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);883if (auto E = OSOrErr.takeError())884return E;885auto OS = std::move(OSOrErr.get());886auto LCPIndexFilePath =887getOutputPath((LCPath + "index").str(), "html", /*InToplevel=*/false);888*OS.get() << R"(<!DOCTYPE html>889<html>890<head>891<meta http-equiv="Refresh" content="0; url=')"892<< LCPIndexFilePath << R"('" />893</head>894<body></body>895</html>896)";897898return Error::success();899}900901void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {902OS << BeginCenteredDiv << BeginTable;903}904905void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {906OS << EndTable << EndCenteredDiv;907}908909void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {910OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))911<< EndSourceNameDiv;912}913914void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {915OS << "<tr>";916}917918void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {919// If this view has sub-views, renderLine() cannot close the view's cell.920// Take care of it here, after all sub-views have been rendered.921if (hasSubViews())922OS << EndCodeTD;923OS << "</tr>";924}925926void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {927// The table-based output makes view dividers unnecessary.928}929930void SourceCoverageViewHTML::renderLine(raw_ostream &OS, LineRef L,931const LineCoverageStats &LCS,932unsigned ExpansionCol, unsigned) {933StringRef Line = L.Line;934unsigned LineNo = L.LineNo;935936// Steps for handling text-escaping, highlighting, and tooltip creation:937//938// 1. Split the line into N+1 snippets, where N = |Segments|. The first939// snippet starts from Col=1 and ends at the start of the first segment.940// The last snippet starts at the last mapped column in the line and ends941// at the end of the line. Both are required but may be empty.942943SmallVector<std::string, 8> Snippets;944CoverageSegmentArray Segments = LCS.getLineSegments();945946unsigned LCol = 1;947auto Snip = [&](unsigned Start, unsigned Len) {948Snippets.push_back(std::string(Line.substr(Start, Len)));949LCol += Len;950};951952Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));953954for (unsigned I = 1, E = Segments.size(); I < E; ++I)955Snip(LCol - 1, Segments[I]->Col - LCol);956957// |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.958Snip(LCol - 1, Line.size() + 1 - LCol);959960// 2. Escape all of the snippets.961962for (unsigned I = 0, E = Snippets.size(); I < E; ++I)963Snippets[I] = escape(Snippets[I], getOptions());964965// 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment966// 1 to set the highlight for snippet 2, segment 2 to set the highlight for967// snippet 3, and so on.968969std::optional<StringRef> Color;970SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;971auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {972if (getOptions().Debug)973HighlightedRanges.emplace_back(LC, RC);974if (Snippet.empty())975return tag("span", Snippet, std::string(*Color));976else977return tag("span", Snippet, "region " + std::string(*Color));978};979980auto CheckIfUncovered = [&](const CoverageSegment *S) {981return S && (!S->IsGapRegion || (Color && *Color == "red")) &&982S->HasCount && S->Count == 0;983};984985if (CheckIfUncovered(LCS.getWrappedSegment())) {986Color = "red";987if (!Snippets[0].empty())988Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());989}990991for (unsigned I = 0, E = Segments.size(); I < E; ++I) {992const auto *CurSeg = Segments[I];993if (CheckIfUncovered(CurSeg))994Color = "red";995else if (CurSeg->Col == ExpansionCol)996Color = "cyan";997else998Color = std::nullopt;9991000if (Color)1001Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,1002CurSeg->Col + Snippets[I + 1].size());1003}10041005if (Color && Segments.empty())1006Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());10071008if (getOptions().Debug) {1009for (const auto &Range : HighlightedRanges) {1010errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";1011if (Range.second == 0)1012errs() << "?";1013else1014errs() << Range.second;1015errs() << "\n";1016}1017}10181019// 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate1020// sub-line region count tooltips if needed.10211022if (shouldRenderRegionMarkers(LCS)) {1023// Just consider the segments which start *and* end on this line.1024for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {1025const auto *CurSeg = Segments[I];1026if (!CurSeg->IsRegionEntry)1027continue;1028if (CurSeg->Count == LCS.getExecutionCount())1029continue;10301031Snippets[I + 1] =1032tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),1033"tooltip-content"),1034"tooltip");10351036if (getOptions().Debug)1037errs() << "Marker at " << CurSeg->Line << ":" << CurSeg->Col << " = "1038<< formatCount(CurSeg->Count) << "\n";1039}1040}10411042OS << BeginCodeTD;1043OS << BeginPre;1044for (const auto &Snippet : Snippets)1045OS << Snippet;1046OS << EndPre;10471048// If there are no sub-views left to attach to this cell, end the cell.1049// Otherwise, end it after the sub-views are rendered (renderLineSuffix()).1050if (!hasSubViews())1051OS << EndCodeTD;1052}10531054void SourceCoverageViewHTML::renderLineCoverageColumn(1055raw_ostream &OS, const LineCoverageStats &Line) {1056std::string Count;1057if (Line.isMapped())1058Count = tag("pre", formatCount(Line.getExecutionCount()));1059std::string CoverageClass =1060(Line.getExecutionCount() > 0)1061? "covered-line"1062: (Line.isMapped() ? "uncovered-line" : "skipped-line");1063OS << tag("td", Count, CoverageClass);1064}10651066void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,1067unsigned LineNo) {1068std::string LineNoStr = utostr(uint64_t(LineNo));1069std::string TargetName = "L" + LineNoStr;1070OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),1071"line-number");1072}10731074void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,1075const LineCoverageStats &Line,1076unsigned) {1077// Region markers are rendered in-line using tooltips.1078}10791080void SourceCoverageViewHTML::renderExpansionSite(raw_ostream &OS, LineRef L,1081const LineCoverageStats &LCS,1082unsigned ExpansionCol,1083unsigned ViewDepth) {1084// Render the line containing the expansion site. No extra formatting needed.1085renderLine(OS, L, LCS, ExpansionCol, ViewDepth);1086}10871088void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,1089ExpansionView &ESV,1090unsigned ViewDepth) {1091OS << BeginExpansionDiv;1092ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,1093/*ShowTitle=*/false, ViewDepth + 1);1094OS << EndExpansionDiv;1095}10961097void SourceCoverageViewHTML::renderBranchView(raw_ostream &OS, BranchView &BRV,1098unsigned ViewDepth) {1099// Render the child subview.1100if (getOptions().Debug)1101errs() << "Branch at line " << BRV.getLine() << '\n';11021103OS << BeginExpansionDiv;1104OS << BeginPre;1105for (const auto &R : BRV.Regions) {1106// Calculate TruePercent and False Percent.1107double TruePercent = 0.0;1108double FalsePercent = 0.0;1109// FIXME: It may overflow when the data is too large, but I have not1110// encountered it in actual use, and not sure whether to use __uint128_t.1111uint64_t Total = R.ExecutionCount + R.FalseExecutionCount;11121113if (!getOptions().ShowBranchCounts && Total != 0) {1114TruePercent = ((double)(R.ExecutionCount) / (double)Total) * 100.0;1115FalsePercent = ((double)(R.FalseExecutionCount) / (double)Total) * 100.0;1116}11171118// Display Line + Column.1119std::string LineNoStr = utostr(uint64_t(R.LineStart));1120std::string ColNoStr = utostr(uint64_t(R.ColumnStart));1121std::string TargetName = "L" + LineNoStr;11221123OS << " Branch (";1124OS << tag("span",1125a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr),1126TargetName),1127"line-number") +1128"): [";11291130if (R.Folded) {1131OS << "Folded - Ignored]\n";1132continue;1133}11341135// Display TrueCount or TruePercent.1136std::string TrueColor = R.ExecutionCount ? "None" : "red branch";1137std::string TrueCovClass =1138(R.ExecutionCount > 0) ? "covered-line" : "uncovered-line";11391140OS << tag("span", "True", TrueColor);1141OS << ": ";1142if (getOptions().ShowBranchCounts)1143OS << tag("span", formatCount(R.ExecutionCount), TrueCovClass) << ", ";1144else1145OS << format("%0.2f", TruePercent) << "%, ";11461147// Display FalseCount or FalsePercent.1148std::string FalseColor = R.FalseExecutionCount ? "None" : "red branch";1149std::string FalseCovClass =1150(R.FalseExecutionCount > 0) ? "covered-line" : "uncovered-line";11511152OS << tag("span", "False", FalseColor);1153OS << ": ";1154if (getOptions().ShowBranchCounts)1155OS << tag("span", formatCount(R.FalseExecutionCount), FalseCovClass);1156else1157OS << format("%0.2f", FalsePercent) << "%";11581159OS << "]\n";1160}1161OS << EndPre;1162OS << EndExpansionDiv;1163}11641165void SourceCoverageViewHTML::renderMCDCView(raw_ostream &OS, MCDCView &MRV,1166unsigned ViewDepth) {1167for (auto &Record : MRV.Records) {1168OS << BeginExpansionDiv;1169OS << BeginPre;1170OS << " MC/DC Decision Region (";11711172// Display Line + Column information.1173const CounterMappingRegion &DecisionRegion = Record.getDecisionRegion();1174std::string LineNoStr = Twine(DecisionRegion.LineStart).str();1175std::string ColNoStr = Twine(DecisionRegion.ColumnStart).str();1176std::string TargetName = "L" + LineNoStr;1177OS << tag("span",1178a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr)),1179"line-number") +1180") to (";1181LineNoStr = utostr(uint64_t(DecisionRegion.LineEnd));1182ColNoStr = utostr(uint64_t(DecisionRegion.ColumnEnd));1183OS << tag("span",1184a("#" + TargetName, tag("span", LineNoStr + ":" + ColNoStr)),1185"line-number") +1186")\n\n";11871188// Display MC/DC Information.1189OS << " Number of Conditions: " << Record.getNumConditions() << "\n";1190for (unsigned i = 0; i < Record.getNumConditions(); i++) {1191OS << " " << Record.getConditionHeaderString(i);1192}1193OS << "\n";1194OS << " Executed MC/DC Test Vectors:\n\n ";1195OS << Record.getTestVectorHeaderString();1196for (unsigned i = 0; i < Record.getNumTestVectors(); i++)1197OS << Record.getTestVectorString(i);1198OS << "\n";1199for (unsigned i = 0; i < Record.getNumConditions(); i++)1200OS << Record.getConditionCoverageString(i);1201OS << " MC/DC Coverage for Expression: ";1202OS << format("%0.2f", Record.getPercentCovered()) << "%\n";1203OS << EndPre;1204OS << EndExpansionDiv;1205}1206return;1207}12081209void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,1210InstantiationView &ISV,1211unsigned ViewDepth) {1212OS << BeginExpansionDiv;1213if (!ISV.View)1214OS << BeginSourceNameDiv1215<< tag("pre",1216escape("Unexecuted instantiation: " + ISV.FunctionName.str(),1217getOptions()))1218<< EndSourceNameDiv;1219else1220ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,1221/*ShowTitle=*/false, ViewDepth);1222OS << EndExpansionDiv;1223}12241225void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {1226if (getOptions().hasProjectTitle())1227OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));1228OS << tag(ReportTitleTag, escape(Title, getOptions()));1229if (getOptions().hasCreatedTime())1230OS << tag(CreatedTimeTag,1231escape(getOptions().CreatedTimeStr, getOptions()));12321233OS << tag("span",1234a("javascript:next_line()", "next uncovered line (L)") + ", " +1235a("javascript:next_region()", "next uncovered region (R)") +1236", " +1237a("javascript:next_branch()", "next uncovered branch (B)"),1238"control");1239}12401241void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,1242unsigned ViewDepth) {1243std::string Links;12441245renderLinePrefix(OS, ViewDepth);1246OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"));1247OS << tag("td", tag("pre", "Source" + Links));1248renderLineSuffix(OS, ViewDepth);1249}125012511252