SourceMgr.cpp revision 234982
11590Srgrimes//===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
21590Srgrimes//
31590Srgrimes//                     The LLVM Compiler Infrastructure
41590Srgrimes//
51590Srgrimes// This file is distributed under the University of Illinois Open Source
61590Srgrimes// License. See LICENSE.TXT for details.
71590Srgrimes//
81590Srgrimes//===----------------------------------------------------------------------===//
91590Srgrimes//
101590Srgrimes// This file implements the SourceMgr class.  This class is used as a simple
111590Srgrimes// substrate for diagnostics, #include handling, and other low level things for
121590Srgrimes// simple parsers.
131590Srgrimes//
141590Srgrimes//===----------------------------------------------------------------------===//
151590Srgrimes
161590Srgrimes#include "llvm/ADT/Twine.h"
171590Srgrimes#include "llvm/Support/SourceMgr.h"
181590Srgrimes#include "llvm/Support/MemoryBuffer.h"
191590Srgrimes#include "llvm/ADT/OwningPtr.h"
201590Srgrimes#include "llvm/Support/raw_ostream.h"
211590Srgrimes#include "llvm/Support/system_error.h"
221590Srgrimesusing namespace llvm;
231590Srgrimes
241590Srgrimesnamespace {
251590Srgrimes  struct LineNoCacheTy {
261590Srgrimes    int LastQueryBufferID;
271590Srgrimes    const char *LastQuery;
281590Srgrimes    unsigned LineNoOfQuery;
291590Srgrimes  };
301590Srgrimes}
311590Srgrimes
321590Srgrimesstatic LineNoCacheTy *getCache(void *Ptr) {
331590Srgrimes  return (LineNoCacheTy*)Ptr;
341590Srgrimes}
3541568Sarchie
361590Srgrimes
371590SrgrimesSourceMgr::~SourceMgr() {
3887258Smarkm  // Delete the line # cache if allocated.
391590Srgrimes  if (LineNoCacheTy *Cache = getCache(LineNoCache))
4087628Sdwmalone    delete Cache;
411590Srgrimes
4287628Sdwmalone  while (!Buffers.empty()) {
4387258Smarkm    delete Buffers.back().Buffer;
4487628Sdwmalone    Buffers.pop_back();
451590Srgrimes  }
4687628Sdwmalone}
4787628Sdwmalone
4887628Sdwmalone/// AddIncludeFile - Search for a file with the specified name in the current
491590Srgrimes/// directory or in one of the IncludeDirs.  If no file is found, this returns
501590Srgrimes/// ~0, otherwise it returns the buffer ID of the stacked file.
511590Srgrimesunsigned SourceMgr::AddIncludeFile(const std::string &Filename,
521590Srgrimes                                   SMLoc IncludeLoc,
531590Srgrimes                                   std::string &IncludedFile) {
541590Srgrimes  OwningPtr<MemoryBuffer> NewBuf;
551590Srgrimes  IncludedFile = Filename;
5626836Scharnier  MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
571590Srgrimes
581590Srgrimes  // If the file didn't exist directly, see if it's in an include path.
591590Srgrimes  for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
6032069Salex    IncludedFile = IncludeDirectories[i] + "/" + Filename;
611590Srgrimes    MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
621590Srgrimes  }
631590Srgrimes
641590Srgrimes  if (NewBuf == 0) return ~0U;
651590Srgrimes
661590Srgrimes  return AddNewSourceBuffer(NewBuf.take(), IncludeLoc);
671590Srgrimes}
681590Srgrimes
691590Srgrimes
7024360Simp/// FindBufferContainingLoc - Return the ID of the buffer containing the
711590Srgrimes/// specified location, returning -1 if not found.
721590Srgrimesint SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
731590Srgrimes  for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
741590Srgrimes    if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
751590Srgrimes        // Use <= here so that a pointer to the null at the end of the buffer
761590Srgrimes        // is included as part of the buffer.
771590Srgrimes        Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
781590Srgrimes      return i;
7926836Scharnier  return -1;
8026836Scharnier}
811590Srgrimes
821590Srgrimes/// FindLineNumber - Find the line number for the specified location in the
8326836Scharnier/// specified file.  This is not a fast method.
841590Srgrimesunsigned SourceMgr::FindLineNumber(SMLoc Loc, int BufferID) const {
851590Srgrimes  if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
8677608Smikeh  assert(BufferID != -1 && "Invalid Location!");
8777608Smikeh
881590Srgrimes  MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
891590Srgrimes
901590Srgrimes  // Count the number of \n's between the start of the file and the specified
911590Srgrimes  // location.
9277608Smikeh  unsigned LineNo = 1;
9362889Skris
941590Srgrimes  const char *Ptr = Buff->getBufferStart();
951590Srgrimes
9677608Smikeh  // If we have a line number cache, and if the query is to a later point in the
9762889Skris  // same file, start searching from the last query location.  This optimizes
981590Srgrimes  // for the case when multiple diagnostics come out of one file in order.
991590Srgrimes  if (LineNoCacheTy *Cache = getCache(LineNoCache))
1001590Srgrimes    if (Cache->LastQueryBufferID == BufferID &&
1011590Srgrimes        Cache->LastQuery <= Loc.getPointer()) {
10277608Smikeh      Ptr = Cache->LastQuery;
1031590Srgrimes      LineNo = Cache->LineNoOfQuery;
1041590Srgrimes    }
1051590Srgrimes
1061590Srgrimes  // Scan for the location being queried, keeping track of the number of lines
1071590Srgrimes  // we see.
1081590Srgrimes  for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
1091590Srgrimes    if (*Ptr == '\n') ++LineNo;
1101590Srgrimes
111
112  // Allocate the line number cache if it doesn't exist.
113  if (LineNoCache == 0)
114    LineNoCache = new LineNoCacheTy();
115
116  // Update the line # cache.
117  LineNoCacheTy &Cache = *getCache(LineNoCache);
118  Cache.LastQueryBufferID = BufferID;
119  Cache.LastQuery = Ptr;
120  Cache.LineNoOfQuery = LineNo;
121  return LineNo;
122}
123
124void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
125  if (IncludeLoc == SMLoc()) return;  // Top of stack.
126
127  int CurBuf = FindBufferContainingLoc(IncludeLoc);
128  assert(CurBuf != -1 && "Invalid or unspecified location!");
129
130  PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
131
132  OS << "Included from "
133     << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
134     << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
135}
136
137
138/// GetMessage - Return an SMDiagnostic at the specified location with the
139/// specified string.
140///
141/// @param Type - If non-null, the kind of message (e.g., "error") which is
142/// prefixed to the message.
143SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
144                                   const Twine &Msg,
145                                   ArrayRef<SMRange> Ranges) const {
146
147  // First thing to do: find the current buffer containing the specified
148  // location.
149  int CurBuf = FindBufferContainingLoc(Loc);
150  assert(CurBuf != -1 && "Invalid or unspecified location!");
151
152  MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
153
154  // Scan backward to find the start of the line.
155  const char *LineStart = Loc.getPointer();
156  while (LineStart != CurMB->getBufferStart() &&
157         LineStart[-1] != '\n' && LineStart[-1] != '\r')
158    --LineStart;
159
160  // Get the end of the line.
161  const char *LineEnd = Loc.getPointer();
162  while (LineEnd != CurMB->getBufferEnd() &&
163         LineEnd[0] != '\n' && LineEnd[0] != '\r')
164    ++LineEnd;
165  std::string LineStr(LineStart, LineEnd);
166
167  // Convert any ranges to column ranges that only intersect the line of the
168  // location.
169  SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
170  for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
171    SMRange R = Ranges[i];
172    if (!R.isValid()) continue;
173
174    // If the line doesn't contain any part of the range, then ignore it.
175    if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
176      continue;
177
178    // Ignore pieces of the range that go onto other lines.
179    if (R.Start.getPointer() < LineStart)
180      R.Start = SMLoc::getFromPointer(LineStart);
181    if (R.End.getPointer() > LineEnd)
182      R.End = SMLoc::getFromPointer(LineEnd);
183
184    // Translate from SMLoc ranges to column ranges.
185    ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
186                                       R.End.getPointer()-LineStart));
187  }
188
189  return SMDiagnostic(*this, Loc,
190                      CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf),
191                      Loc.getPointer()-LineStart, Kind, Msg.str(),
192                      LineStr, ColRanges);
193}
194
195void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
196                             const Twine &Msg, ArrayRef<SMRange> Ranges,
197                             bool ShowColors) const {
198  SMDiagnostic Diagnostic = GetMessage(Loc, Kind, Msg, Ranges);
199
200  // Report the message with the diagnostic handler if present.
201  if (DiagHandler) {
202    DiagHandler(Diagnostic, DiagContext);
203    return;
204  }
205
206  raw_ostream &OS = errs();
207
208  int CurBuf = FindBufferContainingLoc(Loc);
209  assert(CurBuf != -1 && "Invalid or unspecified location!");
210  PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
211
212  Diagnostic.print(0, OS, ShowColors);
213}
214
215//===----------------------------------------------------------------------===//
216// SMDiagnostic Implementation
217//===----------------------------------------------------------------------===//
218
219SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string &FN,
220                           int Line, int Col, SourceMgr::DiagKind Kind,
221                           const std::string &Msg,
222                           const std::string &LineStr,
223                           ArrayRef<std::pair<unsigned,unsigned> > Ranges)
224  : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
225    Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()) {
226}
227
228
229void SMDiagnostic::print(const char *ProgName, raw_ostream &S,
230                         bool ShowColors) const {
231  // Display colors only if OS goes to a tty.
232  ShowColors &= S.is_displayed();
233
234  if (ShowColors)
235    S.changeColor(raw_ostream::SAVEDCOLOR, true);
236
237  if (ProgName && ProgName[0])
238    S << ProgName << ": ";
239
240  if (!Filename.empty()) {
241    if (Filename == "-")
242      S << "<stdin>";
243    else
244      S << Filename;
245
246    if (LineNo != -1) {
247      S << ':' << LineNo;
248      if (ColumnNo != -1)
249        S << ':' << (ColumnNo+1);
250    }
251    S << ": ";
252  }
253
254  switch (Kind) {
255  case SourceMgr::DK_Error:
256    if (ShowColors)
257      S.changeColor(raw_ostream::RED, true);
258    S << "error: ";
259    break;
260  case SourceMgr::DK_Warning:
261    if (ShowColors)
262      S.changeColor(raw_ostream::MAGENTA, true);
263    S << "warning: ";
264    break;
265  case SourceMgr::DK_Note:
266    if (ShowColors)
267      S.changeColor(raw_ostream::BLACK, true);
268    S << "note: ";
269    break;
270  }
271
272  if (ShowColors) {
273    S.resetColor();
274    S.changeColor(raw_ostream::SAVEDCOLOR, true);
275  }
276
277  S << Message << '\n';
278
279  if (ShowColors)
280    S.resetColor();
281
282  if (LineNo == -1 || ColumnNo == -1)
283    return;
284
285  // Build the line with the caret and ranges.
286  std::string CaretLine(LineContents.size()+1, ' ');
287
288  // Expand any ranges.
289  for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
290    std::pair<unsigned, unsigned> R = Ranges[r];
291    for (unsigned i = R.first,
292         e = std::min(R.second, (unsigned)LineContents.size())+1; i != e; ++i)
293      CaretLine[i] = '~';
294  }
295
296  // Finally, plop on the caret.
297  if (unsigned(ColumnNo) <= LineContents.size())
298    CaretLine[ColumnNo] = '^';
299  else
300    CaretLine[LineContents.size()] = '^';
301
302  // ... and remove trailing whitespace so the output doesn't wrap for it.  We
303  // know that the line isn't completely empty because it has the caret in it at
304  // least.
305  CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
306
307  // Print out the source line one character at a time, so we can expand tabs.
308  for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
309    if (LineContents[i] != '\t') {
310      S << LineContents[i];
311      ++OutCol;
312      continue;
313    }
314
315    // If we have a tab, emit at least one space, then round up to 8 columns.
316    do {
317      S << ' ';
318      ++OutCol;
319    } while (OutCol & 7);
320  }
321  S << '\n';
322
323  if (ShowColors)
324    S.changeColor(raw_ostream::GREEN, true);
325
326  // Print out the caret line, matching tabs in the source line.
327  for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
328    if (i >= LineContents.size() || LineContents[i] != '\t') {
329      S << CaretLine[i];
330      ++OutCol;
331      continue;
332    }
333
334    // Okay, we have a tab.  Insert the appropriate number of characters.
335    do {
336      S << CaretLine[i];
337      ++OutCol;
338    } while (OutCol & 7);
339  }
340
341  if (ShowColors)
342    S.resetColor();
343
344  S << '\n';
345}
346
347
348