14c01092aSVedant Kumar //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===//
24c01092aSVedant Kumar //
34c01092aSVedant Kumar //                     The LLVM Compiler Infrastructure
44c01092aSVedant Kumar //
54c01092aSVedant Kumar // This file is distributed under the University of Illinois Open Source
64c01092aSVedant Kumar // License. See LICENSE.TXT for details.
74c01092aSVedant Kumar //
84c01092aSVedant Kumar //===----------------------------------------------------------------------===//
94c01092aSVedant Kumar ///
104c01092aSVedant Kumar /// \file This file implements the html coverage renderer.
114c01092aSVedant Kumar ///
124c01092aSVedant Kumar //===----------------------------------------------------------------------===//
134c01092aSVedant Kumar 
14a59334daSVedant Kumar #include "CoverageReport.h"
154c01092aSVedant Kumar #include "SourceCoverageViewHTML.h"
164c01092aSVedant Kumar #include "llvm/ADT/Optional.h"
174c01092aSVedant Kumar #include "llvm/ADT/SmallString.h"
184c01092aSVedant Kumar #include "llvm/ADT/StringExtras.h"
1984dc971eSYing Yi #include "llvm/Support/FileSystem.h"
20a59334daSVedant Kumar #include "llvm/Support/Format.h"
214c01092aSVedant Kumar #include "llvm/Support/Path.h"
224c01092aSVedant Kumar 
234c01092aSVedant Kumar using namespace llvm;
244c01092aSVedant Kumar 
254c01092aSVedant Kumar namespace {
264c01092aSVedant Kumar 
27c076c490SVedant Kumar // Return a string with the special characters in \p Str escaped.
280ef31b79SYing Yi std::string escape(StringRef Str, const CoverageViewOptions &Opts) {
29c076c490SVedant Kumar   std::string Result;
300ef31b79SYing Yi   unsigned ColNum = 0; // Record the column number.
31c076c490SVedant Kumar   for (char C : Str) {
320ef31b79SYing Yi     ++ColNum;
33c076c490SVedant Kumar     if (C == '&')
34c076c490SVedant Kumar       Result += "&";
35c076c490SVedant Kumar     else if (C == '<')
36c076c490SVedant Kumar       Result += "&lt;";
37c076c490SVedant Kumar     else if (C == '>')
38c076c490SVedant Kumar       Result += "&gt;";
39c076c490SVedant Kumar     else if (C == '\"')
40c076c490SVedant Kumar       Result += "&quot;";
410ef31b79SYing Yi     else if (C == '\n' || C == '\r') {
420ef31b79SYing Yi       Result += C;
430ef31b79SYing Yi       ColNum = 0;
440ef31b79SYing Yi     } else if (C == '\t') {
450ef31b79SYing Yi       // Replace '\t' with TabSize spaces.
460ef31b79SYing Yi       unsigned NumSpaces = Opts.TabSize - (--ColNum % Opts.TabSize);
470ef31b79SYing Yi       for (unsigned I = 0; I < NumSpaces; ++I)
480ef31b79SYing Yi         Result += "&nbsp;";
490ef31b79SYing Yi       ColNum += NumSpaces;
500ef31b79SYing Yi     } else
51c076c490SVedant Kumar       Result += C;
52c076c490SVedant Kumar   }
53c076c490SVedant Kumar   return Result;
54c076c490SVedant Kumar }
55c076c490SVedant Kumar 
56c076c490SVedant Kumar // Create a \p Name tag around \p Str, and optionally set its \p ClassName.
57c076c490SVedant Kumar std::string tag(const std::string &Name, const std::string &Str,
58c076c490SVedant Kumar                 const std::string &ClassName = "") {
59c076c490SVedant Kumar   std::string Tag = "<" + Name;
60c076c490SVedant Kumar   if (ClassName != "")
61c076c490SVedant Kumar     Tag += " class='" + ClassName + "'";
62c076c490SVedant Kumar   return Tag + ">" + Str + "</" + Name + ">";
63c076c490SVedant Kumar }
64c076c490SVedant Kumar 
65c076c490SVedant Kumar // Create an anchor to \p Link with the label \p Str.
66c076c490SVedant Kumar std::string a(const std::string &Link, const std::string &Str,
675a0e92b0SVedant Kumar               const std::string &TargetName = "") {
685a0e92b0SVedant Kumar   std::string Name = TargetName.empty() ? "" : ("name='" + TargetName + "' ");
695a0e92b0SVedant Kumar   return "<a " + Name + "href='" + Link + "'>" + Str + "</a>";
70c076c490SVedant Kumar }
71c076c490SVedant Kumar 
724c01092aSVedant Kumar const char *BeginHeader =
734c01092aSVedant Kumar   "<head>"
744c01092aSVedant Kumar     "<meta name='viewport' content='width=device-width,initial-scale=1'>"
754c01092aSVedant Kumar     "<meta charset='UTF-8'>";
764c01092aSVedant Kumar 
774c01092aSVedant Kumar const char *CSSForCoverage =
78c076c490SVedant Kumar     R"(.red {
79a59334daSVedant Kumar   background-color: #ffd0d0;
804c01092aSVedant Kumar }
814c01092aSVedant Kumar .cyan {
824c01092aSVedant Kumar   background-color: cyan;
834c01092aSVedant Kumar }
844c01092aSVedant Kumar body {
854c01092aSVedant Kumar   font-family: -apple-system, sans-serif;
864c01092aSVedant Kumar }
874c01092aSVedant Kumar pre {
884c01092aSVedant Kumar   margin-top: 0px !important;
894c01092aSVedant Kumar   margin-bottom: 0px !important;
904c01092aSVedant Kumar }
914c01092aSVedant Kumar .source-name-title {
924c01092aSVedant Kumar   padding: 5px 10px;
934c01092aSVedant Kumar   border-bottom: 1px solid #dbdbdb;
944c01092aSVedant Kumar   background-color: #eee;
9584dc971eSYing Yi   line-height: 35px;
964c01092aSVedant Kumar }
974c01092aSVedant Kumar .centered {
984c01092aSVedant Kumar   display: table;
9984dc971eSYing Yi   margin-left: left;
1004c01092aSVedant Kumar   margin-right: auto;
1014c01092aSVedant Kumar   border: 1px solid #dbdbdb;
1024c01092aSVedant Kumar   border-radius: 3px;
1034c01092aSVedant Kumar }
1044c01092aSVedant Kumar .expansion-view {
1054c01092aSVedant Kumar   background-color: rgba(0, 0, 0, 0);
1064c01092aSVedant Kumar   margin-left: 0px;
1074c01092aSVedant Kumar   margin-top: 5px;
1084c01092aSVedant Kumar   margin-right: 5px;
1094c01092aSVedant Kumar   margin-bottom: 5px;
1104c01092aSVedant Kumar   border: 1px solid #dbdbdb;
1114c01092aSVedant Kumar   border-radius: 3px;
1124c01092aSVedant Kumar }
1134c01092aSVedant Kumar table {
1144c01092aSVedant Kumar   border-collapse: collapse;
1154c01092aSVedant Kumar }
116a59334daSVedant Kumar .light-row {
117a59334daSVedant Kumar   background: #ffffff;
118a59334daSVedant Kumar   border: 1px solid #dbdbdb;
119a59334daSVedant Kumar }
120a59334daSVedant Kumar .column-entry {
121a59334daSVedant Kumar   text-align: right;
122a59334daSVedant Kumar }
1237b9e9bb4SVedant Kumar .column-entry-left {
1247b9e9bb4SVedant Kumar   text-align: left;
1257b9e9bb4SVedant Kumar }
126a59334daSVedant Kumar .column-entry-yellow {
127a59334daSVedant Kumar   text-align: right;
128a59334daSVedant Kumar   background-color: #ffffd0;
129a59334daSVedant Kumar }
130a59334daSVedant Kumar .column-entry-red {
131a59334daSVedant Kumar   text-align: right;
132a59334daSVedant Kumar   background-color: #ffd0d0;
133a59334daSVedant Kumar }
134a59334daSVedant Kumar .column-entry-green {
135a59334daSVedant Kumar   text-align: right;
136a59334daSVedant Kumar   background-color: #d0ffd0;
137a59334daSVedant Kumar }
1384c01092aSVedant Kumar .line-number {
1394c01092aSVedant Kumar   text-align: right;
1404c01092aSVedant Kumar   color: #aaa;
1414c01092aSVedant Kumar }
1424c01092aSVedant Kumar .covered-line {
1434c01092aSVedant Kumar   text-align: right;
1444c01092aSVedant Kumar   color: #0080ff;
1454c01092aSVedant Kumar }
1464c01092aSVedant Kumar .uncovered-line {
1474c01092aSVedant Kumar   text-align: right;
1484c01092aSVedant Kumar   color: #ff3300;
1494c01092aSVedant Kumar }
1504c01092aSVedant Kumar .tooltip {
1514c01092aSVedant Kumar   position: relative;
1524c01092aSVedant Kumar   display: inline;
1534c01092aSVedant Kumar   background-color: #b3e6ff;
1544c01092aSVedant Kumar   text-decoration: none;
1554c01092aSVedant Kumar }
1564c01092aSVedant Kumar .tooltip span.tooltip-content {
1574c01092aSVedant Kumar   position: absolute;
1584c01092aSVedant Kumar   width: 100px;
1594c01092aSVedant Kumar   margin-left: -50px;
1604c01092aSVedant Kumar   color: #FFFFFF;
1614c01092aSVedant Kumar   background: #000000;
1624c01092aSVedant Kumar   height: 30px;
1634c01092aSVedant Kumar   line-height: 30px;
1644c01092aSVedant Kumar   text-align: center;
1654c01092aSVedant Kumar   visibility: hidden;
1664c01092aSVedant Kumar   border-radius: 6px;
1674c01092aSVedant Kumar }
1684c01092aSVedant Kumar .tooltip span.tooltip-content:after {
1694c01092aSVedant Kumar   content: '';
1704c01092aSVedant Kumar   position: absolute;
1714c01092aSVedant Kumar   top: 100%;
1724c01092aSVedant Kumar   left: 50%;
1734c01092aSVedant Kumar   margin-left: -8px;
1744c01092aSVedant Kumar   width: 0; height: 0;
1754c01092aSVedant Kumar   border-top: 8px solid #000000;
1764c01092aSVedant Kumar   border-right: 8px solid transparent;
1774c01092aSVedant Kumar   border-left: 8px solid transparent;
1784c01092aSVedant Kumar }
1794c01092aSVedant Kumar :hover.tooltip span.tooltip-content {
1804c01092aSVedant Kumar   visibility: visible;
1814c01092aSVedant Kumar   opacity: 0.8;
1824c01092aSVedant Kumar   bottom: 30px;
1834c01092aSVedant Kumar   left: 50%;
1844c01092aSVedant Kumar   z-index: 999;
1854c01092aSVedant Kumar }
1864c01092aSVedant Kumar th, td {
1874c01092aSVedant Kumar   vertical-align: top;
1884c01092aSVedant Kumar   padding: 2px 5px;
1894c01092aSVedant Kumar   border-collapse: collapse;
1904c01092aSVedant Kumar   border-right: solid 1px #eee;
1914c01092aSVedant Kumar   border-left: solid 1px #eee;
1924c01092aSVedant Kumar }
1934c01092aSVedant Kumar td:first-child {
1944c01092aSVedant Kumar   border-left: none;
1954c01092aSVedant Kumar }
1964c01092aSVedant Kumar td:last-child {
1974c01092aSVedant Kumar   border-right: none;
1984c01092aSVedant Kumar }
199c076c490SVedant Kumar )";
2004c01092aSVedant Kumar 
2014c01092aSVedant Kumar const char *EndHeader = "</head>";
2024c01092aSVedant Kumar 
2034c01092aSVedant Kumar const char *BeginCenteredDiv = "<div class='centered'>";
2044c01092aSVedant Kumar 
2054c01092aSVedant Kumar const char *EndCenteredDiv = "</div>";
2064c01092aSVedant Kumar 
2074c01092aSVedant Kumar const char *BeginSourceNameDiv = "<div class='source-name-title'>";
2084c01092aSVedant Kumar 
2094c01092aSVedant Kumar const char *EndSourceNameDiv = "</div>";
2104c01092aSVedant Kumar 
2114c01092aSVedant Kumar const char *BeginCodeTD = "<td class='code'>";
2124c01092aSVedant Kumar 
2134c01092aSVedant Kumar const char *EndCodeTD = "</td>";
2144c01092aSVedant Kumar 
2154c01092aSVedant Kumar const char *BeginPre = "<pre>";
2164c01092aSVedant Kumar 
2174c01092aSVedant Kumar const char *EndPre = "</pre>";
2184c01092aSVedant Kumar 
2194c01092aSVedant Kumar const char *BeginExpansionDiv = "<div class='expansion-view'>";
2204c01092aSVedant Kumar 
2214c01092aSVedant Kumar const char *EndExpansionDiv = "</div>";
2224c01092aSVedant Kumar 
2234c01092aSVedant Kumar const char *BeginTable = "<table>";
2244c01092aSVedant Kumar 
2254c01092aSVedant Kumar const char *EndTable = "</table>";
2264c01092aSVedant Kumar 
2277b9e9bb4SVedant Kumar const char *ProjectTitleTag = "h1";
22884dc971eSYing Yi 
2297b9e9bb4SVedant Kumar const char *ReportTitleTag = "h2";
23084dc971eSYing Yi 
2317b9e9bb4SVedant Kumar const char *CreatedTimeTag = "h4";
23284dc971eSYing Yi 
233c076c490SVedant Kumar std::string getPathToStyle(StringRef ViewPath) {
234c076c490SVedant Kumar   std::string PathToStyle = "";
235c076c490SVedant Kumar   std::string PathSep = sys::path::get_separator();
236c076c490SVedant Kumar   unsigned NumSeps = ViewPath.count(PathSep);
237c076c490SVedant Kumar   for (unsigned I = 0, E = NumSeps; I < E; ++I)
238c076c490SVedant Kumar     PathToStyle += ".." + PathSep;
239c076c490SVedant Kumar   return PathToStyle + "style.css";
240c076c490SVedant Kumar }
241c076c490SVedant Kumar 
2420ef31b79SYing Yi void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts,
2430ef31b79SYing Yi                  const std::string &PathToStyle = "") {
2444c01092aSVedant Kumar   OS << "<!doctype html>"
2454c01092aSVedant Kumar         "<html>"
246c076c490SVedant Kumar      << BeginHeader;
247c076c490SVedant Kumar 
248c076c490SVedant Kumar   // Link to a stylesheet if one is available. Otherwise, use the default style.
249c076c490SVedant Kumar   if (PathToStyle.empty())
250c076c490SVedant Kumar     OS << "<style>" << CSSForCoverage << "</style>";
251c076c490SVedant Kumar   else
2520ef31b79SYing Yi     OS << "<link rel='stylesheet' type='text/css' href='"
2530ef31b79SYing Yi        << escape(PathToStyle, Opts) << "'>";
254c076c490SVedant Kumar 
25584dc971eSYing Yi   OS << EndHeader << "<body>";
2564c01092aSVedant Kumar }
2574c01092aSVedant Kumar 
2584c01092aSVedant Kumar void emitEpilog(raw_ostream &OS) {
25984dc971eSYing Yi   OS << "</body>"
26084dc971eSYing Yi      << "</html>";
2614c01092aSVedant Kumar }
2624c01092aSVedant Kumar 
2634c01092aSVedant Kumar } // anonymous namespace
2644c01092aSVedant Kumar 
2654c01092aSVedant Kumar Expected<CoveragePrinter::OwnedStream>
2664c01092aSVedant Kumar CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) {
2674c01092aSVedant Kumar   auto OSOrErr = createOutputStream(Path, "html", InToplevel);
2684c01092aSVedant Kumar   if (!OSOrErr)
2694c01092aSVedant Kumar     return OSOrErr;
2704c01092aSVedant Kumar 
2714c01092aSVedant Kumar   OwnedStream OS = std::move(OSOrErr.get());
272c076c490SVedant Kumar 
273c076c490SVedant Kumar   if (!Opts.hasOutputDirectory()) {
2740ef31b79SYing Yi     emitPrelude(*OS.get(), Opts);
275c076c490SVedant Kumar   } else {
276c076c490SVedant Kumar     std::string ViewPath = getOutputPath(Path, "html", InToplevel);
2770ef31b79SYing Yi     emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath));
278c076c490SVedant Kumar   }
279c076c490SVedant Kumar 
2804c01092aSVedant Kumar   return std::move(OS);
2814c01092aSVedant Kumar }
2824c01092aSVedant Kumar 
2834c01092aSVedant Kumar void CoveragePrinterHTML::closeViewFile(OwnedStream OS) {
2844c01092aSVedant Kumar   emitEpilog(*OS.get());
2854c01092aSVedant Kumar }
2864c01092aSVedant Kumar 
287a59334daSVedant Kumar /// Emit column labels for the table in the index.
28850479f60SEli Friedman static void emitColumnLabelsForIndex(raw_ostream &OS,
28950479f60SEli Friedman                                      const CoverageViewOptions &Opts) {
290a59334daSVedant Kumar   SmallVector<std::string, 4> Columns;
2917b9e9bb4SVedant Kumar   Columns.emplace_back(tag("td", "Filename", "column-entry-left"));
29250479f60SEli Friedman   Columns.emplace_back(tag("td", "Function Coverage", "column-entry"));
29350479f60SEli Friedman   if (Opts.ShowInstantiationSummary)
29450479f60SEli Friedman     Columns.emplace_back(tag("td", "Instantiation Coverage", "column-entry"));
29550479f60SEli Friedman   Columns.emplace_back(tag("td", "Line Coverage", "column-entry"));
29650479f60SEli Friedman   if (Opts.ShowRegionSummary)
29750479f60SEli Friedman     Columns.emplace_back(tag("td", "Region Coverage", "column-entry"));
298a59334daSVedant Kumar   OS << tag("tr", join(Columns.begin(), Columns.end(), ""));
299a59334daSVedant Kumar }
300a59334daSVedant Kumar 
301c0c182ccSEli Friedman std::string
302c0c182ccSEli Friedman CoveragePrinterHTML::buildLinkToFile(StringRef SF,
303c0c182ccSEli Friedman                                      const FileCoverageSummary &FCS) const {
304c0c182ccSEli Friedman   SmallString<128> LinkTextStr(sys::path::relative_path(FCS.Name));
305c0c182ccSEli Friedman   sys::path::remove_dots(LinkTextStr, /*remove_dot_dots=*/true);
306c0c182ccSEli Friedman   sys::path::native(LinkTextStr);
307c0c182ccSEli Friedman   std::string LinkText = escape(LinkTextStr, Opts);
308c0c182ccSEli Friedman   std::string LinkTarget =
309c0c182ccSEli Friedman       escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts);
310c0c182ccSEli Friedman   return a(LinkTarget, LinkText);
311c0c182ccSEli Friedman }
312c0c182ccSEli Friedman 
313a59334daSVedant Kumar /// Render a file coverage summary (\p FCS) in a table row. If \p IsTotals is
314a59334daSVedant Kumar /// false, link the summary to \p SF.
315a59334daSVedant Kumar void CoveragePrinterHTML::emitFileSummary(raw_ostream &OS, StringRef SF,
316a59334daSVedant Kumar                                           const FileCoverageSummary &FCS,
317a59334daSVedant Kumar                                           bool IsTotals) const {
318224ef8d7SVedant Kumar   SmallVector<std::string, 8> Columns;
319a59334daSVedant Kumar 
320a59334daSVedant Kumar   // Format a coverage triple and add the result to the list of columns.
321a59334daSVedant Kumar   auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total,
322a59334daSVedant Kumar                                               float Pctg) {
323a59334daSVedant Kumar     std::string S;
324a59334daSVedant Kumar     {
325a59334daSVedant Kumar       raw_string_ostream RSO{S};
32635369c1eSAlex Lorenz       if (Total)
32735369c1eSAlex Lorenz         RSO << format("%*.2f", 7, Pctg) << "% ";
32835369c1eSAlex Lorenz       else
32935369c1eSAlex Lorenz         RSO << "- ";
33035369c1eSAlex Lorenz       RSO << '(' << Hit << '/' << Total << ')';
331a59334daSVedant Kumar     }
332a59334daSVedant Kumar     const char *CellClass = "column-entry-yellow";
33335369c1eSAlex Lorenz     if (Hit == Total)
334a59334daSVedant Kumar       CellClass = "column-entry-green";
33535369c1eSAlex Lorenz     else if (Pctg < 80.0)
33635369c1eSAlex Lorenz       CellClass = "column-entry-red";
3377b9e9bb4SVedant Kumar     Columns.emplace_back(tag("td", tag("pre", S), CellClass));
338a59334daSVedant Kumar   };
339a59334daSVedant Kumar 
340a59334daSVedant Kumar   // Simplify the display file path, and wrap it in a link if requested.
341a59334daSVedant Kumar   std::string Filename;
342224ef8d7SVedant Kumar   if (IsTotals) {
343224ef8d7SVedant Kumar     Filename = "TOTALS";
344224ef8d7SVedant Kumar   } else {
345c0c182ccSEli Friedman     Filename = buildLinkToFile(SF, FCS);
346a59334daSVedant Kumar   }
347a59334daSVedant Kumar 
3487b9e9bb4SVedant Kumar   Columns.emplace_back(tag("td", tag("pre", Filename)));
349c445e65dSVedant Kumar   AddCoverageTripleToColumn(FCS.FunctionCoverage.getExecuted(),
350c445e65dSVedant Kumar                             FCS.FunctionCoverage.getNumFunctions(),
351a59334daSVedant Kumar                             FCS.FunctionCoverage.getPercentCovered());
35250479f60SEli Friedman   if (Opts.ShowInstantiationSummary)
353c445e65dSVedant Kumar     AddCoverageTripleToColumn(FCS.InstantiationCoverage.getExecuted(),
354c445e65dSVedant Kumar                               FCS.InstantiationCoverage.getNumFunctions(),
355016111f7SVedant Kumar                               FCS.InstantiationCoverage.getPercentCovered());
356c445e65dSVedant Kumar   AddCoverageTripleToColumn(FCS.LineCoverage.getCovered(),
357c445e65dSVedant Kumar                             FCS.LineCoverage.getNumLines(),
358673ad727SVedant Kumar                             FCS.LineCoverage.getPercentCovered());
35950479f60SEli Friedman   if (Opts.ShowRegionSummary)
360c445e65dSVedant Kumar     AddCoverageTripleToColumn(FCS.RegionCoverage.getCovered(),
361c445e65dSVedant Kumar                               FCS.RegionCoverage.getNumRegions(),
362673ad727SVedant Kumar                               FCS.RegionCoverage.getPercentCovered());
363a59334daSVedant Kumar 
364a59334daSVedant Kumar   OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row");
365a59334daSVedant Kumar }
366a59334daSVedant Kumar 
367a59334daSVedant Kumar Error CoveragePrinterHTML::createIndexFile(
368bc647985SVedant Kumar     ArrayRef<std::string> SourceFiles,
369*fa8ef35eSSean Eveson     const coverage::CoverageMapping &Coverage, const CoverageFilter &Filters) {
370a59334daSVedant Kumar   // Emit the default stylesheet.
371a59334daSVedant Kumar   auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true);
372a59334daSVedant Kumar   if (Error E = CSSOrErr.takeError())
373a59334daSVedant Kumar     return E;
374a59334daSVedant Kumar 
375a59334daSVedant Kumar   OwnedStream CSS = std::move(CSSOrErr.get());
376a59334daSVedant Kumar   CSS->operator<<(CSSForCoverage);
377a59334daSVedant Kumar 
378a59334daSVedant Kumar   // Emit a file index along with some coverage statistics.
3794c01092aSVedant Kumar   auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true);
3804c01092aSVedant Kumar   if (Error E = OSOrErr.takeError())
3814c01092aSVedant Kumar     return E;
3824c01092aSVedant Kumar   auto OS = std::move(OSOrErr.get());
3834c01092aSVedant Kumar   raw_ostream &OSRef = *OS.get();
3844c01092aSVedant Kumar 
385127d0502SVedant Kumar   assert(Opts.hasOutputDirectory() && "No output directory for index file");
3860ef31b79SYing Yi   emitPrelude(OSRef, Opts, getPathToStyle(""));
387a59334daSVedant Kumar 
388a59334daSVedant Kumar   // Emit some basic information about the coverage report.
38984dc971eSYing Yi   if (Opts.hasProjectTitle())
3907b9e9bb4SVedant Kumar     OSRef << tag(ProjectTitleTag, escape(Opts.ProjectTitle, Opts));
3917b9e9bb4SVedant Kumar   OSRef << tag(ReportTitleTag, "Coverage Report");
39284dc971eSYing Yi   if (Opts.hasCreatedTime())
3937b9e9bb4SVedant Kumar     OSRef << tag(CreatedTimeTag, escape(Opts.CreatedTimeStr, Opts));
394a59334daSVedant Kumar 
39591743f28SVedant Kumar   // Emit a link to some documentation.
39691743f28SVedant Kumar   OSRef << tag("p", "Click " +
39791743f28SVedant Kumar                         a("http://clang.llvm.org/docs/"
39891743f28SVedant Kumar                           "SourceBasedCodeCoverage.html#interpreting-reports",
39991743f28SVedant Kumar                           "here") +
40091743f28SVedant Kumar                         " for information about interpreting this report.");
40191743f28SVedant Kumar 
402a59334daSVedant Kumar   // Emit a table containing links to reports for each file in the covmapping.
403c0c182ccSEli Friedman   // Exclude files which don't contain any regions.
40484dc971eSYing Yi   OSRef << BeginCenteredDiv << BeginTable;
40550479f60SEli Friedman   emitColumnLabelsForIndex(OSRef, Opts);
406a59334daSVedant Kumar   FileCoverageSummary Totals("TOTALS");
407*fa8ef35eSSean Eveson   auto FileReports = CoverageReport::prepareFileReports(
408*fa8ef35eSSean Eveson       Coverage, Totals, SourceFiles, Opts, Filters);
409c0c182ccSEli Friedman   bool EmptyFiles = false;
410c0c182ccSEli Friedman   for (unsigned I = 0, E = FileReports.size(); I < E; ++I) {
411c445e65dSVedant Kumar     if (FileReports[I].FunctionCoverage.getNumFunctions())
412a59334daSVedant Kumar       emitFileSummary(OSRef, SourceFiles[I], FileReports[I]);
413c0c182ccSEli Friedman     else
414c0c182ccSEli Friedman       EmptyFiles = true;
415c0c182ccSEli Friedman   }
416a59334daSVedant Kumar   emitFileSummary(OSRef, "Totals", Totals, /*IsTotals=*/true);
417c0c182ccSEli Friedman   OSRef << EndTable << EndCenteredDiv;
418c0c182ccSEli Friedman 
419c0c182ccSEli Friedman   // Emit links to files which don't contain any functions. These are normally
420c0c182ccSEli Friedman   // not very useful, but could be relevant for code which abuses the
421c0c182ccSEli Friedman   // preprocessor.
422c0c182ccSEli Friedman   if (EmptyFiles) {
423c0c182ccSEli Friedman     OSRef << tag("p", "Files which contain no functions. (These "
424c0c182ccSEli Friedman                       "files contain code pulled into other files "
425c0c182ccSEli Friedman                       "by the preprocessor.)\n");
426c0c182ccSEli Friedman     OSRef << BeginCenteredDiv << BeginTable;
427c0c182ccSEli Friedman     for (unsigned I = 0, E = FileReports.size(); I < E; ++I)
428c445e65dSVedant Kumar       if (!FileReports[I].FunctionCoverage.getNumFunctions()) {
429c0c182ccSEli Friedman         std::string Link = buildLinkToFile(SourceFiles[I], FileReports[I]);
430c0c182ccSEli Friedman         OSRef << tag("tr", tag("td", tag("pre", Link)), "light-row") << '\n';
431c0c182ccSEli Friedman       }
432c0c182ccSEli Friedman     OSRef << EndTable << EndCenteredDiv;
433c0c182ccSEli Friedman   }
434c0c182ccSEli Friedman 
435c0c182ccSEli Friedman   OSRef << tag("h5", escape(Opts.getLLVMVersionString(), Opts));
4364c01092aSVedant Kumar   emitEpilog(OSRef);
4374c01092aSVedant Kumar 
4384c01092aSVedant Kumar   return Error::success();
4394c01092aSVedant Kumar }
4404c01092aSVedant Kumar 
4414c01092aSVedant Kumar void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) {
4427b9e9bb4SVedant Kumar   OS << BeginCenteredDiv << BeginTable;
4434c01092aSVedant Kumar }
4444c01092aSVedant Kumar 
4454c01092aSVedant Kumar void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) {
44684a280adSVedant Kumar   OS << EndTable << EndCenteredDiv;
4474c01092aSVedant Kumar }
4484c01092aSVedant Kumar 
449b1c174aaSVedant Kumar void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) {
4505c61c703SVedant Kumar   OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions()))
4515c61c703SVedant Kumar      << EndSourceNameDiv;
4524c01092aSVedant Kumar }
4534c01092aSVedant Kumar 
4544c01092aSVedant Kumar void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) {
4554c01092aSVedant Kumar   OS << "<tr>";
4564c01092aSVedant Kumar }
4574c01092aSVedant Kumar 
4584c01092aSVedant Kumar void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) {
4594c01092aSVedant Kumar   // If this view has sub-views, renderLine() cannot close the view's cell.
4604c01092aSVedant Kumar   // Take care of it here, after all sub-views have been rendered.
4614c01092aSVedant Kumar   if (hasSubViews())
4624c01092aSVedant Kumar     OS << EndCodeTD;
4634c01092aSVedant Kumar   OS << "</tr>";
4644c01092aSVedant Kumar }
4654c01092aSVedant Kumar 
4664c01092aSVedant Kumar void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) {
4674c01092aSVedant Kumar   // The table-based output makes view dividers unnecessary.
4684c01092aSVedant Kumar }
4694c01092aSVedant Kumar 
4704c01092aSVedant Kumar void SourceCoverageViewHTML::renderLine(
4714c01092aSVedant Kumar     raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
4724c01092aSVedant Kumar     CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned) {
4734c01092aSVedant Kumar   StringRef Line = L.Line;
474fc07e8b4SVedant Kumar   unsigned LineNo = L.LineNo;
4754c01092aSVedant Kumar 
4764c01092aSVedant Kumar   // Steps for handling text-escaping, highlighting, and tooltip creation:
4774c01092aSVedant Kumar   //
4784c01092aSVedant Kumar   // 1. Split the line into N+1 snippets, where N = |Segments|. The first
4794c01092aSVedant Kumar   //    snippet starts from Col=1 and ends at the start of the first segment.
4804c01092aSVedant Kumar   //    The last snippet starts at the last mapped column in the line and ends
4814c01092aSVedant Kumar   //    at the end of the line. Both are required but may be empty.
4824c01092aSVedant Kumar 
4834c01092aSVedant Kumar   SmallVector<std::string, 8> Snippets;
4844c01092aSVedant Kumar 
4854c01092aSVedant Kumar   unsigned LCol = 1;
4864c01092aSVedant Kumar   auto Snip = [&](unsigned Start, unsigned Len) {
4874c01092aSVedant Kumar     Snippets.push_back(Line.substr(Start, Len));
4884c01092aSVedant Kumar     LCol += Len;
4894c01092aSVedant Kumar   };
4904c01092aSVedant Kumar 
4914c01092aSVedant Kumar   Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1));
4924c01092aSVedant Kumar 
493c236e5a0SVedant Kumar   for (unsigned I = 1, E = Segments.size(); I < E; ++I)
4944c01092aSVedant Kumar     Snip(LCol - 1, Segments[I]->Col - LCol);
4954c01092aSVedant Kumar 
4964c01092aSVedant Kumar   // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1.
4974c01092aSVedant Kumar   Snip(LCol - 1, Line.size() + 1 - LCol);
4984c01092aSVedant Kumar 
4994c01092aSVedant Kumar   // 2. Escape all of the snippets.
5004c01092aSVedant Kumar 
5014c01092aSVedant Kumar   for (unsigned I = 0, E = Snippets.size(); I < E; ++I)
5020ef31b79SYing Yi     Snippets[I] = escape(Snippets[I], getOptions());
5034c01092aSVedant Kumar 
504fc07e8b4SVedant Kumar   // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment
505fc07e8b4SVedant Kumar   //    1 to set the highlight for snippet 2, segment 2 to set the highlight for
506fc07e8b4SVedant Kumar   //    snippet 3, and so on.
5074c01092aSVedant Kumar 
5084c01092aSVedant Kumar   Optional<std::string> Color;
5090b33f2c0SVedant Kumar   SmallVector<std::pair<unsigned, unsigned>, 2> HighlightedRanges;
510fc07e8b4SVedant Kumar   auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) {
5110b33f2c0SVedant Kumar     if (getOptions().Debug)
512fc07e8b4SVedant Kumar       HighlightedRanges.emplace_back(LC, RC);
5134c01092aSVedant Kumar     return tag("span", Snippet, Color.getValue());
5144c01092aSVedant Kumar   };
5154c01092aSVedant Kumar 
5164c01092aSVedant Kumar   auto CheckIfUncovered = [](const coverage::CoverageSegment *S) {
5170b33f2c0SVedant Kumar     return S && S->HasCount && S->Count == 0;
5184c01092aSVedant Kumar   };
5194c01092aSVedant Kumar 
5200b33f2c0SVedant Kumar   if (CheckIfUncovered(WrappedSegment)) {
5214c01092aSVedant Kumar     Color = "red";
5220b33f2c0SVedant Kumar     if (!Snippets[0].empty())
5230b33f2c0SVedant Kumar       Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size());
5244c01092aSVedant Kumar   }
5254c01092aSVedant Kumar 
526fc07e8b4SVedant Kumar   for (unsigned I = 0, E = Segments.size(); I < E; ++I) {
5274c01092aSVedant Kumar     const auto *CurSeg = Segments[I];
5284c01092aSVedant Kumar     if (CurSeg->Col == ExpansionCol)
5294c01092aSVedant Kumar       Color = "cyan";
530ad8f637bSVedant Kumar     else if (!CurSeg->IsGapRegion && CheckIfUncovered(CurSeg))
5314c01092aSVedant Kumar       Color = "red";
5324c01092aSVedant Kumar     else
5334c01092aSVedant Kumar       Color = None;
5344c01092aSVedant Kumar 
5354c01092aSVedant Kumar     if (Color.hasValue())
536fc07e8b4SVedant Kumar       Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col,
537fc07e8b4SVedant Kumar                                   CurSeg->Col + Snippets[I + 1].size());
538fc07e8b4SVedant Kumar   }
539fc07e8b4SVedant Kumar 
540fc07e8b4SVedant Kumar   if (Color.hasValue() && Segments.empty())
5410b33f2c0SVedant Kumar     Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size());
542fc07e8b4SVedant Kumar 
543fc07e8b4SVedant Kumar   if (getOptions().Debug) {
544fc07e8b4SVedant Kumar     for (const auto &Range : HighlightedRanges) {
5450b33f2c0SVedant Kumar       errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> ";
546fc07e8b4SVedant Kumar       if (Range.second == 0)
547fc07e8b4SVedant Kumar         errs() << "?";
548fc07e8b4SVedant Kumar       else
5490b33f2c0SVedant Kumar         errs() << Range.second;
550fc07e8b4SVedant Kumar       errs() << "\n";
551fc07e8b4SVedant Kumar     }
5524c01092aSVedant Kumar   }
5534c01092aSVedant Kumar 
5544c01092aSVedant Kumar   // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate
5554c01092aSVedant Kumar   //    sub-line region count tooltips if needed.
5564c01092aSVedant Kumar 
557933b37f9SVedant Kumar   if (shouldRenderRegionMarkers(Segments)) {
558933b37f9SVedant Kumar     // Just consider the segments which start *and* end on this line.
559933b37f9SVedant Kumar     for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
5604c01092aSVedant Kumar       const auto *CurSeg = Segments[I];
561933b37f9SVedant Kumar       if (!CurSeg->IsRegionEntry)
5624c01092aSVedant Kumar         continue;
5634c01092aSVedant Kumar 
5644c01092aSVedant Kumar       Snippets[I + 1] =
5654c01092aSVedant Kumar           tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count),
5664c01092aSVedant Kumar                                            "tooltip-content"),
5674c01092aSVedant Kumar               "tooltip");
568933b37f9SVedant Kumar 
569933b37f9SVedant Kumar       if (getOptions().Debug)
570933b37f9SVedant Kumar         errs() << "Marker at " << CurSeg->Line << ":" << CurSeg->Col << " = "
571933b37f9SVedant Kumar                << formatCount(CurSeg->Count) << "\n";
5724c01092aSVedant Kumar     }
5734c01092aSVedant Kumar   }
5744c01092aSVedant Kumar 
5754c01092aSVedant Kumar   OS << BeginCodeTD;
5764c01092aSVedant Kumar   OS << BeginPre;
5774c01092aSVedant Kumar   for (const auto &Snippet : Snippets)
5784c01092aSVedant Kumar     OS << Snippet;
5794c01092aSVedant Kumar   OS << EndPre;
5804c01092aSVedant Kumar 
5814c01092aSVedant Kumar   // If there are no sub-views left to attach to this cell, end the cell.
5824c01092aSVedant Kumar   // Otherwise, end it after the sub-views are rendered (renderLineSuffix()).
5834c01092aSVedant Kumar   if (!hasSubViews())
5844c01092aSVedant Kumar     OS << EndCodeTD;
5854c01092aSVedant Kumar }
5864c01092aSVedant Kumar 
5874c01092aSVedant Kumar void SourceCoverageViewHTML::renderLineCoverageColumn(
5884c01092aSVedant Kumar     raw_ostream &OS, const LineCoverageStats &Line) {
5894c01092aSVedant Kumar   std::string Count = "";
5904c01092aSVedant Kumar   if (Line.isMapped())
5914c01092aSVedant Kumar     Count = tag("pre", formatCount(Line.ExecutionCount));
5924c01092aSVedant Kumar   std::string CoverageClass =
5934c01092aSVedant Kumar       (Line.ExecutionCount > 0) ? "covered-line" : "uncovered-line";
5944c01092aSVedant Kumar   OS << tag("td", Count, CoverageClass);
5954c01092aSVedant Kumar }
5964c01092aSVedant Kumar 
5974c01092aSVedant Kumar void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS,
5984c01092aSVedant Kumar                                                     unsigned LineNo) {
5992e089362SVedant Kumar   std::string LineNoStr = utostr(uint64_t(LineNo));
6005a0e92b0SVedant Kumar   std::string TargetName = "L" + LineNoStr;
6015a0e92b0SVedant Kumar   OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName),
6022e089362SVedant Kumar             "line-number");
6034c01092aSVedant Kumar }
6044c01092aSVedant Kumar 
6054c01092aSVedant Kumar void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &,
6064c01092aSVedant Kumar                                                  CoverageSegmentArray,
6074c01092aSVedant Kumar                                                  unsigned) {
6084c01092aSVedant Kumar   // Region markers are rendered in-line using tooltips.
6094c01092aSVedant Kumar }
6104c01092aSVedant Kumar 
6114c01092aSVedant Kumar void SourceCoverageViewHTML::renderExpansionSite(
6124c01092aSVedant Kumar     raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment,
6134c01092aSVedant Kumar     CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned ViewDepth) {
6144c01092aSVedant Kumar   // Render the line containing the expansion site. No extra formatting needed.
6154c01092aSVedant Kumar   renderLine(OS, L, WrappedSegment, Segments, ExpansionCol, ViewDepth);
6164c01092aSVedant Kumar }
6174c01092aSVedant Kumar 
6184c01092aSVedant Kumar void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS,
6194c01092aSVedant Kumar                                                  ExpansionView &ESV,
6204c01092aSVedant Kumar                                                  unsigned ViewDepth) {
6214c01092aSVedant Kumar   OS << BeginExpansionDiv;
6224c01092aSVedant Kumar   ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false,
623*fa8ef35eSSean Eveson                   /*ShowTitle=*/false, ViewDepth + 1);
6244c01092aSVedant Kumar   OS << EndExpansionDiv;
6254c01092aSVedant Kumar }
6264c01092aSVedant Kumar 
6274c01092aSVedant Kumar void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS,
6284c01092aSVedant Kumar                                                      InstantiationView &ISV,
6294c01092aSVedant Kumar                                                      unsigned ViewDepth) {
6304c01092aSVedant Kumar   OS << BeginExpansionDiv;
631a8c396d9SVedant Kumar   if (!ISV.View)
632a8c396d9SVedant Kumar     OS << BeginSourceNameDiv
633a8c396d9SVedant Kumar        << tag("pre",
634a8c396d9SVedant Kumar               escape("Unexecuted instantiation: " + ISV.FunctionName.str(),
635a8c396d9SVedant Kumar                      getOptions()))
636a8c396d9SVedant Kumar        << EndSourceNameDiv;
637a8c396d9SVedant Kumar   else
638a8c396d9SVedant Kumar     ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true,
639*fa8ef35eSSean Eveson                     /*ShowTitle=*/false, ViewDepth);
6404c01092aSVedant Kumar   OS << EndExpansionDiv;
6414c01092aSVedant Kumar }
64284dc971eSYing Yi 
643b2edd11fSVedant Kumar void SourceCoverageViewHTML::renderTitle(raw_ostream &OS, StringRef Title) {
64484dc971eSYing Yi   if (getOptions().hasProjectTitle())
6457b9e9bb4SVedant Kumar     OS << tag(ProjectTitleTag, escape(getOptions().ProjectTitle, getOptions()));
646b2edd11fSVedant Kumar   OS << tag(ReportTitleTag, escape(Title, getOptions()));
64784dc971eSYing Yi   if (getOptions().hasCreatedTime())
6487b9e9bb4SVedant Kumar     OS << tag(CreatedTimeTag,
6497b9e9bb4SVedant Kumar               escape(getOptions().CreatedTimeStr, getOptions()));
65084dc971eSYing Yi }
65184dc971eSYing Yi 
65284dc971eSYing Yi void SourceCoverageViewHTML::renderTableHeader(raw_ostream &OS,
653b1c174aaSVedant Kumar                                                unsigned FirstUncoveredLineNo,
65484dc971eSYing Yi                                                unsigned ViewDepth) {
655b1c174aaSVedant Kumar   std::string SourceLabel;
656408866caSVedant Kumar   if (FirstUncoveredLineNo == 0) {
657b1c174aaSVedant Kumar     SourceLabel = tag("td", tag("pre", "Source"));
658b1c174aaSVedant Kumar   } else {
659b1c174aaSVedant Kumar     std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo));
660b1c174aaSVedant Kumar     SourceLabel =
661b1c174aaSVedant Kumar         tag("td", tag("pre", "Source (" +
662b1c174aaSVedant Kumar                                  a(LinkTarget, "jump to first uncovered line") +
663b1c174aaSVedant Kumar                                  ")"));
664b1c174aaSVedant Kumar   }
665b1c174aaSVedant Kumar 
66684dc971eSYing Yi   renderLinePrefix(OS, ViewDepth);
66798ba34e5SVedant Kumar   OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count"))
668b1c174aaSVedant Kumar      << SourceLabel;
66984dc971eSYing Yi   renderLineSuffix(OS, ViewDepth);
67084dc971eSYing Yi }
671