SourceMgr.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- SourceMgr.h - Manager for Source Buffers & Diagnostics ---*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the SMDiagnostic and SourceMgr classes. This
  15. // provides a simple substrate for diagnostics, #include handling, and other low
  16. // level things for simple parsers.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_SUPPORT_SOURCEMGR_H
  20. #define LLVM_SUPPORT_SOURCEMGR_H
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. #include "llvm/Support/SMLoc.h"
  24. #include <vector>
  25. namespace llvm {
  26. class raw_ostream;
  27. class SMDiagnostic;
  28. class SMFixIt;
  29. /// This owns the files read by a parser, handles include stacks,
  30. /// and handles diagnostic wrangling.
  31. class SourceMgr {
  32. public:
  33. enum DiagKind {
  34. DK_Error,
  35. DK_Warning,
  36. DK_Remark,
  37. DK_Note,
  38. };
  39. /// Clients that want to handle their own diagnostics in a custom way can
  40. /// register a function pointer+context as a diagnostic handler.
  41. /// It gets called each time PrintMessage is invoked.
  42. using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
  43. private:
  44. struct SrcBuffer {
  45. /// The memory buffer for the file.
  46. std::unique_ptr<MemoryBuffer> Buffer;
  47. /// Vector of offsets into Buffer at which there are line-endings
  48. /// (lazily populated). Once populated, the '\n' that marks the end of
  49. /// line number N from [1..] is at Buffer[OffsetCache[N-1]]. Since
  50. /// these offsets are in sorted (ascending) order, they can be
  51. /// binary-searched for the first one after any given offset (eg. an
  52. /// offset corresponding to a particular SMLoc).
  53. ///
  54. /// Since we're storing offsets into relatively small files (often smaller
  55. /// than 2^8 or 2^16 bytes), we select the offset vector element type
  56. /// dynamically based on the size of Buffer.
  57. mutable void *OffsetCache = nullptr;
  58. /// Look up a given \p Ptr in in the buffer, determining which line it came
  59. /// from.
  60. unsigned getLineNumber(const char *Ptr) const;
  61. template <typename T>
  62. unsigned getLineNumberSpecialized(const char *Ptr) const;
  63. /// Return a pointer to the first character of the specified line number or
  64. /// null if the line number is invalid.
  65. const char *getPointerForLineNumber(unsigned LineNo) const;
  66. template <typename T>
  67. const char *getPointerForLineNumberSpecialized(unsigned LineNo) const;
  68. /// This is the location of the parent include, or null if at the top level.
  69. SMLoc IncludeLoc;
  70. SrcBuffer() = default;
  71. SrcBuffer(SrcBuffer &&);
  72. SrcBuffer(const SrcBuffer &) = delete;
  73. SrcBuffer &operator=(const SrcBuffer &) = delete;
  74. ~SrcBuffer();
  75. };
  76. /// This is all of the buffers that we are reading from.
  77. std::vector<SrcBuffer> Buffers;
  78. // This is the list of directories we should search for include files in.
  79. std::vector<std::string> IncludeDirectories;
  80. DiagHandlerTy DiagHandler = nullptr;
  81. void *DiagContext = nullptr;
  82. bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); }
  83. public:
  84. SourceMgr() = default;
  85. SourceMgr(const SourceMgr &) = delete;
  86. SourceMgr &operator=(const SourceMgr &) = delete;
  87. SourceMgr(SourceMgr &&) = default;
  88. SourceMgr &operator=(SourceMgr &&) = default;
  89. ~SourceMgr() = default;
  90. /// Return the include directories of this source manager.
  91. ArrayRef<std::string> getIncludeDirs() const { return IncludeDirectories; }
  92. void setIncludeDirs(const std::vector<std::string> &Dirs) {
  93. IncludeDirectories = Dirs;
  94. }
  95. /// Specify a diagnostic handler to be invoked every time PrintMessage is
  96. /// called. \p Ctx is passed into the handler when it is invoked.
  97. void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
  98. DiagHandler = DH;
  99. DiagContext = Ctx;
  100. }
  101. DiagHandlerTy getDiagHandler() const { return DiagHandler; }
  102. void *getDiagContext() const { return DiagContext; }
  103. const SrcBuffer &getBufferInfo(unsigned i) const {
  104. assert(isValidBufferID(i));
  105. return Buffers[i - 1];
  106. }
  107. const MemoryBuffer *getMemoryBuffer(unsigned i) const {
  108. assert(isValidBufferID(i));
  109. return Buffers[i - 1].Buffer.get();
  110. }
  111. unsigned getNumBuffers() const { return Buffers.size(); }
  112. unsigned getMainFileID() const {
  113. assert(getNumBuffers());
  114. return 1;
  115. }
  116. SMLoc getParentIncludeLoc(unsigned i) const {
  117. assert(isValidBufferID(i));
  118. return Buffers[i - 1].IncludeLoc;
  119. }
  120. /// Add a new source buffer to this source manager. This takes ownership of
  121. /// the memory buffer.
  122. unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
  123. SMLoc IncludeLoc) {
  124. SrcBuffer NB;
  125. NB.Buffer = std::move(F);
  126. NB.IncludeLoc = IncludeLoc;
  127. Buffers.push_back(std::move(NB));
  128. return Buffers.size();
  129. }
  130. /// Takes the source buffers from the given source manager and append them to
  131. /// the current manager. `MainBufferIncludeLoc` is an optional include
  132. /// location to attach to the main buffer of `SrcMgr` after it gets moved to
  133. /// the current manager.
  134. void takeSourceBuffersFrom(SourceMgr &SrcMgr,
  135. SMLoc MainBufferIncludeLoc = SMLoc()) {
  136. if (SrcMgr.Buffers.empty())
  137. return;
  138. size_t OldNumBuffers = getNumBuffers();
  139. std::move(SrcMgr.Buffers.begin(), SrcMgr.Buffers.end(),
  140. std::back_inserter(Buffers));
  141. SrcMgr.Buffers.clear();
  142. Buffers[OldNumBuffers].IncludeLoc = MainBufferIncludeLoc;
  143. }
  144. /// Search for a file with the specified name in the current directory or in
  145. /// one of the IncludeDirs.
  146. ///
  147. /// If no file is found, this returns 0, otherwise it returns the buffer ID
  148. /// of the stacked file. The full path to the included file can be found in
  149. /// \p IncludedFile.
  150. unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc,
  151. std::string &IncludedFile);
  152. /// Search for a file with the specified name in the current directory or in
  153. /// one of the IncludeDirs, and try to open it **without** adding to the
  154. /// SourceMgr. If the opened file is intended to be added to the source
  155. /// manager, prefer `AddIncludeFile` instead.
  156. ///
  157. /// If no file is found, this returns an Error, otherwise it returns the
  158. /// buffer of the stacked file. The full path to the included file can be
  159. /// found in \p IncludedFile.
  160. ErrorOr<std::unique_ptr<MemoryBuffer>>
  161. OpenIncludeFile(const std::string &Filename, std::string &IncludedFile);
  162. /// Return the ID of the buffer containing the specified location.
  163. ///
  164. /// 0 is returned if the buffer is not found.
  165. unsigned FindBufferContainingLoc(SMLoc Loc) const;
  166. /// Find the line number for the specified location in the specified file.
  167. /// This is not a fast method.
  168. unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
  169. return getLineAndColumn(Loc, BufferID).first;
  170. }
  171. /// Find the line and column number for the specified location in the
  172. /// specified file. This is not a fast method.
  173. std::pair<unsigned, unsigned> getLineAndColumn(SMLoc Loc,
  174. unsigned BufferID = 0) const;
  175. /// Get a string with the \p SMLoc filename and line number
  176. /// formatted in the standard style.
  177. std::string getFormattedLocationNoOffset(SMLoc Loc,
  178. bool IncludePath = false) const;
  179. /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
  180. /// This will return a null SMLoc if the line/column location is invalid.
  181. SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
  182. unsigned ColNo);
  183. /// Emit a message about the specified location with the specified string.
  184. ///
  185. /// \param ShowColors Display colored messages if output is a terminal and
  186. /// the default error handler is used.
  187. void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg,
  188. ArrayRef<SMRange> Ranges = {},
  189. ArrayRef<SMFixIt> FixIts = {},
  190. bool ShowColors = true) const;
  191. /// Emits a diagnostic to llvm::errs().
  192. void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
  193. ArrayRef<SMRange> Ranges = {},
  194. ArrayRef<SMFixIt> FixIts = {},
  195. bool ShowColors = true) const;
  196. /// Emits a manually-constructed diagnostic to the given output stream.
  197. ///
  198. /// \param ShowColors Display colored messages if output is a terminal and
  199. /// the default error handler is used.
  200. void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
  201. bool ShowColors = true) const;
  202. /// Return an SMDiagnostic at the specified location with the specified
  203. /// string.
  204. ///
  205. /// \param Msg If non-null, the kind of message (e.g., "error") which is
  206. /// prefixed to the message.
  207. SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
  208. ArrayRef<SMRange> Ranges = {},
  209. ArrayRef<SMFixIt> FixIts = {}) const;
  210. /// Prints the names of included files and the line of the file they were
  211. /// included from. A diagnostic handler can use this before printing its
  212. /// custom formatted message.
  213. ///
  214. /// \param IncludeLoc The location of the include.
  215. /// \param OS the raw_ostream to print on.
  216. void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
  217. };
  218. /// Represents a single fixit, a replacement of one range of text with another.
  219. class SMFixIt {
  220. SMRange Range;
  221. std::string Text;
  222. public:
  223. SMFixIt(SMRange R, const Twine &Replacement);
  224. SMFixIt(SMLoc Loc, const Twine &Replacement)
  225. : SMFixIt(SMRange(Loc, Loc), Replacement) {}
  226. StringRef getText() const { return Text; }
  227. SMRange getRange() const { return Range; }
  228. bool operator<(const SMFixIt &Other) const {
  229. if (Range.Start.getPointer() != Other.Range.Start.getPointer())
  230. return Range.Start.getPointer() < Other.Range.Start.getPointer();
  231. if (Range.End.getPointer() != Other.Range.End.getPointer())
  232. return Range.End.getPointer() < Other.Range.End.getPointer();
  233. return Text < Other.Text;
  234. }
  235. };
  236. /// Instances of this class encapsulate one diagnostic report, allowing
  237. /// printing to a raw_ostream as a caret diagnostic.
  238. class SMDiagnostic {
  239. const SourceMgr *SM = nullptr;
  240. SMLoc Loc;
  241. std::string Filename;
  242. int LineNo = 0;
  243. int ColumnNo = 0;
  244. SourceMgr::DiagKind Kind = SourceMgr::DK_Error;
  245. std::string Message, LineContents;
  246. std::vector<std::pair<unsigned, unsigned>> Ranges;
  247. SmallVector<SMFixIt, 4> FixIts;
  248. public:
  249. // Null diagnostic.
  250. SMDiagnostic() = default;
  251. // Diagnostic with no location (e.g. file not found, command line arg error).
  252. SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
  253. : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
  254. // Diagnostic with a location.
  255. SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line, int Col,
  256. SourceMgr::DiagKind Kind, StringRef Msg, StringRef LineStr,
  257. ArrayRef<std::pair<unsigned, unsigned>> Ranges,
  258. ArrayRef<SMFixIt> FixIts = {});
  259. const SourceMgr *getSourceMgr() const { return SM; }
  260. SMLoc getLoc() const { return Loc; }
  261. StringRef getFilename() const { return Filename; }
  262. int getLineNo() const { return LineNo; }
  263. int getColumnNo() const { return ColumnNo; }
  264. SourceMgr::DiagKind getKind() const { return Kind; }
  265. StringRef getMessage() const { return Message; }
  266. StringRef getLineContents() const { return LineContents; }
  267. ArrayRef<std::pair<unsigned, unsigned>> getRanges() const { return Ranges; }
  268. void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
  269. ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
  270. void print(const char *ProgName, raw_ostream &S, bool ShowColors = true,
  271. bool ShowKindLabel = true) const;
  272. };
  273. } // end namespace llvm
  274. #endif // LLVM_SUPPORT_SOURCEMGR_H
  275. #ifdef __GNUC__
  276. #pragma GCC diagnostic pop
  277. #endif