llvm-cov: Use ArrayRef::slice (NFC)
[oota-llvm.git] / tools / llvm-cov / SourceCoverageView.cpp
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 // This class implements rendering for code coverage of source code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SourceCoverageView.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/Support/LineIterator.h"
17
18 using namespace llvm;
19
20 void SourceCoverageView::renderLine(raw_ostream &OS, StringRef Line,
21                                     ArrayRef<HighlightRange> Ranges) {
22   if (Ranges.empty()) {
23     OS << Line << "\n";
24     return;
25   }
26   if (Line.empty())
27     Line = " ";
28
29   unsigned PrevColumnStart = 0;
30   unsigned Start = 1;
31   for (const auto &Range : Ranges) {
32     if (PrevColumnStart == Range.ColumnStart)
33       continue;
34
35     // Show the unhighlighted part
36     unsigned ColumnStart = PrevColumnStart = Range.ColumnStart;
37     OS << Line.substr(Start - 1, ColumnStart - Start);
38
39     // Show the highlighted part
40     auto Color = Range.Kind == HighlightRange::NotCovered ? raw_ostream::RED
41                                                           : raw_ostream::CYAN;
42     OS.changeColor(Color, false, true);
43     unsigned ColumnEnd = std::min(Range.ColumnEnd, (unsigned)Line.size() + 1);
44     OS << Line.substr(ColumnStart - 1, ColumnEnd - ColumnStart);
45     Start = ColumnEnd;
46     OS.resetColor();
47   }
48
49   // Show the rest of the line
50   OS << Line.substr(Start - 1, Line.size() - Start + 1);
51   OS << "\n";
52 }
53
54 void SourceCoverageView::renderOffset(raw_ostream &OS, unsigned I) {
55   for (unsigned J = 0; J < I; ++J)
56     OS << "  |";
57 }
58
59 void SourceCoverageView::renderViewDivider(unsigned Offset, unsigned Length,
60                                            raw_ostream &OS) {
61   for (unsigned J = 1; J < Offset; ++J)
62     OS << "  |";
63   if (Offset != 0)
64     OS.indent(2);
65   for (unsigned I = 0; I < Length; ++I)
66     OS << "-";
67 }
68
69 void
70 SourceCoverageView::renderLineCoverageColumn(raw_ostream &OS,
71                                              const LineCoverageInfo &Line) {
72   if (!Line.isMapped()) {
73     OS.indent(LineCoverageColumnWidth) << '|';
74     return;
75   }
76   SmallString<32> Buffer;
77   raw_svector_ostream BufferOS(Buffer);
78   BufferOS << Line.ExecutionCount;
79   auto Str = BufferOS.str();
80   // Trim
81   Str = Str.substr(0, std::min(Str.size(), (size_t)LineCoverageColumnWidth));
82   // Align to the right
83   OS.indent(LineCoverageColumnWidth - Str.size());
84   colored_ostream(OS, raw_ostream::MAGENTA,
85                   Line.hasMultipleRegions() && Options.Colors)
86       << Str;
87   OS << '|';
88 }
89
90 void SourceCoverageView::renderLineNumberColumn(raw_ostream &OS,
91                                                 unsigned LineNo) {
92   SmallString<32> Buffer;
93   raw_svector_ostream BufferOS(Buffer);
94   BufferOS << LineNo;
95   auto Str = BufferOS.str();
96   // Trim and align to the right
97   Str = Str.substr(0, std::min(Str.size(), (size_t)LineNumberColumnWidth));
98   OS.indent(LineNumberColumnWidth - Str.size()) << Str << '|';
99 }
100
101 void SourceCoverageView::renderRegionMarkers(raw_ostream &OS,
102                                              ArrayRef<RegionMarker> Regions) {
103   SmallString<32> Buffer;
104   raw_svector_ostream BufferOS(Buffer);
105
106   unsigned PrevColumn = 1;
107   for (const auto &Region : Regions) {
108     // Skip to the new region
109     if (Region.Column > PrevColumn)
110       OS.indent(Region.Column - PrevColumn);
111     PrevColumn = Region.Column + 1;
112     BufferOS << Region.ExecutionCount;
113     StringRef Str = BufferOS.str();
114     // Trim the execution count
115     Str = Str.substr(0, std::min(Str.size(), (size_t)7));
116     PrevColumn += Str.size();
117     OS << '^' << Str;
118     Buffer.clear();
119   }
120   OS << "\n";
121 }
122
123 /// \brief Insert a new highlighting range into the line's highlighting ranges
124 /// Return line's new highlighting ranges in result.
125 static void insertHighlightRange(
126     ArrayRef<SourceCoverageView::HighlightRange> Ranges,
127     SourceCoverageView::HighlightRange RangeToInsert,
128     SmallVectorImpl<SourceCoverageView::HighlightRange> &Result) {
129   Result.clear();
130   size_t I = 0;
131   auto E = Ranges.size();
132   for (; I < E; ++I) {
133     if (RangeToInsert.ColumnStart < Ranges[I].ColumnEnd) {
134       const auto &Range = Ranges[I];
135       bool NextRangeContainsInserted = false;
136       // If the next range starts before the inserted range, move the end of the
137       // next range to the start of the inserted range.
138       if (Range.ColumnStart < RangeToInsert.ColumnStart) {
139         if (RangeToInsert.ColumnStart != Range.ColumnStart)
140           Result.push_back(SourceCoverageView::HighlightRange(
141               Range.Line, Range.ColumnStart, RangeToInsert.ColumnStart,
142               Range.Kind));
143         // If the next range also ends after the inserted range, keep this range
144         // and create a new range that starts at the inserted range and ends
145         // at the next range later.
146         if (Range.ColumnEnd > RangeToInsert.ColumnEnd)
147           NextRangeContainsInserted = true;
148       }
149       if (!NextRangeContainsInserted) {
150         ++I;
151         // Ignore ranges that are contained in inserted range
152         while (I < E && RangeToInsert.contains(Ranges[I]))
153           ++I;
154       }
155       break;
156     }
157     Result.push_back(Ranges[I]);
158   }
159   Result.push_back(RangeToInsert);
160   // If the next range starts before the inserted range end, move the start
161   // of the next range to the end of the inserted range.
162   if (I < E && Ranges[I].ColumnStart < RangeToInsert.ColumnEnd) {
163     const auto &Range = Ranges[I];
164     if (RangeToInsert.ColumnEnd != Range.ColumnEnd)
165       Result.push_back(SourceCoverageView::HighlightRange(
166           Range.Line, RangeToInsert.ColumnEnd, Range.ColumnEnd, Range.Kind));
167     ++I;
168   }
169   // Add the remaining ranges that are located after the inserted range
170   for (; I < E; ++I)
171     Result.push_back(Ranges[I]);
172 }
173
174 void SourceCoverageView::sortChildren() {
175   for (auto &I : Children)
176     I->sortChildren();
177   std::sort(Children.begin(), Children.end(),
178             [](const std::unique_ptr<SourceCoverageView> &LHS,
179                const std::unique_ptr<SourceCoverageView> &RHS) {
180     return LHS->ExpansionRegion < RHS->ExpansionRegion;
181   });
182 }
183
184 SourceCoverageView::HighlightRange
185 SourceCoverageView::getExpansionHighlightRange() const {
186   return HighlightRange(ExpansionRegion.LineStart, ExpansionRegion.ColumnStart,
187                         ExpansionRegion.ColumnEnd, HighlightRange::Expanded);
188 }
189
190 template <typename T>
191 ArrayRef<T> gatherLineItems(size_t &CurrentIdx, const std::vector<T> &Items,
192                             unsigned LineNo) {
193   auto PrevIdx = CurrentIdx;
194   auto E = Items.size();
195   while (CurrentIdx < E && Items[CurrentIdx].Line == LineNo)
196     ++CurrentIdx;
197   return ArrayRef<T>(Items.data() + PrevIdx, CurrentIdx - PrevIdx);
198 }
199
200 ArrayRef<std::unique_ptr<SourceCoverageView>>
201 gatherLineSubViews(size_t &CurrentIdx,
202                    ArrayRef<std::unique_ptr<SourceCoverageView>> Items,
203                    unsigned LineNo) {
204   auto PrevIdx = CurrentIdx;
205   auto E = Items.size();
206   while (CurrentIdx < E &&
207          Items[CurrentIdx]->getSubViewsExpansionLine() == LineNo)
208     ++CurrentIdx;
209   return Items.slice(PrevIdx, CurrentIdx);
210 }
211
212 void SourceCoverageView::render(raw_ostream &OS, unsigned Offset) {
213   // Make sure that the children are in sorted order.
214   sortChildren();
215
216   SmallVector<HighlightRange, 8> AdjustedLineHighlightRanges;
217   size_t CurrentChild = 0;
218   size_t CurrentHighlightRange = 0;
219   size_t CurrentRegionMarker = 0;
220
221   line_iterator Lines(File);
222   // Advance the line iterator to the first line.
223   while (Lines.line_number() < LineStart)
224     ++Lines;
225
226   // The width of the leading columns
227   unsigned CombinedColumnWidth =
228       (Options.ShowLineStats ? LineCoverageColumnWidth + 1 : 0) +
229       (Options.ShowLineNumbers ? LineNumberColumnWidth + 1 : 0);
230   // The width of the line that is used to divide between the view and the
231   // subviews.
232   unsigned DividerWidth = CombinedColumnWidth + 4;
233
234   for (size_t I = 0; I < LineCount; ++I) {
235     unsigned LineNo = I + LineStart;
236
237     // Gather the child subviews that are visible on this line.
238     auto LineSubViews = gatherLineSubViews(CurrentChild, Children, LineNo);
239
240     renderOffset(OS, Offset);
241     if (Options.ShowLineStats)
242       renderLineCoverageColumn(OS, LineStats[I]);
243     if (Options.ShowLineNumbers)
244       renderLineNumberColumn(OS, LineNo);
245
246     // Gather highlighting ranges.
247     auto LineHighlightRanges =
248         gatherLineItems(CurrentHighlightRange, HighlightRanges, LineNo);
249     auto LineRanges = LineHighlightRanges;
250     // Highlight the expansion range if there is an expansion subview on this
251     // line.
252     if (!LineSubViews.empty() && LineSubViews.front()->isExpansionSubView() &&
253         Options.Colors) {
254       insertHighlightRange(LineHighlightRanges,
255                            LineSubViews.front()->getExpansionHighlightRange(),
256                            AdjustedLineHighlightRanges);
257       LineRanges = AdjustedLineHighlightRanges;
258     }
259
260     // Display the source code for the current line.
261     StringRef Line = *Lines;
262     // Check if the line is empty, as line_iterator skips blank lines.
263     if (LineNo < Lines.line_number())
264       Line = "";
265     else if (!Lines.is_at_eof())
266       ++Lines;
267     renderLine(OS, Line, LineRanges);
268
269     // Show the region markers.
270     bool ShowMarkers = !Options.ShowLineStatsOrRegionMarkers ||
271                        LineStats[I].hasMultipleRegions();
272     auto LineMarkers = gatherLineItems(CurrentRegionMarker, Markers, LineNo);
273     if (ShowMarkers && !LineMarkers.empty()) {
274       renderOffset(OS, Offset);
275       OS.indent(CombinedColumnWidth);
276       renderRegionMarkers(OS, LineMarkers);
277     }
278
279     // Show the line's expanded child subviews.
280     bool FirstChildExpansion = true;
281     if (LineSubViews.empty())
282       continue;
283     unsigned NewOffset = Offset + 1;
284     renderViewDivider(NewOffset, DividerWidth, OS);
285     OS << "\n";
286     for (const auto &Child : LineSubViews) {
287       // If this subview shows a function instantiation, render the function's
288       // name.
289       if (Child->isInstantiationSubView()) {
290         renderOffset(OS, NewOffset);
291         OS << ' ';
292         Options.colored_ostream(OS, raw_ostream::CYAN) << Child->FunctionName
293                                                        << ":";
294         OS << "\n";
295       } else {
296         if (!FirstChildExpansion) {
297           // Re-render the current line and highlight the expansion range for
298           // this
299           // subview.
300           insertHighlightRange(LineHighlightRanges,
301                                Child->getExpansionHighlightRange(),
302                                AdjustedLineHighlightRanges);
303           renderOffset(OS, Offset);
304           OS.indent(CombinedColumnWidth + (Offset == 0 ? 0 : 1));
305           renderLine(OS, Line, AdjustedLineHighlightRanges);
306           renderViewDivider(NewOffset, DividerWidth, OS);
307           OS << "\n";
308         } else
309           FirstChildExpansion = false;
310       }
311       // Render the child subview
312       Child->render(OS, NewOffset);
313       renderViewDivider(NewOffset, DividerWidth, OS);
314       OS << "\n";
315     }
316   }
317 }
318
319 void
320 SourceCoverageView::createLineCoverageInfo(SourceCoverageDataManager &Data) {
321   LineStats.resize(LineCount);
322   for (const auto &CR : Data.getSourceRegions()) {
323     if (CR.Kind == coverage::CounterMappingRegion::SkippedRegion) {
324       // Reset the line stats for skipped regions.
325       for (unsigned Line = CR.LineStart; Line <= CR.LineEnd;
326            ++Line)
327         LineStats[Line - LineStart] = LineCoverageInfo();
328       continue;
329     }
330     LineStats[CR.LineStart - LineStart].addRegionStartCount(CR.ExecutionCount);
331     for (unsigned Line = CR.LineStart + 1; Line <= CR.LineEnd; ++Line)
332       LineStats[Line - LineStart].addRegionCount(CR.ExecutionCount);
333   }
334 }
335
336 void
337 SourceCoverageView::createHighlightRanges(SourceCoverageDataManager &Data) {
338   auto CountedRegions = Data.getSourceRegions();
339   std::vector<bool> AlreadyHighlighted;
340   AlreadyHighlighted.resize(CountedRegions.size(), false);
341
342   for (size_t I = 0, S = CountedRegions.size(); I < S; ++I) {
343     const auto &CR = CountedRegions[I];
344     if (CR.Kind == coverage::CounterMappingRegion::SkippedRegion ||
345         CR.ExecutionCount != 0)
346       continue;
347     if (AlreadyHighlighted[I])
348       continue;
349     for (size_t J = 0; J < S; ++J) {
350       if (CR.contains(CountedRegions[J])) {
351         AlreadyHighlighted[J] = true;
352       }
353     }
354     if (CR.LineStart == CR.LineEnd) {
355       HighlightRanges.push_back(HighlightRange(
356           CR.LineStart, CR.ColumnStart, CR.ColumnEnd));
357       continue;
358     }
359     HighlightRanges.push_back(
360         HighlightRange(CR.LineStart, CR.ColumnStart,
361                        std::numeric_limits<unsigned>::max()));
362     HighlightRanges.push_back(
363         HighlightRange(CR.LineEnd, 1, CR.ColumnEnd));
364     for (unsigned Line = CR.LineStart + 1; Line < CR.LineEnd;
365          ++Line) {
366       HighlightRanges.push_back(
367           HighlightRange(Line, 1, std::numeric_limits<unsigned>::max()));
368     }
369   }
370
371   std::sort(HighlightRanges.begin(), HighlightRanges.end());
372
373   if (Options.Debug) {
374     for (const auto &Range : HighlightRanges) {
375       outs() << "Highlighted line " << Range.Line << ", " << Range.ColumnStart
376              << " -> ";
377       if (Range.ColumnEnd == std::numeric_limits<unsigned>::max()) {
378         outs() << "?\n";
379       } else {
380         outs() << Range.ColumnEnd << "\n";
381       }
382     }
383   }
384 }
385
386 void SourceCoverageView::createRegionMarkers(SourceCoverageDataManager &Data) {
387   for (const auto &CR : Data.getSourceRegions()) {
388     if (CR.Kind == coverage::CounterMappingRegion::SkippedRegion)
389       continue;
390     if (CR.LineStart >= LineStart)
391       Markers.push_back(
392           RegionMarker(CR.LineStart, CR.ColumnStart, CR.ExecutionCount));
393   }
394
395   if (Options.Debug) {
396     for (const auto &Marker : Markers) {
397       outs() << "Marker at " << Marker.Line << ":" << Marker.Column << " = "
398              << Marker.ExecutionCount << "\n";
399     }
400   }
401 }
402
403 void SourceCoverageView::load(SourceCoverageDataManager &Data) {
404   if (Options.ShowLineStats)
405     createLineCoverageInfo(Data);
406   if (Options.Colors)
407     createHighlightRanges(Data);
408   if (Options.ShowRegionMarkers)
409     createRegionMarkers(Data);
410 }