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/STLExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Locale.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
25 static const size_t TabStop = 8;
28 struct LineNoCacheTy {
29 const char *LastQuery;
30 unsigned LastQueryBufferID;
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))
46 unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
48 std::string &IncludedFile) {
49 IncludedFile = Filename;
50 ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
51 MemoryBuffer::getFile(IncludedFile);
53 // If the file didn't exist directly, see if it's in an include path.
54 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
57 IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
58 NewBufOrErr = MemoryBuffer::getFile(IncludedFile);
64 return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc);
67 unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
68 for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
69 if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
70 // Use <= here so that a pointer to the null at the end of the buffer
71 // is included as part of the buffer.
72 Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
77 std::pair<unsigned, unsigned>
78 SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
80 BufferID = FindBufferContainingLoc(Loc);
81 assert(BufferID && "Invalid Location!");
83 const MemoryBuffer *Buff = getMemoryBuffer(BufferID);
85 // Count the number of \n's between the start of the file and the specified
89 const char *BufStart = Buff->getBufferStart();
90 const char *Ptr = BufStart;
92 // If we have a line number cache, and if the query is to a later point in the
93 // same file, start searching from the last query location. This optimizes
94 // for the case when multiple diagnostics come out of one file in order.
95 if (LineNoCacheTy *Cache = getCache(LineNoCache))
96 if (Cache->LastQueryBufferID == BufferID &&
97 Cache->LastQuery <= Loc.getPointer()) {
98 Ptr = Cache->LastQuery;
99 LineNo = Cache->LineNoOfQuery;
102 // Scan for the location being queried, keeping track of the number of lines
104 for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
105 if (*Ptr == '\n') ++LineNo;
107 // Allocate the line number cache if it doesn't exist.
109 LineNoCache = new LineNoCacheTy();
111 // Update the line # cache.
112 LineNoCacheTy &Cache = *getCache(LineNoCache);
113 Cache.LastQueryBufferID = BufferID;
114 Cache.LastQuery = Ptr;
115 Cache.LineNoOfQuery = LineNo;
117 size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
118 if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
119 return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
122 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
123 if (IncludeLoc == SMLoc()) return; // Top of stack.
125 unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
126 assert(CurBuf && "Invalid or unspecified location!");
128 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
130 OS << "Included from "
131 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
132 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
136 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
138 ArrayRef<SMRange> Ranges,
139 ArrayRef<SMFixIt> FixIts) const {
141 // First thing to do: find the current buffer containing the specified
142 // location to pull out the source line.
143 SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
144 std::pair<unsigned, unsigned> LineAndCol;
145 StringRef BufferID = "<unknown>";
149 unsigned CurBuf = FindBufferContainingLoc(Loc);
150 assert(CurBuf && "Invalid or unspecified location!");
152 const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
153 BufferID = CurMB->getBufferIdentifier();
155 // Scan backward to find the start of the line.
156 const char *LineStart = Loc.getPointer();
157 const char *BufStart = CurMB->getBufferStart();
158 while (LineStart != BufStart && LineStart[-1] != '\n' &&
159 LineStart[-1] != '\r')
162 // Get the end of the line.
163 const char *LineEnd = Loc.getPointer();
164 const char *BufEnd = CurMB->getBufferEnd();
165 while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
167 LineStr = std::string(LineStart, LineEnd);
169 // Convert any ranges to column ranges that only intersect the line of the
171 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
172 SMRange R = Ranges[i];
173 if (!R.isValid()) continue;
175 // If the line doesn't contain any part of the range, then ignore it.
176 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
179 // Ignore pieces of the range that go onto other lines.
180 if (R.Start.getPointer() < LineStart)
181 R.Start = SMLoc::getFromPointer(LineStart);
182 if (R.End.getPointer() > LineEnd)
183 R.End = SMLoc::getFromPointer(LineEnd);
185 // Translate from SMLoc ranges to column ranges.
186 // FIXME: Handle multibyte characters.
187 ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
188 R.End.getPointer()-LineStart));
191 LineAndCol = getLineAndColumn(Loc, CurBuf);
194 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
195 LineAndCol.second-1, Kind, Msg.str(),
196 LineStr, ColRanges, FixIts);
199 void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
200 bool ShowColors) const {
201 // Report the message with the diagnostic handler if present.
203 DiagHandler(Diagnostic, DiagContext);
207 if (Diagnostic.getLoc().isValid()) {
208 unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
209 assert(CurBuf && "Invalid or unspecified location!");
210 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
213 Diagnostic.print(nullptr, OS, ShowColors);
216 void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
217 SourceMgr::DiagKind Kind,
218 const Twine &Msg, ArrayRef<SMRange> Ranges,
219 ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
220 PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
223 void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
224 const Twine &Msg, ArrayRef<SMRange> Ranges,
225 ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
226 PrintMessage(llvm::errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
229 //===----------------------------------------------------------------------===//
230 // SMDiagnostic Implementation
231 //===----------------------------------------------------------------------===//
233 SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
234 int Line, int Col, SourceMgr::DiagKind Kind,
235 StringRef Msg, StringRef LineStr,
236 ArrayRef<std::pair<unsigned,unsigned> > Ranges,
237 ArrayRef<SMFixIt> Hints)
238 : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
239 Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
240 FixIts(Hints.begin(), Hints.end()) {
241 std::sort(FixIts.begin(), FixIts.end());
244 static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
245 ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
249 const char *LineStart = SourceLine.begin();
250 const char *LineEnd = SourceLine.end();
252 size_t PrevHintEndCol = 0;
254 for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
256 // If the fixit contains a newline or tab, ignore it.
257 if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
260 SMRange R = I->getRange();
262 // If the line doesn't contain any part of the range, then ignore it.
263 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
266 // Translate from SMLoc to column.
267 // Ignore pieces of the range that go onto other lines.
268 // FIXME: Handle multibyte characters in the source line.
270 if (R.Start.getPointer() < LineStart)
273 FirstCol = R.Start.getPointer() - LineStart;
275 // If we inserted a long previous hint, push this one forwards, and add
276 // an extra space to show that this is not part of the previous
277 // completion. This is sort of the best we can do when two hints appear
280 // Note that if this hint is located immediately after the previous
281 // hint, no space will be added, since the location is more important.
282 unsigned HintCol = FirstCol;
283 if (HintCol < PrevHintEndCol)
284 HintCol = PrevHintEndCol + 1;
286 // FIXME: This assertion is intended to catch unintended use of multibyte
287 // characters in fixits. If we decide to do this, we'll have to track
288 // separate byte widths for the source and fixit lines.
289 assert((size_t)llvm::sys::locale::columnWidth(I->getText()) ==
290 I->getText().size());
292 // This relies on one byte per column in our fixit hints.
293 unsigned LastColumnModified = HintCol + I->getText().size();
294 if (LastColumnModified > FixItLine.size())
295 FixItLine.resize(LastColumnModified, ' ');
297 std::copy(I->getText().begin(), I->getText().end(),
298 FixItLine.begin() + HintCol);
300 PrevHintEndCol = LastColumnModified;
302 // For replacements, mark the removal range with '~'.
303 // FIXME: Handle multibyte characters in the source line.
305 if (R.End.getPointer() >= LineEnd)
306 LastCol = LineEnd - LineStart;
308 LastCol = R.End.getPointer() - LineStart;
310 std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
314 static void printSourceLine(raw_ostream &S, StringRef LineContents) {
315 // Print out the source line one character at a time, so we can expand tabs.
316 for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
317 if (LineContents[i] != '\t') {
318 S << LineContents[i];
323 // If we have a tab, emit at least one space, then round up to 8 columns.
327 } while ((OutCol % TabStop) != 0);
332 static bool isNonASCII(char c) {
336 void SMDiagnostic::print(const char *ProgName, raw_ostream &S, bool ShowColors,
337 bool ShowKindLabel) const {
338 // Display colors only if OS supports colors.
339 ShowColors &= S.has_colors();
342 S.changeColor(raw_ostream::SAVEDCOLOR, true);
344 if (ProgName && ProgName[0])
345 S << ProgName << ": ";
347 if (!Filename.empty()) {
356 S << ':' << (ColumnNo+1);
363 case SourceMgr::DK_Error:
365 S.changeColor(raw_ostream::RED, true);
368 case SourceMgr::DK_Warning:
370 S.changeColor(raw_ostream::MAGENTA, true);
373 case SourceMgr::DK_Note:
375 S.changeColor(raw_ostream::BLACK, true);
382 S.changeColor(raw_ostream::SAVEDCOLOR, true);
386 S << Message << '\n';
391 if (LineNo == -1 || ColumnNo == -1)
394 // FIXME: If there are multibyte or multi-column characters in the source, all
395 // our ranges will be wrong. To do this properly, we'll need a byte-to-column
396 // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
397 // expanding them later, and bail out rather than show incorrect ranges and
398 // misaligned fixits for any other odd characters.
399 if (find_if(LineContents, isNonASCII) != LineContents.end()) {
400 printSourceLine(S, LineContents);
403 size_t NumColumns = LineContents.size();
405 // Build the line with the caret and ranges.
406 std::string CaretLine(NumColumns+1, ' ');
408 // Expand any ranges.
409 for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
410 std::pair<unsigned, unsigned> R = Ranges[r];
411 std::fill(&CaretLine[R.first],
412 &CaretLine[std::min((size_t)R.second, CaretLine.size())],
417 // FIXME: Find the beginning of the line properly for multibyte characters.
418 std::string FixItInsertionLine;
419 buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
420 makeArrayRef(Loc.getPointer() - ColumnNo,
421 LineContents.size()));
423 // Finally, plop on the caret.
424 if (unsigned(ColumnNo) <= NumColumns)
425 CaretLine[ColumnNo] = '^';
427 CaretLine[NumColumns] = '^';
429 // ... and remove trailing whitespace so the output doesn't wrap for it. We
430 // know that the line isn't completely empty because it has the caret in it at
432 CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
434 printSourceLine(S, LineContents);
437 S.changeColor(raw_ostream::GREEN, true);
439 // Print out the caret line, matching tabs in the source line.
440 for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
441 if (i >= LineContents.size() || LineContents[i] != '\t') {
447 // Okay, we have a tab. Insert the appropriate number of characters.
451 } while ((OutCol % TabStop) != 0);
458 // Print out the replacement line, matching tabs in the source line.
459 if (FixItInsertionLine.empty())
462 for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
463 if (i >= LineContents.size() || LineContents[i] != '\t') {
464 S << FixItInsertionLine[i];
469 // Okay, we have a tab. Insert the appropriate number of characters.
471 S << FixItInsertionLine[i];
472 // FIXME: This is trying not to break up replacements, but then to re-sync
473 // with the tabs between replacements. This will fail, though, if two
474 // fix-it replacements are exactly adjacent, or if a fix-it contains a
475 // space. Really we should be precomputing column widths, which we'll
476 // need anyway for multibyte chars.
477 if (FixItInsertionLine[i] != ' ')
480 } while (((OutCol % TabStop) != 0) && i != e);