xref: /llvm-project/llvm/tools/llvm-cov/SourceCoverageView.cpp (revision 25710a66a94d003944bd616706c8cacdd3b49e23)
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 = new raw_fd_ostream(FullPath, E, sys::fs::F_RW);
69   auto OS = CoveragePrinter::OwnedStream(RawStream);
70   if (E)
71     return errorCodeToError(E);
72   return std::move(OS);
73 }
74 
75 std::unique_ptr<CoveragePrinter>
76 CoveragePrinter::create(const CoverageViewOptions &Opts) {
77   switch (Opts.Format) {
78   case CoverageViewOptions::OutputFormat::Text:
79     return llvm::make_unique<CoveragePrinterText>(Opts);
80   case CoverageViewOptions::OutputFormat::HTML:
81     return llvm::make_unique<CoveragePrinterHTML>(Opts);
82   }
83   llvm_unreachable("Unknown coverage output format!");
84 }
85 
86 LineCoverageStats::LineCoverageStats(
87     ArrayRef<const coverage::CoverageSegment *> LineSegments,
88     const coverage::CoverageSegment *WrappedSegment) {
89   // Find the minimum number of regions which start in this line.
90   unsigned MinRegionCount = 0;
91   auto isStartOfRegion = [](const coverage::CoverageSegment *S) {
92     return S->HasCount && S->IsRegionEntry;
93   };
94   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
95     if (isStartOfRegion(LineSegments[I]))
96       ++MinRegionCount;
97 
98   bool StartOfSkippedRegion = !LineSegments.empty() &&
99                               !LineSegments.front()->HasCount &&
100                               LineSegments.front()->IsRegionEntry;
101 
102   ExecutionCount = 0;
103   HasMultipleRegions = MinRegionCount > 1;
104   Mapped =
105       !StartOfSkippedRegion &&
106       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
107 
108   if (!Mapped)
109     return;
110 
111   // Pick the max count among regions which start and end on this line, to
112   // avoid erroneously using the wrapped count, and to avoid picking region
113   // counts which come from deferred regions.
114   if (LineSegments.size() > 1) {
115     for (unsigned I = 0; I < LineSegments.size() - 1; ++I)
116       ExecutionCount = std::max(ExecutionCount, LineSegments[I]->Count);
117     return;
118   }
119 
120   // Just pick the maximum count.
121   if (WrappedSegment && WrappedSegment->HasCount)
122     ExecutionCount = WrappedSegment->Count;
123   if (!LineSegments.empty())
124     ExecutionCount = std::max(ExecutionCount, LineSegments[0]->Count);
125 }
126 
127 unsigned SourceCoverageView::getFirstUncoveredLineNo() {
128   const auto MinSegIt =
129       find_if(CoverageInfo, [](const coverage::CoverageSegment &S) {
130         return S.HasCount && S.Count == 0;
131       });
132 
133   // There is no uncovered line, return zero.
134   if (MinSegIt == CoverageInfo.end())
135     return 0;
136 
137   return (*MinSegIt).Line;
138 }
139 
140 std::string SourceCoverageView::formatCount(uint64_t N) {
141   std::string Number = utostr(N);
142   int Len = Number.size();
143   if (Len <= 3)
144     return Number;
145   int IntLen = Len % 3 == 0 ? 3 : Len % 3;
146   std::string Result(Number.data(), IntLen);
147   if (IntLen != 3) {
148     Result.push_back('.');
149     Result += Number.substr(IntLen, 3 - IntLen);
150   }
151   Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
152   return Result;
153 }
154 
155 bool SourceCoverageView::shouldRenderRegionMarkers(
156     CoverageSegmentArray Segments) const {
157   if (!getOptions().ShowRegionMarkers)
158     return false;
159 
160   // Render the region markers if there's more than one count to show.
161   unsigned RegionCount = 0;
162   for (const auto *S : Segments)
163     if (S->IsRegionEntry)
164       if (++RegionCount > 1)
165         return true;
166   return false;
167 }
168 
169 bool SourceCoverageView::hasSubViews() const {
170   return !ExpansionSubViews.empty() || !InstantiationSubViews.empty();
171 }
172 
173 std::unique_ptr<SourceCoverageView>
174 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
175                            const CoverageViewOptions &Options,
176                            coverage::CoverageData &&CoverageInfo) {
177   switch (Options.Format) {
178   case CoverageViewOptions::OutputFormat::Text:
179     return llvm::make_unique<SourceCoverageViewText>(
180         SourceName, File, Options, std::move(CoverageInfo));
181   case CoverageViewOptions::OutputFormat::HTML:
182     return llvm::make_unique<SourceCoverageViewHTML>(
183         SourceName, File, Options, std::move(CoverageInfo));
184   }
185   llvm_unreachable("Unknown coverage output format!");
186 }
187 
188 std::string SourceCoverageView::getSourceName() const {
189   SmallString<128> SourceText(SourceName);
190   sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true);
191   sys::path::native(SourceText);
192   return SourceText.str();
193 }
194 
195 void SourceCoverageView::addExpansion(
196     const coverage::CounterMappingRegion &Region,
197     std::unique_ptr<SourceCoverageView> View) {
198   ExpansionSubViews.emplace_back(Region, std::move(View));
199 }
200 
201 void SourceCoverageView::addInstantiation(
202     StringRef FunctionName, unsigned Line,
203     std::unique_ptr<SourceCoverageView> View) {
204   InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
205 }
206 
207 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
208                                bool ShowSourceName, unsigned ViewDepth) {
209   if (WholeFile && getOptions().hasOutputDirectory())
210     renderTitle(OS, "Coverage Report");
211 
212   renderViewHeader(OS);
213 
214   if (ShowSourceName)
215     renderSourceName(OS, WholeFile);
216 
217   renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
218                     ViewDepth);
219 
220   // We need the expansions and instantiations sorted so we can go through them
221   // while we iterate lines.
222   std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end());
223   std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end());
224   auto NextESV = ExpansionSubViews.begin();
225   auto EndESV = ExpansionSubViews.end();
226   auto NextISV = InstantiationSubViews.begin();
227   auto EndISV = InstantiationSubViews.end();
228 
229   // Get the coverage information for the file.
230   auto NextSegment = CoverageInfo.begin();
231   auto EndSegment = CoverageInfo.end();
232 
233   unsigned FirstLine = NextSegment != EndSegment ? NextSegment->Line : 0;
234   const coverage::CoverageSegment *WrappedSegment = nullptr;
235   SmallVector<const coverage::CoverageSegment *, 8> LineSegments;
236   for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof(); ++LI) {
237     // If we aren't rendering the whole file, we need to filter out the prologue
238     // and epilogue.
239     if (!WholeFile) {
240       if (NextSegment == EndSegment)
241         break;
242       else if (LI.line_number() < FirstLine)
243         continue;
244     }
245 
246     // Collect the coverage information relevant to this line.
247     if (LineSegments.size())
248       WrappedSegment = LineSegments.back();
249     LineSegments.clear();
250     while (NextSegment != EndSegment && NextSegment->Line == LI.line_number())
251       LineSegments.push_back(&*NextSegment++);
252 
253     renderLinePrefix(OS, ViewDepth);
254     if (getOptions().ShowLineNumbers)
255       renderLineNumberColumn(OS, LI.line_number());
256 
257     LineCoverageStats LineCount{LineSegments, WrappedSegment};
258     if (getOptions().ShowLineStats)
259       renderLineCoverageColumn(OS, LineCount);
260 
261     // If there are expansion subviews, we want to highlight the first one.
262     unsigned ExpansionColumn = 0;
263     if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
264         getOptions().Colors)
265       ExpansionColumn = NextESV->getStartCol();
266 
267     // Display the source code for the current line.
268     renderLine(OS, {*LI, LI.line_number()}, WrappedSegment, LineSegments,
269                ExpansionColumn, ViewDepth);
270 
271     // Show the region markers.
272     if (shouldRenderRegionMarkers(LineSegments))
273       renderRegionMarkers(OS, LineSegments, ViewDepth);
274 
275     // Show the expansions and instantiations for this line.
276     bool RenderedSubView = false;
277     for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
278          ++NextESV) {
279       renderViewDivider(OS, ViewDepth + 1);
280 
281       // Re-render the current line and highlight the expansion range for
282       // this subview.
283       if (RenderedSubView) {
284         ExpansionColumn = NextESV->getStartCol();
285         renderExpansionSite(OS, {*LI, LI.line_number()}, WrappedSegment,
286                             LineSegments, ExpansionColumn, ViewDepth);
287         renderViewDivider(OS, ViewDepth + 1);
288       }
289 
290       renderExpansionView(OS, *NextESV, ViewDepth + 1);
291       RenderedSubView = true;
292     }
293     for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
294       renderViewDivider(OS, ViewDepth + 1);
295       renderInstantiationView(OS, *NextISV, ViewDepth + 1);
296       RenderedSubView = true;
297     }
298     if (RenderedSubView)
299       renderViewDivider(OS, ViewDepth + 1);
300     renderLineSuffix(OS, ViewDepth);
301   }
302 
303   renderViewFooter(OS);
304 }
305