1e82d89ccSAlex Lorenz //===- SourceCoverageView.cpp - Code coverage view for source code --------===//
2e82d89ccSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e82d89ccSAlex Lorenz //
7e82d89ccSAlex Lorenz //===----------------------------------------------------------------------===//
8ee5a5e9bSVedant Kumar ///
9ee5a5e9bSVedant Kumar /// \file This class implements rendering for code coverage of source code.
10ee5a5e9bSVedant Kumar ///
11e82d89ccSAlex Lorenz //===----------------------------------------------------------------------===//
12e82d89ccSAlex Lorenz 
13e82d89ccSAlex Lorenz #include "SourceCoverageView.h"
144c01092aSVedant Kumar #include "SourceCoverageViewHTML.h"
15f9151b93SVedant Kumar #include "SourceCoverageViewText.h"
16e82d89ccSAlex Lorenz #include "llvm/ADT/SmallString.h"
17d0ceebf1SJustin Bogner #include "llvm/ADT/StringExtras.h"
187937ef37SVedant Kumar #include "llvm/Support/FileSystem.h"
19e82d89ccSAlex Lorenz #include "llvm/Support/LineIterator.h"
207937ef37SVedant Kumar #include "llvm/Support/Path.h"
21e82d89ccSAlex Lorenz 
22e82d89ccSAlex Lorenz using namespace llvm;
23e82d89ccSAlex Lorenz 
operator ()(raw_ostream * OS) const249cbad2c2SVedant Kumar void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
259cbad2c2SVedant Kumar   if (OS == &outs())
269cbad2c2SVedant Kumar     return;
279cbad2c2SVedant Kumar   delete OS;
289cbad2c2SVedant Kumar }
299cbad2c2SVedant Kumar 
getOutputPath(StringRef Path,StringRef Extension,bool InToplevel,bool Relative) const309cbad2c2SVedant Kumar std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
31aae0ba70SVedant Kumar                                            bool InToplevel,
32aae0ba70SVedant Kumar                                            bool Relative) const {
3316a0de2eSJordan Rupprecht   assert(!Extension.empty() && "The file extension may not be empty");
349cbad2c2SVedant Kumar 
35d6d192cdSVedant Kumar   SmallString<256> FullPath;
36d6d192cdSVedant Kumar 
37d6d192cdSVedant Kumar   if (!Relative)
38d6d192cdSVedant Kumar     FullPath.append(Opts.ShowOutputDirectory);
39d6d192cdSVedant Kumar 
409cbad2c2SVedant Kumar   if (!InToplevel)
419cbad2c2SVedant Kumar     sys::path::append(FullPath, getCoverageDir());
429cbad2c2SVedant Kumar 
434a54abeaSVedant Kumar   SmallString<256> ParentPath = sys::path::parent_path(Path);
44*435a5a36SKazu Hirata   sys::path::remove_dots(ParentPath, /*remove_dot_dot=*/true);
454a54abeaSVedant Kumar   sys::path::append(FullPath, sys::path::relative_path(ParentPath));
469cbad2c2SVedant Kumar 
479cbad2c2SVedant Kumar   auto PathFilename = (sys::path::filename(Path) + "." + Extension).str();
489cbad2c2SVedant Kumar   sys::path::append(FullPath, PathFilename);
4976eb219cSYing Yi   sys::path::native(FullPath);
509cbad2c2SVedant Kumar 
51adcd0268SBenjamin Kramer   return std::string(FullPath.str());
529cbad2c2SVedant Kumar }
539cbad2c2SVedant Kumar 
549cbad2c2SVedant Kumar Expected<CoveragePrinter::OwnedStream>
createOutputStream(StringRef Path,StringRef Extension,bool InToplevel) const559cbad2c2SVedant Kumar CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
56aae0ba70SVedant Kumar                                     bool InToplevel) const {
579cbad2c2SVedant Kumar   if (!Opts.hasOutputDirectory())
589cbad2c2SVedant Kumar     return OwnedStream(&outs());
599cbad2c2SVedant Kumar 
60d6d192cdSVedant Kumar   std::string FullPath = getOutputPath(Path, Extension, InToplevel, false);
619cbad2c2SVedant Kumar 
629cbad2c2SVedant Kumar   auto ParentDir = sys::path::parent_path(FullPath);
639cbad2c2SVedant Kumar   if (auto E = sys::fs::create_directories(ParentDir))
649cbad2c2SVedant Kumar     return errorCodeToError(E);
659cbad2c2SVedant Kumar 
669cbad2c2SVedant Kumar   std::error_code E;
671f67a3cbSZachary Turner   raw_ostream *RawStream =
681f67a3cbSZachary Turner       new raw_fd_ostream(FullPath, E, sys::fs::FA_Read | sys::fs::FA_Write);
699cbad2c2SVedant Kumar   auto OS = CoveragePrinter::OwnedStream(RawStream);
709cbad2c2SVedant Kumar   if (E)
719cbad2c2SVedant Kumar     return errorCodeToError(E);
72c55cf4afSBill Wendling   return std::move(OS);
739cbad2c2SVedant Kumar }
749cbad2c2SVedant Kumar 
759cbad2c2SVedant Kumar std::unique_ptr<CoveragePrinter>
create(const CoverageViewOptions & Opts)769cbad2c2SVedant Kumar CoveragePrinter::create(const CoverageViewOptions &Opts) {
779cbad2c2SVedant Kumar   switch (Opts.Format) {
789cbad2c2SVedant Kumar   case CoverageViewOptions::OutputFormat::Text:
790eaee545SJonas Devlieghere     return std::make_unique<CoveragePrinterText>(Opts);
804c01092aSVedant Kumar   case CoverageViewOptions::OutputFormat::HTML:
810eaee545SJonas Devlieghere     return std::make_unique<CoveragePrinterHTML>(Opts);
82b2091c93SMax Moroz   case CoverageViewOptions::OutputFormat::Lcov:
83b2091c93SMax Moroz     // Unreachable because CodeCoverage.cpp should terminate with an error
84b2091c93SMax Moroz     // before we get here.
85b2091c93SMax Moroz     llvm_unreachable("Lcov format is not supported!");
869cbad2c2SVedant Kumar   }
870fecee9cSSimon Pilgrim   llvm_unreachable("Unknown coverage output format!");
889cbad2c2SVedant Kumar }
899cbad2c2SVedant Kumar 
getFirstUncoveredLineNo()90d36b47c4SYing Yi unsigned SourceCoverageView::getFirstUncoveredLineNo() {
91e955f618SVedant Kumar   const auto MinSegIt = find_if(CoverageInfo, [](const CoverageSegment &S) {
9225710a66SVedant Kumar     return S.HasCount && S.Count == 0;
93d36b47c4SYing Yi   });
9425710a66SVedant Kumar 
95d36b47c4SYing Yi   // There is no uncovered line, return zero.
9625710a66SVedant Kumar   if (MinSegIt == CoverageInfo.end())
97d36b47c4SYing Yi     return 0;
9825710a66SVedant Kumar 
9925710a66SVedant Kumar   return (*MinSegIt).Line;
100d36b47c4SYing Yi }
101d36b47c4SYing Yi 
formatCount(uint64_t N)102f9151b93SVedant Kumar std::string SourceCoverageView::formatCount(uint64_t N) {
103d0ceebf1SJustin Bogner   std::string Number = utostr(N);
104d0ceebf1SJustin Bogner   int Len = Number.size();
105d0ceebf1SJustin Bogner   if (Len <= 3)
106d0ceebf1SJustin Bogner     return Number;
107d0ceebf1SJustin Bogner   int IntLen = Len % 3 == 0 ? 3 : Len % 3;
108d0ceebf1SJustin Bogner   std::string Result(Number.data(), IntLen);
109d0ceebf1SJustin Bogner   if (IntLen != 3) {
110d0ceebf1SJustin Bogner     Result.push_back('.');
111d0ceebf1SJustin Bogner     Result += Number.substr(IntLen, 3 - IntLen);
112d0ceebf1SJustin Bogner   }
113d0ceebf1SJustin Bogner   Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
114d0ceebf1SJustin Bogner   return Result;
115d0ceebf1SJustin Bogner }
116d0ceebf1SJustin Bogner 
shouldRenderRegionMarkers(const LineCoverageStats & LCS) const1178d74cb27SVedant Kumar bool SourceCoverageView::shouldRenderRegionMarkers(
11869597042SVedant Kumar     const LineCoverageStats &LCS) const {
119933b37f9SVedant Kumar   if (!getOptions().ShowRegionMarkers)
120933b37f9SVedant Kumar     return false;
121933b37f9SVedant Kumar 
12269597042SVedant Kumar   CoverageSegmentArray Segments = LCS.getLineSegments();
12369597042SVedant Kumar   if (Segments.empty())
12469597042SVedant Kumar     return false;
12569597042SVedant Kumar   for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
12669597042SVedant Kumar     const auto *CurSeg = Segments[I];
12769597042SVedant Kumar     if (!CurSeg->IsRegionEntry || CurSeg->Count == LCS.getExecutionCount())
12869597042SVedant Kumar       continue;
129933b37f9SVedant Kumar     return true;
13069597042SVedant Kumar   }
131933b37f9SVedant Kumar   return false;
1328d74cb27SVedant Kumar }
1338d74cb27SVedant Kumar 
hasSubViews() const1348d74cb27SVedant Kumar bool SourceCoverageView::hasSubViews() const {
1359f2967bcSAlan Phipps   return !ExpansionSubViews.empty() || !InstantiationSubViews.empty() ||
1369f2967bcSAlan Phipps          !BranchSubViews.empty();
1378d74cb27SVedant Kumar }
1388d74cb27SVedant Kumar 
1399cbad2c2SVedant Kumar std::unique_ptr<SourceCoverageView>
create(StringRef SourceName,const MemoryBuffer & File,const CoverageViewOptions & Options,CoverageData && CoverageInfo)1409cbad2c2SVedant Kumar SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
1419cbad2c2SVedant Kumar                            const CoverageViewOptions &Options,
142e955f618SVedant Kumar                            CoverageData &&CoverageInfo) {
1439cbad2c2SVedant Kumar   switch (Options.Format) {
1449cbad2c2SVedant Kumar   case CoverageViewOptions::OutputFormat::Text:
1450eaee545SJonas Devlieghere     return std::make_unique<SourceCoverageViewText>(
1460053c0b6SVedant Kumar         SourceName, File, Options, std::move(CoverageInfo));
1474c01092aSVedant Kumar   case CoverageViewOptions::OutputFormat::HTML:
1480eaee545SJonas Devlieghere     return std::make_unique<SourceCoverageViewHTML>(
1490053c0b6SVedant Kumar         SourceName, File, Options, std::move(CoverageInfo));
150b2091c93SMax Moroz   case CoverageViewOptions::OutputFormat::Lcov:
151b2091c93SMax Moroz     // Unreachable because CodeCoverage.cpp should terminate with an error
152b2091c93SMax Moroz     // before we get here.
153b2091c93SMax Moroz     llvm_unreachable("Lcov format is not supported!");
1547937ef37SVedant Kumar   }
1559cbad2c2SVedant Kumar   llvm_unreachable("Unknown coverage output format!");
1567937ef37SVedant Kumar }
1577937ef37SVedant Kumar 
getSourceName() const1580053c0b6SVedant Kumar std::string SourceCoverageView::getSourceName() const {
1590053c0b6SVedant Kumar   SmallString<128> SourceText(SourceName);
160*435a5a36SKazu Hirata   sys::path::remove_dots(SourceText, /*remove_dot_dot=*/true);
16124e91bd0SYing Yi   sys::path::native(SourceText);
162adcd0268SBenjamin Kramer   return std::string(SourceText.str());
1630053c0b6SVedant Kumar }
1640053c0b6SVedant Kumar 
addExpansion(const CounterMappingRegion & Region,std::unique_ptr<SourceCoverageView> View)165f9151b93SVedant Kumar void SourceCoverageView::addExpansion(
166e955f618SVedant Kumar     const CounterMappingRegion &Region,
167f9151b93SVedant Kumar     std::unique_ptr<SourceCoverageView> View) {
168f9151b93SVedant Kumar   ExpansionSubViews.emplace_back(Region, std::move(View));
169e82d89ccSAlex Lorenz }
170e82d89ccSAlex Lorenz 
addBranch(unsigned Line,ArrayRef<CountedRegion> Regions,std::unique_ptr<SourceCoverageView> View)1719f2967bcSAlan Phipps void SourceCoverageView::addBranch(unsigned Line,
1729f2967bcSAlan Phipps                                    ArrayRef<CountedRegion> Regions,
1739f2967bcSAlan Phipps                                    std::unique_ptr<SourceCoverageView> View) {
1749f2967bcSAlan Phipps   BranchSubViews.emplace_back(Line, Regions, std::move(View));
1759f2967bcSAlan Phipps }
1769f2967bcSAlan Phipps 
addInstantiation(StringRef FunctionName,unsigned Line,std::unique_ptr<SourceCoverageView> View)177f9151b93SVedant Kumar void SourceCoverageView::addInstantiation(
178f9151b93SVedant Kumar     StringRef FunctionName, unsigned Line,
179f9151b93SVedant Kumar     std::unique_ptr<SourceCoverageView> View) {
180f9151b93SVedant Kumar   InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
181e82d89ccSAlex Lorenz }
182e82d89ccSAlex Lorenz 
print(raw_ostream & OS,bool WholeFile,bool ShowSourceName,bool ShowTitle,unsigned ViewDepth)183f9151b93SVedant Kumar void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
184fa8ef35eSSean Eveson                                bool ShowSourceName, bool ShowTitle,
185fa8ef35eSSean Eveson                                unsigned ViewDepth) {
186fa8ef35eSSean Eveson   if (ShowTitle)
187b2edd11fSVedant Kumar     renderTitle(OS, "Coverage Report");
188e82d89ccSAlex Lorenz 
1898d74cb27SVedant Kumar   renderViewHeader(OS);
1908d74cb27SVedant Kumar 
19184dc971eSYing Yi   if (ShowSourceName)
192b1c174aaSVedant Kumar     renderSourceName(OS, WholeFile);
19384dc971eSYing Yi 
194408866caSVedant Kumar   renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
195408866caSVedant Kumar                     ViewDepth);
196b1c174aaSVedant Kumar 
1979f2967bcSAlan Phipps   // We need the expansions, instantiations, and branches sorted so we can go
1989f2967bcSAlan Phipps   // through them while we iterate lines.
199a5355a5eSFangrui Song   llvm::stable_sort(ExpansionSubViews);
200a5355a5eSFangrui Song   llvm::stable_sort(InstantiationSubViews);
2019f2967bcSAlan Phipps   llvm::stable_sort(BranchSubViews);
2025e1400a8SJustin Bogner   auto NextESV = ExpansionSubViews.begin();
2035e1400a8SJustin Bogner   auto EndESV = ExpansionSubViews.end();
2045e1400a8SJustin Bogner   auto NextISV = InstantiationSubViews.begin();
2055e1400a8SJustin Bogner   auto EndISV = InstantiationSubViews.end();
2069f2967bcSAlan Phipps   auto NextBRV = BranchSubViews.begin();
2079f2967bcSAlan Phipps   auto EndBRV = BranchSubViews.end();
2085e1400a8SJustin Bogner 
209fe357c00SJustin Bogner   // Get the coverage information for the file.
2101963f51fSVedant Kumar   auto StartSegment = CoverageInfo.begin();
211953e2407SJustin Bogner   auto EndSegment = CoverageInfo.end();
2121963f51fSVedant Kumar   LineCoverageIterator LCI{CoverageInfo, 1};
2131963f51fSVedant Kumar   LineCoverageIterator LCIEnd = LCI.getEnd();
214e82d89ccSAlex Lorenz 
2151963f51fSVedant Kumar   unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
2161963f51fSVedant Kumar   for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
2171963f51fSVedant Kumar        ++LI, ++LCI) {
218fe357c00SJustin Bogner     // If we aren't rendering the whole file, we need to filter out the prologue
219fe357c00SJustin Bogner     // and epilogue.
220fe357c00SJustin Bogner     if (!WholeFile) {
2211963f51fSVedant Kumar       if (LCI == LCIEnd)
222fe357c00SJustin Bogner         break;
22313ba23bbSJustin Bogner       else if (LI.line_number() < FirstLine)
224fe357c00SJustin Bogner         continue;
225e82d89ccSAlex Lorenz     }
226e82d89ccSAlex Lorenz 
227f9151b93SVedant Kumar     renderLinePrefix(OS, ViewDepth);
2281c4f588dSVedant Kumar     if (getOptions().ShowLineNumbers)
229fe357c00SJustin Bogner       renderLineNumberColumn(OS, LI.line_number());
230846b985aSVedant Kumar 
2316b1f5f89SYing Yi     if (getOptions().ShowLineStats)
2321963f51fSVedant Kumar       renderLineCoverageColumn(OS, *LCI);
233fe357c00SJustin Bogner 
234fe357c00SJustin Bogner     // If there are expansion subviews, we want to highlight the first one.
235fe357c00SJustin Bogner     unsigned ExpansionColumn = 0;
236fe357c00SJustin Bogner     if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
2371c4f588dSVedant Kumar         getOptions().Colors)
238fe357c00SJustin Bogner       ExpansionColumn = NextESV->getStartCol();
239fe357c00SJustin Bogner 
240e82d89ccSAlex Lorenz     // Display the source code for the current line.
24108a0a310SVedant Kumar     renderLine(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn, ViewDepth);
242e82d89ccSAlex Lorenz 
243e82d89ccSAlex Lorenz     // Show the region markers.
24469597042SVedant Kumar     if (shouldRenderRegionMarkers(*LCI))
24508a0a310SVedant Kumar       renderRegionMarkers(OS, *LCI, ViewDepth);
246e82d89ccSAlex Lorenz 
2479f2967bcSAlan Phipps     // Show the expansions, instantiations, and branches for this line.
2485e1400a8SJustin Bogner     bool RenderedSubView = false;
249fe357c00SJustin Bogner     for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
250fe357c00SJustin Bogner          ++NextESV) {
251f9151b93SVedant Kumar       renderViewDivider(OS, ViewDepth + 1);
252861a19c2SVedant Kumar 
253861a19c2SVedant Kumar       // Re-render the current line and highlight the expansion range for
254861a19c2SVedant Kumar       // this subview.
255861a19c2SVedant Kumar       if (RenderedSubView) {
256861a19c2SVedant Kumar         ExpansionColumn = NextESV->getStartCol();
25708a0a310SVedant Kumar         renderExpansionSite(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn,
25808a0a310SVedant Kumar                             ViewDepth);
259861a19c2SVedant Kumar         renderViewDivider(OS, ViewDepth + 1);
260861a19c2SVedant Kumar       }
261861a19c2SVedant Kumar 
262861a19c2SVedant Kumar       renderExpansionView(OS, *NextESV, ViewDepth + 1);
2635e1400a8SJustin Bogner       RenderedSubView = true;
2645e1400a8SJustin Bogner     }
265fe357c00SJustin Bogner     for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
266861a19c2SVedant Kumar       renderViewDivider(OS, ViewDepth + 1);
267f9151b93SVedant Kumar       renderInstantiationView(OS, *NextISV, ViewDepth + 1);
2685e1400a8SJustin Bogner       RenderedSubView = true;
2695e1400a8SJustin Bogner     }
2709f2967bcSAlan Phipps     for (; NextBRV != EndBRV && NextBRV->Line == LI.line_number(); ++NextBRV) {
2719f2967bcSAlan Phipps       renderViewDivider(OS, ViewDepth + 1);
2729f2967bcSAlan Phipps       renderBranchView(OS, *NextBRV, ViewDepth + 1);
2739f2967bcSAlan Phipps       RenderedSubView = true;
2749f2967bcSAlan Phipps     }
275f9151b93SVedant Kumar     if (RenderedSubView)
276f9151b93SVedant Kumar       renderViewDivider(OS, ViewDepth + 1);
2778d74cb27SVedant Kumar     renderLineSuffix(OS, ViewDepth);
278e82d89ccSAlex Lorenz   }
2798d74cb27SVedant Kumar 
2808d74cb27SVedant Kumar   renderViewFooter(OS);
281e82d89ccSAlex Lorenz }
282