LLVM  9.0.0svn
SourceMgr.h
Go to the documentation of this file.
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 
15 #ifndef LLVM_SUPPORT_SOURCEMGR_H
16 #define LLVM_SUPPORT_SOURCEMGR_H
17 
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SMLoc.h"
26 #include <algorithm>
27 #include <cassert>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 namespace llvm {
34 
35 class raw_ostream;
36 class SMDiagnostic;
37 class SMFixIt;
38 
39 /// This owns the files read by a parser, handles include stacks,
40 /// and handles diagnostic wrangling.
41 class SourceMgr {
42 public:
43  enum DiagKind {
48  };
49 
50  /// Clients that want to handle their own diagnostics in a custom way can
51  /// register a function pointer+context as a diagnostic handler.
52  /// It gets called each time PrintMessage is invoked.
53  using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
54 
55 private:
56  struct SrcBuffer {
57  /// The memory buffer for the file.
58  std::unique_ptr<MemoryBuffer> Buffer;
59 
60  /// Helper type for OffsetCache below: since we're storing many offsets
61  /// into relatively small files (often smaller than 2^8 or 2^16 bytes),
62  /// we select the offset vector element type dynamically based on the
63  /// size of Buffer.
64  using VariableSizeOffsets = PointerUnion4<std::vector<uint8_t> *,
65  std::vector<uint16_t> *,
66  std::vector<uint32_t> *,
67  std::vector<uint64_t> *>;
68 
69  /// Vector of offsets into Buffer at which there are line-endings
70  /// (lazily populated). Once populated, the '\n' that marks the end of
71  /// line number N from [1..] is at Buffer[OffsetCache[N-1]]. Since
72  /// these offsets are in sorted (ascending) order, they can be
73  /// binary-searched for the first one after any given offset (eg. an
74  /// offset corresponding to a particular SMLoc).
75  mutable VariableSizeOffsets OffsetCache;
76 
77  /// Populate \c OffsetCache and look up a given \p Ptr in it, assuming
78  /// it points somewhere into \c Buffer. The static type parameter \p T
79  /// must be an unsigned integer type from uint{8,16,32,64}_t large
80  /// enough to store offsets inside \c Buffer.
81  template<typename T>
82  unsigned getLineNumber(const char *Ptr) const;
83 
84  /// This is the location of the parent include, or null if at the top level.
85  SMLoc IncludeLoc;
86 
87  SrcBuffer() = default;
88  SrcBuffer(SrcBuffer &&);
89  SrcBuffer(const SrcBuffer &) = delete;
90  SrcBuffer &operator=(const SrcBuffer &) = delete;
91  ~SrcBuffer();
92  };
93 
94  /// This is all of the buffers that we are reading from.
95  std::vector<SrcBuffer> Buffers;
96 
97  // This is the list of directories we should search for include files in.
98  std::vector<std::string> IncludeDirectories;
99 
100  DiagHandlerTy DiagHandler = nullptr;
101  void *DiagContext = nullptr;
102 
103  bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); }
104 
105 public:
106  SourceMgr() = default;
107  SourceMgr(const SourceMgr &) = delete;
108  SourceMgr &operator=(const SourceMgr &) = delete;
109  ~SourceMgr() = default;
110 
111  void setIncludeDirs(const std::vector<std::string> &Dirs) {
112  IncludeDirectories = Dirs;
113  }
114 
115  /// Specify a diagnostic handler to be invoked every time PrintMessage is
116  /// called. \p Ctx is passed into the handler when it is invoked.
117  void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
118  DiagHandler = DH;
119  DiagContext = Ctx;
120  }
121 
122  DiagHandlerTy getDiagHandler() const { return DiagHandler; }
123  void *getDiagContext() const { return DiagContext; }
124 
125  const SrcBuffer &getBufferInfo(unsigned i) const {
126  assert(isValidBufferID(i));
127  return Buffers[i - 1];
128  }
129 
130  const MemoryBuffer *getMemoryBuffer(unsigned i) const {
131  assert(isValidBufferID(i));
132  return Buffers[i - 1].Buffer.get();
133  }
134 
135  unsigned getNumBuffers() const {
136  return Buffers.size();
137  }
138 
139  unsigned getMainFileID() const {
141  return 1;
142  }
143 
144  SMLoc getParentIncludeLoc(unsigned i) const {
145  assert(isValidBufferID(i));
146  return Buffers[i - 1].IncludeLoc;
147  }
148 
149  /// Add a new source buffer to this source manager. This takes ownership of
150  /// the memory buffer.
151  unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
152  SMLoc IncludeLoc) {
153  SrcBuffer NB;
154  NB.Buffer = std::move(F);
155  NB.IncludeLoc = IncludeLoc;
156  Buffers.push_back(std::move(NB));
157  return Buffers.size();
158  }
159 
160  /// Search for a file with the specified name in the current directory or in
161  /// one of the IncludeDirs.
162  ///
163  /// If no file is found, this returns 0, otherwise it returns the buffer ID
164  /// of the stacked file. The full path to the included file can be found in
165  /// \p IncludedFile.
166  unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc,
167  std::string &IncludedFile);
168 
169  /// Return the ID of the buffer containing the specified location.
170  ///
171  /// 0 is returned if the buffer is not found.
172  unsigned FindBufferContainingLoc(SMLoc Loc) const;
173 
174  /// Find the line number for the specified location in the specified file.
175  /// This is not a fast method.
176  unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
177  return getLineAndColumn(Loc, BufferID).first;
178  }
179 
180  /// Find the line and column number for the specified location in the
181  /// specified file. This is not a fast method.
182  std::pair<unsigned, unsigned> getLineAndColumn(SMLoc Loc,
183  unsigned BufferID = 0) const;
184 
185  /// Emit a message about the specified location with the specified string.
186  ///
187  /// \param ShowColors Display colored messages if output is a terminal and
188  /// the default error handler is used.
189  void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind,
190  const Twine &Msg,
191  ArrayRef<SMRange> Ranges = None,
192  ArrayRef<SMFixIt> FixIts = None,
193  bool ShowColors = true) const;
194 
195  /// Emits a diagnostic to llvm::errs().
196  void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
197  ArrayRef<SMRange> Ranges = None,
198  ArrayRef<SMFixIt> FixIts = None,
199  bool ShowColors = true) const;
200 
201  /// Emits a manually-constructed diagnostic to the given output stream.
202  ///
203  /// \param ShowColors Display colored messages if output is a terminal and
204  /// the default error handler is used.
205  void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
206  bool ShowColors = true) const;
207 
208  /// Return an SMDiagnostic at the specified location with the specified
209  /// string.
210  ///
211  /// \param Msg If non-null, the kind of message (e.g., "error") which is
212  /// prefixed to the message.
213  SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
214  ArrayRef<SMRange> Ranges = None,
215  ArrayRef<SMFixIt> FixIts = None) const;
216 
217  /// Prints the names of included files and the line of the file they were
218  /// included from. A diagnostic handler can use this before printing its
219  /// custom formatted message.
220  ///
221  /// \param IncludeLoc The location of the include.
222  /// \param OS the raw_ostream to print on.
223  void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
224 };
225 
226 /// Represents a single fixit, a replacement of one range of text with another.
227 class SMFixIt {
228  SMRange Range;
229 
230  std::string Text;
231 
232 public:
233  // FIXME: Twine.str() is not very efficient.
234  SMFixIt(SMLoc Loc, const Twine &Insertion)
235  : Range(Loc, Loc), Text(Insertion.str()) {
236  assert(Loc.isValid());
237  }
238 
239  // FIXME: Twine.str() is not very efficient.
240  SMFixIt(SMRange R, const Twine &Replacement)
241  : Range(R), Text(Replacement.str()) {
242  assert(R.isValid());
243  }
244 
245  StringRef getText() const { return Text; }
246  SMRange getRange() const { return Range; }
247 
248  bool operator<(const SMFixIt &Other) const {
249  if (Range.Start.getPointer() != Other.Range.Start.getPointer())
250  return Range.Start.getPointer() < Other.Range.Start.getPointer();
251  if (Range.End.getPointer() != Other.Range.End.getPointer())
252  return Range.End.getPointer() < Other.Range.End.getPointer();
253  return Text < Other.Text;
254  }
255 };
256 
257 /// Instances of this class encapsulate one diagnostic report, allowing
258 /// printing to a raw_ostream as a caret diagnostic.
260  const SourceMgr *SM = nullptr;
261  SMLoc Loc;
262  std::string Filename;
263  int LineNo = 0;
264  int ColumnNo = 0;
266  std::string Message, LineContents;
267  std::vector<std::pair<unsigned, unsigned>> Ranges;
269 
270 public:
271  // Null diagnostic.
272  SMDiagnostic() = default;
273  // Diagnostic with no location (e.g. file not found, command line arg error).
275  : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
276 
277  // Diagnostic with a location.
278  SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
279  int Line, int Col, SourceMgr::DiagKind Kind,
280  StringRef Msg, StringRef LineStr,
281  ArrayRef<std::pair<unsigned,unsigned>> Ranges,
282  ArrayRef<SMFixIt> FixIts = None);
283 
284  const SourceMgr *getSourceMgr() const { return SM; }
285  SMLoc getLoc() const { return Loc; }
286  StringRef getFilename() const { return Filename; }
287  int getLineNo() const { return LineNo; }
288  int getColumnNo() const { return ColumnNo; }
289  SourceMgr::DiagKind getKind() const { return Kind; }
290  StringRef getMessage() const { return Message; }
291  StringRef getLineContents() const { return LineContents; }
293 
294  void addFixIt(const SMFixIt &Hint) {
295  FixIts.push_back(Hint);
296  }
297 
299  return FixIts;
300  }
301 
302  void print(const char *ProgName, raw_ostream &S, bool ShowColors = true,
303  bool ShowKindLabel = true) const;
304 };
305 
306 } // end namespace llvm
307 
308 #endif // LLVM_SUPPORT_SOURCEMGR_H
Represents a range in source code.
Definition: SMLoc.h:48
unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:61
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
SMLoc getLoc() const
Definition: SourceMgr.h:285
DiagHandlerTy getDiagHandler() const
Definition: SourceMgr.h:122
SMFixIt(SMLoc Loc, const Twine &Insertion)
Definition: SourceMgr.h:234
unsigned getNumBuffers() const
Definition: SourceMgr.h:135
void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const
Prints the names of included files and the line of the file they were included from.
Definition: SourceMgr.cpp:155
F(f)
ArrayRef< SMFixIt > getFixIts() const
Definition: SourceMgr.h:298
std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file. ...
Definition: SourceMgr.cpp:130
SMRange getRange() const
Definition: SourceMgr.h:246
void addFixIt(const SMFixIt &Hint)
Definition: SourceMgr.h:294
SMLoc Start
Definition: SMLoc.h:50
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
Definition: SourceMgr.cpp:247
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
int getLineNo() const
Definition: SourceMgr.h:287
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:130
StringRef getLineContents() const
Definition: SourceMgr.h:291
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:151
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
StringRef getText() const
Definition: SourceMgr.h:245
unsigned getMainFileID() const
Definition: SourceMgr.h:139
const char * getPointer() const
Definition: SMLoc.h:34
void setDiagHandler(DiagHandlerTy DH, void *Ctx=nullptr)
Specify a diagnostic handler to be invoked every time PrintMessage is called.
Definition: SourceMgr.h:117
SourceMgr()=default
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
Represents a single fixit, a replacement of one range of text with another.
Definition: SourceMgr.h:227
void(*)(const SMDiagnostic &, void *Context) DiagHandlerTy
Clients that want to handle their own diagnostics in a custom way can register a function pointer+con...
Definition: SourceMgr.h:53
SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:168
const SrcBuffer & getBufferInfo(unsigned i) const
Definition: SourceMgr.h:125
bool isValid() const
Definition: SMLoc.h:59
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
StringRef getMessage() const
Definition: SourceMgr.h:290
ArrayRef< std::pair< unsigned, unsigned > > getRanges() const
Definition: SourceMgr.h:292
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:41
bool isValid() const
Definition: SMLoc.h:29
StringRef getFilename() const
Definition: SourceMgr.h:286
SMLoc End
Definition: SMLoc.h:50
SourceMgr::DiagKind getKind() const
Definition: SourceMgr.h:289
unsigned FindLineNumber(SMLoc Loc, unsigned BufferID=0) const
Find the line number for the specified location in the specified file.
Definition: SourceMgr.h:176
bool operator<(const SMFixIt &Other) const
Definition: SourceMgr.h:248
unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc, std::string &IncludedFile)
Search for a file with the specified name in the current directory or in one of the IncludeDirs...
Definition: SourceMgr.cpp:40
int getColumnNo() const
Definition: SourceMgr.h:288
SMLoc getParentIncludeLoc(unsigned i) const
Definition: SourceMgr.h:144
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:564
void * getDiagContext() const
Definition: SourceMgr.h:123
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
~SourceMgr()=default
SourceMgr & operator=(const SourceMgr &)=delete
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition: SourceMgr.h:111
SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
Definition: SourceMgr.h:274
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Represents a location in source code.
Definition: SMLoc.h:23
SMFixIt(SMRange R, const Twine &Replacement)
Definition: SourceMgr.h:240
const SourceMgr * getSourceMgr() const
Definition: SourceMgr.h:284
A pointer union of four pointer types.
Definition: PointerUnion.h:357
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:259