SourceMgr.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. void setIncludeDirs(const std::vector<std::string> &Dirs) {
  91. IncludeDirectories = Dirs;
  92. }
  93. /// Specify a diagnostic handler to be invoked every time PrintMessage is
  94. /// called. \p Ctx is passed into the handler when it is invoked.
  95. void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
  96. DiagHandler = DH;
  97. DiagContext = Ctx;
  98. }
  99. DiagHandlerTy getDiagHandler() const { return DiagHandler; }
  100. void *getDiagContext() const { return DiagContext; }
  101. const SrcBuffer &getBufferInfo(unsigned i) const {
  102. assert(isValidBufferID(i));
  103. return Buffers[i - 1];
  104. }
  105. const MemoryBuffer *getMemoryBuffer(unsigned i) const {
  106. assert(isValidBufferID(i));
  107. return Buffers[i - 1].Buffer.get();
  108. }
  109. unsigned getNumBuffers() const { return Buffers.size(); }
  110. unsigned getMainFileID() const {
  111. assert(getNumBuffers());
  112. return 1;
  113. }
  114. SMLoc getParentIncludeLoc(unsigned i) const {
  115. assert(isValidBufferID(i));
  116. return Buffers[i - 1].IncludeLoc;
  117. }
  118. /// Add a new source buffer to this source manager. This takes ownership of
  119. /// the memory buffer.
  120. unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
  121. SMLoc IncludeLoc) {
  122. SrcBuffer NB;
  123. NB.Buffer = std::move(F);
  124. NB.IncludeLoc = IncludeLoc;
  125. Buffers.push_back(std::move(NB));
  126. return Buffers.size();
  127. }
  128. /// Search for a file with the specified name in the current directory or in
  129. /// one of the IncludeDirs.
  130. ///
  131. /// If no file is found, this returns 0, otherwise it returns the buffer ID
  132. /// of the stacked file. The full path to the included file can be found in
  133. /// \p IncludedFile.
  134. unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc,
  135. std::string &IncludedFile);
  136. /// Return the ID of the buffer containing the specified location.
  137. ///
  138. /// 0 is returned if the buffer is not found.
  139. unsigned FindBufferContainingLoc(SMLoc Loc) const;
  140. /// Find the line number for the specified location in the specified file.
  141. /// This is not a fast method.
  142. unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
  143. return getLineAndColumn(Loc, BufferID).first;
  144. }
  145. /// Find the line and column number for the specified location in the
  146. /// specified file. This is not a fast method.
  147. std::pair<unsigned, unsigned> getLineAndColumn(SMLoc Loc,
  148. unsigned BufferID = 0) const;
  149. /// Get a string with the \p SMLoc filename and line number
  150. /// formatted in the standard style.
  151. std::string getFormattedLocationNoOffset(SMLoc Loc,
  152. bool IncludePath = false) const;
  153. /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
  154. /// This will return a null SMLoc if the line/column location is invalid.
  155. SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
  156. unsigned ColNo);
  157. /// Emit a message about the specified location with the specified string.
  158. ///
  159. /// \param ShowColors Display colored messages if output is a terminal and
  160. /// the default error handler is used.
  161. void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg,
  162. ArrayRef<SMRange> Ranges = {},
  163. ArrayRef<SMFixIt> FixIts = {},
  164. bool ShowColors = true) const;
  165. /// Emits a diagnostic to llvm::errs().
  166. void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
  167. ArrayRef<SMRange> Ranges = {},
  168. ArrayRef<SMFixIt> FixIts = {},
  169. bool ShowColors = true) const;
  170. /// Emits a manually-constructed diagnostic to the given output stream.
  171. ///
  172. /// \param ShowColors Display colored messages if output is a terminal and
  173. /// the default error handler is used.
  174. void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
  175. bool ShowColors = true) const;
  176. /// Return an SMDiagnostic at the specified location with the specified
  177. /// string.
  178. ///
  179. /// \param Msg If non-null, the kind of message (e.g., "error") which is
  180. /// prefixed to the message.
  181. SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
  182. ArrayRef<SMRange> Ranges = {},
  183. ArrayRef<SMFixIt> FixIts = {}) const;
  184. /// Prints the names of included files and the line of the file they were
  185. /// included from. A diagnostic handler can use this before printing its
  186. /// custom formatted message.
  187. ///
  188. /// \param IncludeLoc The location of the include.
  189. /// \param OS the raw_ostream to print on.
  190. void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
  191. };
  192. /// Represents a single fixit, a replacement of one range of text with another.
  193. class SMFixIt {
  194. SMRange Range;
  195. std::string Text;
  196. public:
  197. SMFixIt(SMRange R, const Twine &Replacement);
  198. SMFixIt(SMLoc Loc, const Twine &Replacement)
  199. : SMFixIt(SMRange(Loc, Loc), Replacement) {}
  200. StringRef getText() const { return Text; }
  201. SMRange getRange() const { return Range; }
  202. bool operator<(const SMFixIt &Other) const {
  203. if (Range.Start.getPointer() != Other.Range.Start.getPointer())
  204. return Range.Start.getPointer() < Other.Range.Start.getPointer();
  205. if (Range.End.getPointer() != Other.Range.End.getPointer())
  206. return Range.End.getPointer() < Other.Range.End.getPointer();
  207. return Text < Other.Text;
  208. }
  209. };
  210. /// Instances of this class encapsulate one diagnostic report, allowing
  211. /// printing to a raw_ostream as a caret diagnostic.
  212. class SMDiagnostic {
  213. const SourceMgr *SM = nullptr;
  214. SMLoc Loc;
  215. std::string Filename;
  216. int LineNo = 0;
  217. int ColumnNo = 0;
  218. SourceMgr::DiagKind Kind = SourceMgr::DK_Error;
  219. std::string Message, LineContents;
  220. std::vector<std::pair<unsigned, unsigned>> Ranges;
  221. SmallVector<SMFixIt, 4> FixIts;
  222. public:
  223. // Null diagnostic.
  224. SMDiagnostic() = default;
  225. // Diagnostic with no location (e.g. file not found, command line arg error).
  226. SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
  227. : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
  228. // Diagnostic with a location.
  229. SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line, int Col,
  230. SourceMgr::DiagKind Kind, StringRef Msg, StringRef LineStr,
  231. ArrayRef<std::pair<unsigned, unsigned>> Ranges,
  232. ArrayRef<SMFixIt> FixIts = {});
  233. const SourceMgr *getSourceMgr() const { return SM; }
  234. SMLoc getLoc() const { return Loc; }
  235. StringRef getFilename() const { return Filename; }
  236. int getLineNo() const { return LineNo; }
  237. int getColumnNo() const { return ColumnNo; }
  238. SourceMgr::DiagKind getKind() const { return Kind; }
  239. StringRef getMessage() const { return Message; }
  240. StringRef getLineContents() const { return LineContents; }
  241. ArrayRef<std::pair<unsigned, unsigned>> getRanges() const { return Ranges; }
  242. void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
  243. ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
  244. void print(const char *ProgName, raw_ostream &S, bool ShowColors = true,
  245. bool ShowKindLabel = true) const;
  246. };
  247. } // end namespace llvm
  248. #endif // LLVM_SUPPORT_SOURCEMGR_H
  249. #ifdef __GNUC__
  250. #pragma GCC diagnostic pop
  251. #endif