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 {
147 return static_cast<unsigned>(Buffers.size());
148 }
149
150 unsigned getMainFileID() const {
152 return 1;
153 }
154
155 SMLoc getParentIncludeLoc(unsigned i) const {
156 assert(isValidBufferID(i));
157 return Buffers[i - 1].IncludeLoc;
158 }
159
160 /// Add a new source buffer to this source manager. This takes ownership of
161 /// the memory buffer.
162 unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
163 SMLoc IncludeLoc) {
164 SrcBuffer NB;
165 NB.Buffer = std::move(F);
166 NB.IncludeLoc = IncludeLoc;
167 Buffers.push_back(std::move(NB));
168 return static_cast<unsigned>(Buffers.size());
169 }
170
171 /// Takes the source buffers from the given source manager and append them to
172 /// the current manager. `MainBufferIncludeLoc` is an optional include
173 /// location to attach to the main buffer of `SrcMgr` after it gets moved to
174 /// the current manager.
176 SMLoc MainBufferIncludeLoc = SMLoc()) {
177 if (SrcMgr.Buffers.empty())
178 return;
179
180 size_t OldNumBuffers = getNumBuffers();
181 std::move(SrcMgr.Buffers.begin(), SrcMgr.Buffers.end(),
182 std::back_inserter(Buffers));
183 SrcMgr.Buffers.clear();
184 Buffers[OldNumBuffers].IncludeLoc = MainBufferIncludeLoc;
185 }
186
187 /// Search for a file with the specified name in the current directory or in
188 /// one of the IncludeDirs.
189 ///
190 /// If no file is found, this returns 0, otherwise it returns the buffer ID
191 /// of the stacked file. The full path to the included file can be found in
192 /// \p IncludedFile.
193 LLVM_ABI unsigned AddIncludeFile(const std::string &Filename,
194 SMLoc IncludeLoc, std::string &IncludedFile);
195
196 /// Search for a file with the specified name in the current directory or in
197 /// one of the IncludeDirs, and try to open it **without** adding to the
198 /// SourceMgr. If the opened file is intended to be added to the source
199 /// manager, prefer `AddIncludeFile` instead.
200 ///
201 /// If no file is found, this returns an Error, otherwise it returns the
202 /// buffer of the stacked file. The full path to the included file can be
203 /// found in \p IncludedFile.
205 OpenIncludeFile(const std::string &Filename, std::string &IncludedFile,
206 bool RequiresNullTerminator = true);
207
208 /// Return the ID of the buffer containing the specified location.
209 ///
210 /// 0 is returned if the buffer is not found.
212
213 /// Find the line number for the specified location in the specified file.
214 /// This method has O(log n) complexity, where n is the number of lines in the
215 /// buffer.
216 unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
217 return getLineAndColumn(Loc, BufferID).first;
218 }
219
220 /// Find the line and column number for the specified location in the
221 /// specified file. This method has O(log n) complexity, where n is the number
222 /// of lines in the buffer.
223 LLVM_ABI std::pair<unsigned, unsigned>
224 getLineAndColumn(SMLoc Loc, unsigned BufferID = 0) const;
225
226 /// Get a string with the \p SMLoc filename and line number
227 /// formatted in the standard style.
228 LLVM_ABI std::string
229 getFormattedLocationNoOffset(SMLoc Loc, bool IncludePath = false) const;
230
231 /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
232 /// This will return a null SMLoc if the line/column location is invalid.
233 LLVM_ABI SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
234 unsigned ColNo);
235
236 /// Emit a message about the specified location with the specified string.
237 ///
238 /// \param ShowColors Display colored messages if output is a terminal and
239 /// the default error handler is used.
240 LLVM_ABI void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind,
241 const Twine &Msg, ArrayRef<SMRange> Ranges = {},
242 ArrayRef<SMFixIt> FixIts = {},
243 bool ShowColors = true) const;
244
245 /// Emits a diagnostic to llvm::errs().
246 LLVM_ABI void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
247 ArrayRef<SMRange> Ranges = {},
248 ArrayRef<SMFixIt> FixIts = {},
249 bool ShowColors = true) const;
250
251 /// Emits a manually-constructed diagnostic to the given output stream.
252 ///
253 /// \param ShowColors Display colored messages if output is a terminal and
254 /// the default error handler is used.
255 LLVM_ABI void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
256 bool ShowColors = true) const;
257
258 /// Return an SMDiagnostic at the specified location with the specified
259 /// string.
260 ///
261 /// \param Msg If non-null, the kind of message (e.g., "error") which is
262 /// prefixed to the message.
263 LLVM_ABI SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
264 ArrayRef<SMRange> Ranges = {},
265 ArrayRef<SMFixIt> FixIts = {}) const;
266
267 /// Prints the names of included files and the line of the file they were
268 /// included from. A diagnostic handler can use this before printing its
269 /// custom formatted message.
270 ///
271 /// \param IncludeLoc The location of the include.
272 /// \param OS the raw_ostream to print on.
273 LLVM_ABI void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
274
275 /// Prints the include stack of a buffer unless it is a macro instantiation
276 /// buffer.
278 raw_ostream &OS) const;
279};
280
281/// Represents a single fixit, a replacement of one range of text with another.
282class SMFixIt {
283 SMRange Range;
284
285 std::string Text;
286
287public:
288 LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement);
289
290 SMFixIt(SMLoc Loc, const Twine &Replacement)
291 : SMFixIt(SMRange(Loc, Loc), Replacement) {}
292
293 StringRef getText() const { return Text; }
294 SMRange getRange() const { return Range; }
295
296 bool operator<(const SMFixIt &Other) const {
297 if (Range.Start.getPointer() != Other.Range.Start.getPointer())
298 return Range.Start.getPointer() < Other.Range.Start.getPointer();
299 if (Range.End.getPointer() != Other.Range.End.getPointer())
300 return Range.End.getPointer() < Other.Range.End.getPointer();
301 return Text < Other.Text;
302 }
303};
304
305/// Instances of this class encapsulate one diagnostic report, allowing
306/// printing to a raw_ostream as a caret diagnostic.
308 const SourceMgr *SM = nullptr;
309 SMLoc Loc;
310 std::string Filename;
311 int LineNo = 0;
312 int ColumnNo = 0;
314 std::string Message, LineContents;
315 std::vector<std::pair<unsigned, unsigned>> Ranges;
317
318public:
319 // Null diagnostic.
320 SMDiagnostic() = default;
321 // Diagnostic with no location (e.g. file not found, command line arg error).
323 : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
324
325 // Diagnostic with a location.
326 LLVM_ABI SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line,
327 int Col, SourceMgr::DiagKind Kind, StringRef Msg,
328 StringRef LineStr,
329 ArrayRef<std::pair<unsigned, unsigned>> Ranges,
330 ArrayRef<SMFixIt> FixIts = {});
331
332 const SourceMgr *getSourceMgr() const { return SM; }
333 SMLoc getLoc() const { return Loc; }
334 StringRef getFilename() const { return Filename; }
335 int getLineNo() const { return LineNo; }
336 int getColumnNo() const { return ColumnNo; }
337 SourceMgr::DiagKind getKind() const { return Kind; }
338 StringRef getMessage() const { return Message; }
339 StringRef getLineContents() const { return LineContents; }
341
342 void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
343
344 ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
345
346 LLVM_ABI void print(const char *ProgName, raw_ostream &S,
347 bool ShowColors = true, bool ShowKindLabel = true,
348 bool ShowLocation = true) const;
349};
350
351} // end namespace llvm
352
353#endif // LLVM_SUPPORT_SOURCEMGR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:211
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:307
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:337
StringRef getFilename() const
Definition SourceMgr.h:334
SMDiagnostic()=default
int getLineNo() const
Definition SourceMgr.h:335
SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
Definition SourceMgr.h:322
StringRef getLineContents() const
Definition SourceMgr.h:339
SMLoc getLoc() const
Definition SourceMgr.h:333
StringRef getMessage() const
Definition SourceMgr.h:338
ArrayRef< SMFixIt > getFixIts() const
Definition SourceMgr.h:344
ArrayRef< std::pair< unsigned, unsigned > > getRanges() const
Definition SourceMgr.h:340
void addFixIt(const SMFixIt &Hint)
Definition SourceMgr.h:342
const SourceMgr * getSourceMgr() const
Definition SourceMgr.h:332
int getColumnNo() const
Definition SourceMgr.h:336
Represents a single fixit, a replacement of one range of text with another.
Definition SourceMgr.h:282
bool operator<(const SMFixIt &Other) const
Definition SourceMgr.h:296
StringRef getText() const
Definition SourceMgr.h:293
LLVM_ABI SMFixIt(SMRange R, const Twine &Replacement)
SMFixIt(SMLoc Loc, const Twine &Replacement)
Definition SourceMgr.h:290
SMRange getRange() const
Definition SourceMgr.h:294
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:150
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:155
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:216
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:175
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:162
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 >