1//===- SourceCoverageView.cpp - Code coverage view for source code --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file This class implements rendering for code coverage of source code.
10///
11//===----------------------------------------------------------------------===//
12
13#include "SourceCoverageView.h"
14#include "SourceCoverageViewHTML.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
22using namespace llvm;
23
24void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
25 if (OS == &outs())
26 return;
27 delete OS;
28}
29
30std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
31 bool InToplevel,
32 bool Relative) const {
33 assert(!Extension.empty() && "The file extension may not be empty");
34
35 SmallString<256> FullPath;
36
37 if (!Relative)
38 FullPath.append(RHS: Opts.ShowOutputDirectory);
39
40 if (!InToplevel)
41 sys::path::append(path&: FullPath, a: getCoverageDir());
42
43 SmallString<256> ParentPath = sys::path::parent_path(path: Path);
44 sys::path::remove_dots(path&: ParentPath, /*remove_dot_dot=*/true);
45 sys::path::append(path&: FullPath, a: sys::path::relative_path(path: ParentPath));
46
47 auto PathFilename = (sys::path::filename(path: Path) + "." + Extension).str();
48 sys::path::append(path&: FullPath, a: PathFilename);
49 sys::path::native(path&: FullPath);
50
51 return std::string(FullPath);
52}
53
54Expected<CoveragePrinter::OwnedStream>
55CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
56 bool InToplevel) const {
57 if (!Opts.hasOutputDirectory())
58 return OwnedStream(&outs());
59
60 std::string FullPath = getOutputPath(Path, Extension, InToplevel, Relative: false);
61
62 auto ParentDir = sys::path::parent_path(path: FullPath);
63 if (auto E = sys::fs::create_directories(path: ParentDir))
64 return errorCodeToError(EC: E);
65
66 std::error_code E;
67 raw_ostream *RawStream =
68 new raw_fd_ostream(FullPath, E, sys::fs::FA_Read | sys::fs::FA_Write);
69 auto OS = CoveragePrinter::OwnedStream(RawStream);
70 if (E)
71 return errorCodeToError(EC: E);
72 return std::move(OS);
73}
74
75std::unique_ptr<CoveragePrinter>
76CoveragePrinter::create(const CoverageViewOptions &Opts) {
77 switch (Opts.Format) {
78 case CoverageViewOptions::OutputFormat::Text:
79 if (Opts.ShowDirectoryCoverage)
80 return std::make_unique<CoveragePrinterTextDirectory>(args: Opts);
81 return std::make_unique<CoveragePrinterText>(args: Opts);
82 case CoverageViewOptions::OutputFormat::HTML:
83 if (Opts.ShowDirectoryCoverage)
84 return std::make_unique<CoveragePrinterHTMLDirectory>(args: Opts);
85 return std::make_unique<CoveragePrinterHTML>(args: Opts);
86 case CoverageViewOptions::OutputFormat::Lcov:
87 // Unreachable because CodeCoverage.cpp should terminate with an error
88 // before we get here.
89 llvm_unreachable("Lcov format is not supported!");
90 }
91 llvm_unreachable("Unknown coverage output format!");
92}
93
94unsigned SourceCoverageView::getFirstUncoveredLineNo() {
95 const auto MinSegIt = find_if(Range&: CoverageInfo, P: [](const CoverageSegment &S) {
96 return S.HasCount && S.Count == 0;
97 });
98
99 // There is no uncovered line, return zero.
100 if (MinSegIt == CoverageInfo.end())
101 return 0;
102
103 return (*MinSegIt).Line;
104}
105
106std::string SourceCoverageView::formatCount(uint64_t N) {
107 std::string Number = utostr(X: N);
108 int Len = Number.size();
109 if (Len <= 3)
110 return Number;
111 int IntLen = Len % 3 == 0 ? 3 : Len % 3;
112 std::string Result(Number.data(), IntLen);
113 if (IntLen != 3) {
114 Result.push_back(c: '.');
115 Result += Number.substr(pos: IntLen, n: 3 - IntLen);
116 }
117 Result.push_back(c: " kMGTPEZY"[(Len - 1) / 3]);
118 return Result;
119}
120
121bool SourceCoverageView::shouldRenderRegionMarkers(
122 const LineCoverageStats &LCS) const {
123 if (!getOptions().ShowRegionMarkers)
124 return false;
125
126 CoverageSegmentArray Segments = LCS.getLineSegments();
127 if (Segments.empty())
128 return false;
129 for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
130 const auto *CurSeg = Segments[I];
131 if (!CurSeg->IsRegionEntry || CurSeg->Count == LCS.getExecutionCount())
132 continue;
133 if (!CurSeg->HasCount) // don't show tooltips for SkippedRegions
134 continue;
135 return true;
136 }
137 return false;
138}
139
140bool SourceCoverageView::hasSubViews() const {
141 return !ExpansionSubViews.empty() || !InstantiationSubViews.empty() ||
142 !BranchSubViews.empty() || !MCDCSubViews.empty();
143}
144
145std::unique_ptr<SourceCoverageView>
146SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
147 const CoverageViewOptions &Options,
148 CoverageData &&CoverageInfo) {
149 switch (Options.Format) {
150 case CoverageViewOptions::OutputFormat::Text:
151 return std::make_unique<SourceCoverageViewText>(
152 args&: SourceName, args: File, args: Options, args: std::move(CoverageInfo));
153 case CoverageViewOptions::OutputFormat::HTML:
154 return std::make_unique<SourceCoverageViewHTML>(
155 args&: SourceName, args: File, args: Options, args: std::move(CoverageInfo));
156 case CoverageViewOptions::OutputFormat::Lcov:
157 // Unreachable because CodeCoverage.cpp should terminate with an error
158 // before we get here.
159 llvm_unreachable("Lcov format is not supported!");
160 }
161 llvm_unreachable("Unknown coverage output format!");
162}
163
164std::string SourceCoverageView::getSourceName() const {
165 SmallString<128> SourceText(SourceName);
166 sys::path::remove_dots(path&: SourceText, /*remove_dot_dot=*/true);
167 sys::path::native(path&: SourceText);
168 return std::string(SourceText);
169}
170
171void SourceCoverageView::addExpansion(
172 const CounterMappingRegion &Region,
173 std::unique_ptr<SourceCoverageView> View) {
174 ExpansionSubViews.emplace_back(args: Region, args: std::move(View));
175}
176
177void SourceCoverageView::addBranch(unsigned Line,
178 SmallVector<CountedRegion, 0> Regions,
179 std::unique_ptr<SourceCoverageView> View) {
180 BranchSubViews.emplace_back(Args&: Line, Args: std::move(Regions), Args: std::move(View));
181}
182
183void SourceCoverageView::addMCDCRecord(
184 unsigned Line, SmallVector<MCDCRecord, 0> Records,
185 std::unique_ptr<SourceCoverageView> View) {
186 MCDCSubViews.emplace_back(Args&: Line, Args: std::move(Records), Args: std::move(View));
187}
188
189void SourceCoverageView::addInstantiation(
190 StringRef FunctionName, unsigned Line,
191 std::unique_ptr<SourceCoverageView> View) {
192 InstantiationSubViews.emplace_back(args&: FunctionName, args&: Line, args: std::move(View));
193}
194
195void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
196 bool ShowSourceName, bool ShowTitle,
197 unsigned ViewDepth) {
198 if (ShowTitle)
199 renderTitle(OS, CellText: "Coverage Report");
200
201 renderViewHeader(OS);
202
203 if (ShowSourceName)
204 renderSourceName(OS, WholeFile);
205
206 renderTableHeader(OS, FirstUncoveredLineNo: (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
207 IndentLevel: ViewDepth);
208
209 // We need the expansions, instantiations, and branches sorted so we can go
210 // through them while we iterate lines.
211 llvm::stable_sort(Range&: ExpansionSubViews);
212 llvm::stable_sort(Range&: InstantiationSubViews);
213 llvm::stable_sort(Range&: BranchSubViews);
214 llvm::stable_sort(Range&: MCDCSubViews);
215 auto NextESV = ExpansionSubViews.begin();
216 auto EndESV = ExpansionSubViews.end();
217 auto NextISV = InstantiationSubViews.begin();
218 auto EndISV = InstantiationSubViews.end();
219 auto NextBRV = BranchSubViews.begin();
220 auto EndBRV = BranchSubViews.end();
221 auto NextMSV = MCDCSubViews.begin();
222 auto EndMSV = MCDCSubViews.end();
223
224 // Get the coverage information for the file.
225 auto StartSegment = CoverageInfo.begin();
226 auto EndSegment = CoverageInfo.end();
227 LineCoverageIterator LCI{CoverageInfo, 1};
228 LineCoverageIterator LCIEnd = LCI.getEnd();
229
230 unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
231 for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
232 ++LI, ++LCI) {
233 // If we aren't rendering the whole file, we need to filter out the prologue
234 // and epilogue.
235 if (!WholeFile) {
236 if (LCI == LCIEnd)
237 break;
238 else if (LI.line_number() < FirstLine)
239 continue;
240 }
241
242 renderLinePrefix(OS, ViewDepth);
243 if (getOptions().ShowLineNumbers)
244 renderLineNumberColumn(OS, LineNo: LI.line_number());
245
246 if (getOptions().ShowLineStats)
247 renderLineCoverageColumn(OS, Line: *LCI);
248
249 // If there are expansion subviews, we want to highlight the first one.
250 unsigned ExpansionColumn = 0;
251 if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
252 getOptions().Colors)
253 ExpansionColumn = NextESV->getStartCol();
254
255 // Display the source code for the current line.
256 renderLine(OS, L: {*LI, LI.line_number()}, LCS: *LCI, ExpansionCol: ExpansionColumn, ViewDepth);
257
258 // Show the region markers.
259 if (shouldRenderRegionMarkers(LCS: *LCI))
260 renderRegionMarkers(OS, Line: *LCI, ViewDepth);
261
262 // Show the expansions, instantiations, and branches for this line.
263 bool RenderedSubView = false;
264 for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
265 ++NextESV) {
266 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
267
268 // Re-render the current line and highlight the expansion range for
269 // this subview.
270 if (RenderedSubView) {
271 ExpansionColumn = NextESV->getStartCol();
272 renderExpansionSite(OS, L: {*LI, LI.line_number()}, LCS: *LCI, ExpansionCol: ExpansionColumn,
273 ViewDepth);
274 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
275 }
276
277 renderExpansionView(OS, ESV&: *NextESV, ViewDepth: ViewDepth + 1);
278 RenderedSubView = true;
279 }
280 for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
281 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
282 renderInstantiationView(OS, ISV&: *NextISV, ViewDepth: ViewDepth + 1);
283 RenderedSubView = true;
284 }
285 for (; NextBRV != EndBRV && NextBRV->Line == LI.line_number(); ++NextBRV) {
286 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
287 renderBranchView(OS, BRV&: *NextBRV, ViewDepth: ViewDepth + 1);
288 RenderedSubView = true;
289 }
290 for (; NextMSV != EndMSV && NextMSV->Line == LI.line_number(); ++NextMSV) {
291 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
292 renderMCDCView(OS, BRV&: *NextMSV, ViewDepth: ViewDepth + 1);
293 RenderedSubView = true;
294 }
295 if (RenderedSubView)
296 renderViewDivider(OS, ViewDepth: ViewDepth + 1);
297 renderLineSuffix(OS, ViewDepth);
298 }
299
300 renderViewFooter(OS);
301}
302

source code of llvm/tools/llvm-cov/SourceCoverageView.cpp