Home | History | Annotate | Download | only in llvm-cov
      1 //===- SourceCoverageView.cpp - Code coverage view for source code --------===//
      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 class implements rendering for code coverage of source code.
     11 ///
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "SourceCoverageView.h"
     15 #include "SourceCoverageViewHTML.h"
     16 #include "SourceCoverageViewText.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/ADT/StringExtras.h"
     19 #include "llvm/Support/FileSystem.h"
     20 #include "llvm/Support/LineIterator.h"
     21 #include "llvm/Support/Path.h"
     22 
     23 using namespace llvm;
     24 
     25 void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
     26   if (OS == &outs())
     27     return;
     28   delete OS;
     29 }
     30 
     31 std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
     32                                            bool InToplevel,
     33                                            bool Relative) const {
     34   assert(Extension.size() && "The file extension may not be empty");
     35 
     36   SmallString<256> FullPath;
     37 
     38   if (!Relative)
     39     FullPath.append(Opts.ShowOutputDirectory);
     40 
     41   if (!InToplevel)
     42     sys::path::append(FullPath, getCoverageDir());
     43 
     44   SmallString<256> ParentPath = sys::path::parent_path(Path);
     45   sys::path::remove_dots(ParentPath, /*remove_dot_dots=*/true);
     46   sys::path::append(FullPath, sys::path::relative_path(ParentPath));
     47 
     48   auto PathFilename = (sys::path::filename(Path) + "." + Extension).str();
     49   sys::path::append(FullPath, PathFilename);
     50   sys::path::native(FullPath);
     51 
     52   return FullPath.str();
     53 }
     54 
     55 Expected<CoveragePrinter::OwnedStream>
     56 CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
     57                                     bool InToplevel) const {
     58   if (!Opts.hasOutputDirectory())
     59     return OwnedStream(&outs());
     60 
     61   std::string FullPath = getOutputPath(Path, Extension, InToplevel, false);
     62 
     63   auto ParentDir = sys::path::parent_path(FullPath);
     64   if (auto E = sys::fs::create_directories(ParentDir))
     65     return errorCodeToError(E);
     66 
     67   std::error_code E;
     68   raw_ostream *RawStream =
     69       new raw_fd_ostream(FullPath, E, sys::fs::FA_Read | sys::fs::FA_Write);
     70   auto OS = CoveragePrinter::OwnedStream(RawStream);
     71   if (E)
     72     return errorCodeToError(E);
     73   return std::move(OS);
     74 }
     75 
     76 std::unique_ptr<CoveragePrinter>
     77 CoveragePrinter::create(const CoverageViewOptions &Opts) {
     78   switch (Opts.Format) {
     79   case CoverageViewOptions::OutputFormat::Text:
     80     return llvm::make_unique<CoveragePrinterText>(Opts);
     81   case CoverageViewOptions::OutputFormat::HTML:
     82     return llvm::make_unique<CoveragePrinterHTML>(Opts);
     83   }
     84   llvm_unreachable("Unknown coverage output format!");
     85 }
     86 
     87 unsigned SourceCoverageView::getFirstUncoveredLineNo() {
     88   const auto MinSegIt = find_if(CoverageInfo, [](const CoverageSegment &S) {
     89     return S.HasCount && S.Count == 0;
     90   });
     91 
     92   // There is no uncovered line, return zero.
     93   if (MinSegIt == CoverageInfo.end())
     94     return 0;
     95 
     96   return (*MinSegIt).Line;
     97 }
     98 
     99 std::string SourceCoverageView::formatCount(uint64_t N) {
    100   std::string Number = utostr(N);
    101   int Len = Number.size();
    102   if (Len <= 3)
    103     return Number;
    104   int IntLen = Len % 3 == 0 ? 3 : Len % 3;
    105   std::string Result(Number.data(), IntLen);
    106   if (IntLen != 3) {
    107     Result.push_back('.');
    108     Result += Number.substr(IntLen, 3 - IntLen);
    109   }
    110   Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
    111   return Result;
    112 }
    113 
    114 bool SourceCoverageView::shouldRenderRegionMarkers(
    115     const LineCoverageStats &LCS) const {
    116   if (!getOptions().ShowRegionMarkers)
    117     return false;
    118 
    119   CoverageSegmentArray Segments = LCS.getLineSegments();
    120   if (Segments.empty())
    121     return false;
    122   for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
    123     const auto *CurSeg = Segments[I];
    124     if (!CurSeg->IsRegionEntry || CurSeg->Count == LCS.getExecutionCount())
    125       continue;
    126     return true;
    127   }
    128   return false;
    129 }
    130 
    131 bool SourceCoverageView::hasSubViews() const {
    132   return !ExpansionSubViews.empty() || !InstantiationSubViews.empty();
    133 }
    134 
    135 std::unique_ptr<SourceCoverageView>
    136 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
    137                            const CoverageViewOptions &Options,
    138                            CoverageData &&CoverageInfo) {
    139   switch (Options.Format) {
    140   case CoverageViewOptions::OutputFormat::Text:
    141     return llvm::make_unique<SourceCoverageViewText>(
    142         SourceName, File, Options, std::move(CoverageInfo));
    143   case CoverageViewOptions::OutputFormat::HTML:
    144     return llvm::make_unique<SourceCoverageViewHTML>(
    145         SourceName, File, Options, std::move(CoverageInfo));
    146   }
    147   llvm_unreachable("Unknown coverage output format!");
    148 }
    149 
    150 std::string SourceCoverageView::getSourceName() const {
    151   SmallString<128> SourceText(SourceName);
    152   sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true);
    153   sys::path::native(SourceText);
    154   return SourceText.str();
    155 }
    156 
    157 void SourceCoverageView::addExpansion(
    158     const CounterMappingRegion &Region,
    159     std::unique_ptr<SourceCoverageView> View) {
    160   ExpansionSubViews.emplace_back(Region, std::move(View));
    161 }
    162 
    163 void SourceCoverageView::addInstantiation(
    164     StringRef FunctionName, unsigned Line,
    165     std::unique_ptr<SourceCoverageView> View) {
    166   InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
    167 }
    168 
    169 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
    170                                bool ShowSourceName, bool ShowTitle,
    171                                unsigned ViewDepth) {
    172   if (ShowTitle)
    173     renderTitle(OS, "Coverage Report");
    174 
    175   renderViewHeader(OS);
    176 
    177   if (ShowSourceName)
    178     renderSourceName(OS, WholeFile);
    179 
    180   renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
    181                     ViewDepth);
    182 
    183   // We need the expansions and instantiations sorted so we can go through them
    184   // while we iterate lines.
    185   std::stable_sort(ExpansionSubViews.begin(), ExpansionSubViews.end());
    186   std::stable_sort(InstantiationSubViews.begin(), InstantiationSubViews.end());
    187   auto NextESV = ExpansionSubViews.begin();
    188   auto EndESV = ExpansionSubViews.end();
    189   auto NextISV = InstantiationSubViews.begin();
    190   auto EndISV = InstantiationSubViews.end();
    191 
    192   // Get the coverage information for the file.
    193   auto StartSegment = CoverageInfo.begin();
    194   auto EndSegment = CoverageInfo.end();
    195   LineCoverageIterator LCI{CoverageInfo, 1};
    196   LineCoverageIterator LCIEnd = LCI.getEnd();
    197 
    198   unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
    199   for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
    200        ++LI, ++LCI) {
    201     // If we aren't rendering the whole file, we need to filter out the prologue
    202     // and epilogue.
    203     if (!WholeFile) {
    204       if (LCI == LCIEnd)
    205         break;
    206       else if (LI.line_number() < FirstLine)
    207         continue;
    208     }
    209 
    210     renderLinePrefix(OS, ViewDepth);
    211     if (getOptions().ShowLineNumbers)
    212       renderLineNumberColumn(OS, LI.line_number());
    213 
    214     if (getOptions().ShowLineStats)
    215       renderLineCoverageColumn(OS, *LCI);
    216 
    217     // If there are expansion subviews, we want to highlight the first one.
    218     unsigned ExpansionColumn = 0;
    219     if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
    220         getOptions().Colors)
    221       ExpansionColumn = NextESV->getStartCol();
    222 
    223     // Display the source code for the current line.
    224     renderLine(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn, ViewDepth);
    225 
    226     // Show the region markers.
    227     if (shouldRenderRegionMarkers(*LCI))
    228       renderRegionMarkers(OS, *LCI, ViewDepth);
    229 
    230     // Show the expansions and instantiations for this line.
    231     bool RenderedSubView = false;
    232     for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
    233          ++NextESV) {
    234       renderViewDivider(OS, ViewDepth + 1);
    235 
    236       // Re-render the current line and highlight the expansion range for
    237       // this subview.
    238       if (RenderedSubView) {
    239         ExpansionColumn = NextESV->getStartCol();
    240         renderExpansionSite(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn,
    241                             ViewDepth);
    242         renderViewDivider(OS, ViewDepth + 1);
    243       }
    244 
    245       renderExpansionView(OS, *NextESV, ViewDepth + 1);
    246       RenderedSubView = true;
    247     }
    248     for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
    249       renderViewDivider(OS, ViewDepth + 1);
    250       renderInstantiationView(OS, *NextISV, ViewDepth + 1);
    251       RenderedSubView = true;
    252     }
    253     if (RenderedSubView)
    254       renderViewDivider(OS, ViewDepth + 1);
    255     renderLineSuffix(OS, ViewDepth);
    256   }
    257 
    258   renderViewFooter(OS);
    259 }
    260