SourceCoverageView.cpp 8.8 KB

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