LLVM  6.0.0svn
SourceMgr.h
Go to the documentation of this file.
1 //===- SourceMgr.h - Manager for Source Buffers & Diagnostics ---*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the SMDiagnostic and SourceMgr classes. This
11 // provides a simple substrate for diagnostics, #include handling, and other low
12 // level things for simple parsers.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_SUPPORT_SOURCEMGR_H
17 #define LLVM_SUPPORT_SOURCEMGR_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SMLoc.h"
26 #include <algorithm>
27 #include <cassert>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32 
33 namespace llvm {
34 
35 class raw_ostream;
36 class SMDiagnostic;
37 class SMFixIt;
38 
39 /// This owns the files read by a parser, handles include stacks,
40 /// and handles diagnostic wrangling.
41 class SourceMgr {
42 public:
43  enum DiagKind {
48  };
49 
50  /// Clients that want to handle their own diagnostics in a custom way can
51  /// register a function pointer+context as a diagnostic handler.
52  /// It gets called each time PrintMessage is invoked.
53  using DiagHandlerTy = void (*)(const SMDiagnostic &, void *Context);
54 
55 private:
56  struct SrcBuffer {
57  /// The memory buffer for the file.
58  std::unique_ptr<MemoryBuffer> Buffer;
59 
60  /// This is the location of the parent include, or null if at the top level.
61  SMLoc IncludeLoc;
62  };
63 
64  /// This is all of the buffers that we are reading from.
65  std::vector<SrcBuffer> Buffers;
66 
67  // This is the list of directories we should search for include files in.
68  std::vector<std::string> IncludeDirectories;
69 
70  /// This is a cache for line number queries, its implementation is really
71  /// private to SourceMgr.cpp.
72  mutable void *LineNoCache = nullptr;
73 
74  DiagHandlerTy DiagHandler = nullptr;
75  void *DiagContext = nullptr;
76 
77  bool isValidBufferID(unsigned i) const { return i && i <= Buffers.size(); }
78 
79 public:
80  SourceMgr() = default;
81  SourceMgr(const SourceMgr &) = delete;
82  SourceMgr &operator=(const SourceMgr &) = delete;
83  ~SourceMgr();
84 
85  void setIncludeDirs(const std::vector<std::string> &Dirs) {
86  IncludeDirectories = Dirs;
87  }
88 
89  /// Specify a diagnostic handler to be invoked every time PrintMessage is
90  /// called. \p Ctx is passed into the handler when it is invoked.
91  void setDiagHandler(DiagHandlerTy DH, void *Ctx = nullptr) {
92  DiagHandler = DH;
93  DiagContext = Ctx;
94  }
95 
96  DiagHandlerTy getDiagHandler() const { return DiagHandler; }
97  void *getDiagContext() const { return DiagContext; }
98 
99  const SrcBuffer &getBufferInfo(unsigned i) const {
100  assert(isValidBufferID(i));
101  return Buffers[i - 1];
102  }
103 
104  const MemoryBuffer *getMemoryBuffer(unsigned i) const {
105  assert(isValidBufferID(i));
106  return Buffers[i - 1].Buffer.get();
107  }
108 
109  unsigned getNumBuffers() const {
110  return Buffers.size();
111  }
112 
113  unsigned getMainFileID() const {
115  return 1;
116  }
117 
118  SMLoc getParentIncludeLoc(unsigned i) const {
119  assert(isValidBufferID(i));
120  return Buffers[i - 1].IncludeLoc;
121  }
122 
123  /// Add a new source buffer to this source manager. This takes ownership of
124  /// the memory buffer.
125  unsigned AddNewSourceBuffer(std::unique_ptr<MemoryBuffer> F,
126  SMLoc IncludeLoc) {
127  SrcBuffer NB;
128  NB.Buffer = std::move(F);
129  NB.IncludeLoc = IncludeLoc;
130  Buffers.push_back(std::move(NB));
131  return Buffers.size();
132  }
133 
134  /// Search for a file with the specified name in the current directory or in
135  /// one of the IncludeDirs.
136  ///
137  /// If no file is found, this returns 0, otherwise it returns the buffer ID
138  /// of the stacked file. The full path to the included file can be found in
139  /// \p IncludedFile.
140  unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc,
141  std::string &IncludedFile);
142 
143  /// Return the ID of the buffer containing the specified location.
144  ///
145  /// 0 is returned if the buffer is not found.
146  unsigned FindBufferContainingLoc(SMLoc Loc) const;
147 
148  /// Find the line number for the specified location in the specified file.
149  /// This is not a fast method.
150  unsigned FindLineNumber(SMLoc Loc, unsigned BufferID = 0) const {
151  return getLineAndColumn(Loc, BufferID).first;
152  }
153 
154  /// Find the line and column number for the specified location in the
155  /// specified file. This is not a fast method.
156  std::pair<unsigned, unsigned> getLineAndColumn(SMLoc Loc,
157  unsigned BufferID = 0) const;
158 
159  /// Emit a message about the specified location with the specified string.
160  ///
161  /// \param ShowColors Display colored messages if output is a terminal and
162  /// the default error handler is used.
163  void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind,
164  const Twine &Msg,
165  ArrayRef<SMRange> Ranges = None,
166  ArrayRef<SMFixIt> FixIts = None,
167  bool ShowColors = true) const;
168 
169  /// Emits a diagnostic to llvm::errs().
170  void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
171  ArrayRef<SMRange> Ranges = None,
172  ArrayRef<SMFixIt> FixIts = None,
173  bool ShowColors = true) const;
174 
175  /// Emits a manually-constructed diagnostic to the given output stream.
176  ///
177  /// \param ShowColors Display colored messages if output is a terminal and
178  /// the default error handler is used.
179  void PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
180  bool ShowColors = true) const;
181 
182  /// Return an SMDiagnostic at the specified location with the specified
183  /// string.
184  ///
185  /// \param Msg If non-null, the kind of message (e.g., "error") which is
186  /// prefixed to the message.
187  SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
188  ArrayRef<SMRange> Ranges = None,
189  ArrayRef<SMFixIt> FixIts = None) const;
190 
191  /// Prints the names of included files and the line of the file they were
192  /// included from. A diagnostic handler can use this before printing its
193  /// custom formatted message.
194  ///
195  /// \param IncludeLoc The location of the include.
196  /// \param OS the raw_ostream to print on.
197  void PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const;
198 };
199 
200 /// Represents a single fixit, a replacement of one range of text with another.
201 class SMFixIt {
202  SMRange Range;
203 
204  std::string Text;
205 
206 public:
207  // FIXME: Twine.str() is not very efficient.
208  SMFixIt(SMLoc Loc, const Twine &Insertion)
209  : Range(Loc, Loc), Text(Insertion.str()) {
210  assert(Loc.isValid());
211  }
212 
213  // FIXME: Twine.str() is not very efficient.
214  SMFixIt(SMRange R, const Twine &Replacement)
215  : Range(R), Text(Replacement.str()) {
216  assert(R.isValid());
217  }
218 
219  StringRef getText() const { return Text; }
220  SMRange getRange() const { return Range; }
221 
222  bool operator<(const SMFixIt &Other) const {
223  if (Range.Start.getPointer() != Other.Range.Start.getPointer())
224  return Range.Start.getPointer() < Other.Range.Start.getPointer();
225  if (Range.End.getPointer() != Other.Range.End.getPointer())
226  return Range.End.getPointer() < Other.Range.End.getPointer();
227  return Text < Other.Text;
228  }
229 };
230 
231 /// Instances of this class encapsulate one diagnostic report, allowing
232 /// printing to a raw_ostream as a caret diagnostic.
234  const SourceMgr *SM = nullptr;
235  SMLoc Loc;
236  std::string Filename;
237  int LineNo = 0;
238  int ColumnNo = 0;
240  std::string Message, LineContents;
241  std::vector<std::pair<unsigned, unsigned>> Ranges;
243 
244 public:
245  // Null diagnostic.
246  SMDiagnostic() = default;
247  // Diagnostic with no location (e.g. file not found, command line arg error).
249  : Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {}
250 
251  // Diagnostic with a location.
252  SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
253  int Line, int Col, SourceMgr::DiagKind Kind,
254  StringRef Msg, StringRef LineStr,
255  ArrayRef<std::pair<unsigned,unsigned>> Ranges,
256  ArrayRef<SMFixIt> FixIts = None);
257 
258  const SourceMgr *getSourceMgr() const { return SM; }
259  SMLoc getLoc() const { return Loc; }
260  StringRef getFilename() const { return Filename; }
261  int getLineNo() const { return LineNo; }
262  int getColumnNo() const { return ColumnNo; }
263  SourceMgr::DiagKind getKind() const { return Kind; }
264  StringRef getMessage() const { return Message; }
265  StringRef getLineContents() const { return LineContents; }
267 
268  void addFixIt(const SMFixIt &Hint) {
269  FixIts.push_back(Hint);
270  }
271 
273  return FixIts;
274  }
275 
276  void print(const char *ProgName, raw_ostream &S, bool ShowColors = true,
277  bool ShowKindLabel = true) const;
278 };
279 
280 } // end namespace llvm
281 
282 #endif // LLVM_SUPPORT_SOURCEMGR_H
Represents a range in source code.
Definition: SMLoc.h:49
unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:78
LLVMContext & Context
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
SMLoc getLoc() const
Definition: SourceMgr.h:259
DiagHandlerTy getDiagHandler() const
Definition: SourceMgr.h:96
SMFixIt(SMLoc Loc, const Twine &Insertion)
Definition: SourceMgr.h:208
unsigned getNumBuffers() const
Definition: SourceMgr.h:109
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:133
F(f)
ArrayRef< SMFixIt > getFixIts() const
Definition: SourceMgr.h:272
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:89
SMRange getRange() const
Definition: SourceMgr.h:220
void addFixIt(const SMFixIt &Hint)
Definition: SourceMgr.h:268
SMLoc Start
Definition: SMLoc.h:51
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
Definition: SourceMgr.cpp:225
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
int getLineNo() const
Definition: SourceMgr.h:261
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:104
StringRef getLineContents() const
Definition: SourceMgr.h:265
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:125
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
StringRef getText() const
Definition: SourceMgr.h:219
unsigned getMainFileID() const
Definition: SourceMgr.h:113
const char * getPointer() const
Definition: SMLoc.h:35
void setDiagHandler(DiagHandlerTy DH, void *Ctx=nullptr)
Specify a diagnostic handler to be invoked every time PrintMessage is called.
Definition: SourceMgr.h:91
SourceMgr()=default
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
Represents a single fixit, a replacement of one range of text with another.
Definition: SourceMgr.h:201
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:53
SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:146
const SrcBuffer & getBufferInfo(unsigned i) const
Definition: SourceMgr.h:99
bool isValid() const
Definition: SMLoc.h:60
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
StringRef getMessage() const
Definition: SourceMgr.h:264
ArrayRef< std::pair< unsigned, unsigned > > getRanges() const
Definition: SourceMgr.h:266
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:40
bool isValid() const
Definition: SMLoc.h:30
StringRef getFilename() const
Definition: SourceMgr.h:260
SMLoc End
Definition: SMLoc.h:51
SourceMgr::DiagKind getKind() const
Definition: SourceMgr.h:263
unsigned FindLineNumber(SMLoc Loc, unsigned BufferID=0) const
Find the line number for the specified location in the specified file.
Definition: SourceMgr.h:150
bool operator<(const SMFixIt &Other) const
Definition: SourceMgr.h:222
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:57
int getColumnNo() const
Definition: SourceMgr.h:262
SMLoc getParentIncludeLoc(unsigned i) const
Definition: SourceMgr.h:118
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:575
void * getDiagContext() const
Definition: SourceMgr.h:97
const unsigned Kind
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SourceMgr & operator=(const SourceMgr &)=delete
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition: SourceMgr.h:85
SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg)
Definition: SourceMgr.h:248
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Represents a location in source code.
Definition: SMLoc.h:24
SMFixIt(SMRange R, const Twine &Replacement)
Definition: SourceMgr.h:214
const SourceMgr * getSourceMgr() const
Definition: SourceMgr.h:258
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:233