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