Spicy
location.h
1 // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <string>
6 #include <utility>
7 
8 #include <hilti/rt/filesystem.h>
9 
10 #include <hilti/base/util.h>
11 
12 namespace hilti {
13 
17 class Location {
18 public:
29  constexpr Location(std::string file = "",
30  int from_line = -1,
31  int to_line = -1,
32  int from_character = -1,
33  int to_character = -1)
34  : _file(std::move(file)),
35  _from_line(from_line),
36  _to_line(to_line),
37  _from_character(from_character),
38  _to_character(to_character) {}
39 
40  Location(const Location&) = default;
41  Location(Location&&) = default;
42  Location& operator=(const Location&) = default;
43  Location& operator=(Location&&) = default;
44  ~Location() = default;
45 
46  const auto& file() const { return _file; }
47  auto from() const { return _from_line; }
48  auto to() const { return _to_line; }
49 
54  Location merge(const Location& loc) const;
55 
61  std::string dump(bool no_path = false) const;
62 
67  explicit operator bool() const;
68 
70  operator std::string() const { return dump(); }
71 
72  bool operator<(const Location& other) const {
73  return std::tie(_file, _from_line, _from_character, _to_line, _to_character) <
74  std::tie(other._file, other._from_line, other._from_character, other._to_line, other._to_character);
75  }
76 
77  bool operator==(const Location& other) const {
78  return std::tie(_file, _from_line, _from_character, _to_line, _to_character) ==
79  std::tie(other._file, other._from_line, other._from_character, other._to_line, other._to_character);
80  }
81 
82 private:
83  std::string _file;
84  int _from_line = -1;
85  int _to_line = -1;
86 
87  int _from_character = -1;
88  int _to_character = -1;
89 
90  friend struct std::hash<Location>;
91 };
92 
94 inline auto to_string(const Location& l) { return l.dump(); }
95 
97 inline std::ostream& operator<<(std::ostream& out, const Location& l) {
98  out << l.dump();
99  return out;
100 }
101 
102 namespace location {
103 // TODO: This should be `constinit` to guarantee initialization at compile
104 // time, but gcc-12 used on e.g., debian-12 does not recognize this as a
105 // valid use.
107 /*constinit*/ static inline const Location None;
108 } // namespace location
109 
110 } // namespace hilti
111 
112 namespace std {
113 template<>
114 struct hash<hilti::Location> {
115  size_t operator()(const hilti::Location& x) const {
116  return hilti::rt::hashCombine(std::hash<std::string>()(x._file),
117  x._from_line,
118  x._to_line,
119  x._from_character,
120  x._to_character);
121  }
122 };
123 } // namespace std
Definition: location.h:17
constexpr Location(std::string file="", int from_line=-1, int to_line=-1, int from_character=-1, int to_character=-1)
Definition: location.h:29
Location merge(const Location &loc) const
Definition: location.cc:13
std::string dump(bool no_path=false) const
Definition: location.cc:26