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