xref: /llvm-project/llvm/tools/llvm-cov/SourceCoverageView.cpp (revision e955f6183749410992ef358b2d49b8cae2acaae1)
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 unsigned SourceCoverageView::getFirstUncoveredLineNo() {
87   const auto MinSegIt = find_if(CoverageInfo, [](const CoverageSegment &S) {
88     return S.HasCount && S.Count == 0;
89   });
90 
91   // There is no uncovered line, return zero.
92   if (MinSegIt == CoverageInfo.end())
93     return 0;
94 
95   return (*MinSegIt).Line;
96 }
97 
98 std::string SourceCoverageView::formatCount(uint64_t N) {
99   std::string Number = utostr(N);
100   int Len = Number.size();
101   if (Len <= 3)
102     return Number;
103   int IntLen = Len % 3 == 0 ? 3 : Len % 3;
104   std::string Result(Number.data(), IntLen);
105   if (IntLen != 3) {
106     Result.push_back('.');
107     Result += Number.substr(IntLen, 3 - IntLen);
108   }
109   Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
110   return Result;
111 }
112 
113 bool SourceCoverageView::shouldRenderRegionMarkers(
114     CoverageSegmentArray Segments) const {
115   if (!getOptions().ShowRegionMarkers)
116     return false;
117 
118   // Render the region markers if there's more than one count to show.
119   unsigned RegionCount = 0;
120   for (const auto *S : Segments)
121     if (S->IsRegionEntry)
122       if (++RegionCount > 1)
123         return true;
124   return false;
125 }
126 
127 bool SourceCoverageView::hasSubViews() const {
128   return !ExpansionSubViews.empty() || !InstantiationSubViews.empty();
129 }
130 
131 std::unique_ptr<SourceCoverageView>
132 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
133                            const CoverageViewOptions &Options,
134                            CoverageData &&CoverageInfo) {
135   switch (Options.Format) {
136   case CoverageViewOptions::OutputFormat::Text:
137     return llvm::make_unique<SourceCoverageViewText>(
138         SourceName, File, Options, std::move(CoverageInfo));
139   case CoverageViewOptions::OutputFormat::HTML:
140     return llvm::make_unique<SourceCoverageViewHTML>(
141         SourceName, File, Options, std::move(CoverageInfo));
142   }
143   llvm_unreachable("Unknown coverage output format!");
144 }
145 
146 std::string SourceCoverageView::getSourceName() const {
147   SmallString<128> SourceText(SourceName);
148   sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true);
149   sys::path::native(SourceText);
150   return SourceText.str();
151 }
152 
153 void SourceCoverageView::addExpansion(
154     const CounterMappingRegion &Region,
155     std::unique_ptr<SourceCoverageView> View) {
156   ExpansionSubViews.emplace_back(Region, std::move(View));
157 }
158 
159 void SourceCoverageView::addInstantiation(
160     StringRef FunctionName, unsigned Line,
161     std::unique_ptr<SourceCoverageView> View) {
162   InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
163 }
164 
165 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
166                                bool ShowSourceName, bool ShowTitle,
167                                unsigned ViewDepth) {
168   if (ShowTitle)
169     renderTitle(OS, "Coverage Report");
170 
171   renderViewHeader(OS);
172 
173   if (ShowSourceName)
174     renderSourceName(OS, WholeFile);
175 
176   renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
177                     ViewDepth);
178 
179   // We need the expansions and instantiations sorted so we can go through them
180   // while we iterate lines.
181   std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end());
182   std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end());
183   auto NextESV = ExpansionSubViews.begin();
184   auto EndESV = ExpansionSubViews.end();
185   auto NextISV = InstantiationSubViews.begin();
186   auto EndISV = InstantiationSubViews.end();
187 
188   // Get the coverage information for the file.
189   auto StartSegment = CoverageInfo.begin();
190   auto EndSegment = CoverageInfo.end();
191   LineCoverageIterator LCI{CoverageInfo, 1};
192   LineCoverageIterator LCIEnd = LCI.getEnd();
193 
194   unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
195   for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
196        ++LI, ++LCI) {
197     // If we aren't rendering the whole file, we need to filter out the prologue
198     // and epilogue.
199     if (!WholeFile) {
200       if (LCI == LCIEnd)
201         break;
202       else if (LI.line_number() < FirstLine)
203         continue;
204     }
205 
206     renderLinePrefix(OS, ViewDepth);
207     if (getOptions().ShowLineNumbers)
208       renderLineNumberColumn(OS, LI.line_number());
209 
210     if (getOptions().ShowLineStats)
211       renderLineCoverageColumn(OS, *LCI);
212 
213     // If there are expansion subviews, we want to highlight the first one.
214     unsigned ExpansionColumn = 0;
215     if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
216         getOptions().Colors)
217       ExpansionColumn = NextESV->getStartCol();
218 
219     // Display the source code for the current line.
220     renderLine(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn, ViewDepth);
221 
222     // Show the region markers.
223     if (shouldRenderRegionMarkers(LCI->getLineSegments()))
224       renderRegionMarkers(OS, *LCI, ViewDepth);
225 
226     // Show the expansions and instantiations for this line.
227     bool RenderedSubView = false;
228     for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
229          ++NextESV) {
230       renderViewDivider(OS, ViewDepth + 1);
231 
232       // Re-render the current line and highlight the expansion range for
233       // this subview.
234       if (RenderedSubView) {
235         ExpansionColumn = NextESV->getStartCol();
236         renderExpansionSite(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn,
237                             ViewDepth);
238         renderViewDivider(OS, ViewDepth + 1);
239       }
240 
241       renderExpansionView(OS, *NextESV, ViewDepth + 1);
242       RenderedSubView = true;
243     }
244     for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
245       renderViewDivider(OS, ViewDepth + 1);
246       renderInstantiationView(OS, *NextISV, ViewDepth + 1);
247       RenderedSubView = true;
248     }
249     if (RenderedSubView)
250       renderViewDivider(OS, ViewDepth + 1);
251     renderLineSuffix(OS, ViewDepth);
252   }
253 
254   renderViewFooter(OS);
255 }
256