LLVM 24.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"
24#include <vector>
25
26namespace llvm {
27
28class raw_ostream;
29class SMDiagnostic;
30class SMFixIt;
31
32/// This owns the files read by a parser, handles include stacks,
33/// and handles diagnostic wrangling.
34class SourceMgr {
35public:
42
43 /// Clients that want to handle their own diagnostics in a custom way can
44 /// register a function pointer+context as a diagnostic handler.
45 /// It gets called each time PrintMessage is invoked.
46 using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
47
48private:
49 struct SrcBuffer {
50 /// The memory buffer for the file.
51 std::unique_ptr<MemoryBuffer> Buffer;
52
53 /// Vector of offsets into Buffer at which there are line-endings
54 /// (lazily populated). Once populated, the '\n' that marks the end of
55 /// line number N from [1..] is at Buffer[OffsetCache[N-1]]. Since
56 /// these offsets are in sorted (ascending) order, they can be
57 /// binary-searched for the first one after any given offset (eg. an
58 /// offset corresponding to a particular SMLoc).
59 ///
60 /// Since we're storing offsets into relatively small files (often smaller
61 /// than 2^8 or 2^16 bytes), we select the offset vector element type
62 /// dynamically based on the size of Buffer.
63 mutable void *OffsetCache = nullptr;
64
65 /// Look up a given \p Ptr in the buffer, determining which line and column
66 /// it came from. This method has O(log n) complexity, where n is the number
67 /// of lines in the buffer.
68 LLVM_ABI std::pair<unsigned, unsigned>
69 getLineAndColumn(const char *Ptr) const;
70 template <typename T>
71 std::pair<unsigned, unsigned>
72 getLineAndColumnSpecialized(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 bool RequiresNullTerminator = true);
205
206 /// Return the ID of the buffer containing the specified location.
207 ///
208 /// 0 is returned if the buffer is not found.
210
211 /// Find the line number for the specified location in the specified file.
212 /// This method has O(log n) complexity, where n is the number of lines in the
213 /// buffer.
214 unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
215 return getLineAndColumn(Loc, BufferID).first;
216 }
217
218 /// Find the line and column number for the specified location in the
219 /// specified file. This method has O(log n) complexity, where n is the number
220 /// of lines in the buffer.
221 LLVM_ABI std::pair<unsigned, unsigned>
222 getLineAndColumn(SMLoc Loc, unsigned BufferID = 0) const;
223
224 /// Get a string with the \p SMLoc filename and line number
225 /// formatted in the standard style.
226 LLVM_ABI std::string
227 getFormattedLocationNoOffset(SMLoc Loc, bool IncludePath = false) const;
228
229 /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
230 /// This will return a null SMLoc if the line/column location is invalid.
231 LLVM_ABI SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
232 unsigned ColNo);
233
234 /// Emit a message about the specified location with the specified string.
235 ///
236 /// \param ShowColors Display colored messages if output is a terminal and
237 /// the default error handler is used.
238 LLVM_ABI void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind,
239 const Twine &Msg, ArrayRef<SMRange> Ranges = {},
240 ArrayRef<SMFixIt> FixIts = {},
241 bool ShowColors = true) const;
242
243 /// Emits a diagnostic to llvm::errs().
244 LLVM_ABI void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
245 ArrayRef<SMRange> Ranges = {},
246 ArrayRef<SMFixIt> FixIts = {},
247 bool ShowColors = true) const;
248
249 /// Emits a manually-constructed diagnostic to the given output stream.
250 ///
251 /// \param ShowColors Display colored messages if output is a terminal and
252 /// the default error handler is used.
253 LLVM_ABI void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
254 bool ShowColors = true) const;
255
256 /// Return an SMDiagnostic at the specified location with the specified
257 /// string.
258 ///
259 /// \param Msg If non-null, the kind of message (e.g., "error") which is
260 /// prefixed to the message.
261 LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
262 ArrayRef<SMRange> Ranges = {},
263 ArrayRef<SMFixIt> FixIts = {}) const;
264
265 /// Prints the names of included files and the line of the file they were
266 /// included from. A diagnostic handler can use this before printing its
267 /// custom formatted message.
268 ///
269 /// \param IncludeLoc The location of the include.
270 /// \param OS the raw_ostream to print on.
271 LLVM_ABI void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
272
273 /// Prints the include stack of a buffer unless it is a macro instantiation
274 /// buffer.
276 raw_ostream &OS) const;
277};
278
279/// Represents a single fixit, a replacement of one range of text with another.
280class SMFixIt {
281 SMRange Range;
282
283 std::string Text;
284
285public:
286 LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement);
287
288 SMFixIt(SMLoc Loc, const Twine &Replacement)
289 : SMFixIt(SMRange(Loc, Loc), Replacement) {}
290
291 StringRef getText() const { return Text; }
292 SMRange getRange() const { return Range; }
293
294 bool operator<(const SMFixIt &Other) const {
295 if (Range.Start.getPointer() != Other.Range.Start.getPointer())
296 return Range.Start.getPointer() < Other.Range.Start.getPointer();
297 if (Range.End.getPointer() != Other.Range.End.getPointer())
298 return Range.End.getPointer() < Other.Range.End.getPointer();
299 return Text < Other.Text;
300 }
301};
302
303/// Instances of this class encapsulate one diagnostic report, allowing
304/// printing to a raw_ostream as a caret diagnostic.
306 const SourceMgr *SM = nullptr;
307 SMLoc Loc;
308 std::string Filename;
309 int LineNo = 0;
310 int ColumnNo = 0;
312 std::string Message, LineContents;
313 std::vector<std::pair<unsigned, unsigned>> Ranges;
315
316public:
317 // Null diagnostic.
318 SMDiagnostic() = default;
319 // Diagnostic with no location (e.g. file not found, command line arg error).
321 : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
322
323 // Diagnostic with a location.
324 LLVM_ABI SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line,
325 int Col, SourceMgr::DiagKind Kind, StringRef Msg,
326 StringRef LineStr,
327 ArrayRef<std::pair<unsigned, unsigned>> Ranges,
328 ArrayRef<SMFixIt> FixIts = {});
329
330 const SourceMgr *getSourceMgr() const { return SM; }
331 SMLoc getLoc() const { return Loc; }
332 StringRef getFilename() const { return Filename; }
333 int getLineNo() const { return LineNo; }
334 int getColumnNo() const { return ColumnNo; }
335 SourceMgr::DiagKind getKind() const { return Kind; }
336 StringRef getMessage() const { return Message; }
337 StringRef getLineContents() const { return LineContents; }
339
340 void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
341
342 ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
343
344 LLVM_ABI void print(const char *ProgName, raw_ostream &S,
345 bool ShowColors = true, bool ShowKindLabel = true,
346 bool ShowLocation = true) const;
347};
348
349} // end namespace llvm
350
351#endif // LLVM_SUPPORT_SOURCEMGR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:54
static constexpr StringLiteral Filename
const char * Msg
This file defines the SmallVector class.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Contains the forward declaration for vfs::FileSystem, as well as the IntrusiveRefCntPtrInfo specializ...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:305
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:335
StringRef getFilename() const
Definition SourceMgr.h:332
SMDiagnostic()=default
int getLineNo() const
Definition SourceMgr.h:333
SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
Definition SourceMgr.h:320
StringRef getLineContents() const
Definition SourceMgr.h:337
SMLoc getLoc() const
Definition SourceMgr.h:331
StringRef getMessage() const
Definition SourceMgr.h:336
ArrayRef< SMFixIt > getFixIts() const
Definition SourceMgr.h:342
ArrayRef< std::pair< unsigned, unsigned > > getRanges() const
Definition SourceMgr.h:338
void addFixIt(const SMFixIt &Hint)
Definition SourceMgr.h:340
const SourceMgr * getSourceMgr() const
Definition SourceMgr.h:330
int getColumnNo() const
Definition SourceMgr.h:334
Represents a single fixit, a replacement of one range of text with another.
Definition SourceMgr.h:280
bool operator<(const SMFixIt &Other) const
Definition SourceMgr.h:294
StringRef getText() const
Definition SourceMgr.h:291
LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement)
SMFixIt(SMLoc Loc, const Twine &Replacement)
Definition SourceMgr.h:288
SMRange getRange() const
Definition SourceMgr.h:292
Represents a location in source code.
Definition SMLoc.h:22
Represents a range in source code.
Definition SMLoc.h:47
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:34
void * getDiagContext() const
Definition SourceMgr.h:134
LLVM_ABI void printIncludeStackForDiagnostic(SMLoc Loc, raw_ostream &OS) const
Prints the include stack of a buffer unless it is a macro instantiation buffer.
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.
LLVM_ABI 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.
LLVM_ABI 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:97
LLVM_ABI IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Definition SourceMgr.cpp:50
LLVM_ABI SourceMgr & operator=(SourceMgr &&)
LLVM_ABI ErrorOr< std::unique_ptr< MemoryBuffer > > OpenIncludeFile(const std::string &Filename, std::string &IncludedFile, bool RequiresNullTerminator=true)
Search for a file with the specified name in the current directory or in one of the IncludeDirs,...
Definition SourceMgr.cpp:70
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:46
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:214
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
LLVM_ABI ~SourceMgr()
LLVM_ABI 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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI SourceMgr SrcMgr
Definition Error.cpp:24
@ Other
Any other memory.
Definition ModRef.h:68
ArrayRef(const T &OneElt) -> ArrayRef< T >