1 //===- SourceCoverageView.cpp - Code coverage view for source code --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \file This class implements rendering for code coverage of source code.
12 //===----------------------------------------------------------------------===//
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"
25 void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
31 std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
33 bool Relative) const {
34 assert(Extension.size() && "The file extension may not be empty");
36 SmallString<256> FullPath;
39 FullPath.append(Opts.ShowOutputDirectory);
42 sys::path::append(FullPath, getCoverageDir());
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));
48 auto PathFilename = (sys::path::filename(Path) + "." + Extension).str();
49 sys::path::append(FullPath, PathFilename);
50 sys::path::native(FullPath);
52 return FullPath.str();
55 Expected<CoveragePrinter::OwnedStream>
56 CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
57 bool InToplevel) const {
58 if (!Opts.hasOutputDirectory())
59 return OwnedStream(&outs());
61 std::string FullPath = getOutputPath(Path, Extension, InToplevel, false);
63 auto ParentDir = sys::path::parent_path(FullPath);
64 if (auto E = sys::fs::create_directories(ParentDir))
65 return errorCodeToError(E);
68 raw_ostream *RawStream = new raw_fd_ostream(FullPath, E, sys::fs::F_RW);
69 auto OS = CoveragePrinter::OwnedStream(RawStream);
71 return errorCodeToError(E);
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);
83 llvm_unreachable("Unknown coverage output format!");
86 unsigned SourceCoverageView::getFirstUncoveredLineNo() {
87 const auto MinSegIt = find_if(CoverageInfo, [](const CoverageSegment &S) {
88 return S.HasCount && S.Count == 0;
91 // There is no uncovered line, return zero.
92 if (MinSegIt == CoverageInfo.end())
95 return (*MinSegIt).Line;
98 std::string SourceCoverageView::formatCount(uint64_t N) {
99 std::string Number = utostr(N);
100 int Len = Number.size();
103 int IntLen = Len % 3 == 0 ? 3 : Len % 3;
104 std::string Result(Number.data(), IntLen);
106 Result.push_back('.');
107 Result += Number.substr(IntLen, 3 - IntLen);
109 Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
113 bool SourceCoverageView::shouldRenderRegionMarkers(
114 const LineCoverageStats &LCS) const {
115 if (!getOptions().ShowRegionMarkers)
118 CoverageSegmentArray Segments = LCS.getLineSegments();
119 if (Segments.empty())
121 for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
122 const auto *CurSeg = Segments[I];
123 if (!CurSeg->IsRegionEntry || CurSeg->Count == LCS.getExecutionCount())
130 bool SourceCoverageView::hasSubViews() const {
131 return !ExpansionSubViews.empty() || !InstantiationSubViews.empty();
134 std::unique_ptr<SourceCoverageView>
135 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
136 const CoverageViewOptions &Options,
137 CoverageData &&CoverageInfo) {
138 switch (Options.Format) {
139 case CoverageViewOptions::OutputFormat::Text:
140 return llvm::make_unique<SourceCoverageViewText>(
141 SourceName, File, Options, std::move(CoverageInfo));
142 case CoverageViewOptions::OutputFormat::HTML:
143 return llvm::make_unique<SourceCoverageViewHTML>(
144 SourceName, File, Options, std::move(CoverageInfo));
146 llvm_unreachable("Unknown coverage output format!");
149 std::string SourceCoverageView::getSourceName() const {
150 SmallString<128> SourceText(SourceName);
151 sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true);
152 sys::path::native(SourceText);
153 return SourceText.str();
156 void SourceCoverageView::addExpansion(
157 const CounterMappingRegion &Region,
158 std::unique_ptr<SourceCoverageView> View) {
159 ExpansionSubViews.emplace_back(Region, std::move(View));
162 void SourceCoverageView::addInstantiation(
163 StringRef FunctionName, unsigned Line,
164 std::unique_ptr<SourceCoverageView> View) {
165 InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
168 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
169 bool ShowSourceName, bool ShowTitle,
170 unsigned ViewDepth) {
172 renderTitle(OS, "Coverage Report");
174 renderViewHeader(OS);
177 renderSourceName(OS, WholeFile);
179 renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
182 // We need the expansions and instantiations sorted so we can go through them
183 // while we iterate lines.
184 std::stable_sort(ExpansionSubViews.begin(), ExpansionSubViews.end());
185 std::stable_sort(InstantiationSubViews.begin(), InstantiationSubViews.end());
186 auto NextESV = ExpansionSubViews.begin();
187 auto EndESV = ExpansionSubViews.end();
188 auto NextISV = InstantiationSubViews.begin();
189 auto EndISV = InstantiationSubViews.end();
191 // Get the coverage information for the file.
192 auto StartSegment = CoverageInfo.begin();
193 auto EndSegment = CoverageInfo.end();
194 LineCoverageIterator LCI{CoverageInfo, 1};
195 LineCoverageIterator LCIEnd = LCI.getEnd();
197 unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
198 for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
200 // If we aren't rendering the whole file, we need to filter out the prologue
205 else if (LI.line_number() < FirstLine)
209 renderLinePrefix(OS, ViewDepth);
210 if (getOptions().ShowLineNumbers)
211 renderLineNumberColumn(OS, LI.line_number());
213 if (getOptions().ShowLineStats)
214 renderLineCoverageColumn(OS, *LCI);
216 // If there are expansion subviews, we want to highlight the first one.
217 unsigned ExpansionColumn = 0;
218 if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
220 ExpansionColumn = NextESV->getStartCol();
222 // Display the source code for the current line.
223 renderLine(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn, ViewDepth);
225 // Show the region markers.
226 if (shouldRenderRegionMarkers(*LCI))
227 renderRegionMarkers(OS, *LCI, ViewDepth);
229 // Show the expansions and instantiations for this line.
230 bool RenderedSubView = false;
231 for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
233 renderViewDivider(OS, ViewDepth + 1);
235 // Re-render the current line and highlight the expansion range for
237 if (RenderedSubView) {
238 ExpansionColumn = NextESV->getStartCol();
239 renderExpansionSite(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn,
241 renderViewDivider(OS, ViewDepth + 1);
244 renderExpansionView(OS, *NextESV, ViewDepth + 1);
245 RenderedSubView = true;
247 for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
248 renderViewDivider(OS, ViewDepth + 1);
249 renderInstantiationView(OS, *NextISV, ViewDepth + 1);
250 RenderedSubView = true;
253 renderViewDivider(OS, ViewDepth + 1);
254 renderLineSuffix(OS, ViewDepth);
257 renderViewFooter(OS);