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