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