1 //===- SourceMgr.h - Manager for Source Buffers & Diagnostics ---*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_SUPPORT_SOURCEMGR_H
16 #define LLVM_SUPPORT_SOURCEMGR_H
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/SMLoc.h"
29 /// This owns the files read by a parser, handles include stacks,
30 /// and handles diagnostic wrangling.
40 /// Clients that want to handle their own diagnostics in a custom way can
41 /// register a function pointer+context as a diagnostic handler.
42 /// It gets called each time PrintMessage is invoked.
43 using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
47 /// The memory buffer for the file.
48 std::unique_ptr<MemoryBuffer> Buffer;
50 /// Vector of offsets into Buffer at which there are line-endings
51 /// (lazily populated). Once populated, the '\n' that marks the end of
52 /// line number N from [1..] is at Buffer[OffsetCache[N-1]]. Since
53 /// these offsets are in sorted (ascending) order, they can be
54 /// binary-searched for the first one after any given offset (eg. an
55 /// offset corresponding to a particular SMLoc).
57 /// Since we're storing offsets into relatively small files (often smaller
58 /// than 2^8 or 2^16 bytes), we select the offset vector element type
59 /// dynamically based on the size of Buffer.
60 mutable void *OffsetCache = nullptr;
62 /// Look up a given \p Ptr in in the buffer, determining which line it came
64 unsigned getLineNumber(const char *Ptr) const;
66 unsigned getLineNumberSpecialized(const char *Ptr) const;
68 /// Return a pointer to the first character of the specified line number or
69 /// null if the line number is invalid.
70 const char *getPointerForLineNumber(unsigned LineNo) const;
72 const char *getPointerForLineNumberSpecialized(unsigned LineNo) const;
74 /// This is the location of the parent include, or null if at the top level.
77 SrcBuffer() = default;
78 SrcBuffer(SrcBuffer &&);
79 SrcBuffer(const SrcBuffer &) = delete;
80 SrcBuffer &operator=(const SrcBuffer &) = delete;
84 /// This is all of the buffers that we are reading from.
85 std::vector<SrcBuffer> Buffers;
87 // This is the list of directories we should search for include files in.
88 std::vector<std::string> IncludeDirectories;
90 DiagHandlerTy DiagHandler = nullptr;
91 void *DiagContext = nullptr;
93 bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); }
96 SourceMgr() = default;
97 SourceMgr(const SourceMgr &) = delete;
98 SourceMgr &operator=(const SourceMgr &) = delete;
99 SourceMgr(SourceMgr &&) = default;
100 SourceMgr &operator=(SourceMgr &&) = default;
101 ~SourceMgr() = default;
103 void setIncludeDirs(const std::vector<std::string> &Dirs) {
104 IncludeDirectories = Dirs;
107 /// Specify a diagnostic handler to be invoked every time PrintMessage is
108 /// called. \p Ctx is passed into the handler when it is invoked.
109 void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
114 DiagHandlerTy getDiagHandler() const { return DiagHandler; }
115 void *getDiagContext() const { return DiagContext; }
117 const SrcBuffer &getBufferInfo(unsigned i) const {
118 assert(isValidBufferID(i));
119 return Buffers[i - 1];
122 const MemoryBuffer *getMemoryBuffer(unsigned i) const {
123 assert(isValidBufferID(i));
124 return Buffers[i - 1].Buffer.get();
127 unsigned getNumBuffers() const { return Buffers.size(); }
129 unsigned getMainFileID() const {
130 assert(getNumBuffers());
134 SMLoc getParentIncludeLoc(unsigned i) const {
135 assert(isValidBufferID(i));
136 return Buffers[i - 1].IncludeLoc;
139 /// Add a new source buffer to this source manager. This takes ownership of
140 /// the memory buffer.
141 unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
144 NB.Buffer = std::move(F);
145 NB.IncludeLoc = IncludeLoc;
146 Buffers.push_back(std::move(NB));
147 return Buffers.size();
150 /// Search for a file with the specified name in the current directory or in
151 /// one of the IncludeDirs.
153 /// If no file is found, this returns 0, otherwise it returns the buffer ID
154 /// of the stacked file. The full path to the included file can be found in
156 unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc,
157 std::string &IncludedFile);
159 /// Return the ID of the buffer containing the specified location.
161 /// 0 is returned if the buffer is not found.
162 unsigned FindBufferContainingLoc(SMLoc Loc) const;
164 /// Find the line number for the specified location in the specified file.
165 /// This is not a fast method.
166 unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
167 return getLineAndColumn(Loc, BufferID).first;
170 /// Find the line and column number for the specified location in the
171 /// specified file. This is not a fast method.
172 std::pair<unsigned, unsigned> getLineAndColumn(SMLoc Loc,
173 unsigned BufferID = 0) const;
175 /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
176 /// This will return a null SMLoc if the line/column location is invalid.
177 SMLoc FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
180 /// Emit a message about the specified location with the specified string.
182 /// \param ShowColors Display colored messages if output is a terminal and
183 /// the default error handler is used.
184 void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg,
185 ArrayRef<SMRange> Ranges = {},
186 ArrayRef<SMFixIt> FixIts = {},
187 bool ShowColors = true) const;
189 /// Emits a diagnostic to llvm::errs().
190 void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
191 ArrayRef<SMRange> Ranges = {},
192 ArrayRef<SMFixIt> FixIts = {},
193 bool ShowColors = true) const;
195 /// Emits a manually-constructed diagnostic to the given output stream.
197 /// \param ShowColors Display colored messages if output is a terminal and
198 /// the default error handler is used.
199 void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
200 bool ShowColors = true) const;
202 /// Return an SMDiagnostic at the specified location with the specified
205 /// \param Msg If non-null, the kind of message (e.g., "error") which is
206 /// prefixed to the message.
207 SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = {},
209 ArrayRef<SMFixIt> FixIts = {}) const;
211 /// Prints the names of included files and the line of the file they were
212 /// included from. A diagnostic handler can use this before printing its
213 /// custom formatted message.
215 /// \param IncludeLoc The location of the include.
216 /// \param OS the raw_ostream to print on.
217 void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
220 /// Represents a single fixit, a replacement of one range of text with another.
227 SMFixIt(SMRange R, const Twine &Replacement);
229 SMFixIt(SMLoc Loc, const Twine &Replacement)
230 : SMFixIt(SMRange(Loc, Loc), Replacement) {}
232 StringRef getText() const { return Text; }
233 SMRange getRange() const { return Range; }
235 bool operator<(const SMFixIt &Other) const {
236 if (Range.Start.getPointer() != Other.Range.Start.getPointer())
237 return Range.Start.getPointer() < Other.Range.Start.getPointer();
238 if (Range.End.getPointer() != Other.Range.End.getPointer())
239 return Range.End.getPointer() < Other.Range.End.getPointer();
240 return Text < Other.Text;
244 /// Instances of this class encapsulate one diagnostic report, allowing
245 /// printing to a raw_ostream as a caret diagnostic.
247 const SourceMgr *SM = nullptr;
249 std::string Filename;
252 SourceMgr::DiagKind Kind = SourceMgr::DK_Error;
253 std::string Message, LineContents;
254 std::vector<std::pair<unsigned, unsigned>> Ranges;
255 SmallVector<SMFixIt, 4> FixIts;
259 SMDiagnostic() = default;
260 // Diagnostic with no location (e.g. file not found, command line arg error).
261 SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
262 : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
264 // Diagnostic with a location.
265 SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line, int Col,
266 SourceMgr::DiagKind Kind, StringRef Msg, StringRef LineStr,
267 ArrayRef<std::pair<unsigned, unsigned>> Ranges,
268 ArrayRef<SMFixIt> FixIts = {});
270 const SourceMgr *getSourceMgr() const { return SM; }
271 SMLoc getLoc() const { return Loc; }
272 StringRef getFilename() const { return Filename; }
273 int getLineNo() const { return LineNo; }
274 int getColumnNo() const { return ColumnNo; }
275 SourceMgr::DiagKind getKind() const { return Kind; }
276 StringRef getMessage() const { return Message; }
277 StringRef getLineContents() const { return LineContents; }
278 ArrayRef<std::pair<unsigned, unsigned>> getRanges() const { return Ranges; }
280 void addFixIt(const SMFixIt &Hint) { FixIts.push_back(Hint); }
282 ArrayRef<SMFixIt> getFixIts() const { return FixIts; }
284 void print(const char *ProgName, raw_ostream &S, bool ShowColors = true,
285 bool ShowKindLabel = true) const;
288 } // end namespace llvm
290 #endif // LLVM_SUPPORT_SOURCEMGR_H