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/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"
25 static const size_t TabStop = 8;
28 struct LineNoCacheTy {
29 int LastQueryBufferID;
30 const char *LastQuery;
31 unsigned LineNoOfQuery;
35 static LineNoCacheTy *getCache(void *Ptr) {
36 return (LineNoCacheTy*)Ptr;
40 SourceMgr::~SourceMgr() {
41 // Delete the line # cache if allocated.
42 if (LineNoCacheTy *Cache = getCache(LineNoCache))
45 while (!Buffers.empty()) {
46 delete Buffers.back().Buffer;
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,
56 std::string &IncludedFile) {
57 std::unique_ptr<MemoryBuffer> NewBuf;
58 IncludedFile = Filename;
59 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
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);
67 if (!NewBuf) return ~0U;
69 return AddNewSourceBuffer(NewBuf.release(), IncludeLoc);
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())
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!");
92 MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
94 // Count the number of \n's between the start of the file and the specified
98 const char *BufStart = Buff->getBufferStart();
99 const char *Ptr = BufStart;
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;
111 // Scan for the location being queried, keeping track of the number of lines
113 for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
114 if (*Ptr == '\n') ++LineNo;
116 // Allocate the line number cache if it doesn't exist.
118 LineNoCache = new LineNoCacheTy();
120 // Update the line # cache.
121 LineNoCacheTy &Cache = *getCache(LineNoCache);
122 Cache.LastQueryBufferID = BufferID;
123 Cache.LastQuery = Ptr;
124 Cache.LineNoOfQuery = LineNo;
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);
131 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
132 if (IncludeLoc == SMLoc()) return; // Top of stack.
134 int CurBuf = FindBufferContainingLoc(IncludeLoc);
135 assert(CurBuf != -1 && "Invalid or unspecified location!");
137 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
139 OS << "Included from "
140 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
141 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
145 /// GetMessage - Return an SMDiagnostic at the specified location with the
146 /// specified string.
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,
152 ArrayRef<SMRange> Ranges,
153 ArrayRef<SMFixIt> FixIts) const {
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>";
163 int CurBuf = FindBufferContainingLoc(Loc);
164 assert(CurBuf != -1 && "Invalid or unspecified location!");
166 MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
167 BufferID = CurMB->getBufferIdentifier();
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')
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')
181 LineStr = std::string(LineStart, LineEnd);
183 // Convert any ranges to column ranges that only intersect the line of the
185 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
186 SMRange R = Ranges[i];
187 if (!R.isValid()) continue;
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)
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);
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));
205 LineAndCol = getLineAndColumn(Loc, CurBuf);
208 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
209 LineAndCol.second-1, Kind, Msg.str(),
210 LineStr, ColRanges, FixIts);
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);
219 // Report the message with the diagnostic handler if present.
221 DiagHandler(Diagnostic, DiagContext);
225 if (Loc != SMLoc()) {
226 int CurBuf = FindBufferContainingLoc(Loc);
227 assert(CurBuf != -1 && "Invalid or unspecified location!");
228 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
231 Diagnostic.print(nullptr, OS, ShowColors);
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);
240 //===----------------------------------------------------------------------===//
241 // SMDiagnostic Implementation
242 //===----------------------------------------------------------------------===//
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());
255 static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
256 ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
260 const char *LineStart = SourceLine.begin();
261 const char *LineEnd = SourceLine.end();
263 size_t PrevHintEndCol = 0;
265 for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
267 // If the fixit contains a newline or tab, ignore it.
268 if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
271 SMRange R = I->getRange();
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)
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.
281 if (R.Start.getPointer() < LineStart)
284 FirstCol = R.Start.getPointer() - LineStart;
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
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;
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());
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, ' ');
308 std::copy(I->getText().begin(), I->getText().end(),
309 FixItLine.begin() + HintCol);
311 PrevHintEndCol = LastColumnModified;
313 // For replacements, mark the removal range with '~'.
314 // FIXME: Handle multibyte characters in the source line.
316 if (R.End.getPointer() >= LineEnd)
317 LastCol = LineEnd - LineStart;
319 LastCol = R.End.getPointer() - LineStart;
321 std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
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];
334 // If we have a tab, emit at least one space, then round up to 8 columns.
338 } while ((OutCol % TabStop) != 0);
343 static bool isNonASCII(char c) {
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();
353 S.changeColor(raw_ostream::SAVEDCOLOR, true);
355 if (ProgName && ProgName[0])
356 S << ProgName << ": ";
358 if (!Filename.empty()) {
367 S << ':' << (ColumnNo+1);
373 case SourceMgr::DK_Error:
375 S.changeColor(raw_ostream::RED, true);
378 case SourceMgr::DK_Warning:
380 S.changeColor(raw_ostream::MAGENTA, true);
383 case SourceMgr::DK_Note:
385 S.changeColor(raw_ostream::BLACK, true);
392 S.changeColor(raw_ostream::SAVEDCOLOR, true);
395 S << Message << '\n';
400 if (LineNo == -1 || ColumnNo == -1)
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);
413 size_t NumColumns = LineContents.size();
415 // Build the line with the caret and ranges.
416 std::string CaretLine(NumColumns+1, ' ');
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())],
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()));
433 // Finally, plop on the caret.
434 if (unsigned(ColumnNo) <= NumColumns)
435 CaretLine[ColumnNo] = '^';
437 CaretLine[NumColumns] = '^';
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
442 CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
444 printSourceLine(S, LineContents);
447 S.changeColor(raw_ostream::GREEN, true);
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') {
457 // Okay, we have a tab. Insert the appropriate number of characters.
461 } while ((OutCol % TabStop) != 0);
468 // Print out the replacement line, matching tabs in the source line.
469 if (FixItInsertionLine.empty())
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];
479 // Okay, we have a tab. Insert the appropriate number of characters.
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] != ' ')
490 } while (((OutCol % TabStop) != 0) && i != e);