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