SourceCoverageView.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. #include "SourceCoverageView.h"
  13. #include "SourceCoverageViewHTML.h"
  14. #include "SourceCoverageViewText.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/LineIterator.h"
  19. #include "llvm/Support/Path.h"
  20. using namespace llvm;
  21. void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const {
  22. if (OS == &outs())
  23. return;
  24. delete OS;
  25. }
  26. std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension,
  27. bool InToplevel,
  28. bool Relative) const {
  29. assert(!Extension.empty() && "The file extension may not be empty");
  30. SmallString<256> FullPath;
  31. if (!Relative)
  32. FullPath.append(Opts.ShowOutputDirectory);
  33. if (!InToplevel)
  34. sys::path::append(FullPath, getCoverageDir());
  35. SmallString<256> ParentPath = sys::path::parent_path(Path);
  36. sys::path::remove_dots(ParentPath, /*remove_dot_dot=*/true);
  37. sys::path::append(FullPath, sys::path::relative_path(ParentPath));
  38. auto PathFilename = (sys::path::filename(Path) + "." + Extension).str();
  39. sys::path::append(FullPath, PathFilename);
  40. sys::path::native(FullPath);
  41. return std::string(FullPath.str());
  42. }
  43. Expected<CoveragePrinter::OwnedStream>
  44. CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension,
  45. bool InToplevel) const {
  46. if (!Opts.hasOutputDirectory())
  47. return OwnedStream(&outs());
  48. std::string FullPath = getOutputPath(Path, Extension, InToplevel, false);
  49. auto ParentDir = sys::path::parent_path(FullPath);
  50. if (auto E = sys::fs::create_directories(ParentDir))
  51. return errorCodeToError(E);
  52. std::error_code E;
  53. raw_ostream *RawStream =
  54. new raw_fd_ostream(FullPath, E, sys::fs::FA_Read | sys::fs::FA_Write);
  55. auto OS = CoveragePrinter::OwnedStream(RawStream);
  56. if (E)
  57. return errorCodeToError(E);
  58. return std::move(OS);
  59. }
  60. std::unique_ptr<CoveragePrinter>
  61. CoveragePrinter::create(const CoverageViewOptions &Opts) {
  62. switch (Opts.Format) {
  63. case CoverageViewOptions::OutputFormat::Text:
  64. return std::make_unique<CoveragePrinterText>(Opts);
  65. case CoverageViewOptions::OutputFormat::HTML:
  66. return std::make_unique<CoveragePrinterHTML>(Opts);
  67. case CoverageViewOptions::OutputFormat::Lcov:
  68. // Unreachable because CodeCoverage.cpp should terminate with an error
  69. // before we get here.
  70. llvm_unreachable("Lcov format is not supported!");
  71. }
  72. llvm_unreachable("Unknown coverage output format!");
  73. }
  74. unsigned SourceCoverageView::getFirstUncoveredLineNo() {
  75. const auto MinSegIt = find_if(CoverageInfo, [](const CoverageSegment &S) {
  76. return S.HasCount && S.Count == 0;
  77. });
  78. // There is no uncovered line, return zero.
  79. if (MinSegIt == CoverageInfo.end())
  80. return 0;
  81. return (*MinSegIt).Line;
  82. }
  83. std::string SourceCoverageView::formatCount(uint64_t N) {
  84. std::string Number = utostr(N);
  85. int Len = Number.size();
  86. if (Len <= 3)
  87. return Number;
  88. int IntLen = Len % 3 == 0 ? 3 : Len % 3;
  89. std::string Result(Number.data(), IntLen);
  90. if (IntLen != 3) {
  91. Result.push_back('.');
  92. Result += Number.substr(IntLen, 3 - IntLen);
  93. }
  94. Result.push_back(" kMGTPEZY"[(Len - 1) / 3]);
  95. return Result;
  96. }
  97. bool SourceCoverageView::shouldRenderRegionMarkers(
  98. const LineCoverageStats &LCS) const {
  99. if (!getOptions().ShowRegionMarkers)
  100. return false;
  101. CoverageSegmentArray Segments = LCS.getLineSegments();
  102. if (Segments.empty())
  103. return false;
  104. for (unsigned I = 0, E = Segments.size() - 1; I < E; ++I) {
  105. const auto *CurSeg = Segments[I];
  106. if (!CurSeg->IsRegionEntry || CurSeg->Count == LCS.getExecutionCount())
  107. continue;
  108. return true;
  109. }
  110. return false;
  111. }
  112. bool SourceCoverageView::hasSubViews() const {
  113. return !ExpansionSubViews.empty() || !InstantiationSubViews.empty() ||
  114. !BranchSubViews.empty();
  115. }
  116. std::unique_ptr<SourceCoverageView>
  117. SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File,
  118. const CoverageViewOptions &Options,
  119. CoverageData &&CoverageInfo) {
  120. switch (Options.Format) {
  121. case CoverageViewOptions::OutputFormat::Text:
  122. return std::make_unique<SourceCoverageViewText>(
  123. SourceName, File, Options, std::move(CoverageInfo));
  124. case CoverageViewOptions::OutputFormat::HTML:
  125. return std::make_unique<SourceCoverageViewHTML>(
  126. SourceName, File, Options, std::move(CoverageInfo));
  127. case CoverageViewOptions::OutputFormat::Lcov:
  128. // Unreachable because CodeCoverage.cpp should terminate with an error
  129. // before we get here.
  130. llvm_unreachable("Lcov format is not supported!");
  131. }
  132. llvm_unreachable("Unknown coverage output format!");
  133. }
  134. std::string SourceCoverageView::getSourceName() const {
  135. SmallString<128> SourceText(SourceName);
  136. sys::path::remove_dots(SourceText, /*remove_dot_dot=*/true);
  137. sys::path::native(SourceText);
  138. return std::string(SourceText.str());
  139. }
  140. void SourceCoverageView::addExpansion(
  141. const CounterMappingRegion &Region,
  142. std::unique_ptr<SourceCoverageView> View) {
  143. ExpansionSubViews.emplace_back(Region, std::move(View));
  144. }
  145. void SourceCoverageView::addBranch(unsigned Line,
  146. ArrayRef<CountedRegion> Regions,
  147. std::unique_ptr<SourceCoverageView> View) {
  148. BranchSubViews.emplace_back(Line, Regions, std::move(View));
  149. }
  150. void SourceCoverageView::addInstantiation(
  151. StringRef FunctionName, unsigned Line,
  152. std::unique_ptr<SourceCoverageView> View) {
  153. InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View));
  154. }
  155. void SourceCoverageView::print(raw_ostream &OS, bool WholeFile,
  156. bool ShowSourceName, bool ShowTitle,
  157. unsigned ViewDepth) {
  158. if (ShowTitle)
  159. renderTitle(OS, "Coverage Report");
  160. renderViewHeader(OS);
  161. if (ShowSourceName)
  162. renderSourceName(OS, WholeFile);
  163. renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(),
  164. ViewDepth);
  165. // We need the expansions, instantiations, and branches sorted so we can go
  166. // through them while we iterate lines.
  167. llvm::stable_sort(ExpansionSubViews);
  168. llvm::stable_sort(InstantiationSubViews);
  169. llvm::stable_sort(BranchSubViews);
  170. auto NextESV = ExpansionSubViews.begin();
  171. auto EndESV = ExpansionSubViews.end();
  172. auto NextISV = InstantiationSubViews.begin();
  173. auto EndISV = InstantiationSubViews.end();
  174. auto NextBRV = BranchSubViews.begin();
  175. auto EndBRV = BranchSubViews.end();
  176. // Get the coverage information for the file.
  177. auto StartSegment = CoverageInfo.begin();
  178. auto EndSegment = CoverageInfo.end();
  179. LineCoverageIterator LCI{CoverageInfo, 1};
  180. LineCoverageIterator LCIEnd = LCI.getEnd();
  181. unsigned FirstLine = StartSegment != EndSegment ? StartSegment->Line : 0;
  182. for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof();
  183. ++LI, ++LCI) {
  184. // If we aren't rendering the whole file, we need to filter out the prologue
  185. // and epilogue.
  186. if (!WholeFile) {
  187. if (LCI == LCIEnd)
  188. break;
  189. else if (LI.line_number() < FirstLine)
  190. continue;
  191. }
  192. renderLinePrefix(OS, ViewDepth);
  193. if (getOptions().ShowLineNumbers)
  194. renderLineNumberColumn(OS, LI.line_number());
  195. if (getOptions().ShowLineStats)
  196. renderLineCoverageColumn(OS, *LCI);
  197. // If there are expansion subviews, we want to highlight the first one.
  198. unsigned ExpansionColumn = 0;
  199. if (NextESV != EndESV && NextESV->getLine() == LI.line_number() &&
  200. getOptions().Colors)
  201. ExpansionColumn = NextESV->getStartCol();
  202. // Display the source code for the current line.
  203. renderLine(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn, ViewDepth);
  204. // Show the region markers.
  205. if (shouldRenderRegionMarkers(*LCI))
  206. renderRegionMarkers(OS, *LCI, ViewDepth);
  207. // Show the expansions, instantiations, and branches for this line.
  208. bool RenderedSubView = false;
  209. for (; NextESV != EndESV && NextESV->getLine() == LI.line_number();
  210. ++NextESV) {
  211. renderViewDivider(OS, ViewDepth + 1);
  212. // Re-render the current line and highlight the expansion range for
  213. // this subview.
  214. if (RenderedSubView) {
  215. ExpansionColumn = NextESV->getStartCol();
  216. renderExpansionSite(OS, {*LI, LI.line_number()}, *LCI, ExpansionColumn,
  217. ViewDepth);
  218. renderViewDivider(OS, ViewDepth + 1);
  219. }
  220. renderExpansionView(OS, *NextESV, ViewDepth + 1);
  221. RenderedSubView = true;
  222. }
  223. for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) {
  224. renderViewDivider(OS, ViewDepth + 1);
  225. renderInstantiationView(OS, *NextISV, ViewDepth + 1);
  226. RenderedSubView = true;
  227. }
  228. for (; NextBRV != EndBRV && NextBRV->Line == LI.line_number(); ++NextBRV) {
  229. renderViewDivider(OS, ViewDepth + 1);
  230. renderBranchView(OS, *NextBRV, ViewDepth + 1);
  231. RenderedSubView = true;
  232. }
  233. if (RenderedSubView)
  234. renderViewDivider(OS, ViewDepth + 1);
  235. renderLineSuffix(OS, ViewDepth);
  236. }
  237. renderViewFooter(OS);
  238. }