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