SourceMgr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. #include "llvm/Support/SourceMgr.h"
  16. #include "llvm/ADT/Twine.h"
  17. #include "llvm/Support/Locale.h"
  18. #include "llvm/Support/MemoryBuffer.h"
  19. #include "llvm/Support/Path.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace llvm;
  22. static const size_t TabStop = 8;
  23. namespace {
  24. struct LineNoCacheTy {
  25. unsigned LastQueryBufferID;
  26. const char *LastQuery;
  27. unsigned LineNoOfQuery;
  28. };
  29. }
  30. static LineNoCacheTy *getCache(void *Ptr) {
  31. return (LineNoCacheTy*)Ptr;
  32. }
  33. // HLSL Change Starts: add a Reset version of the destructor
  34. SourceMgr::~SourceMgr() {
  35. Reset();
  36. }
  37. void SourceMgr::Reset() {
  38. // Delete the line # cache if allocated.
  39. if (LineNoCacheTy *Cache = getCache(LineNoCache)) {
  40. delete Cache;
  41. LineNoCache = nullptr; // MS Change
  42. }
  43. Buffers.clear();
  44. IncludeDirectories.clear();
  45. }
  46. // HLSL Change Ends: add a Reset version of the destructor
  47. unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
  48. SMLoc IncludeLoc,
  49. std::string &IncludedFile) {
  50. IncludedFile = Filename;
  51. ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
  52. 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;
  55. ++i) {
  56. IncludedFile =
  57. IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
  58. NewBufOrErr = MemoryBuffer::getFile(IncludedFile);
  59. }
  60. if (!NewBufOrErr)
  61. return 0;
  62. return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc);
  63. }
  64. unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
  65. for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
  66. if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
  67. // Use <= here so that a pointer to the null at the end of the buffer
  68. // is included as part of the buffer.
  69. Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
  70. return i + 1;
  71. return 0;
  72. }
  73. std::pair<unsigned, unsigned>
  74. SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
  75. if (!BufferID)
  76. BufferID = FindBufferContainingLoc(Loc);
  77. assert(BufferID && "Invalid Location!");
  78. const MemoryBuffer *Buff = getMemoryBuffer(BufferID);
  79. // Count the number of \n's between the start of the file and the specified
  80. // location.
  81. unsigned LineNo = 1;
  82. const char *BufStart = Buff->getBufferStart();
  83. const char *Ptr = BufStart;
  84. // If we have a line number cache, and if the query is to a later point in the
  85. // same file, start searching from the last query location. This optimizes
  86. // for the case when multiple diagnostics come out of one file in order.
  87. if (LineNoCacheTy *Cache = getCache(LineNoCache))
  88. if (Cache->LastQueryBufferID == BufferID &&
  89. Cache->LastQuery <= Loc.getPointer()) {
  90. Ptr = Cache->LastQuery;
  91. LineNo = Cache->LineNoOfQuery;
  92. }
  93. // Scan for the location being queried, keeping track of the number of lines
  94. // we see.
  95. for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
  96. if (*Ptr == '\n') ++LineNo;
  97. // Allocate the line number cache if it doesn't exist.
  98. if (!LineNoCache)
  99. LineNoCache = new LineNoCacheTy();
  100. // Update the line # cache.
  101. LineNoCacheTy &Cache = *getCache(LineNoCache);
  102. Cache.LastQueryBufferID = BufferID;
  103. Cache.LastQuery = Ptr;
  104. Cache.LineNoOfQuery = LineNo;
  105. size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
  106. if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
  107. return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
  108. }
  109. void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
  110. if (IncludeLoc == SMLoc()) return; // Top of stack.
  111. unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
  112. assert(CurBuf && "Invalid or unspecified location!");
  113. PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
  114. OS << "Included from "
  115. << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
  116. << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
  117. }
  118. SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
  119. const Twine &Msg,
  120. ArrayRef<SMRange> Ranges,
  121. ArrayRef<SMFixIt> FixIts) const {
  122. // First thing to do: find the current buffer containing the specified
  123. // location to pull out the source line.
  124. SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
  125. std::pair<unsigned, unsigned> LineAndCol;
  126. const char *BufferID = "<unknown>";
  127. std::string LineStr;
  128. if (Loc.isValid()) {
  129. unsigned CurBuf = FindBufferContainingLoc(Loc);
  130. assert(CurBuf && "Invalid or unspecified location!");
  131. const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
  132. BufferID = CurMB->getBufferIdentifier();
  133. // Scan backward to find the start of the line.
  134. const char *LineStart = Loc.getPointer();
  135. const char *BufStart = CurMB->getBufferStart();
  136. while (LineStart != BufStart && LineStart[-1] != '\n' &&
  137. LineStart[-1] != '\r')
  138. --LineStart;
  139. // Get the end of the line.
  140. const char *LineEnd = Loc.getPointer();
  141. const char *BufEnd = CurMB->getBufferEnd();
  142. while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
  143. ++LineEnd;
  144. LineStr = std::string(LineStart, LineEnd);
  145. // Convert any ranges to column ranges that only intersect the line of the
  146. // location.
  147. for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
  148. SMRange R = Ranges[i];
  149. if (!R.isValid()) continue;
  150. // If the line doesn't contain any part of the range, then ignore it.
  151. if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
  152. continue;
  153. // Ignore pieces of the range that go onto other lines.
  154. if (R.Start.getPointer() < LineStart)
  155. R.Start = SMLoc::getFromPointer(LineStart);
  156. if (R.End.getPointer() > LineEnd)
  157. R.End = SMLoc::getFromPointer(LineEnd);
  158. // Translate from SMLoc ranges to column ranges.
  159. // FIXME: Handle multibyte characters.
  160. ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
  161. R.End.getPointer()-LineStart));
  162. }
  163. LineAndCol = getLineAndColumn(Loc, CurBuf);
  164. }
  165. return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
  166. LineAndCol.second-1, Kind, Msg.str(),
  167. LineStr, ColRanges, FixIts);
  168. }
  169. void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
  170. bool ShowColors) const {
  171. // Report the message with the diagnostic handler if present.
  172. if (DiagHandler) {
  173. DiagHandler(Diagnostic, DiagContext);
  174. return;
  175. }
  176. if (Diagnostic.getLoc().isValid()) {
  177. unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
  178. assert(CurBuf && "Invalid or unspecified location!");
  179. PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
  180. }
  181. Diagnostic.print(nullptr, OS, ShowColors);
  182. }
  183. void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
  184. SourceMgr::DiagKind Kind,
  185. const Twine &Msg, ArrayRef<SMRange> Ranges,
  186. ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
  187. PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
  188. }
  189. void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
  190. const Twine &Msg, ArrayRef<SMRange> Ranges,
  191. ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
  192. PrintMessage(llvm::errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
  193. }
  194. //===----------------------------------------------------------------------===//
  195. // SMDiagnostic Implementation
  196. //===----------------------------------------------------------------------===//
  197. SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
  198. int Line, int Col, SourceMgr::DiagKind Kind,
  199. StringRef Msg, StringRef LineStr,
  200. ArrayRef<std::pair<unsigned,unsigned> > Ranges,
  201. ArrayRef<SMFixIt> Hints)
  202. : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
  203. Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
  204. FixIts(Hints.begin(), Hints.end()) {
  205. std::sort(FixIts.begin(), FixIts.end());
  206. }
  207. static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
  208. ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
  209. if (FixIts.empty())
  210. return;
  211. const char *LineStart = SourceLine.begin();
  212. const char *LineEnd = SourceLine.end();
  213. size_t PrevHintEndCol = 0;
  214. for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
  215. I != E; ++I) {
  216. // If the fixit contains a newline or tab, ignore it.
  217. if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
  218. continue;
  219. SMRange R = I->getRange();
  220. // If the line doesn't contain any part of the range, then ignore it.
  221. if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
  222. continue;
  223. // Translate from SMLoc to column.
  224. // Ignore pieces of the range that go onto other lines.
  225. // FIXME: Handle multibyte characters in the source line.
  226. unsigned FirstCol;
  227. if (R.Start.getPointer() < LineStart)
  228. FirstCol = 0;
  229. else
  230. FirstCol = R.Start.getPointer() - LineStart;
  231. // If we inserted a long previous hint, push this one forwards, and add
  232. // an extra space to show that this is not part of the previous
  233. // completion. This is sort of the best we can do when two hints appear
  234. // to overlap.
  235. //
  236. // Note that if this hint is located immediately after the previous
  237. // hint, no space will be added, since the location is more important.
  238. unsigned HintCol = FirstCol;
  239. if (HintCol < PrevHintEndCol)
  240. HintCol = PrevHintEndCol + 1;
  241. // FIXME: This assertion is intended to catch unintended use of multibyte
  242. // characters in fixits. If we decide to do this, we'll have to track
  243. // separate byte widths for the source and fixit lines.
  244. assert((size_t)llvm::sys::locale::columnWidth(I->getText()) ==
  245. I->getText().size());
  246. // This relies on one byte per column in our fixit hints.
  247. unsigned LastColumnModified = HintCol + I->getText().size();
  248. if (LastColumnModified > FixItLine.size())
  249. FixItLine.resize(LastColumnModified, ' ');
  250. std::copy(I->getText().begin(), I->getText().end(),
  251. FixItLine.begin() + HintCol);
  252. PrevHintEndCol = LastColumnModified;
  253. // For replacements, mark the removal range with '~'.
  254. // FIXME: Handle multibyte characters in the source line.
  255. unsigned LastCol;
  256. if (R.End.getPointer() >= LineEnd)
  257. LastCol = LineEnd - LineStart;
  258. else
  259. LastCol = R.End.getPointer() - LineStart;
  260. std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
  261. }
  262. }
  263. static void printSourceLine(raw_ostream &S, StringRef LineContents) {
  264. // Print out the source line one character at a time, so we can expand tabs.
  265. for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
  266. if (LineContents[i] != '\t') {
  267. S << LineContents[i];
  268. ++OutCol;
  269. continue;
  270. }
  271. // If we have a tab, emit at least one space, then round up to 8 columns.
  272. do {
  273. S << ' ';
  274. ++OutCol;
  275. } while ((OutCol % TabStop) != 0);
  276. }
  277. S << '\n';
  278. }
  279. static bool isNonASCII(char c) {
  280. return c & 0x80;
  281. }
  282. void SMDiagnostic::print(const char *ProgName, raw_ostream &S, bool ShowColors,
  283. bool ShowKindLabel) const {
  284. // Display colors only if OS supports colors.
  285. ShowColors &= S.has_colors();
  286. if (ShowColors)
  287. S.changeColor(raw_ostream::SAVEDCOLOR, true);
  288. if (ProgName && ProgName[0])
  289. S << ProgName << ": ";
  290. if (!Filename.empty()) {
  291. if (Filename == "-")
  292. S << "<stdin>";
  293. else
  294. S << Filename;
  295. if (LineNo != -1) {
  296. S << ':' << LineNo;
  297. if (ColumnNo != -1)
  298. S << ':' << (ColumnNo+1);
  299. }
  300. S << ": ";
  301. }
  302. if (ShowKindLabel) {
  303. switch (Kind) {
  304. case SourceMgr::DK_Error:
  305. if (ShowColors)
  306. S.changeColor(raw_ostream::RED, true);
  307. S << "error: ";
  308. break;
  309. case SourceMgr::DK_Warning:
  310. if (ShowColors)
  311. S.changeColor(raw_ostream::MAGENTA, true);
  312. S << "warning: ";
  313. break;
  314. case SourceMgr::DK_Note:
  315. if (ShowColors)
  316. S.changeColor(raw_ostream::BLACK, true);
  317. S << "note: ";
  318. break;
  319. }
  320. if (ShowColors) {
  321. S.resetColor();
  322. S.changeColor(raw_ostream::SAVEDCOLOR, true);
  323. }
  324. }
  325. S << Message << '\n';
  326. if (ShowColors)
  327. S.resetColor();
  328. if (LineNo == -1 || ColumnNo == -1)
  329. return;
  330. // FIXME: If there are multibyte or multi-column characters in the source, all
  331. // our ranges will be wrong. To do this properly, we'll need a byte-to-column
  332. // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
  333. // expanding them later, and bail out rather than show incorrect ranges and
  334. // misaligned fixits for any other odd characters.
  335. if (std::find_if(LineContents.begin(), LineContents.end(), isNonASCII) !=
  336. LineContents.end()) {
  337. printSourceLine(S, LineContents);
  338. return;
  339. }
  340. size_t NumColumns = LineContents.size();
  341. // Build the line with the caret and ranges.
  342. std::string CaretLine(NumColumns+1, ' ');
  343. // Expand any ranges.
  344. for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
  345. std::pair<unsigned, unsigned> R = Ranges[r];
  346. std::fill(&CaretLine[R.first],
  347. &CaretLine[std::min((size_t)R.second, CaretLine.size())],
  348. '~');
  349. }
  350. // Add any fix-its.
  351. // FIXME: Find the beginning of the line properly for multibyte characters.
  352. std::string FixItInsertionLine;
  353. buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
  354. makeArrayRef(Loc.getPointer() - ColumnNo,
  355. LineContents.size()));
  356. // Finally, plop on the caret.
  357. if (unsigned(ColumnNo) <= NumColumns)
  358. CaretLine[ColumnNo] = '^';
  359. else
  360. CaretLine[NumColumns] = '^';
  361. // ... and remove trailing whitespace so the output doesn't wrap for it. We
  362. // know that the line isn't completely empty because it has the caret in it at
  363. // least.
  364. CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
  365. printSourceLine(S, LineContents);
  366. if (ShowColors)
  367. S.changeColor(raw_ostream::GREEN, true);
  368. // Print out the caret line, matching tabs in the source line.
  369. for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
  370. if (i >= LineContents.size() || LineContents[i] != '\t') {
  371. S << CaretLine[i];
  372. ++OutCol;
  373. continue;
  374. }
  375. // Okay, we have a tab. Insert the appropriate number of characters.
  376. do {
  377. S << CaretLine[i];
  378. ++OutCol;
  379. } while ((OutCol % TabStop) != 0);
  380. }
  381. S << '\n';
  382. if (ShowColors)
  383. S.resetColor();
  384. // Print out the replacement line, matching tabs in the source line.
  385. if (FixItInsertionLine.empty())
  386. return;
  387. for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
  388. if (i >= LineContents.size() || LineContents[i] != '\t') {
  389. S << FixItInsertionLine[i];
  390. ++OutCol;
  391. continue;
  392. }
  393. // Okay, we have a tab. Insert the appropriate number of characters.
  394. do {
  395. S << FixItInsertionLine[i];
  396. // FIXME: This is trying not to break up replacements, but then to re-sync
  397. // with the tabs between replacements. This will fail, though, if two
  398. // fix-it replacements are exactly adjacent, or if a fix-it contains a
  399. // space. Really we should be precomputing column widths, which we'll
  400. // need anyway for multibyte chars.
  401. if (FixItInsertionLine[i] != ' ')
  402. ++i;
  403. ++OutCol;
  404. } while (((OutCol % TabStop) != 0) && i != e);
  405. }
  406. S << '\n';
  407. }