SourceMgr.cpp revision 3ff9563c3e391954b2e224afcf8b2b0fcc3888aa
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/ADT/Twine.h"
17#include "llvm/Support/SourceMgr.h"
18#include "llvm/Support/MemoryBuffer.h"
19#include "llvm/ADT/OwningPtr.h"
20#include "llvm/Support/raw_ostream.h"
21#include "llvm/Support/system_error.h"
22using namespace llvm;
23
24namespace {
25  struct LineNoCacheTy {
26    int LastQueryBufferID;
27    const char *LastQuery;
28    unsigned LineNoOfQuery;
29  };
30}
31
32static LineNoCacheTy *getCache(void *Ptr) {
33  return (LineNoCacheTy*)Ptr;
34}
35
36
37SourceMgr::~SourceMgr() {
38  // Delete the line # cache if allocated.
39  if (LineNoCacheTy *Cache = getCache(LineNoCache))
40    delete Cache;
41
42  while (!Buffers.empty()) {
43    delete Buffers.back().Buffer;
44    Buffers.pop_back();
45  }
46}
47
48/// AddIncludeFile - Search for a file with the specified name in the current
49/// directory or in one of the IncludeDirs.  If no file is found, this returns
50/// ~0, otherwise it returns the buffer ID of the stacked file.
51unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
52                                   SMLoc IncludeLoc) {
53  OwningPtr<MemoryBuffer> NewBuf;
54  MemoryBuffer::getFile(Filename.c_str(), NewBuf);
55
56  // If the file didn't exist directly, see if it's in an include path.
57  for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
58    std::string IncFile = IncludeDirectories[i] + "/" + Filename;
59    MemoryBuffer::getFile(IncFile.c_str(), NewBuf);
60  }
61
62  if (NewBuf == 0) return ~0U;
63
64  return AddNewSourceBuffer(NewBuf.take(), IncludeLoc);
65}
66
67
68/// FindBufferContainingLoc - Return the ID of the buffer containing the
69/// specified location, returning -1 if not found.
70int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
71  for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
72    if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
73        // Use <= here so that a pointer to the null at the end of the buffer
74        // is included as part of the buffer.
75        Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
76      return i;
77  return -1;
78}
79
80/// FindLineNumber - Find the line number for the specified location in the
81/// specified file.  This is not a fast method.
82unsigned SourceMgr::FindLineNumber(SMLoc Loc, int BufferID) const {
83  if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
84  assert(BufferID != -1 && "Invalid Location!");
85
86  MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
87
88  // Count the number of \n's between the start of the file and the specified
89  // location.
90  unsigned LineNo = 1;
91
92  const char *Ptr = Buff->getBufferStart();
93
94  // If we have a line number cache, and if the query is to a later point in the
95  // same file, start searching from the last query location.  This optimizes
96  // for the case when multiple diagnostics come out of one file in order.
97  if (LineNoCacheTy *Cache = getCache(LineNoCache))
98    if (Cache->LastQueryBufferID == BufferID &&
99        Cache->LastQuery <= Loc.getPointer()) {
100      Ptr = Cache->LastQuery;
101      LineNo = Cache->LineNoOfQuery;
102    }
103
104  // Scan for the location being queried, keeping track of the number of lines
105  // we see.
106  for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
107    if (*Ptr == '\n') ++LineNo;
108
109
110  // Allocate the line number cache if it doesn't exist.
111  if (LineNoCache == 0)
112    LineNoCache = new LineNoCacheTy();
113
114  // Update the line # cache.
115  LineNoCacheTy &Cache = *getCache(LineNoCache);
116  Cache.LastQueryBufferID = BufferID;
117  Cache.LastQuery = Ptr;
118  Cache.LineNoOfQuery = LineNo;
119  return LineNo;
120}
121
122void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
123  if (IncludeLoc == SMLoc()) return;  // Top of stack.
124
125  int CurBuf = FindBufferContainingLoc(IncludeLoc);
126  assert(CurBuf != -1 && "Invalid or unspecified location!");
127
128  PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
129
130  OS << "Included from "
131     << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
132     << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
133}
134
135
136/// GetMessage - Return an SMDiagnostic at the specified location with the
137/// specified string.
138///
139/// @param Type - If non-null, the kind of message (e.g., "error") which is
140/// prefixed to the message.
141SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, const Twine &Msg,
142                                   const char *Type, bool ShowLine) const {
143
144  // First thing to do: find the current buffer containing the specified
145  // location.
146  int CurBuf = FindBufferContainingLoc(Loc);
147  assert(CurBuf != -1 && "Invalid or unspecified location!");
148
149  MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
150
151  // Scan backward to find the start of the line.
152  const char *LineStart = Loc.getPointer();
153  while (LineStart != CurMB->getBufferStart() &&
154         LineStart[-1] != '\n' && LineStart[-1] != '\r')
155    --LineStart;
156
157  std::string LineStr;
158  if (ShowLine) {
159    // Get the end of the line.
160    const char *LineEnd = Loc.getPointer();
161    while (LineEnd != CurMB->getBufferEnd() &&
162           LineEnd[0] != '\n' && LineEnd[0] != '\r')
163      ++LineEnd;
164    LineStr = std::string(LineStart, LineEnd);
165  }
166
167  std::string PrintedMsg;
168  raw_string_ostream OS(PrintedMsg);
169  if (Type)
170    OS << Type << ": ";
171  OS << Msg;
172
173  return SMDiagnostic(*this, Loc,
174                      CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf),
175                      Loc.getPointer()-LineStart, OS.str(),
176                      LineStr, ShowLine);
177}
178
179void SourceMgr::PrintMessage(SMLoc Loc, const Twine &Msg,
180                             const char *Type, bool ShowLine) const {
181  // Report the message with the diagnostic handler if present.
182  if (DiagHandler) {
183    DiagHandler(GetMessage(Loc, Msg, Type, ShowLine), DiagContext);
184    return;
185  }
186
187  raw_ostream &OS = errs();
188
189  int CurBuf = FindBufferContainingLoc(Loc);
190  assert(CurBuf != -1 && "Invalid or unspecified location!");
191  PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
192
193  GetMessage(Loc, Msg, Type, ShowLine).Print(0, OS);
194}
195
196//===----------------------------------------------------------------------===//
197// SMDiagnostic Implementation
198//===----------------------------------------------------------------------===//
199
200void SMDiagnostic::Print(const char *ProgName, raw_ostream &S) const {
201  if (ProgName && ProgName[0])
202    S << ProgName << ": ";
203
204  if (!Filename.empty()) {
205    if (Filename == "-")
206      S << "<stdin>";
207    else
208      S << Filename;
209
210    if (LineNo != -1) {
211      S << ':' << LineNo;
212      if (ColumnNo != -1)
213        S << ':' << (ColumnNo+1);
214    }
215    S << ": ";
216  }
217
218  S << Message << '\n';
219
220  if (LineNo != -1 && ColumnNo != -1 && ShowLine) {
221    S << LineContents << '\n';
222
223    // Print out spaces/tabs before the caret.
224    for (unsigned i = 0; i != unsigned(ColumnNo); ++i)
225      S << (LineContents[i] == '\t' ? '\t' : ' ');
226    S << "^\n";
227  }
228}
229
230
231