xref: /llvm-project/llvm/lib/Support/SourceMgr.cpp (revision a55b95b58ad8f2d474564eefd3815759c5a0d1c2)
1 //===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
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 file implements the SourceMgr class.  This class is used as a simple
11 // substrate for diagnostics, #include handling, and other low level things for
12 // simple parsers.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Support/SourceMgr.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Locale.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <system_error>
24 using namespace llvm;
25 
26 static const size_t TabStop = 8;
27 
28 namespace {
29   struct LineNoCacheTy {
30     unsigned LastQueryBufferID;
31     const char *LastQuery;
32     unsigned LineNoOfQuery;
33   };
34 }
35 
36 static LineNoCacheTy *getCache(void *Ptr) {
37   return (LineNoCacheTy*)Ptr;
38 }
39 
40 
41 SourceMgr::~SourceMgr() {
42   // Delete the line # cache if allocated.
43   if (LineNoCacheTy *Cache = getCache(LineNoCache))
44     delete Cache;
45 
46   while (!Buffers.empty()) {
47     delete Buffers.back().Buffer;
48     Buffers.pop_back();
49   }
50 }
51 
52 size_t SourceMgr::AddIncludeFile(const std::string &Filename,
53                                  SMLoc IncludeLoc,
54                                  std::string &IncludedFile) {
55   std::unique_ptr<MemoryBuffer> NewBuf;
56   IncludedFile = Filename;
57   MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
58 
59   // If the file didn't exist directly, see if it's in an include path.
60   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
61     IncludedFile = IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
62     MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
63   }
64 
65   if (!NewBuf)
66     return 0;
67 
68   return AddNewSourceBuffer(NewBuf.release(), IncludeLoc);
69 }
70 
71 unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
72   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
73     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
74         // Use <= here so that a pointer to the null at the end of the buffer
75         // is included as part of the buffer.
76         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
77       return i + 1;
78   return 0;
79 }
80 
81 std::pair<unsigned, unsigned>
82 SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
83   if (!BufferID)
84     BufferID = FindBufferContainingLoc(Loc);
85   assert(BufferID && "Invalid Location!");
86 
87   const MemoryBuffer *Buff = getMemoryBuffer(BufferID);
88 
89   // Count the number of \n's between the start of the file and the specified
90   // location.
91   unsigned LineNo = 1;
92 
93   const char *BufStart = Buff->getBufferStart();
94   const char *Ptr = BufStart;
95 
96   // If we have a line number cache, and if the query is to a later point in the
97   // same file, start searching from the last query location.  This optimizes
98   // for the case when multiple diagnostics come out of one file in order.
99   if (LineNoCacheTy *Cache = getCache(LineNoCache))
100     if (Cache->LastQueryBufferID == BufferID &&
101         Cache->LastQuery <= Loc.getPointer()) {
102       Ptr = Cache->LastQuery;
103       LineNo = Cache->LineNoOfQuery;
104     }
105 
106   // Scan for the location being queried, keeping track of the number of lines
107   // we see.
108   for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
109     if (*Ptr == '\n') ++LineNo;
110 
111   // Allocate the line number cache if it doesn't exist.
112   if (!LineNoCache)
113     LineNoCache = new LineNoCacheTy();
114 
115   // Update the line # cache.
116   LineNoCacheTy &Cache = *getCache(LineNoCache);
117   Cache.LastQueryBufferID = BufferID;
118   Cache.LastQuery = Ptr;
119   Cache.LineNoOfQuery = LineNo;
120 
121   size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
122   if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
123   return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
124 }
125 
126 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
127   if (IncludeLoc == SMLoc()) return;  // Top of stack.
128 
129   unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
130   assert(CurBuf && "Invalid or unspecified location!");
131 
132   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
133 
134   OS << "Included from "
135      << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
136      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
137 }
138 
139 
140 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
141                                    const Twine &Msg,
142                                    ArrayRef<SMRange> Ranges,
143                                    ArrayRef<SMFixIt> FixIts) const {
144 
145   // First thing to do: find the current buffer containing the specified
146   // location to pull out the source line.
147   SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
148   std::pair<unsigned, unsigned> LineAndCol;
149   const char *BufferID = "<unknown>";
150   std::string LineStr;
151 
152   if (Loc.isValid()) {
153     unsigned CurBuf = FindBufferContainingLoc(Loc);
154     assert(CurBuf && "Invalid or unspecified location!");
155 
156     const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
157     BufferID = CurMB->getBufferIdentifier();
158 
159     // Scan backward to find the start of the line.
160     const char *LineStart = Loc.getPointer();
161     const char *BufStart = CurMB->getBufferStart();
162     while (LineStart != BufStart && LineStart[-1] != '\n' &&
163            LineStart[-1] != '\r')
164       --LineStart;
165 
166     // Get the end of the line.
167     const char *LineEnd = Loc.getPointer();
168     const char *BufEnd = CurMB->getBufferEnd();
169     while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
170       ++LineEnd;
171     LineStr = std::string(LineStart, LineEnd);
172 
173     // Convert any ranges to column ranges that only intersect the line of the
174     // location.
175     for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
176       SMRange R = Ranges[i];
177       if (!R.isValid()) continue;
178 
179       // If the line doesn't contain any part of the range, then ignore it.
180       if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
181         continue;
182 
183       // Ignore pieces of the range that go onto other lines.
184       if (R.Start.getPointer() < LineStart)
185         R.Start = SMLoc::getFromPointer(LineStart);
186       if (R.End.getPointer() > LineEnd)
187         R.End = SMLoc::getFromPointer(LineEnd);
188 
189       // Translate from SMLoc ranges to column ranges.
190       // FIXME: Handle multibyte characters.
191       ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
192                                          R.End.getPointer()-LineStart));
193     }
194 
195     LineAndCol = getLineAndColumn(Loc, CurBuf);
196   }
197 
198   return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
199                       LineAndCol.second-1, Kind, Msg.str(),
200                       LineStr, ColRanges, FixIts);
201 }
202 
203 void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
204                              bool ShowColors) const {
205   // Report the message with the diagnostic handler if present.
206   if (DiagHandler) {
207     DiagHandler(Diagnostic, DiagContext);
208     return;
209   }
210 
211   if (Diagnostic.getLoc().isValid()) {
212     unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
213     assert(CurBuf && "Invalid or unspecified location!");
214     PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
215   }
216 
217   Diagnostic.print(nullptr, OS, ShowColors);
218 }
219 
220 void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
221                              SourceMgr::DiagKind Kind,
222                              const Twine &Msg, ArrayRef<SMRange> Ranges,
223                              ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
224   PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
225 }
226 
227 void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
228                              const Twine &Msg, ArrayRef<SMRange> Ranges,
229                              ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
230   PrintMessage(llvm::errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
231 }
232 
233 //===----------------------------------------------------------------------===//
234 // SMDiagnostic Implementation
235 //===----------------------------------------------------------------------===//
236 
237 SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
238                            int Line, int Col, SourceMgr::DiagKind Kind,
239                            StringRef Msg, StringRef LineStr,
240                            ArrayRef<std::pair<unsigned,unsigned> > Ranges,
241                            ArrayRef<SMFixIt> Hints)
242   : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
243     Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
244     FixIts(Hints.begin(), Hints.end()) {
245   std::sort(FixIts.begin(), FixIts.end());
246 }
247 
248 static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
249                            ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
250   if (FixIts.empty())
251     return;
252 
253   const char *LineStart = SourceLine.begin();
254   const char *LineEnd = SourceLine.end();
255 
256   size_t PrevHintEndCol = 0;
257 
258   for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
259        I != E; ++I) {
260     // If the fixit contains a newline or tab, ignore it.
261     if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
262       continue;
263 
264     SMRange R = I->getRange();
265 
266     // If the line doesn't contain any part of the range, then ignore it.
267     if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
268       continue;
269 
270     // Translate from SMLoc to column.
271     // Ignore pieces of the range that go onto other lines.
272     // FIXME: Handle multibyte characters in the source line.
273     unsigned FirstCol;
274     if (R.Start.getPointer() < LineStart)
275       FirstCol = 0;
276     else
277       FirstCol = R.Start.getPointer() - LineStart;
278 
279     // If we inserted a long previous hint, push this one forwards, and add
280     // an extra space to show that this is not part of the previous
281     // completion. This is sort of the best we can do when two hints appear
282     // to overlap.
283     //
284     // Note that if this hint is located immediately after the previous
285     // hint, no space will be added, since the location is more important.
286     unsigned HintCol = FirstCol;
287     if (HintCol < PrevHintEndCol)
288       HintCol = PrevHintEndCol + 1;
289 
290     // FIXME: This assertion is intended to catch unintended use of multibyte
291     // characters in fixits. If we decide to do this, we'll have to track
292     // separate byte widths for the source and fixit lines.
293     assert((size_t)llvm::sys::locale::columnWidth(I->getText()) ==
294            I->getText().size());
295 
296     // This relies on one byte per column in our fixit hints.
297     unsigned LastColumnModified = HintCol + I->getText().size();
298     if (LastColumnModified > FixItLine.size())
299       FixItLine.resize(LastColumnModified, ' ');
300 
301     std::copy(I->getText().begin(), I->getText().end(),
302               FixItLine.begin() + HintCol);
303 
304     PrevHintEndCol = LastColumnModified;
305 
306     // For replacements, mark the removal range with '~'.
307     // FIXME: Handle multibyte characters in the source line.
308     unsigned LastCol;
309     if (R.End.getPointer() >= LineEnd)
310       LastCol = LineEnd - LineStart;
311     else
312       LastCol = R.End.getPointer() - LineStart;
313 
314     std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
315   }
316 }
317 
318 static void printSourceLine(raw_ostream &S, StringRef LineContents) {
319   // Print out the source line one character at a time, so we can expand tabs.
320   for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
321     if (LineContents[i] != '\t') {
322       S << LineContents[i];
323       ++OutCol;
324       continue;
325     }
326 
327     // If we have a tab, emit at least one space, then round up to 8 columns.
328     do {
329       S << ' ';
330       ++OutCol;
331     } while ((OutCol % TabStop) != 0);
332   }
333   S << '\n';
334 }
335 
336 static bool isNonASCII(char c) {
337   return c & 0x80;
338 }
339 
340 void SMDiagnostic::print(const char *ProgName, raw_ostream &S,
341                          bool ShowColors) const {
342   // Display colors only if OS supports colors.
343   ShowColors &= S.has_colors();
344 
345   if (ShowColors)
346     S.changeColor(raw_ostream::SAVEDCOLOR, true);
347 
348   if (ProgName && ProgName[0])
349     S << ProgName << ": ";
350 
351   if (!Filename.empty()) {
352     if (Filename == "-")
353       S << "<stdin>";
354     else
355       S << Filename;
356 
357     if (LineNo != -1) {
358       S << ':' << LineNo;
359       if (ColumnNo != -1)
360         S << ':' << (ColumnNo+1);
361     }
362     S << ": ";
363   }
364 
365   switch (Kind) {
366   case SourceMgr::DK_Error:
367     if (ShowColors)
368       S.changeColor(raw_ostream::RED, true);
369     S << "error: ";
370     break;
371   case SourceMgr::DK_Warning:
372     if (ShowColors)
373       S.changeColor(raw_ostream::MAGENTA, true);
374     S << "warning: ";
375     break;
376   case SourceMgr::DK_Note:
377     if (ShowColors)
378       S.changeColor(raw_ostream::BLACK, true);
379     S << "note: ";
380     break;
381   }
382 
383   if (ShowColors) {
384     S.resetColor();
385     S.changeColor(raw_ostream::SAVEDCOLOR, true);
386   }
387 
388   S << Message << '\n';
389 
390   if (ShowColors)
391     S.resetColor();
392 
393   if (LineNo == -1 || ColumnNo == -1)
394     return;
395 
396   // FIXME: If there are multibyte or multi-column characters in the source, all
397   // our ranges will be wrong. To do this properly, we'll need a byte-to-column
398   // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
399   // expanding them later, and bail out rather than show incorrect ranges and
400   // misaligned fixits for any other odd characters.
401   if (std::find_if(LineContents.begin(), LineContents.end(), isNonASCII) !=
402       LineContents.end()) {
403     printSourceLine(S, LineContents);
404     return;
405   }
406   size_t NumColumns = LineContents.size();
407 
408   // Build the line with the caret and ranges.
409   std::string CaretLine(NumColumns+1, ' ');
410 
411   // Expand any ranges.
412   for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
413     std::pair<unsigned, unsigned> R = Ranges[r];
414     std::fill(&CaretLine[R.first],
415               &CaretLine[std::min((size_t)R.second, CaretLine.size())],
416               '~');
417   }
418 
419   // Add any fix-its.
420   // FIXME: Find the beginning of the line properly for multibyte characters.
421   std::string FixItInsertionLine;
422   buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
423                  makeArrayRef(Loc.getPointer() - ColumnNo,
424                               LineContents.size()));
425 
426   // Finally, plop on the caret.
427   if (unsigned(ColumnNo) <= NumColumns)
428     CaretLine[ColumnNo] = '^';
429   else
430     CaretLine[NumColumns] = '^';
431 
432   // ... and remove trailing whitespace so the output doesn't wrap for it.  We
433   // know that the line isn't completely empty because it has the caret in it at
434   // least.
435   CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
436 
437   printSourceLine(S, LineContents);
438 
439   if (ShowColors)
440     S.changeColor(raw_ostream::GREEN, true);
441 
442   // Print out the caret line, matching tabs in the source line.
443   for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
444     if (i >= LineContents.size() || LineContents[i] != '\t') {
445       S << CaretLine[i];
446       ++OutCol;
447       continue;
448     }
449 
450     // Okay, we have a tab.  Insert the appropriate number of characters.
451     do {
452       S << CaretLine[i];
453       ++OutCol;
454     } while ((OutCol % TabStop) != 0);
455   }
456   S << '\n';
457 
458   if (ShowColors)
459     S.resetColor();
460 
461   // Print out the replacement line, matching tabs in the source line.
462   if (FixItInsertionLine.empty())
463     return;
464 
465   for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
466     if (i >= LineContents.size() || LineContents[i] != '\t') {
467       S << FixItInsertionLine[i];
468       ++OutCol;
469       continue;
470     }
471 
472     // Okay, we have a tab.  Insert the appropriate number of characters.
473     do {
474       S << FixItInsertionLine[i];
475       // FIXME: This is trying not to break up replacements, but then to re-sync
476       // with the tabs between replacements. This will fail, though, if two
477       // fix-it replacements are exactly adjacent, or if a fix-it contains a
478       // space. Really we should be precomputing column widths, which we'll
479       // need anyway for multibyte chars.
480       if (FixItInsertionLine[i] != ' ')
481         ++i;
482       ++OutCol;
483     } while (((OutCol % TabStop) != 0) && i != e);
484   }
485   S << '\n';
486 }
487