SourceCoverageView.cpp 8.2 KB

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