SourceLocation.h revision a83f4d2315dbeb3914868f1ccb8e74fb2ccdbb0c
1//===--- SourceLocation.h - Compact identifier for Source Files -*- 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 defines the SourceLocation class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SOURCELOCATION_H
15#define LLVM_CLANG_SOURCELOCATION_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/Support/PointerLikeTypeTraits.h"
19#include <utility>
20#include <functional>
21#include <cassert>
22
23namespace llvm {
24  class MemoryBuffer;
25  template <typename T> struct DenseMapInfo;
26  template <typename T> struct isPodLike;
27}
28
29namespace clang {
30
31class SourceManager;
32
33/// FileID - This is an opaque identifier used by SourceManager which refers to
34/// a source file (MemoryBuffer) along with its #include path and #line data.
35///
36class FileID {
37  /// ID - Opaque identifier, 0 is "invalid". >0 is this module, <-1 is
38  /// something loaded from another module.
39  int ID;
40public:
41  FileID() : ID(0) {}
42
43  bool isInvalid() const { return ID == 0; }
44
45  bool operator==(const FileID &RHS) const { return ID == RHS.ID; }
46  bool operator<(const FileID &RHS) const { return ID < RHS.ID; }
47  bool operator<=(const FileID &RHS) const { return ID <= RHS.ID; }
48  bool operator!=(const FileID &RHS) const { return !(*this == RHS); }
49  bool operator>(const FileID &RHS) const { return RHS < *this; }
50  bool operator>=(const FileID &RHS) const { return RHS <= *this; }
51
52  static FileID getSentinel() { return get(-1); }
53  unsigned getHashValue() const { return static_cast<unsigned>(ID); }
54
55private:
56  friend class SourceManager;
57  friend class ASTWriter;
58  friend class ASTReader;
59
60  static FileID get(int V) {
61    FileID F;
62    F.ID = V;
63    return F;
64  }
65  int getOpaqueValue() const { return ID; }
66};
67
68
69/// \brief Encodes a location in the source. The SourceManager can decode this
70/// to get at the full include stack, line and column information.
71///
72/// Technically, a source location is simply an offset into the manager's view
73/// of the input source, which is all input buffers (including macro
74/// expansions) concatenated in an effectively arbitrary order. The manager
75/// actually maintains two blocks of input buffers. One, starting at offset
76/// 0 and growing upwards, contains all buffers from this module. The other,
77/// starting at the highest possible offset and growing downwards, contains
78/// buffers of loaded modules.
79///
80/// In addition, one bit of SourceLocation is used for quick access to the
81/// information whether the location is in a file or a macro expansion.
82///
83/// It is important that this type remains small. It is currently 32 bits wide.
84class SourceLocation {
85  unsigned ID;
86  friend class SourceManager;
87  friend class ASTReader;
88  friend class ASTWriter;
89  enum {
90    MacroIDBit = 1U << 31
91  };
92public:
93
94  SourceLocation() : ID(0) {}
95
96  bool isFileID() const  { return (ID & MacroIDBit) == 0; }
97  bool isMacroID() const { return (ID & MacroIDBit) != 0; }
98
99  /// \brief Return true if this is a valid SourceLocation object.
100  ///
101  /// Invalid SourceLocations are often used when events have no corresponding
102  /// location in the source (e.g. a diagnostic is required for a command line
103  /// option).
104  bool isValid() const { return ID != 0; }
105  bool isInvalid() const { return ID == 0; }
106
107private:
108  /// \brief Return the offset into the manager's global input view.
109  unsigned getOffset() const {
110    return ID & ~MacroIDBit;
111  }
112
113  static SourceLocation getFileLoc(unsigned ID) {
114    assert((ID & MacroIDBit) == 0 && "Ran out of source locations!");
115    SourceLocation L;
116    L.ID = ID;
117    return L;
118  }
119
120  static SourceLocation getMacroLoc(unsigned ID) {
121    assert((ID & MacroIDBit) == 0 && "Ran out of source locations!");
122    SourceLocation L;
123    L.ID = MacroIDBit | ID;
124    return L;
125  }
126public:
127
128  /// \brief Return a source location with the specified offset from this
129  /// SourceLocation.
130  SourceLocation getLocWithOffset(int Offset) const {
131    assert(((getOffset()+Offset) & MacroIDBit) == 0 && "offset overflow");
132    SourceLocation L;
133    L.ID = ID+Offset;
134    return L;
135  }
136
137  /// getRawEncoding - When a SourceLocation itself cannot be used, this returns
138  /// an (opaque) 32-bit integer encoding for it.  This should only be passed
139  /// to SourceLocation::getFromRawEncoding, it should not be inspected
140  /// directly.
141  unsigned getRawEncoding() const { return ID; }
142
143  /// getFromRawEncoding - Turn a raw encoding of a SourceLocation object into
144  /// a real SourceLocation.
145  static SourceLocation getFromRawEncoding(unsigned Encoding) {
146    SourceLocation X;
147    X.ID = Encoding;
148    return X;
149  }
150
151  /// getPtrEncoding - When a SourceLocation itself cannot be used, this returns
152  /// an (opaque) pointer encoding for it.  This should only be passed
153  /// to SourceLocation::getFromPtrEncoding, it should not be inspected
154  /// directly.
155  void* getPtrEncoding() const {
156    // Double cast to avoid a warning "cast to pointer from integer of different
157    // size".
158    return (void*)(uintptr_t)getRawEncoding();
159  }
160
161  /// getFromPtrEncoding - Turn a pointer encoding of a SourceLocation object
162  /// into a real SourceLocation.
163  static SourceLocation getFromPtrEncoding(void *Encoding) {
164    return getFromRawEncoding((unsigned)(uintptr_t)Encoding);
165  }
166
167  void print(raw_ostream &OS, const SourceManager &SM) const;
168  void dump(const SourceManager &SM) const;
169};
170
171inline bool operator==(const SourceLocation &LHS, const SourceLocation &RHS) {
172  return LHS.getRawEncoding() == RHS.getRawEncoding();
173}
174
175inline bool operator!=(const SourceLocation &LHS, const SourceLocation &RHS) {
176  return !(LHS == RHS);
177}
178
179inline bool operator<(const SourceLocation &LHS, const SourceLocation &RHS) {
180  return LHS.getRawEncoding() < RHS.getRawEncoding();
181}
182
183/// SourceRange - a trival tuple used to represent a source range.
184class SourceRange {
185  SourceLocation B;
186  SourceLocation E;
187public:
188  SourceRange(): B(SourceLocation()), E(SourceLocation()) {}
189  SourceRange(SourceLocation loc) : B(loc), E(loc) {}
190  SourceRange(SourceLocation begin, SourceLocation end) : B(begin), E(end) {}
191
192  SourceLocation getBegin() const { return B; }
193  SourceLocation getEnd() const { return E; }
194
195  void setBegin(SourceLocation b) { B = b; }
196  void setEnd(SourceLocation e) { E = e; }
197
198  bool isValid() const { return B.isValid() && E.isValid(); }
199  bool isInvalid() const { return !isValid(); }
200
201  bool operator==(const SourceRange &X) const {
202    return B == X.B && E == X.E;
203  }
204
205  bool operator!=(const SourceRange &X) const {
206    return B != X.B || E != X.E;
207  }
208};
209
210/// CharSourceRange - This class represents a character granular source range.
211/// The underlying SourceRange can either specify the starting/ending character
212/// of the range, or it can specify the start or the range and the start of the
213/// last token of the range (a "token range").  In the token range case, the
214/// size of the last token must be measured to determine the actual end of the
215/// range.
216class CharSourceRange {
217  SourceRange Range;
218  bool IsTokenRange;
219public:
220  CharSourceRange() : IsTokenRange(false) {}
221  CharSourceRange(SourceRange R, bool ITR) : Range(R),IsTokenRange(ITR){}
222
223  static CharSourceRange getTokenRange(SourceRange R) {
224    CharSourceRange Result;
225    Result.Range = R;
226    Result.IsTokenRange = true;
227    return Result;
228  }
229
230  static CharSourceRange getCharRange(SourceRange R) {
231    CharSourceRange Result;
232    Result.Range = R;
233    Result.IsTokenRange = false;
234    return Result;
235  }
236
237  static CharSourceRange getTokenRange(SourceLocation B, SourceLocation E) {
238    return getTokenRange(SourceRange(B, E));
239  }
240  static CharSourceRange getCharRange(SourceLocation B, SourceLocation E) {
241    return getCharRange(SourceRange(B, E));
242  }
243
244  /// isTokenRange - Return true if the end of this range specifies the start of
245  /// the last token.  Return false if the end of this range specifies the last
246  /// character in the range.
247  bool isTokenRange() const { return IsTokenRange; }
248  bool isCharRange() const { return !IsTokenRange; }
249
250  SourceLocation getBegin() const { return Range.getBegin(); }
251  SourceLocation getEnd() const { return Range.getEnd(); }
252  const SourceRange &getAsRange() const { return Range; }
253
254  void setBegin(SourceLocation b) { Range.setBegin(b); }
255  void setEnd(SourceLocation e) { Range.setEnd(e); }
256
257  bool isValid() const { return Range.isValid(); }
258  bool isInvalid() const { return !isValid(); }
259};
260
261/// FullSourceLoc - A SourceLocation and its associated SourceManager.  Useful
262/// for argument passing to functions that expect both objects.
263class FullSourceLoc : public SourceLocation {
264  const SourceManager *SrcMgr;
265public:
266  /// Creates a FullSourceLoc where isValid() returns false.
267  explicit FullSourceLoc() : SrcMgr(0) {}
268
269  explicit FullSourceLoc(SourceLocation Loc, const SourceManager &SM)
270    : SourceLocation(Loc), SrcMgr(&SM) {}
271
272  const SourceManager &getManager() const {
273    assert(SrcMgr && "SourceManager is NULL.");
274    return *SrcMgr;
275  }
276
277  FileID getFileID() const;
278
279  FullSourceLoc getExpansionLoc() const;
280  FullSourceLoc getSpellingLoc() const;
281
282  unsigned getExpansionLineNumber(bool *Invalid = 0) const;
283  unsigned getExpansionColumnNumber(bool *Invalid = 0) const;
284
285  unsigned getSpellingLineNumber(bool *Invalid = 0) const;
286  unsigned getSpellingColumnNumber(bool *Invalid = 0) const;
287
288  const char *getCharacterData(bool *Invalid = 0) const;
289
290  const llvm::MemoryBuffer* getBuffer(bool *Invalid = 0) const;
291
292  /// getBufferData - Return a StringRef to the source buffer data for the
293  /// specified FileID.
294  StringRef getBufferData(bool *Invalid = 0) const;
295
296  /// getDecomposedLoc - Decompose the specified location into a raw FileID +
297  /// Offset pair.  The first element is the FileID, the second is the
298  /// offset from the start of the buffer of the location.
299  std::pair<FileID, unsigned> getDecomposedLoc() const;
300
301  bool isInSystemHeader() const;
302
303  /// \brief Determines the order of 2 source locations in the translation unit.
304  ///
305  /// \returns true if this source location comes before 'Loc', false otherwise.
306  bool isBeforeInTranslationUnitThan(SourceLocation Loc) const;
307
308  /// \brief Determines the order of 2 source locations in the translation unit.
309  ///
310  /// \returns true if this source location comes before 'Loc', false otherwise.
311  bool isBeforeInTranslationUnitThan(FullSourceLoc Loc) const {
312    assert(Loc.isValid());
313    assert(SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!");
314    return isBeforeInTranslationUnitThan((SourceLocation)Loc);
315  }
316
317  /// \brief Comparison function class, useful for sorting FullSourceLocs.
318  struct BeforeThanCompare : public std::binary_function<FullSourceLoc,
319                                                         FullSourceLoc, bool> {
320    bool operator()(const FullSourceLoc& lhs, const FullSourceLoc& rhs) const {
321      return lhs.isBeforeInTranslationUnitThan(rhs);
322    }
323  };
324
325  /// Prints information about this FullSourceLoc to stderr. Useful for
326  ///  debugging.
327  void dump() const { SourceLocation::dump(*SrcMgr); }
328
329  friend inline bool
330  operator==(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
331    return LHS.getRawEncoding() == RHS.getRawEncoding() &&
332          LHS.SrcMgr == RHS.SrcMgr;
333  }
334
335  friend inline bool
336  operator!=(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
337    return !(LHS == RHS);
338  }
339
340};
341
342/// PresumedLoc - This class represents an unpacked "presumed" location which
343/// can be presented to the user.  A 'presumed' location can be modified by
344/// #line and GNU line marker directives and is always the expansion point of
345/// a normal location.
346///
347/// You can get a PresumedLoc from a SourceLocation with SourceManager.
348class PresumedLoc {
349  const char *Filename;
350  unsigned Line, Col;
351  SourceLocation IncludeLoc;
352public:
353  PresumedLoc() : Filename(0) {}
354  PresumedLoc(const char *FN, unsigned Ln, unsigned Co, SourceLocation IL)
355    : Filename(FN), Line(Ln), Col(Co), IncludeLoc(IL) {
356  }
357
358  /// isInvalid - Return true if this object is invalid or uninitialized. This
359  /// occurs when created with invalid source locations or when walking off
360  /// the top of a #include stack.
361  bool isInvalid() const { return Filename == 0; }
362  bool isValid() const { return Filename != 0; }
363
364  /// getFilename - Return the presumed filename of this location.  This can be
365  /// affected by #line etc.
366  const char *getFilename() const { return Filename; }
367
368  /// getLine - Return the presumed line number of this location.  This can be
369  /// affected by #line etc.
370  unsigned getLine() const { return Line; }
371
372  /// getColumn - Return the presumed column number of this location.  This can
373  /// not be affected by #line, but is packaged here for convenience.
374  unsigned getColumn() const { return Col; }
375
376  /// getIncludeLoc - Return the presumed include location of this location.
377  /// This can be affected by GNU linemarker directives.
378  SourceLocation getIncludeLoc() const { return IncludeLoc; }
379};
380
381
382}  // end namespace clang
383
384namespace llvm {
385  /// Define DenseMapInfo so that FileID's can be used as keys in DenseMap and
386  /// DenseSets.
387  template <>
388  struct DenseMapInfo<clang::FileID> {
389    static inline clang::FileID getEmptyKey() {
390      return clang::FileID();
391    }
392    static inline clang::FileID getTombstoneKey() {
393      return clang::FileID::getSentinel();
394    }
395
396    static unsigned getHashValue(clang::FileID S) {
397      return S.getHashValue();
398    }
399
400    static bool isEqual(clang::FileID LHS, clang::FileID RHS) {
401      return LHS == RHS;
402    }
403  };
404
405  template <>
406  struct isPodLike<clang::SourceLocation> { static const bool value = true; };
407  template <>
408  struct isPodLike<clang::FileID> { static const bool value = true; };
409
410  // Teach SmallPtrSet how to handle SourceLocation.
411  template<>
412  class PointerLikeTypeTraits<clang::SourceLocation> {
413  public:
414    static inline void *getAsVoidPointer(clang::SourceLocation L) {
415      return L.getPtrEncoding();
416    }
417    static inline clang::SourceLocation getFromVoidPointer(void *P) {
418      return clang::SourceLocation::getFromRawEncoding((unsigned)(uintptr_t)P);
419    }
420    enum { NumLowBitsAvailable = 0 };
421  };
422
423}  // end namespace llvm
424
425#endif
426