LLVM 22.0.0git
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
22#include "llvm/Support/SMLoc.h"
23#include <vector>
24
25namespace llvm {
26
27namespace vfs {
28class FileSystem;
29} // end namespace vfs
30
31class raw_ostream;
32class SMDiagnostic;
33class SMFixIt;
34
35/// This owns the files read by a parser, handles include stacks,
36/// and handles diagnostic wrangling.
37class SourceMgr {
38public:
45
46 /// Clients that want to handle their own diagnostics in a custom way can
47 /// register a function pointer+context as a diagnostic handler.
48 /// It gets called each time PrintMessage is invoked.
49 using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
50
51private:
52 struct SrcBuffer {
53 /// The memory buffer for the file.
54 std::unique_ptr<MemoryBuffer> Buffer;
55
56 /// Vector of offsets into Buffer at which there are line-endings
57 /// (lazily populated). Once populated, the '\n' that marks the end of
58 /// line number N from [1..] is at Buffer[OffsetCache[N-1]]. Since
59 /// these offsets are in sorted (ascending) order, they can be
60 /// binary-searched for the first one after any given offset (eg. an
61 /// offset corresponding to a particular SMLoc).
62 ///
63 /// Since we're storing offsets into relatively small files (often smaller
64 /// than 2^8 or 2^16 bytes), we select the offset vector element type
65 /// dynamically based on the size of Buffer.
66 mutable void *OffsetCache = nullptr;
67
68 /// Look up a given \p Ptr in the buffer, determining which line it came
69 /// from.
70 LLVM_ABI unsigned getLineNumber(const char *Ptr) const;
71 template <typename T>
72 unsigned getLineNumberSpecialized(const char *Ptr) const;
73
74 /// Return a pointer to the first character of the specified line number or
75 /// null if the line number is invalid.
76 LLVM_ABI const char *getPointerForLineNumber(unsigned LineNo) const;
77 template <typename T>
78 const char *getPointerForLineNumberSpecialized(unsigned LineNo) const;
79
80 /// This is the location of the parent include, or null if at the top level.
81 SMLoc IncludeLoc;
82
83 SrcBuffer() = default;
84 LLVM_ABI SrcBuffer(SrcBuffer &&);
85 SrcBuffer(const SrcBuffer &) = delete;
86 SrcBuffer &operator=(const SrcBuffer &) = delete;
87 LLVM_ABI ~SrcBuffer();
88 };
89
90 /// This is all of the buffers that we are reading from.
91 std::vector<SrcBuffer> Buffers;
92
93 // This is the list of directories we should search for include files in.
94 std::vector<std::string> IncludeDirectories;
95
96 DiagHandlerTy DiagHandler = nullptr;
97 void *DiagContext = nullptr;
98
99 // Optional file system for finding include files.
101
102 bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); }
103
104public:
105 /// Create new source manager without support for include files.
107 /// Create new source manager with the capability of finding include files
108 /// via the provided file system.
110 SourceMgr(const SourceMgr &) = delete;
111 SourceMgr &operator=(const SourceMgr &) = delete;
115
118
119 /// Return the include directories of this source manager.
120 ArrayRef<std::string> getIncludeDirs() const { return IncludeDirectories; }
121
122 void setIncludeDirs(const std::vector<std::string> &Dirs) {
123 IncludeDirectories = Dirs;
124 }
125
126 /// Specify a diagnostic handler to be invoked every time PrintMessage is
127 /// called. \p Ctx is passed into the handler when it is invoked.
128 void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
129 DiagHandler = DH;
130 DiagContext = Ctx;
131 }
132
133 DiagHandlerTy getDiagHandler() const { return DiagHandler; }
134 void *getDiagContext() const { return DiagContext; }
135
136 const SrcBuffer &getBufferInfo(unsigned i) const {
137 assert(isValidBufferID(i));
138 return Buffers[i - 1];
139 }
140
141 const MemoryBuffer *getMemoryBuffer(unsigned i) const {
142 assert(isValidBufferID(i));
143 return Buffers[i - 1].Buffer.get();
144 }
145
146 unsigned getNumBuffers() const { return Buffers.size(); }
147
148 unsigned getMainFileID() const {
150 return 1;
151 }
152
153 SMLoc getParentIncludeLoc(unsigned i) const {
154 assert(isValidBufferID(i));
155 return Buffers[i - 1].IncludeLoc;
156 }
157
158 /// Add a new source buffer to this source manager. This takes ownership of
159 /// the memory buffer.
160 unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
161 SMLoc IncludeLoc) {
162 SrcBuffer NB;
163 NB.Buffer = std::move(F);
164 NB.IncludeLoc = IncludeLoc;
165 Buffers.push_back(std::move(NB));
166 return Buffers.size();
167 }
168
169 /// Takes the source buffers from the given source manager and append them to
170 /// the current manager. `MainBufferIncludeLoc` is an optional include
171 /// location to attach to the main buffer of `SrcMgr` after it gets moved to
172 /// the current manager.
174 SMLoc MainBufferIncludeLoc = SMLoc()) {
175 if (SrcMgr.Buffers.empty())
176 return;
177
178 size_t OldNumBuffers = getNumBuffers();
179 std::move(SrcMgr.Buffers.begin(), SrcMgr.Buffers.end(),
180 std::back_inserter(Buffers));
181 SrcMgr.Buffers.clear();
182 Buffers[OldNumBuffers].IncludeLoc = MainBufferIncludeLoc;
183 }
184
185 /// Search for a file with the specified name in the current directory or in
186 /// one of the IncludeDirs.
187 ///
188 /// If no file is found, this returns 0, otherwise it returns the buffer ID
189 /// of the stacked file. The full path to the included file can be found in
190 /// \p IncludedFile.
191 LLVM_ABI unsigned AddIncludeFile(const std::string &Filename,
192 SMLoc IncludeLoc, std::string &IncludedFile);
193
194 /// Search for a file with the specified name in the current directory or in
195 /// one of the IncludeDirs, and try to open it **without** adding to the
196 /// SourceMgr. If the opened file is intended to be added to the source
197 /// manager, prefer `AddIncludeFile` instead.
198 ///
199 /// If no file is found, this returns an Error, otherwise it returns the
200 /// buffer of the stacked file. The full path to the included file can be
201 /// found in \p IncludedFile.
203 OpenIncludeFile(const std::string &Filename, std::string &IncludedFile);
204
205 /// Return the ID of the buffer containing the specified location.
206 ///
207 /// 0 is returned if the buffer is not found.
209
210 /// Find the line number for the specified location in the specified file.
211 /// This is not a fast method.
212 unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
213 return getLineAndColumn(Loc, BufferID).first;
214 }
215
216 /// Find the line and column number for the specified location in the
217 /// specified file. This is not a fast method.
218 LLVM_ABI std::pair<unsigned, unsigned>
219 getLineAndColumn(SMLoc Loc, unsigned BufferID = 0) const;
220
221 /// Get a string with the \p SMLoc filename and line number
222 /// formatted in the standard style.
223 LLVM_ABI std::string
224 getFormattedLocationNoOffset(SMLoc Loc, bool IncludePath = false) const;
225
226 /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
227 /// This will return a null SMLoc if the line/column location is invalid.
228 LLVM_ABI SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
229 unsigned ColNo);
230
231 /// Emit a message about the specified location with the specified string.
232 ///
233 /// \param ShowColors Display colored messages if output is a terminal and
234 /// the default error handler is used.
235 LLVM_ABI void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind,
236 const Twine &Msg, ArrayRef<SMRange> Ranges = {},
237 ArrayRef<SMFixIt> FixIts = {},
238 bool ShowColors = true) const;
239
240 /// Emits a diagnostic to llvm::errs().
241 LLVM_ABI void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
242 ArrayRef<SMRange> Ranges = {},
243 ArrayRef<SMFixIt> FixIts = {},
244 bool ShowColors = true) const;
245
246 /// Emits a manually-constructed diagnostic to the given output stream.
247 ///
248 /// \param ShowColors Display colored messages if output is a terminal and
249 /// the default error handler is used.
250 LLVM_ABI void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
251 bool ShowColors = true) const;
252
253 /// Return an SMDiagnostic at the specified location with the specified
254 /// string.
255 ///
256 /// \param Msg If non-null, the kind of message (e.g., "error") which is
257 /// prefixed to the message.
258 LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
259 ArrayRef<SMRange> Ranges = {},
260 ArrayRef<SMFixIt> FixIts = {}) const;
261
262 /// Prints the names of included files and the line of the file they were
263 /// included from. A diagnostic handler can use this before printing its
264 /// custom formatted message.
265 ///
266 /// \param IncludeLoc The location of the include.
267 /// \param OS the raw_ostream to print on.
268 LLVM_ABI void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
269};
270
271/// Represents a single fixit, a replacement of one range of text with another.
272class SMFixIt {
273 SMRange Range;
274
275 std::string Text;
276
277public:
278 LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement);
279
280 SMFixIt(SMLoc Loc, const Twine &Replacement)
281 : SMFixIt(SMRange(Loc, Loc), Replacement) {}
282
283 StringRef getText() const { return Text; }
284 SMRange getRange() const { return Range; }
285
286 bool operator<(const SMFixIt &Other) const {
287 if (Range.Start.getPointer() != Other.Range.Start.getPointer())
288 return Range.Start.getPointer() < Other.Range.Start.getPointer();
289 if (Range.End.getPointer() != Other.Range.End.getPointer())
290 return Range.End.getPointer() < Other.Range.End.getPointer();
291 return Text < Other.Text;
292 }
293};
294
295/// Instances of this class encapsulate one diagnostic report, allowing
296/// printing to a raw_ostream as a caret diagnostic.
298 const SourceMgr *SM = nullptr;
299 SMLoc Loc;
300 std::string Filename;
301 int LineNo = 0;
302 int ColumnNo = 0;
304 std::string Message, LineContents;
305 std::vector<std::pair<unsigned, unsigned>> Ranges;
307
308public:
309 // Null diagnostic.
310 SMDiagnostic() = default;
311 // Diagnostic with no location (e.g. file not found, command line arg error).
313 : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
314
315 // Diagnostic with a location.
316 LLVM_ABI SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line,
317 int Col, SourceMgr::DiagKind Kind, StringRef Msg,
318 StringRef LineStr,
319 ArrayRef<std::pair<unsigned, unsigned>> Ranges,
320 ArrayRef<SMFixIt> FixIts = {});
321
322 const SourceMgr *getSourceMgr() const { return SM; }
323 SMLoc getLoc() const { return Loc; }
324 StringRef getFilename() const { return Filename; }
325 int getLineNo() const { return LineNo; }
326 int getColumnNo() const { return ColumnNo; }
327 SourceMgr::DiagKind getKind() const { return Kind; }
328 StringRef getMessage() const { return Message; }
329 StringRef getLineContents() const { return LineContents; }
331
332 void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
333
334 ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
335
336 LLVM_ABI void print(const char *ProgName, raw_ostream &S,
337 bool ShowColors = true, bool ShowKindLabel = true,
338 bool ShowLocation = true) const;
339};
340
341} // end namespace llvm
342
343#endif // LLVM_SUPPORT_SOURCEMGR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:55
This file defines the SmallVector class.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
Represents either an error or a value T.
Definition ErrorOr.h:56
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:297
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
SourceMgr::DiagKind getKind() const
Definition SourceMgr.h:327
StringRef getFilename() const
Definition SourceMgr.h:324
SMDiagnostic()=default
int getLineNo() const
Definition SourceMgr.h:325
SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
Definition SourceMgr.h:312
StringRef getLineContents() const
Definition SourceMgr.h:329
SMLoc getLoc() const
Definition SourceMgr.h:323
StringRef getMessage() const
Definition SourceMgr.h:328
ArrayRef< SMFixIt > getFixIts() const
Definition SourceMgr.h:334
ArrayRef< std::pair< unsigned, unsigned > > getRanges() const
Definition SourceMgr.h:330
void addFixIt(const SMFixIt &Hint)
Definition SourceMgr.h:332
const SourceMgr * getSourceMgr() const
Definition SourceMgr.h:322
int getColumnNo() const
Definition SourceMgr.h:326
Represents a single fixit, a replacement of one range of text with another.
Definition SourceMgr.h:272
bool operator<(const SMFixIt &Other) const
Definition SourceMgr.h:286
StringRef getText() const
Definition SourceMgr.h:283
LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement)
SMFixIt(SMLoc Loc, const Twine &Replacement)
Definition SourceMgr.h:280
SMRange getRange() const
Definition SourceMgr.h:284
Represents a location in source code.
Definition SMLoc.h:23
Represents a range in source code.
Definition SMLoc.h:48
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
LLVM_ABI ErrorOr< std::unique_ptr< MemoryBuffer > > OpenIncludeFile(const std::string &Filename, std::string &IncludedFile)
Search for a file with the specified name in the current directory or in one of the IncludeDirs,...
Definition SourceMgr.cpp:70
void * getDiagContext() const
Definition SourceMgr.h:134
ArrayRef< std::string > getIncludeDirs() const
Return the include directories of this source manager.
Definition SourceMgr.h:120
unsigned getMainFileID() const
Definition SourceMgr.h:148
DiagHandlerTy getDiagHandler() const
Definition SourceMgr.h:133
SourceMgr & operator=(const SourceMgr &)=delete
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition SourceMgr.h:122
LLVM_ABI 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.
void setVirtualFileSystem(IntrusiveRefCntPtr< vfs::FileSystem > FS)
Definition SourceMgr.cpp:54
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition SourceMgr.h:141
unsigned getNumBuffers() const
Definition SourceMgr.h:146
LLVM_ABI void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
SMLoc getParentIncludeLoc(unsigned i) const
Definition SourceMgr.h:153
LLVM_ABI void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const
Prints the names of included files and the line of the file they were included from.
SourceMgr()
Create new source manager without support for include files.
LLVM_ABI unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition SourceMgr.cpp:93
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Definition SourceMgr.cpp:50
SourceMgr & operator=(SourceMgr &&)
LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
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:49
void setDiagHandler(DiagHandlerTy DH, void *Ctx=nullptr)
Specify a diagnostic handler to be invoked every time PrintMessage is called.
Definition SourceMgr.h:128
LLVM_ABI 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:58
SourceMgr(const SourceMgr &)=delete
unsigned FindLineNumber(SMLoc Loc, unsigned BufferID=0) const
Find the line number for the specified location in the specified file.
Definition SourceMgr.h:212
LLVM_ABI std::string getFormattedLocationNoOffset(SMLoc Loc, bool IncludePath=false) const
Get a string with the SMLoc filename and line number formatted in the standard style.
void takeSourceBuffersFrom(SourceMgr &SrcMgr, SMLoc MainBufferIncludeLoc=SMLoc())
Takes the source buffers from the given source manager and append them to the current manager.
Definition SourceMgr.h:173
SourceMgr(SourceMgr &&)
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition SourceMgr.h:160
LLVM_ABI SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo, unsigned ColNo)
Given a line and column number in a mapped buffer, turn it into an SMLoc.
const SrcBuffer & getBufferInfo(unsigned i) const
Definition SourceMgr.h:136
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
The virtual file system interface.
This is an optimization pass for GlobalISel generic memory operations.
SourceMgr SrcMgr
Definition Error.cpp:24
@ Other
Any other memory.
Definition ModRef.h:68
ArrayRef(const T &OneElt) -> ArrayRef< T >