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 "SourceCoverageViewHTML.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Support/Path.h" 19 20 using namespace llvm; 21 22 namespace { 23 24 // Return a string with the special characters in \p Str escaped. 25 std::string escape(StringRef Str, const CoverageViewOptions &Opts) { 26 std::string Result; 27 unsigned ColNum = 0; // Record the column number. 28 for (char C : Str) { 29 ++ColNum; 30 if (C == '&') 31 Result += "&"; 32 else if (C == '<') 33 Result += "<"; 34 else if (C == '>') 35 Result += ">"; 36 else if (C == '\"') 37 Result += """; 38 else if (C == '\n' || C == '\r') { 39 Result += C; 40 ColNum = 0; 41 } else if (C == '\t') { 42 // Replace '\t' with TabSize spaces. 43 unsigned NumSpaces = Opts.TabSize - (--ColNum % Opts.TabSize); 44 for (unsigned I = 0; I < NumSpaces; ++I) 45 Result += " "; 46 ColNum += NumSpaces; 47 } else 48 Result += C; 49 } 50 return Result; 51 } 52 53 // Create a \p Name tag around \p Str, and optionally set its \p ClassName. 54 std::string tag(const std::string &Name, const std::string &Str, 55 const std::string &ClassName = "") { 56 std::string Tag = "<" + Name; 57 if (ClassName != "") 58 Tag += " class='" + ClassName + "'"; 59 return Tag + ">" + Str + "</" + Name + ">"; 60 } 61 62 // Create an anchor to \p Link with the label \p Str. 63 std::string a(const std::string &Link, const std::string &Str, 64 const std::string &TargetType = "href") { 65 return "<a " + TargetType + "='" + Link + "'>" + Str + "</a>"; 66 } 67 68 const char *BeginHeader = 69 "<head>" 70 "<meta name='viewport' content='width=device-width,initial-scale=1'>" 71 "<meta charset='UTF-8'>"; 72 73 const char *CSSForCoverage = 74 R"(.red { 75 background-color: #FFD0D0; 76 } 77 .cyan { 78 background-color: cyan; 79 } 80 body { 81 font-family: -apple-system, sans-serif; 82 } 83 pre { 84 margin-top: 0px !important; 85 margin-bottom: 0px !important; 86 } 87 .source-name-title { 88 padding: 5px 10px; 89 border-bottom: 1px solid #dbdbdb; 90 background-color: #eee; 91 } 92 .centered { 93 display: table; 94 margin-left: auto; 95 margin-right: auto; 96 border: 1px solid #dbdbdb; 97 border-radius: 3px; 98 } 99 .expansion-view { 100 background-color: rgba(0, 0, 0, 0); 101 margin-left: 0px; 102 margin-top: 5px; 103 margin-right: 5px; 104 margin-bottom: 5px; 105 border: 1px solid #dbdbdb; 106 border-radius: 3px; 107 } 108 table { 109 border-collapse: collapse; 110 } 111 .line-number { 112 text-align: right; 113 color: #aaa; 114 } 115 .covered-line { 116 text-align: right; 117 color: #0080ff; 118 } 119 .uncovered-line { 120 text-align: right; 121 color: #ff3300; 122 } 123 .tooltip { 124 position: relative; 125 display: inline; 126 background-color: #b3e6ff; 127 text-decoration: none; 128 } 129 .tooltip span.tooltip-content { 130 position: absolute; 131 width: 100px; 132 margin-left: -50px; 133 color: #FFFFFF; 134 background: #000000; 135 height: 30px; 136 line-height: 30px; 137 text-align: center; 138 visibility: hidden; 139 border-radius: 6px; 140 } 141 .tooltip span.tooltip-content:after { 142 content: ''; 143 position: absolute; 144 top: 100%; 145 left: 50%; 146 margin-left: -8px; 147 width: 0; height: 0; 148 border-top: 8px solid #000000; 149 border-right: 8px solid transparent; 150 border-left: 8px solid transparent; 151 } 152 :hover.tooltip span.tooltip-content { 153 visibility: visible; 154 opacity: 0.8; 155 bottom: 30px; 156 left: 50%; 157 z-index: 999; 158 } 159 th, td { 160 vertical-align: top; 161 padding: 2px 5px; 162 border-collapse: collapse; 163 border-right: solid 1px #eee; 164 border-left: solid 1px #eee; 165 } 166 td:first-child { 167 border-left: none; 168 } 169 td:last-child { 170 border-right: none; 171 } 172 )"; 173 174 const char *EndHeader = "</head>"; 175 176 const char *BeginCenteredDiv = "<div class='centered'>"; 177 178 const char *EndCenteredDiv = "</div>"; 179 180 const char *BeginSourceNameDiv = "<div class='source-name-title'>"; 181 182 const char *EndSourceNameDiv = "</div>"; 183 184 const char *BeginCodeTD = "<td class='code'>"; 185 186 const char *EndCodeTD = "</td>"; 187 188 const char *BeginPre = "<pre>"; 189 190 const char *EndPre = "</pre>"; 191 192 const char *BeginExpansionDiv = "<div class='expansion-view'>"; 193 194 const char *EndExpansionDiv = "</div>"; 195 196 const char *BeginTable = "<table>"; 197 198 const char *EndTable = "</table>"; 199 200 std::string getPathToStyle(StringRef ViewPath) { 201 std::string PathToStyle = ""; 202 std::string PathSep = sys::path::get_separator(); 203 unsigned NumSeps = ViewPath.count(PathSep); 204 for (unsigned I = 0, E = NumSeps; I < E; ++I) 205 PathToStyle += ".." + PathSep; 206 return PathToStyle + "style.css"; 207 } 208 209 void emitPrelude(raw_ostream &OS, const CoverageViewOptions &Opts, 210 const std::string &PathToStyle = "") { 211 OS << "<!doctype html>" 212 "<html>" 213 << BeginHeader; 214 215 // Link to a stylesheet if one is available. Otherwise, use the default style. 216 if (PathToStyle.empty()) 217 OS << "<style>" << CSSForCoverage << "</style>"; 218 else 219 OS << "<link rel='stylesheet' type='text/css' href='" 220 << escape(PathToStyle, Opts) << "'>"; 221 222 OS << EndHeader << "<body>" << BeginCenteredDiv; 223 } 224 225 void emitEpilog(raw_ostream &OS) { 226 OS << EndCenteredDiv << "</body>" 227 "</html>"; 228 } 229 230 } // anonymous namespace 231 232 Expected<CoveragePrinter::OwnedStream> 233 CoveragePrinterHTML::createViewFile(StringRef Path, bool InToplevel) { 234 auto OSOrErr = createOutputStream(Path, "html", InToplevel); 235 if (!OSOrErr) 236 return OSOrErr; 237 238 OwnedStream OS = std::move(OSOrErr.get()); 239 240 if (!Opts.hasOutputDirectory()) { 241 emitPrelude(*OS.get(), Opts); 242 } else { 243 std::string ViewPath = getOutputPath(Path, "html", InToplevel); 244 emitPrelude(*OS.get(), Opts, getPathToStyle(ViewPath)); 245 } 246 247 return std::move(OS); 248 } 249 250 void CoveragePrinterHTML::closeViewFile(OwnedStream OS) { 251 emitEpilog(*OS.get()); 252 } 253 254 Error CoveragePrinterHTML::createIndexFile(ArrayRef<StringRef> SourceFiles) { 255 auto OSOrErr = createOutputStream("index", "html", /*InToplevel=*/true); 256 if (Error E = OSOrErr.takeError()) 257 return E; 258 auto OS = std::move(OSOrErr.get()); 259 raw_ostream &OSRef = *OS.get(); 260 261 // Emit a table containing links to reports for each file in the covmapping. 262 assert(Opts.hasOutputDirectory() && "No output directory for index file"); 263 emitPrelude(OSRef, Opts, getPathToStyle("")); 264 OSRef << BeginSourceNameDiv << "Index" << EndSourceNameDiv; 265 OSRef << BeginTable; 266 for (StringRef SF : SourceFiles) { 267 std::string LinkText = escape(sys::path::relative_path(SF), Opts); 268 std::string LinkTarget = 269 escape(getOutputPath(SF, "html", /*InToplevel=*/false), Opts); 270 OSRef << tag("tr", tag("td", tag("pre", a(LinkTarget, LinkText), "code"))); 271 } 272 OSRef << EndTable; 273 emitEpilog(OSRef); 274 275 // Emit the default stylesheet. 276 auto CSSOrErr = createOutputStream("style", "css", /*InToplevel=*/true); 277 if (Error E = CSSOrErr.takeError()) 278 return E; 279 280 OwnedStream CSS = std::move(CSSOrErr.get()); 281 CSS->operator<<(CSSForCoverage); 282 283 return Error::success(); 284 } 285 286 void SourceCoverageViewHTML::renderViewHeader(raw_ostream &OS) { 287 OS << BeginTable; 288 } 289 290 void SourceCoverageViewHTML::renderViewFooter(raw_ostream &OS) { 291 OS << EndTable; 292 } 293 294 void SourceCoverageViewHTML::renderSourceName(raw_ostream &OS) { 295 OS << BeginSourceNameDiv << tag("pre", escape(getSourceName(), getOptions())) 296 << EndSourceNameDiv; 297 } 298 299 void SourceCoverageViewHTML::renderLinePrefix(raw_ostream &OS, unsigned) { 300 OS << "<tr>"; 301 } 302 303 void SourceCoverageViewHTML::renderLineSuffix(raw_ostream &OS, unsigned) { 304 // If this view has sub-views, renderLine() cannot close the view's cell. 305 // Take care of it here, after all sub-views have been rendered. 306 if (hasSubViews()) 307 OS << EndCodeTD; 308 OS << "</tr>"; 309 } 310 311 void SourceCoverageViewHTML::renderViewDivider(raw_ostream &, unsigned) { 312 // The table-based output makes view dividers unnecessary. 313 } 314 315 void SourceCoverageViewHTML::renderLine( 316 raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment, 317 CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned) { 318 StringRef Line = L.Line; 319 unsigned LineNo = L.LineNo; 320 321 // Steps for handling text-escaping, highlighting, and tooltip creation: 322 // 323 // 1. Split the line into N+1 snippets, where N = |Segments|. The first 324 // snippet starts from Col=1 and ends at the start of the first segment. 325 // The last snippet starts at the last mapped column in the line and ends 326 // at the end of the line. Both are required but may be empty. 327 328 SmallVector<std::string, 8> Snippets; 329 330 unsigned LCol = 1; 331 auto Snip = [&](unsigned Start, unsigned Len) { 332 assert(Start + Len <= Line.size() && "Snippet extends past the EOL"); 333 Snippets.push_back(Line.substr(Start, Len)); 334 LCol += Len; 335 }; 336 337 Snip(LCol - 1, Segments.empty() ? 0 : (Segments.front()->Col - 1)); 338 339 for (unsigned I = 1, E = Segments.size(); I < E; ++I) { 340 assert(LCol == Segments[I - 1]->Col && "Snippet start position is wrong"); 341 Snip(LCol - 1, Segments[I]->Col - LCol); 342 } 343 344 // |Line| + 1 is needed to avoid underflow when, e.g |Line| = 0 and LCol = 1. 345 Snip(LCol - 1, Line.size() + 1 - LCol); 346 assert(LCol == Line.size() + 1 && "Final snippet doesn't reach the EOL"); 347 348 // 2. Escape all of the snippets. 349 350 for (unsigned I = 0, E = Snippets.size(); I < E; ++I) 351 Snippets[I] = escape(Snippets[I], getOptions()); 352 353 // 3. Use \p WrappedSegment to set the highlight for snippet 0. Use segment 354 // 1 to set the highlight for snippet 2, segment 2 to set the highlight for 355 // snippet 3, and so on. 356 357 Optional<std::string> Color; 358 SmallVector<std::pair<unsigned, unsigned>, 4> HighlightedRanges; 359 auto Highlight = [&](const std::string &Snippet, unsigned LC, unsigned RC) { 360 if (getOptions().Debug) { 361 if (!HighlightedRanges.empty() && 362 HighlightedRanges.back().second == LC - 1) { 363 HighlightedRanges.back().second = RC; 364 } else 365 HighlightedRanges.emplace_back(LC, RC); 366 } 367 return tag("span", Snippet, Color.getValue()); 368 }; 369 370 auto CheckIfUncovered = [](const coverage::CoverageSegment *S) { 371 return S && (S->HasCount && S->Count == 0); 372 }; 373 374 if (CheckIfUncovered(WrappedSegment) || 375 CheckIfUncovered(Segments.empty() ? nullptr : Segments.front())) { 376 Color = "red"; 377 Snippets[0] = Highlight(Snippets[0], 0, Snippets[0].size()); 378 } 379 380 for (unsigned I = 0, E = Segments.size(); I < E; ++I) { 381 const auto *CurSeg = Segments[I]; 382 if (CurSeg->Col == ExpansionCol) 383 Color = "cyan"; 384 else if (CheckIfUncovered(CurSeg)) 385 Color = "red"; 386 else 387 Color = None; 388 389 if (Color.hasValue()) 390 Snippets[I + 1] = Highlight(Snippets[I + 1], CurSeg->Col, 391 CurSeg->Col + Snippets[I + 1].size()); 392 } 393 394 if (Color.hasValue() && Segments.empty()) 395 Snippets.back() = Highlight(Snippets.back(), Snippets[0].size(), 0); 396 397 if (getOptions().Debug) { 398 for (const auto &Range : HighlightedRanges) { 399 errs() << "Highlighted line " << LineNo << ", " << Range.first + 1 400 << " -> "; 401 if (Range.second == 0) 402 errs() << "?"; 403 else 404 errs() << Range.second + 1; 405 errs() << "\n"; 406 } 407 } 408 409 // 4. Snippets[1:N+1] correspond to \p Segments[0:N]: use these to generate 410 // sub-line region count tooltips if needed. 411 412 bool HasMultipleRegions = [&] { 413 unsigned RegionCount = 0; 414 for (const auto *S : Segments) 415 if (S->HasCount && S->IsRegionEntry) 416 if (++RegionCount > 1) 417 return true; 418 return false; 419 }(); 420 421 if (shouldRenderRegionMarkers(HasMultipleRegions)) { 422 for (unsigned I = 0, E = Segments.size(); I < E; ++I) { 423 const auto *CurSeg = Segments[I]; 424 if (!CurSeg->IsRegionEntry || !CurSeg->HasCount) 425 continue; 426 427 Snippets[I + 1] = 428 tag("div", Snippets[I + 1] + tag("span", formatCount(CurSeg->Count), 429 "tooltip-content"), 430 "tooltip"); 431 } 432 } 433 434 OS << BeginCodeTD; 435 OS << BeginPre; 436 for (const auto &Snippet : Snippets) 437 OS << Snippet; 438 OS << EndPre; 439 440 // If there are no sub-views left to attach to this cell, end the cell. 441 // Otherwise, end it after the sub-views are rendered (renderLineSuffix()). 442 if (!hasSubViews()) 443 OS << EndCodeTD; 444 } 445 446 void SourceCoverageViewHTML::renderLineCoverageColumn( 447 raw_ostream &OS, const LineCoverageStats &Line) { 448 std::string Count = ""; 449 if (Line.isMapped()) 450 Count = tag("pre", formatCount(Line.ExecutionCount)); 451 std::string CoverageClass = 452 (Line.ExecutionCount > 0) ? "covered-line" : "uncovered-line"; 453 OS << tag("td", Count, CoverageClass); 454 } 455 456 void SourceCoverageViewHTML::renderLineNumberColumn(raw_ostream &OS, 457 unsigned LineNo) { 458 std::string LineNoStr = utostr(uint64_t(LineNo)); 459 OS << tag("td", a("L" + LineNoStr, tag("pre", LineNoStr), "name"), 460 "line-number"); 461 } 462 463 void SourceCoverageViewHTML::renderRegionMarkers(raw_ostream &, 464 CoverageSegmentArray, 465 unsigned) { 466 // Region markers are rendered in-line using tooltips. 467 } 468 469 void SourceCoverageViewHTML::renderExpansionSite( 470 raw_ostream &OS, LineRef L, const coverage::CoverageSegment *WrappedSegment, 471 CoverageSegmentArray Segments, unsigned ExpansionCol, unsigned ViewDepth) { 472 // Render the line containing the expansion site. No extra formatting needed. 473 renderLine(OS, L, WrappedSegment, Segments, ExpansionCol, ViewDepth); 474 } 475 476 void SourceCoverageViewHTML::renderExpansionView(raw_ostream &OS, 477 ExpansionView &ESV, 478 unsigned ViewDepth) { 479 OS << BeginExpansionDiv; 480 ESV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/false, 481 ViewDepth + 1); 482 OS << EndExpansionDiv; 483 } 484 485 void SourceCoverageViewHTML::renderInstantiationView(raw_ostream &OS, 486 InstantiationView &ISV, 487 unsigned ViewDepth) { 488 OS << BeginExpansionDiv; 489 ISV.View->print(OS, /*WholeFile=*/false, /*ShowSourceName=*/true, ViewDepth); 490 OS << EndExpansionDiv; 491 } 492