blob: e4e01be0380291848330485f04318340d4799ac3 [file] [log] [blame]
Chris Lattner099e1982009-06-21 03:36:54 +00001//===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
Chris Lattneraa739d22009-03-13 07:05:43 +00002//
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//
Chris Lattner099e1982009-06-21 03:36:54 +000010// 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.
Chris Lattneraa739d22009-03-13 07:05:43 +000013//
14//===----------------------------------------------------------------------===//
15
Benjamin Kramerd1e17032010-09-27 17:42:11 +000016#include "llvm/ADT/Twine.h"
Chris Lattner099e1982009-06-21 03:36:54 +000017#include "llvm/Support/SourceMgr.h"
Chris Lattneraa739d22009-03-13 07:05:43 +000018#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer3ff95632010-12-16 03:29:14 +000019#include "llvm/ADT/OwningPtr.h"
Chris Lattneraa739d22009-03-13 07:05:43 +000020#include "llvm/Support/raw_ostream.h"
Michael J. Spencer333fb042010-12-09 17:36:48 +000021#include "llvm/Support/system_error.h"
Chris Lattneraa739d22009-03-13 07:05:43 +000022using namespace llvm;
23
Chris Lattner1d96ccc2009-08-11 17:49:14 +000024namespace {
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
Chris Lattner8070ea32009-06-21 03:41:50 +000037SourceMgr::~SourceMgr() {
Chris Lattner1d96ccc2009-08-11 17:49:14 +000038 // Delete the line # cache if allocated.
39 if (LineNoCacheTy *Cache = getCache(LineNoCache))
40 delete Cache;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +000041
Chris Lattneraa739d22009-03-13 07:05:43 +000042 while (!Buffers.empty()) {
43 delete Buffers.back().Buffer;
44 Buffers.pop_back();
45 }
46}
47
Chris Lattner7ee5d5f2009-06-21 05:06:04 +000048/// 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,
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +000052 SMLoc IncludeLoc,
53 std::string &IncludedFile) {
Michael J. Spencer3ff95632010-12-16 03:29:14 +000054 OwningPtr<MemoryBuffer> NewBuf;
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +000055 IncludedFile = Filename;
56 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
Chris Lattner7ee5d5f2009-06-21 05:06:04 +000057
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) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +000060 IncludedFile = IncludeDirectories[i] + "/" + Filename;
61 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
Chris Lattner7ee5d5f2009-06-21 05:06:04 +000062 }
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +000063
Chris Lattner7ee5d5f2009-06-21 05:06:04 +000064 if (NewBuf == 0) return ~0U;
65
Michael J. Spencer3ff95632010-12-16 03:29:14 +000066 return AddNewSourceBuffer(NewBuf.take(), IncludeLoc);
Chris Lattner7ee5d5f2009-06-21 05:06:04 +000067}
68
69
Chris Lattneraa739d22009-03-13 07:05:43 +000070/// FindBufferContainingLoc - Return the ID of the buffer containing the
71/// specified location, returning -1 if not found.
Chris Lattner8070ea32009-06-21 03:41:50 +000072int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
Chris Lattneraa739d22009-03-13 07:05:43 +000073 for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
Chris Lattner1c8ae592009-03-13 16:01:53 +000074 if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
Chris Lattnerd4771822009-03-18 20:36:45 +000075 // 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())
Chris Lattneraa739d22009-03-13 07:05:43 +000078 return i;
79 return -1;
80}
81
Chris Lattner77eafd92012-05-05 22:17:32 +000082/// getLineAndColumn - Find the line and column number for the specified
83/// location in the specified file. This is not a fast method.
84std::pair<unsigned, unsigned>
85SourceMgr::getLineAndColumn(SMLoc Loc, int BufferID) const {
Chris Lattneraa739d22009-03-13 07:05:43 +000086 if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
87 assert(BufferID != -1 && "Invalid Location!");
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +000088
Chris Lattneraa739d22009-03-13 07:05:43 +000089 MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +000090
Chris Lattneraa739d22009-03-13 07:05:43 +000091 // Count the number of \n's between the start of the file and the specified
92 // location.
93 unsigned LineNo = 1;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +000094
Chris Lattner77eafd92012-05-05 22:17:32 +000095 const char *BufStart = Buff->getBufferStart();
96 const char *Ptr = BufStart;
Chris Lattneraa739d22009-03-13 07:05:43 +000097
Chris Lattner1d96ccc2009-08-11 17:49:14 +000098 // 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))
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000102 if (Cache->LastQueryBufferID == BufferID &&
Chris Lattner1d96ccc2009-08-11 17:49:14 +0000103 Cache->LastQuery <= Loc.getPointer()) {
104 Ptr = Cache->LastQuery;
105 LineNo = Cache->LineNoOfQuery;
106 }
107
108 // Scan for the location being queried, keeping track of the number of lines
109 // we see.
Chris Lattner1e3a8a42009-06-21 03:39:35 +0000110 for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
Chris Lattneraa739d22009-03-13 07:05:43 +0000111 if (*Ptr == '\n') ++LineNo;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000112
Chris Lattner1d96ccc2009-08-11 17:49:14 +0000113 // Allocate the line number cache if it doesn't exist.
114 if (LineNoCache == 0)
115 LineNoCache = new LineNoCacheTy();
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000116
Chris Lattner1d96ccc2009-08-11 17:49:14 +0000117 // Update the line # cache.
118 LineNoCacheTy &Cache = *getCache(LineNoCache);
119 Cache.LastQueryBufferID = BufferID;
120 Cache.LastQuery = Ptr;
121 Cache.LineNoOfQuery = LineNo;
Chris Lattner77eafd92012-05-05 22:17:32 +0000122
123 size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
Matt Beaumont-Gayd58518a2012-05-07 18:12:42 +0000124 if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
Chris Lattner77eafd92012-05-05 22:17:32 +0000125 return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
Chris Lattneraa739d22009-03-13 07:05:43 +0000126}
127
Chris Lattner2f510ae2009-07-02 22:24:20 +0000128void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
Chris Lattner1e3a8a42009-06-21 03:39:35 +0000129 if (IncludeLoc == SMLoc()) return; // Top of stack.
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000130
Chris Lattneraa739d22009-03-13 07:05:43 +0000131 int CurBuf = FindBufferContainingLoc(IncludeLoc);
132 assert(CurBuf != -1 && "Invalid or unspecified location!");
133
Chris Lattner2f510ae2009-07-02 22:24:20 +0000134 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000135
Chris Lattner2f510ae2009-07-02 22:24:20 +0000136 OS << "Included from "
137 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
138 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
Chris Lattneraa739d22009-03-13 07:05:43 +0000139}
140
141
Chris Lattnereeb4a842009-07-02 23:08:13 +0000142/// GetMessage - Return an SMDiagnostic at the specified location with the
143/// specified string.
144///
145/// @param Type - If non-null, the kind of message (e.g., "error") which is
146/// prefixed to the message.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000147SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
Chris Lattner462b43c2011-10-16 05:47:55 +0000148 const Twine &Msg,
149 ArrayRef<SMRange> Ranges) const {
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000150
Chris Lattneraa739d22009-03-13 07:05:43 +0000151 // First thing to do: find the current buffer containing the specified
Chris Lattnereb034f42012-05-06 16:20:49 +0000152 // location to pull out the source line.
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000153 SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
Chris Lattnereb034f42012-05-06 16:20:49 +0000154 std::pair<unsigned, unsigned> LineAndCol;
155 const char *BufferID = "<unknown>";
156 std::string LineStr;
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000157
Chris Lattnereb034f42012-05-06 16:20:49 +0000158 if (Loc.isValid()) {
159 int CurBuf = FindBufferContainingLoc(Loc);
160 assert(CurBuf != -1 && "Invalid or unspecified location!");
161
162 MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
163 BufferID = CurMB->getBufferIdentifier();
164
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')
170 --LineStart;
171
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')
176 ++LineEnd;
177 LineStr = std::string(LineStart, LineEnd);
178
179 // Convert any ranges to column ranges that only intersect the line of the
180 // location.
181 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
182 SMRange R = Ranges[i];
183 if (!R.isValid()) continue;
184
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)
187 continue;
188
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);
194
195 // Translate from SMLoc ranges to column ranges.
196 ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
197 R.End.getPointer()-LineStart));
198 }
199
200 LineAndCol = getLineAndColumn(Loc, CurBuf);
201 }
202
203 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
Chris Lattner77eafd92012-05-05 22:17:32 +0000204 LineAndCol.second-1, Kind, Msg.str(),
Chris Lattner462b43c2011-10-16 05:47:55 +0000205 LineStr, ColRanges);
Chris Lattnereeb4a842009-07-02 23:08:13 +0000206}
207
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000208void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000209 const Twine &Msg, ArrayRef<SMRange> Ranges,
210 bool ShowColors) const {
Chris Lattner462b43c2011-10-16 05:47:55 +0000211 SMDiagnostic Diagnostic = GetMessage(Loc, Kind, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000212
Chris Lattner8f0f4802010-04-06 00:26:48 +0000213 // Report the message with the diagnostic handler if present.
214 if (DiagHandler) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000215 DiagHandler(Diagnostic, DiagContext);
Chris Lattner8f0f4802010-04-06 00:26:48 +0000216 return;
217 }
Michael J. Spencer333ad3f2010-12-09 17:37:32 +0000218
Chris Lattnereeb4a842009-07-02 23:08:13 +0000219 raw_ostream &OS = errs();
220
Chris Lattnereb034f42012-05-06 16:20:49 +0000221 if (Loc != SMLoc()) {
222 int CurBuf = FindBufferContainingLoc(Loc);
223 assert(CurBuf != -1 && "Invalid or unspecified location!");
224 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
225 }
Chris Lattnereeb4a842009-07-02 23:08:13 +0000226
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000227 Diagnostic.print(0, OS, ShowColors);
Chris Lattneraa739d22009-03-13 07:05:43 +0000228}
Chris Lattner2f510ae2009-07-02 22:24:20 +0000229
230//===----------------------------------------------------------------------===//
231// SMDiagnostic Implementation
232//===----------------------------------------------------------------------===//
233
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000234SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string &FN,
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000235 int Line, int Col, SourceMgr::DiagKind Kind,
236 const std::string &Msg,
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000237 const std::string &LineStr,
Chris Lattner462b43c2011-10-16 05:47:55 +0000238 ArrayRef<std::pair<unsigned,unsigned> > Ranges)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000239 : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
Chris Lattner462b43c2011-10-16 05:47:55 +0000240 Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()) {
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000241}
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000242
243
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000244void SMDiagnostic::print(const char *ProgName, raw_ostream &S,
245 bool ShowColors) const {
Daniel Dunbara7eb5832012-07-20 18:29:44 +0000246 // Display colors only if OS supports colors.
247 ShowColors &= S.has_colors();
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000248
249 if (ShowColors)
250 S.changeColor(raw_ostream::SAVEDCOLOR, true);
251
Chris Lattner2f510ae2009-07-02 22:24:20 +0000252 if (ProgName && ProgName[0])
253 S << ProgName << ": ";
254
Dan Gohman5e5442c2010-01-21 10:13:27 +0000255 if (!Filename.empty()) {
256 if (Filename == "-")
257 S << "<stdin>";
258 else
259 S << Filename;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000260
Dan Gohman5e5442c2010-01-21 10:13:27 +0000261 if (LineNo != -1) {
262 S << ':' << LineNo;
263 if (ColumnNo != -1)
264 S << ':' << (ColumnNo+1);
265 }
266 S << ": ";
Chris Lattner2f510ae2009-07-02 22:24:20 +0000267 }
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000268
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000269 switch (Kind) {
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000270 case SourceMgr::DK_Error:
271 if (ShowColors)
272 S.changeColor(raw_ostream::RED, true);
273 S << "error: ";
274 break;
275 case SourceMgr::DK_Warning:
276 if (ShowColors)
277 S.changeColor(raw_ostream::MAGENTA, true);
278 S << "warning: ";
279 break;
280 case SourceMgr::DK_Note:
281 if (ShowColors)
282 S.changeColor(raw_ostream::BLACK, true);
283 S << "note: ";
284 break;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000285 }
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000286
287 if (ShowColors) {
288 S.resetColor();
289 S.changeColor(raw_ostream::SAVEDCOLOR, true);
290 }
291
Dan Gohman5e5442c2010-01-21 10:13:27 +0000292 S << Message << '\n';
Daniel Dunbar41539822009-11-22 22:08:00 +0000293
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000294 if (ShowColors)
295 S.resetColor();
296
Chris Lattner462b43c2011-10-16 05:47:55 +0000297 if (LineNo == -1 || ColumnNo == -1)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000298 return;
Mikhail Glushenkove690ffb2010-01-27 10:13:11 +0000299
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000300 // Build the line with the caret and ranges.
301 std::string CaretLine(LineContents.size()+1, ' ');
302
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)
308 CaretLine[i] = '~';
Chris Lattner2f510ae2009-07-02 22:24:20 +0000309 }
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000310
311 // Finally, plop on the caret.
312 if (unsigned(ColumnNo) <= LineContents.size())
313 CaretLine[ColumnNo] = '^';
314 else
315 CaretLine[LineContents.size()] = '^';
316
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
319 // least.
320 CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
321
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];
326 ++OutCol;
327 continue;
328 }
329
330 // If we have a tab, emit at least one space, then round up to 8 columns.
331 do {
332 S << ' ';
333 ++OutCol;
334 } while (OutCol & 7);
335 }
336 S << '\n';
337
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000338 if (ShowColors)
339 S.changeColor(raw_ostream::GREEN, true);
340
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000341 // 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') {
344 S << CaretLine[i];
345 ++OutCol;
346 continue;
347 }
348
349 // Okay, we have a tab. Insert the appropriate number of characters.
350 do {
351 S << CaretLine[i];
352 ++OutCol;
353 } while (OutCol & 7);
354 }
Benjamin Kramer89f33fd2012-04-18 19:04:15 +0000355
356 if (ShowColors)
357 S.resetColor();
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000358
359 S << '\n';
Chris Lattner2f510ae2009-07-02 22:24:20 +0000360}