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