1 //===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
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"
25 struct LineNoCacheTy {
26 int LastQueryBufferID;
27 const char *LastQuery;
28 unsigned LineNoOfQuery;
32 static LineNoCacheTy *getCache(void *Ptr) {
33 return (LineNoCacheTy*)Ptr;
37 SourceMgr::~SourceMgr() {
38 // Delete the line # cache if allocated.
39 if (LineNoCacheTy *Cache = getCache(LineNoCache))
42 while (!Buffers.empty()) {
43 delete Buffers.back().Buffer;
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.
51 unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
53 std::string &IncludedFile) {
54 OwningPtr<MemoryBuffer> NewBuf;
55 IncludedFile = Filename;
56 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
58 // If the file didn't exist directly, see if it's in an include path.
59 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
60 IncludedFile = IncludeDirectories[i] + "/" + Filename;
61 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
64 if (NewBuf == 0) return ~0U;
66 return AddNewSourceBuffer(NewBuf.take(), IncludeLoc);
70 /// FindBufferContainingLoc - Return the ID of the buffer containing the
71 /// specified location, returning -1 if not found.
72 int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
73 for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
74 if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
75 // Use <= here so that a pointer to the null at the end of the buffer
76 // is included as part of the buffer.
77 Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
82 /// getLineAndColumn - Find the line and column number for the specified
83 /// location in the specified file. This is not a fast method.
84 std::pair<unsigned, unsigned>
85 SourceMgr::getLineAndColumn(SMLoc Loc, int BufferID) const {
86 if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
87 assert(BufferID != -1 && "Invalid Location!");
89 MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
91 // Count the number of \n's between the start of the file and the specified
95 const char *BufStart = Buff->getBufferStart();
96 const char *Ptr = BufStart;
98 // If we have a line number cache, and if the query is to a later point in the
99 // same file, start searching from the last query location. This optimizes
100 // for the case when multiple diagnostics come out of one file in order.
101 if (LineNoCacheTy *Cache = getCache(LineNoCache))
102 if (Cache->LastQueryBufferID == BufferID &&
103 Cache->LastQuery <= Loc.getPointer()) {
104 Ptr = Cache->LastQuery;
105 LineNo = Cache->LineNoOfQuery;
108 // Scan for the location being queried, keeping track of the number of lines
110 for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
111 if (*Ptr == '\n') ++LineNo;
113 // Allocate the line number cache if it doesn't exist.
114 if (LineNoCache == 0)
115 LineNoCache = new LineNoCacheTy();
117 // Update the line # cache.
118 LineNoCacheTy &Cache = *getCache(LineNoCache);
119 Cache.LastQueryBufferID = BufferID;
120 Cache.LastQuery = Ptr;
121 Cache.LineNoOfQuery = LineNo;
123 size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
124 if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
125 return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
128 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
129 if (IncludeLoc == SMLoc()) return; // Top of stack.
131 int CurBuf = FindBufferContainingLoc(IncludeLoc);
132 assert(CurBuf != -1 && "Invalid or unspecified location!");
134 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
136 OS << "Included from "
137 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
138 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
142 /// GetMessage - Return an SMDiagnostic at the specified location with the
143 /// specified string.
145 /// @param Type - If non-null, the kind of message (e.g., "error") which is
146 /// prefixed to the message.
147 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
149 ArrayRef<SMRange> Ranges) const {
151 // First thing to do: find the current buffer containing the specified
152 // location to pull out the source line.
153 SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
154 std::pair<unsigned, unsigned> LineAndCol;
155 const char *BufferID = "<unknown>";
159 int CurBuf = FindBufferContainingLoc(Loc);
160 assert(CurBuf != -1 && "Invalid or unspecified location!");
162 MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
163 BufferID = CurMB->getBufferIdentifier();
165 // Scan backward to find the start of the line.
166 const char *LineStart = Loc.getPointer();
167 const char *BufStart = CurMB->getBufferStart();
168 while (LineStart != BufStart && LineStart[-1] != '\n' &&
169 LineStart[-1] != '\r')
172 // Get the end of the line.
173 const char *LineEnd = Loc.getPointer();
174 const char *BufEnd = CurMB->getBufferEnd();
175 while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
177 LineStr = std::string(LineStart, LineEnd);
179 // Convert any ranges to column ranges that only intersect the line of the
181 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
182 SMRange R = Ranges[i];
183 if (!R.isValid()) continue;
185 // If the line doesn't contain any part of the range, then ignore it.
186 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
189 // Ignore pieces of the range that go onto other lines.
190 if (R.Start.getPointer() < LineStart)
191 R.Start = SMLoc::getFromPointer(LineStart);
192 if (R.End.getPointer() > LineEnd)
193 R.End = SMLoc::getFromPointer(LineEnd);
195 // Translate from SMLoc ranges to column ranges.
196 ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
197 R.End.getPointer()-LineStart));
200 LineAndCol = getLineAndColumn(Loc, CurBuf);
203 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
204 LineAndCol.second-1, Kind, Msg.str(),
208 void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
209 const Twine &Msg, ArrayRef<SMRange> Ranges,
210 bool ShowColors) const {
211 SMDiagnostic Diagnostic = GetMessage(Loc, Kind, Msg, Ranges);
213 // Report the message with the diagnostic handler if present.
215 DiagHandler(Diagnostic, DiagContext);
219 raw_ostream &OS = errs();
221 if (Loc != SMLoc()) {
222 int CurBuf = FindBufferContainingLoc(Loc);
223 assert(CurBuf != -1 && "Invalid or unspecified location!");
224 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
227 Diagnostic.print(0, OS, ShowColors);
230 //===----------------------------------------------------------------------===//
231 // SMDiagnostic Implementation
232 //===----------------------------------------------------------------------===//
234 SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string &FN,
235 int Line, int Col, SourceMgr::DiagKind Kind,
236 const std::string &Msg,
237 const std::string &LineStr,
238 ArrayRef<std::pair<unsigned,unsigned> > Ranges)
239 : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
240 Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()) {
244 void SMDiagnostic::print(const char *ProgName, raw_ostream &S,
245 bool ShowColors) const {
246 // Display colors only if OS supports colors.
247 ShowColors &= S.has_colors();
250 S.changeColor(raw_ostream::SAVEDCOLOR, true);
252 if (ProgName && ProgName[0])
253 S << ProgName << ": ";
255 if (!Filename.empty()) {
264 S << ':' << (ColumnNo+1);
270 case SourceMgr::DK_Error:
272 S.changeColor(raw_ostream::RED, true);
275 case SourceMgr::DK_Warning:
277 S.changeColor(raw_ostream::MAGENTA, true);
280 case SourceMgr::DK_Note:
282 S.changeColor(raw_ostream::BLACK, true);
289 S.changeColor(raw_ostream::SAVEDCOLOR, true);
292 S << Message << '\n';
297 if (LineNo == -1 || ColumnNo == -1)
300 // Build the line with the caret and ranges.
301 std::string CaretLine(LineContents.size()+1, ' ');
303 // Expand any ranges.
304 for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
305 std::pair<unsigned, unsigned> R = Ranges[r];
306 for (unsigned i = R.first,
307 e = std::min(R.second, (unsigned)LineContents.size())+1; i != e; ++i)
311 // Finally, plop on the caret.
312 if (unsigned(ColumnNo) <= LineContents.size())
313 CaretLine[ColumnNo] = '^';
315 CaretLine[LineContents.size()] = '^';
317 // ... and remove trailing whitespace so the output doesn't wrap for it. We
318 // know that the line isn't completely empty because it has the caret in it at
320 CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
322 // Print out the source line one character at a time, so we can expand tabs.
323 for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
324 if (LineContents[i] != '\t') {
325 S << LineContents[i];
330 // If we have a tab, emit at least one space, then round up to 8 columns.
334 } while (OutCol & 7);
339 S.changeColor(raw_ostream::GREEN, true);
341 // Print out the caret line, matching tabs in the source line.
342 for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
343 if (i >= LineContents.size() || LineContents[i] != '\t') {
349 // Okay, we have a tab. Insert the appropriate number of characters.
353 } while (OutCol & 7);