SourceMgr.h 11 KB

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