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/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/Path.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include <system_error> 24 using namespace llvm; 25 26 static const size_t TabStop = 8; 27 28 namespace { 29 struct LineNoCacheTy { 30 int LastQueryBufferID; 31 const char *LastQuery; 32 unsigned LineNoOfQuery; 33 }; 34 } 35 36 static LineNoCacheTy *getCache(void *Ptr) { 37 return (LineNoCacheTy*)Ptr; 38 } 39 40 41 SourceMgr::~SourceMgr() { 42 // Delete the line # cache if allocated. 43 if (LineNoCacheTy *Cache = getCache(LineNoCache)) 44 delete Cache; 45 46 while (!Buffers.empty()) { 47 delete Buffers.back().Buffer; 48 Buffers.pop_back(); 49 } 50 } 51 52 size_t SourceMgr::AddIncludeFile(const std::string &Filename, 53 SMLoc IncludeLoc, 54 std::string &IncludedFile) { 55 std::unique_ptr<MemoryBuffer> NewBuf; 56 IncludedFile = Filename; 57 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf); 58 59 // If the file didn't exist directly, see if it's in an include path. 60 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) { 61 IncludedFile = IncludeDirectories[i] + sys::path::get_separator().data() + Filename; 62 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf); 63 } 64 65 if (!NewBuf) return ~0U; 66 67 return AddNewSourceBuffer(NewBuf.release(), IncludeLoc); 68 } 69 70 71 int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const { 72 for (unsigned i = 0, e = Buffers.size(); i != e; ++i) 73 if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() && 74 // Use <= here so that a pointer to the null at the end of the buffer 75 // is included as part of the buffer. 76 Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd()) 77 return i; 78 return -1; 79 } 80 81 std::pair<unsigned, unsigned> 82 SourceMgr::getLineAndColumn(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 *BufStart = Buff->getBufferStart(); 93 const char *Ptr = BufStart; 94 95 // If we have a line number cache, and if the query is to a later point in the 96 // same file, start searching from the last query location. This optimizes 97 // for the case when multiple diagnostics come out of one file in order. 98 if (LineNoCacheTy *Cache = getCache(LineNoCache)) 99 if (Cache->LastQueryBufferID == BufferID && 100 Cache->LastQuery <= Loc.getPointer()) { 101 Ptr = Cache->LastQuery; 102 LineNo = Cache->LineNoOfQuery; 103 } 104 105 // Scan for the location being queried, keeping track of the number of lines 106 // we see. 107 for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr) 108 if (*Ptr == '\n') ++LineNo; 109 110 // Allocate the line number cache if it doesn't exist. 111 if (!LineNoCache) 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 120 size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r"); 121 if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0; 122 return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs); 123 } 124 125 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const { 126 if (IncludeLoc == SMLoc()) return; // Top of stack. 127 128 int CurBuf = FindBufferContainingLoc(IncludeLoc); 129 assert(CurBuf != -1 && "Invalid or unspecified location!"); 130 131 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS); 132 133 OS << "Included from " 134 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier() 135 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n"; 136 } 137 138 139 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind, 140 const Twine &Msg, 141 ArrayRef<SMRange> Ranges, 142 ArrayRef<SMFixIt> FixIts) const { 143 144 // First thing to do: find the current buffer containing the specified 145 // location to pull out the source line. 146 SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges; 147 std::pair<unsigned, unsigned> LineAndCol; 148 const char *BufferID = "<unknown>"; 149 std::string LineStr; 150 151 if (Loc.isValid()) { 152 int CurBuf = FindBufferContainingLoc(Loc); 153 assert(CurBuf != -1 && "Invalid or unspecified location!"); 154 155 MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer; 156 BufferID = CurMB->getBufferIdentifier(); 157 158 // Scan backward to find the start of the line. 159 const char *LineStart = Loc.getPointer(); 160 const char *BufStart = CurMB->getBufferStart(); 161 while (LineStart != BufStart && LineStart[-1] != '\n' && 162 LineStart[-1] != '\r') 163 --LineStart; 164 165 // Get the end of the line. 166 const char *LineEnd = Loc.getPointer(); 167 const char *BufEnd = CurMB->getBufferEnd(); 168 while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r') 169 ++LineEnd; 170 LineStr = std::string(LineStart, LineEnd); 171 172 // Convert any ranges to column ranges that only intersect the line of the 173 // location. 174 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { 175 SMRange R = Ranges[i]; 176 if (!R.isValid()) continue; 177 178 // If the line doesn't contain any part of the range, then ignore it. 179 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart) 180 continue; 181 182 // Ignore pieces of the range that go onto other lines. 183 if (R.Start.getPointer() < LineStart) 184 R.Start = SMLoc::getFromPointer(LineStart); 185 if (R.End.getPointer() > LineEnd) 186 R.End = SMLoc::getFromPointer(LineEnd); 187 188 // Translate from SMLoc ranges to column ranges. 189 // FIXME: Handle multibyte characters. 190 ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart, 191 R.End.getPointer()-LineStart)); 192 } 193 194 LineAndCol = getLineAndColumn(Loc, CurBuf); 195 } 196 197 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first, 198 LineAndCol.second-1, Kind, Msg.str(), 199 LineStr, ColRanges, FixIts); 200 } 201 202 void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc, 203 SourceMgr::DiagKind Kind, 204 const Twine &Msg, ArrayRef<SMRange> Ranges, 205 ArrayRef<SMFixIt> FixIts, bool ShowColors) const { 206 SMDiagnostic Diagnostic = GetMessage(Loc, Kind, Msg, Ranges, FixIts); 207 208 // Report the message with the diagnostic handler if present. 209 if (DiagHandler) { 210 DiagHandler(Diagnostic, DiagContext); 211 return; 212 } 213 214 if (Loc != SMLoc()) { 215 int CurBuf = FindBufferContainingLoc(Loc); 216 assert(CurBuf != -1 && "Invalid or unspecified location!"); 217 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS); 218 } 219 220 Diagnostic.print(nullptr, OS, ShowColors); 221 } 222 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); 227 } 228 229 //===----------------------------------------------------------------------===// 230 // SMDiagnostic Implementation 231 //===----------------------------------------------------------------------===// 232 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()); 242 } 243 244 static void buildFixItLine(std::string &CaretLine, std::string &FixItLine, 245 ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){ 246 if (FixIts.empty()) 247 return; 248 249 const char *LineStart = SourceLine.begin(); 250 const char *LineEnd = SourceLine.end(); 251 252 size_t PrevHintEndCol = 0; 253 254 for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end(); 255 I != E; ++I) { 256 // If the fixit contains a newline or tab, ignore it. 257 if (I->getText().find_first_of("\n\r\t") != StringRef::npos) 258 continue; 259 260 SMRange R = I->getRange(); 261 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) 264 continue; 265 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. 269 unsigned FirstCol; 270 if (R.Start.getPointer() < LineStart) 271 FirstCol = 0; 272 else 273 FirstCol = R.Start.getPointer() - LineStart; 274 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 278 // to overlap. 279 // 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; 285 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()); 291 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, ' '); 296 297 std::copy(I->getText().begin(), I->getText().end(), 298 FixItLine.begin() + HintCol); 299 300 PrevHintEndCol = LastColumnModified; 301 302 // For replacements, mark the removal range with '~'. 303 // FIXME: Handle multibyte characters in the source line. 304 unsigned LastCol; 305 if (R.End.getPointer() >= LineEnd) 306 LastCol = LineEnd - LineStart; 307 else 308 LastCol = R.End.getPointer() - LineStart; 309 310 std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~'); 311 } 312 } 313 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]; 319 ++OutCol; 320 continue; 321 } 322 323 // If we have a tab, emit at least one space, then round up to 8 columns. 324 do { 325 S << ' '; 326 ++OutCol; 327 } while ((OutCol % TabStop) != 0); 328 } 329 S << '\n'; 330 } 331 332 static bool isNonASCII(char c) { 333 return c & 0x80; 334 } 335 336 void SMDiagnostic::print(const char *ProgName, raw_ostream &S, 337 bool ShowColors) const { 338 // Display colors only if OS supports colors. 339 ShowColors &= S.has_colors(); 340 341 if (ShowColors) 342 S.changeColor(raw_ostream::SAVEDCOLOR, true); 343 344 if (ProgName && ProgName[0]) 345 S << ProgName << ": "; 346 347 if (!Filename.empty()) { 348 if (Filename == "-") 349 S << "<stdin>"; 350 else 351 S << Filename; 352 353 if (LineNo != -1) { 354 S << ':' << LineNo; 355 if (ColumnNo != -1) 356 S << ':' << (ColumnNo+1); 357 } 358 S << ": "; 359 } 360 361 switch (Kind) { 362 case SourceMgr::DK_Error: 363 if (ShowColors) 364 S.changeColor(raw_ostream::RED, true); 365 S << "error: "; 366 break; 367 case SourceMgr::DK_Warning: 368 if (ShowColors) 369 S.changeColor(raw_ostream::MAGENTA, true); 370 S << "warning: "; 371 break; 372 case SourceMgr::DK_Note: 373 if (ShowColors) 374 S.changeColor(raw_ostream::BLACK, true); 375 S << "note: "; 376 break; 377 } 378 379 if (ShowColors) { 380 S.resetColor(); 381 S.changeColor(raw_ostream::SAVEDCOLOR, true); 382 } 383 384 S << Message << '\n'; 385 386 if (ShowColors) 387 S.resetColor(); 388 389 if (LineNo == -1 || ColumnNo == -1) 390 return; 391 392 // FIXME: If there are multibyte or multi-column characters in the source, all 393 // our ranges will be wrong. To do this properly, we'll need a byte-to-column 394 // map like Clang's TextDiagnostic. For now, we'll just handle tabs by 395 // expanding them later, and bail out rather than show incorrect ranges and 396 // misaligned fixits for any other odd characters. 397 if (std::find_if(LineContents.begin(), LineContents.end(), isNonASCII) != 398 LineContents.end()) { 399 printSourceLine(S, LineContents); 400 return; 401 } 402 size_t NumColumns = LineContents.size(); 403 404 // Build the line with the caret and ranges. 405 std::string CaretLine(NumColumns+1, ' '); 406 407 // Expand any ranges. 408 for (unsigned r = 0, e = Ranges.size(); r != e; ++r) { 409 std::pair<unsigned, unsigned> R = Ranges[r]; 410 std::fill(&CaretLine[R.first], 411 &CaretLine[std::min((size_t)R.second, CaretLine.size())], 412 '~'); 413 } 414 415 // Add any fix-its. 416 // FIXME: Find the beginning of the line properly for multibyte characters. 417 std::string FixItInsertionLine; 418 buildFixItLine(CaretLine, FixItInsertionLine, FixIts, 419 makeArrayRef(Loc.getPointer() - ColumnNo, 420 LineContents.size())); 421 422 // Finally, plop on the caret. 423 if (unsigned(ColumnNo) <= NumColumns) 424 CaretLine[ColumnNo] = '^'; 425 else 426 CaretLine[NumColumns] = '^'; 427 428 // ... and remove trailing whitespace so the output doesn't wrap for it. We 429 // know that the line isn't completely empty because it has the caret in it at 430 // least. 431 CaretLine.erase(CaretLine.find_last_not_of(' ')+1); 432 433 printSourceLine(S, LineContents); 434 435 if (ShowColors) 436 S.changeColor(raw_ostream::GREEN, true); 437 438 // Print out the caret line, matching tabs in the source line. 439 for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) { 440 if (i >= LineContents.size() || LineContents[i] != '\t') { 441 S << CaretLine[i]; 442 ++OutCol; 443 continue; 444 } 445 446 // Okay, we have a tab. Insert the appropriate number of characters. 447 do { 448 S << CaretLine[i]; 449 ++OutCol; 450 } while ((OutCol % TabStop) != 0); 451 } 452 S << '\n'; 453 454 if (ShowColors) 455 S.resetColor(); 456 457 // Print out the replacement line, matching tabs in the source line. 458 if (FixItInsertionLine.empty()) 459 return; 460 461 for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) { 462 if (i >= LineContents.size() || LineContents[i] != '\t') { 463 S << FixItInsertionLine[i]; 464 ++OutCol; 465 continue; 466 } 467 468 // Okay, we have a tab. Insert the appropriate number of characters. 469 do { 470 S << FixItInsertionLine[i]; 471 // FIXME: This is trying not to break up replacements, but then to re-sync 472 // with the tabs between replacements. This will fail, though, if two 473 // fix-it replacements are exactly adjacent, or if a fix-it contains a 474 // space. Really we should be precomputing column widths, which we'll 475 // need anyway for multibyte chars. 476 if (FixItInsertionLine[i] != ' ') 477 ++i; 478 ++OutCol; 479 } while (((OutCol % TabStop) != 0) && i != e); 480 } 481 S << '\n'; 482 } 483