1 //===- SourceCoverageViewHTML.cpp - A html code coverage view -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file This file implements the html coverage renderer. 11 /// 12 //===----------------------------------------------------------------------===// 13 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" 22 23 using namespace llvm; 24 25 namespace { 26 27 // Return a string with the special characters in \p Str escaped. 28 std::string escape(StringRef Str, const CoverageViewOptions &Opts) { 29 std::string Result; 30 unsigned ColNum = 0; // Record the column number. 31 for (char C : Str) { 32 ++ColNum; 33 if (C == '&') 34 Result += "&"; 35 else if (C == '<') 36 Result += "<"; 37 else if (C == '>') 38 Result += ">"; 39 else if (C == '\"') 40 Result += """; 41 else if (C == '\n' || C == '\r') { 42 Result += C; 43 ColNum = 0; 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) 48 Result += " "; 49 ColNum += NumSpaces; 50 } else 51 Result += C; 52 } 53 return Result; 54 } 55 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; 60 if (ClassName != "") 61 Tag += " class='" + ClassName + "'"; 62 return Tag + ">" + Str + "</" + Name + ">"; 63 } 64 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>"; 70 } 71 72 const char *BeginHeader = 73 "<head>" 74 "<meta name='viewport' content='width=device-width,initial-scale=1'>" 75 "<meta charset='UTF-8'>"; 76 77 const char *CSSForCoverage = 78 R"(.red { 79 background-color: #ffd0d0; 80 } 81 .cyan { 82 background-color: cyan; 83 } 84 body { 85 font-family: -apple-system, sans-serif; 86 } 87 pre { 88 margin-top: 0px !important; 89 margin-bottom: 0px !important; 90 } 91 .source-name-title { 92 padding: 5px 10px; 93 border-bottom: 1px solid #dbdbdb; 94 background-color: #eee; 95 line-height: 35px; 96 } 97 .centered { 98 display: table; 99 margin-left: left; 100 margin-right: auto; 101 border: 1px solid #dbdbdb; 102 border-radius: 3px; 103 } 104 .expansion-view { 105 background-color: rgba(0, 0, 0, 0); 106 margin-left: 0px; 107 margin-top: 5px; 108 margin-right: 5px; 109 margin-bottom: 5px; 110 border: 1px solid #dbdbdb; 111 border-radius: 3px; 112 } 113 table { 114 border-collapse: collapse; 115 } 116 .light-row { 117 background: #ffffff; 118 border: 1px solid #dbdbdb; 119 } 120 .column-entry { 121 text-align: right; 122 } 123 .column-entry-left { 124 text-align: left; 125 } 126 .column-entry-yellow { 127 text-align: right; 128 background-color: #ffffd0; 129 } 130 .column-entry-red { 131 text-align: right; 132 background-color: #ffd0d0; 133 } 134 .column-entry-green { 135 text-align: right; 136 background-color: #d0ffd0; 137 } 138 .line-number { 139 text-align: right; 140 color: #aaa; 141 } 142 .covered-line { 143 text-align: right; 144 color: #0080ff; 145 } 146 .uncovered-line { 147 text-align: right; 148 color: #ff3300; 149 } 150 .tooltip { 151 position: relative; 152 display: inline; 153 background-color: #b3e6ff; 154 text-decoration: none; 155 } 156 .tooltip span.tooltip-content { 157 position: absolute; 158 width: 100px; 159 margin-left: -50px; 160 color: #FFFFFF; 161 background: #000000; 162 height: 30px; 163 line-height: 30px; 164 text-align: center; 165 visibility: hidden; 166 border-radius: 6px; 167 } 168 .tooltip span.tooltip-content:after { 169 content: ''; 170 position: absolute; 171 top: 100%; 172 left: 50%; 173 margin-left: -8px; 174 width: 0; height: 0; 175 border-top: 8px solid #000000; 176 border-right: 8px solid transparent; 177 border-left: 8px solid transparent; 178 } 179 :hover.tooltip span.tooltip-content { 180 visibility: visible; 181 opacity: 0.8; 182 bottom: 30px; 183 left: 50%; 184 z-index: 999; 185 } 186 th, td { 187 vertical-align: top; 188 padding: 2px 5px; 189 border-collapse: collapse; 190 border-right: solid 1px #eee; 191 border-left: solid 1px #eee; 192 } 193 td:first-child { 194 border-left: none; 195 } 196 td:last-child { 197 border-right: none; 198 } 199 )"; 200 201 const char *EndHeader = "</head>"; 202 203 const char *BeginCenteredDiv = "<div class='centered'>"; 204 205 const char *EndCenteredDiv = "</div>"; 206 207 const char *BeginSourceNameDiv = "<div class='source-name-title'>"; 208 209 const char *EndSourceNameDiv = "</div>"; 210 211 const char *BeginCodeTD = "<td class='code'>"; 212 213 const char *EndCodeTD = "</td>"; 214 215 const char *BeginPre = "<pre>"; 216 217 const char *EndPre = "</pre>"; 218 219 const char *BeginExpansionDiv = "<div class='expansion-view'>"; 220 221 const char *EndExpansionDiv = "</div>"; 222 223 const char *BeginTable = "<table>"; 224 225 const char *EndTable = "</table>"; 226 227 const char *ProjectTitleTag = "h1"; 228 229 const char *ReportTitleTag = "h2"; 230 231 const char *CreatedTimeTag = "h4"; 232 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"; 240 } 241 242 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts, 243 const std::string &PathToStyle = "") { 244 OS << "<!doctype html>" 245 "<html>" 246 << BeginHeader; 247 248 // Link to a stylesheet if one is available. Otherwise, use the default style. 249 if (PathToStyle.empty()) 250 OS << "<style>" << CSSForCoverage << "</style>"; 251 else 252 OS << "<link rel='stylesheet' type='text/css' href='" 253 << escape(PathToStyle, Opts) << "'>"; 254 255 OS << EndHeader << "<body>"; 256 } 257 258 void emitEpilog(raw_ostream &OS) { 259 OS << "</body>" 260 << "</html>"; 261 } 262 263 } // anonymous namespace 264 265 Expected<CoveragePrinter::OwnedStream> 266 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) { 267 auto OSOrErr = createOutputStream(Path, "html", InToplevel); 268 if (!OSOrErr) 269 return OSOrErr; 270 271 OwnedStream OS = std::move(OSOrErr.get()); 272 273 if (!Opts.hasOutputDirectory()) { 274 emitPrelude(*OS.get(), Opts); 275 } else { 276 std::string ViewPath = getOutputPath(Path, "html", InToplevel); 277 emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath)); 278 } 279 280 return std::move(OS); 281 } 282 283 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) { 284 emitEpilog(*OS.get()); 285 } 286 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(), "")); 295 } 296 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; 303 304 // Format a coverage triple and add the result to the list of columns. 305 auto AddCoverageTripleToColumn = [&Columns](unsigned Hit, unsigned Total, 306 float Pctg) { 307 std::string S; 308 { 309 raw_string_ostream RSO{S}; 310 if (Total) 311 RSO << format("%*.2f", 7, Pctg) << "% "; 312 else 313 RSO << "- "; 314 RSO << '(' << Hit << '/' << Total << ')'; 315 } 316 const char *CellClass = "column-entry-yellow"; 317 if (Hit == Total) 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)); 322 }; 323 324 // Simplify the display file path, and wrap it in a link if requested. 325 std::string Filename; 326 if (IsTotals) { 327 Filename = "TOTALS"; 328 } else { 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); 336 } 337 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()); 350 351 OS << tag("tr", join(Columns.begin(), Columns.end(), ""), "light-row"); 352 } 353 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()) 360 return E; 361 362 OwnedStream CSS = std::move(CSSOrErr.get()); 363 CSS->operator<<(CSSForCoverage); 364 365 // Emit a file index along with some coverage statistics. 366 auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true); 367 if (Error E = OSOrErr.takeError()) 368 return E; 369 auto OS = std::move(OSOrErr.get()); 370 raw_ostream &OSRef = *OS.get(); 371 372 assert(Opts.hasOutputDirectory() && "No output directory for index file"); 373 emitPrelude(OSRef, Opts, getPathToStyle("")); 374 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)); 381 382 // Emit a link to some documentation. 383 OSRef << tag("p", "Click " + 384 a("http://clang.llvm.org/docs/" 385 "SourceBasedCodeCoverage.html#interpreting-reports", 386 "here") + 387 " for information about interpreting this report."); 388 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"); 393 auto FileReports = 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)); 400 emitEpilog(OSRef); 401 402 return Error::success(); 403 } 404 405 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) { 406 OS << BeginCenteredDiv << BeginTable; 407 } 408 409 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) { 410 OS << EndTable << EndCenteredDiv; 411 } 412 413 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS, bool WholeFile) { 414 OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions())) 415 << EndSourceNameDiv; 416 } 417 418 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) { 419 OS << "<tr>"; 420 } 421 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. 425 if (hasSubViews()) 426 OS << EndCodeTD; 427 OS << "</tr>"; 428 } 429 430 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) { 431 // The table-based output makes view dividers unnecessary. 432 } 433 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; 439 440 // Steps for handling text-escaping, highlighting, and tooltip creation: 441 // 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. 446 447 SmallVector<std::string, 8> Snippets; 448 449 unsigned LCol = 1; 450 auto Snip = [&](unsigned Start, unsigned Len) { 451 Snippets.push_back(Line.substr(Start, Len)); 452 LCol += Len; 453 }; 454 455 Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1)); 456 457 for (unsigned I = 1, E = Segments.size(); I < E; ++I) 458 Snip(LCol - 1, Segments[I]->Col - LCol); 459 460 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1. 461 Snip(LCol - 1, Line.size() + 1 - LCol); 462 463 // 2. Escape all of the snippets. 464 465 for (unsigned I = 0, E = Snippets.size(); I < E; ++I) 466 Snippets[I] = escape(Snippets[I], getOptions()); 467 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. 471 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()); 478 }; 479 480 auto CheckIfUncovered = [](const coverage::CoverageSegment *S) { 481 return S && S->HasCount && S->Count == 0; 482 }; 483 484 if (CheckIfUncovered(WrappedSegment)) { 485 Color = "red"; 486 if (!Snippets[0].empty()) 487 Snippets[0] = Highlight(Snippets[0], 1, 1 + Snippets[0].size()); 488 } 489 490 for (unsigned I = 0, E = Segments.size(); I < E; ++I) { 491 const auto *CurSeg = Segments[I]; 492 if (CurSeg->Col == ExpansionCol) 493 Color = "cyan"; 494 else if (CheckIfUncovered(CurSeg)) 495 Color = "red"; 496 else 497 Color = None; 498 499 if (Color.hasValue()) 500 Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col, 501 CurSeg->Col + Snippets[I + 1].size()); 502 } 503 504 if (Color.hasValue() && Segments.empty()) 505 Snippets.back() = Highlight(Snippets.back(), 1, 1 + Snippets.back().size()); 506 507 if (getOptions().Debug) { 508 for (const auto &Range : HighlightedRanges) { 509 errs() << "Highlighted line " << LineNo << ", " << Range.first << " -> "; 510 if (Range.second == 0) 511 errs() << "?"; 512 else 513 errs() << Range.second; 514 errs() << "\n"; 515 } 516 } 517 518 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate 519 // sub-line region count tooltips if needed. 520 521 bool HasMultipleRegions = [&] { 522 unsigned RegionCount = 0; 523 for (const auto *S : Segments) 524 if (S->HasCount && S->IsRegionEntry) 525 if (++RegionCount > 1) 526 return true; 527 return false; 528 }(); 529 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) 534 continue; 535 536 Snippets[I + 1] = 537 tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count), 538 "tooltip-content"), 539 "tooltip"); 540 } 541 } 542 543 OS << BeginCodeTD; 544 OS << BeginPre; 545 for (const auto &Snippet : Snippets) 546 OS << Snippet; 547 OS << EndPre; 548 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()). 551 if (!hasSubViews()) 552 OS << EndCodeTD; 553 } 554 555 void SourceCoverageViewHTML::renderLineCoverageColumn( 556 raw_ostream &OS, const LineCoverageStats &Line) { 557 std::string Count = ""; 558 if (Line.isMapped()) 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); 563 } 564 565 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS, 566 unsigned LineNo) { 567 std::string LineNoStr = utostr(uint64_t(LineNo)); 568 std::string TargetName = "L" + LineNoStr; 569 OS << tag("td", a("#" + TargetName, tag("pre", LineNoStr), TargetName), 570 "line-number"); 571 } 572 573 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &, 574 CoverageSegmentArray, 575 unsigned) { 576 // Region markers are rendered in-line using tooltips. 577 } 578 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); 584 } 585 586 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS, 587 ExpansionView &ESV, 588 unsigned ViewDepth) { 589 OS << BeginExpansionDiv; 590 ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false, 591 ViewDepth + 1); 592 OS << EndExpansionDiv; 593 } 594 595 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS, 596 InstantiationView &ISV, 597 unsigned ViewDepth) { 598 OS << BeginExpansionDiv; 599 if (!ISV.View) 600 OS << BeginSourceNameDiv 601 << tag("pre", 602 escape("Unexecuted instantiation: " + ISV.FunctionName.str(), 603 getOptions())) 604 << EndSourceNameDiv; 605 else 606 ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true, 607 ViewDepth); 608 OS << EndExpansionDiv; 609 } 610 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())); 618 } 619 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")); 626 } else { 627 std::string LinkTarget = "#L" + utostr(uint64_t(FirstUncoveredLineNo)); 628 SourceLabel = 629 tag("td", tag("pre", "Source (" + 630 a(LinkTarget, "jump to first uncovered line") + 631 ")")); 632 } 633 634 renderLinePrefix(OS, ViewDepth); 635 OS << tag("td", tag("pre", "Line")) << tag("td", tag("pre", "Count")) 636 << SourceLabel; 637 renderLineSuffix(OS, ViewDepth); 638 } 639