FE 0.17.2
Fast, Effecient FrontEnds
Loading...
Searching...
No Matches
sym.h
Go to the documentation of this file.
1#pragma once
2
3#include <cassert>
4#include <concepts>
5
6#include <array>
7#include <bit>
8#include <iosfwd>
9#include <optional>
10#include <string>
11
12#include <ankerl/unordered_dense.h>
13
14#include "fe/arena.h"
15#include "fe/hash.h"
16
17namespace fe {
18
19/// A Sym%bol just wraps a pointer to Sym::String, so pass Sym itself around as value.
20/// Retrieving a `std::string_view` (via Sym::view) is basically free.
21/// You can also obtain a `std::string` (via Sym::str), but this involves a copy.
22/// The characters are *not* null-terminated.
23/// With the exception of the empty string, you should only create Sym%bols via SymPool::sym.
24/// This in turn will toss all Sym%bols into a big hash set.
25/// This makes Sym::operator== and Sym::operator!= an O(1) operation.
26/// The empty string is internally handled as `nullptr`.
27/// Thus, you can create a Sym%bol representing an empty string without having access to the SymPool.
28/// @note The empty `std::string`/`std::string_view` and `nullptr` are all identified as Sym::Sym().
29/// @warning Big endian version has not been tested.
30class Sym {
31public:
32 static constexpr size_t Short_String_Bytes = sizeof(uintptr_t);
33 static constexpr size_t Short_String_Mask = Short_String_Bytes - 1;
34
35 struct String {
36 constexpr String() noexcept = default;
37 constexpr String(size_t size) noexcept
38 : size(size) {}
39
40 size_t size = 0;
41#if defined(__GNUC__)
42# pragma GCC diagnostic push
43# pragma GCC diagnostic ignored "-Wpedantic"
44#endif
45#if defined(_MSC_VER)
46# pragma warning(push)
47# pragma warning(disable : 4200)
48#endif
49 char chars[]; // This is actually a C-only feature, but all C++ compilers support that anyway.
50#if defined(_MSC_VER)
51# pragma warning(pop)
52#endif
53#if defined(__GNUC__)
54# pragma GCC diagnostic pop
55#endif
56
57 struct Equal {
58 constexpr bool operator()(const String* s1, const String* s2) const noexcept {
59 return std::string_view(s1->chars, s1->size) == std::string_view(s2->chars, s2->size);
60 }
61 };
62
63 /// Hashes the characters, not the pointer - String::Equal compares them, and the two have to agree.
64 struct Hash {
65 using is_avalanching = void;
66
67 size_t operator()(const String* s) const noexcept { return StrHash()(std::string_view(s->chars, s->size)); }
68 };
69 };
70
71 static_assert(sizeof(String) == sizeof(size_t), "String.chars should be 0");
72
73private:
74 constexpr Sym(uintptr_t ptr) noexcept
75 : ptr_(ptr) {}
76
77public:
78 constexpr Sym() noexcept = default;
79
80 /// @name Getters
81 ///@{
82 [[nodiscard]] constexpr bool empty() const noexcept { return ptr_ == 0; }
83 [[nodiscard]] constexpr size_t size() const noexcept {
84 if (empty()) return 0;
85 if (auto size = ptr_ & Short_String_Mask) return size;
86 return ((const String*)ptr_)->size;
87 }
88 [[nodiscard]] constexpr uintptr_t raw() const noexcept { return ptr_; }
89 ///@}
90
91 /// @name Access
92 ///@{
93 constexpr char operator[](size_t i) const noexcept {
94 assert(i < size());
95 return view()[i];
96 }
97 constexpr char front() const noexcept { return (*this)[0]; }
98 constexpr char back() const noexcept { return (*this)[size() - 1]; }
99 ///@}
100
101 /// @name Iterators
102 ///@{
103 constexpr auto begin() const noexcept { return view().data(); }
104 constexpr auto end() const noexcept { return begin() + size(); }
105 constexpr auto cbegin() const noexcept { return begin(); }
106 constexpr auto cend() const noexcept { return end(); }
107 constexpr auto rbegin() const noexcept { return std::reverse_iterator(end()); }
108 constexpr auto rend() const noexcept { return std::reverse_iterator(begin()); }
109 constexpr auto crbegin() const noexcept { return rbegin(); }
110 constexpr auto crend() const noexcept { return rend(); }
111 ///@}
112
113 /// @name Comparison: Sym w/ Sym
114 ///@{
115 friend constexpr auto operator<=>(Sym s1, Sym s2) noexcept { return s1.view() <=> s2.view(); }
116 friend constexpr bool operator==(Sym s1, Sym s2) noexcept { return s1.ptr_ == s2.ptr_; }
117 ///@}
118
119 /// @name Comparison: Sym w/ char
120 ///@{
121 friend constexpr std::strong_ordering operator<=>(Sym s, char c) noexcept { return cmp<false>(s, c); }
122 friend constexpr std::strong_ordering operator<=>(char c, Sym s) noexcept { return cmp<true>(s, c); }
123 friend constexpr bool operator==(Sym s, char c) noexcept { return (s.size() == 1) && (s[0] == c); }
124 friend constexpr bool operator==(char c, Sym s) noexcept { return (s.size() == 1) && (s[0] == c); }
125 ///@}
126
127 /// @name Comparison: Sym w/ convertible to std::string_view
128 ///@{
129 friend constexpr auto operator<=>(Sym lhs, const std::convertible_to<std::string_view> auto& rhs) noexcept {
130 return lhs.view() <=> std::string_view(rhs);
131 }
132 friend constexpr auto operator<=>(const std::convertible_to<std::string_view> auto& lhs, Sym rhs) noexcept {
133 return std::string_view(lhs) <=> rhs.view();
134 }
135
136 friend constexpr bool operator==(Sym lhs, const std::convertible_to<std::string_view> auto& rhs) noexcept {
137 return lhs.view() == std::string_view(rhs);
138 }
139
140 friend constexpr bool operator==(const std::convertible_to<std::string_view> auto& lhs, Sym rhs) noexcept {
141 return std::string_view(lhs) == rhs.view();
142 }
143 ///@}
144
145 /// @name Conversions
146 ///@{
147 /// @warning For a *short* Sym%bol (size < Sym::Short_String_Bytes) the characters are stored inline within this
148 /// object's `ptr_`, so the returned view points into *this* Sym%bol and is only valid as long as it lives - it
149 /// dangles for a temporary (e.g. `pool.sym("ab").view()`). Use Sym::str if the string must outlive the Sym%bol.
150 [[nodiscard]] constexpr std::string_view view() const noexcept {
151 if (empty()) return {std::bit_cast<const char*>(&ptr_), 0};
152 // Little endian: 2 a b ? register: ?ba2
153 // Big endian: a b ? 2 register: ab?2
154 uintptr_t offset = std::endian::native == std::endian::little ? 1 : 0;
155 if (auto size = ptr_ & Short_String_Mask) return {std::bit_cast<const char*>(&ptr_) + offset, size};
156 auto S = std::bit_cast<const String*>(ptr_);
157 return std::string_view(S->chars, S->size);
158 }
159 constexpr operator std::string_view() const noexcept { return view(); }
160 constexpr std::string_view operator*() const noexcept { return view(); }
161 // Unfortunately, this doesn't work:
162 // std::string_view operator->() const { return view(); }
163
164 constexpr std::string str() const { return std::string(view()); } ///< This involves a copy.
165 constexpr explicit operator std::string() const { return str(); } ///< `explicit` as this involves a copy.
166 constexpr explicit operator bool() const noexcept { return ptr_; } ///< Is not empty?
167 ///@}
168
169 friend std::ostream& operator<<(std::ostream& os, Sym sym);
170
171 /// @name Hash/Eq for hash tables.
172 /// Both work on the interned pointer, so they are O(1).
173 /// @note There is deliberately *no* heterogeneous (`std::string_view`) lookup:
174 /// a content-based hash would be inconsistent with the pointer-based one.
175 /// Intern via SymPool::sym first, then look up with the resulting Sym.
176 ///@{
177 struct Hash {
178 using is_avalanching = void;
179
180 size_t operator()(Sym s) const noexcept { return ankerl::unordered_dense::hash<uintptr_t>()(s.ptr_); }
181 };
182
183 struct Eq {
184 constexpr bool operator()(Sym a, Sym b) const noexcept { return a.ptr_ == b.ptr_; }
185 };
186 ///@}
187
188private:
189 template<bool Rev>
190 static constexpr std::strong_ordering cmp(Sym s, char c) noexcept {
191 const auto n = s.size();
192 if (n == 0) return Rev ? std::strong_ordering::greater : std::strong_ordering::less;
193
194 auto cmp = s[0] <=> c;
195 if (cmp != 0) return cmp;
196
197 return (n == 1) ? std::strong_ordering::equal
198 : (Rev ? std::strong_ordering::less : std::strong_ordering::greater);
199 }
200
201 // Little endian: 2 a b ? register: ?ba2
202 // Big endian: a b ? 2 register: ab?2
203 uintptr_t ptr_ = 0;
204
205 friend class SymPool;
206};
207
208#ifndef DOXYGEN
209} // namespace fe
210
211template<>
212struct std::hash<fe::Sym> {
213 size_t operator()(fe::Sym sym) const noexcept { return fe::Sym::Hash()(sym); }
214};
215
216namespace fe {
217#endif
218
219/// @name SymMap/SymSet
220/// Set/Map is keyed by pointer - which is hashed in SymPool.
221///@{
222///
223template<class V>
224using SymMap = ankerl::unordered_dense::map<Sym, V, Sym::Hash, Sym::Eq>;
225using SymSet = ankerl::unordered_dense::set<Sym, Sym::Hash, Sym::Eq>;
226///@}
227
228/// A fixed-capacity Sym%bol -> @p V map for a *closed* set of @p Size entries: filled once, then only
229/// looked up - a Lexer's reserved words, say.
230/// Prefer this over SymMap for that use: both hash and compare the same interned pointer, but SymMap
231/// pays a full finalizer and a SwissTable group probe where this pays one multiply and one probe of
232/// a table whose capacity is a compile-time constant.
233/// @note @p V has to be default-constructible; an absent key yields no @p V at all - see SymTab::find.
234/// @warning Insert-only: there is no erase, and SymTab::emplace asserts on a key already present.
235template<class V, size_t Size>
236class SymTab {
237public:
238 /// Twice @p Size, rounded up to a power of two, so the load factor stays below `1/2`.
239 static constexpr size_t Capacity = std::bit_ceil(2 * Size);
240
241 /// @name Access
242 ///@{
243 void emplace(Sym sym, V v) {
244 assert(!sym.empty() && "the empty Sym%bol marks a free slot");
245 for (auto i = idx(sym);; i = (i + 1) & Mask) {
246 assert(slots_[i].sym != sym && "already present");
247 if (slots_[i].sym.empty()) {
248 slots_[i] = {sym, std::move(v)};
249 return;
250 }
251 }
252 }
253
254 /// Yields nothing if @p sym is not present - the empty Sym%bol never is.
255 /// @note The free-slot test comes first: the empty Sym%bol *is* a free slot's key.
256 std::optional<V> find(Sym sym) const {
257 for (auto i = idx(sym);; i = (i + 1) & Mask) {
258 if (slots_[i].sym.empty()) return {};
259 if (slots_[i].sym == sym) return slots_[i].v;
260 }
261 }
262
263 bool contains(Sym sym) const { return (bool)find(sym); }
264 ///@}
265
266private:
267 static constexpr size_t Mask = Capacity - 1;
268 static constexpr size_t Shift = 64 - std::bit_width(Mask);
269 static constexpr uint64_t Magic = 0x9E3779B97F4A7C15ull; ///< `2^64/phi` - Fibonacci hashing.
270
271 /// Takes the *high* bits of the product: a long Sym%bol is an 8-byte aligned pointer and a short
272 /// one's low byte is a size of `1 .. Sym::Short_String_Bytes-1`, so the low bits cluster.
273 static size_t idx(Sym sym) { return size_t((uint64_t(sym.raw()) * Magic) >> Shift); }
274
275 struct Slot {
276 Sym sym;
277 V v = {};
278 };
279
280 std::array<Slot, Capacity> slots_ = {};
281};
282
283/// Hash set where all strings - wrapped in Sym%bol - live in.
284/// You can access the SymPool from Driver.
285class SymPool {
286public:
288
289 /// @name Constructor & Destruction
290 ///@{
291 SymPool(const SymPool&) = delete;
292 SymPool() noexcept {}
293 SymPool(SymPool&& other) noexcept
294 : SymPool() {
295 swap(*this, other);
296 }
298 ///@}
299
300 /// @name sym
301 ///@{
302 Sym sym(std::string_view s);
303 Sym sym(const std::string& s) { return sym((std::string_view)s); }
304 /// @p s is a null-terminated C-string.
305 Sym sym(const char* s) { return s == nullptr ? Sym() : sym(std::string_view(s)); }
306 // TODO we can try to fit s in current page and hence eliminate the explicit use of strlen
307 ///@}
308
309 friend void swap(SymPool& p1, SymPool& p2) noexcept {
310 using std::swap;
311 // clang-format off
312 swap(p1.strings_, p2.strings_);
313 swap(p1.pool_, p2.pool_ );
314 // clang-format on
315 }
316
317private:
318 Arena strings_;
319 ankerl::unordered_dense::set<const String*, String::Hash, String::Equal> pool_;
320};
321
322static_assert(std::is_trivially_copyable_v<Sym>);
323static_assert(sizeof(uintptr_t) == sizeof(void*), "uintptr_t must match pointer size");
324static_assert(std::has_unique_object_representations_v<uintptr_t>);
325static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big,
326 "mixed endianness not supported");
327
328} // namespace fe
An arena pre-allocates so-called pages of size Arena::page_size_.
Definition arena.h:25
Sym sym(const char *s)
s is a null-terminated C-string.
Definition sym.h:305
Sym::String String
Definition sym.h:287
Sym sym(std::string_view s)
SymPool & operator=(SymPool)=delete
SymPool(const SymPool &)=delete
Sym sym(const std::string &s)
Definition sym.h:303
SymPool(SymPool &&other) noexcept
Definition sym.h:293
SymPool() noexcept
Definition sym.h:292
friend void swap(SymPool &p1, SymPool &p2) noexcept
Definition sym.h:309
A fixed-capacity Symbol -> V map for a closed set of Size entries: filled once, then only looked up -...
Definition sym.h:236
static constexpr size_t Capacity
Twice Size, rounded up to a power of two, so the load factor stays below 1/2.
Definition sym.h:239
void emplace(Sym sym, V v)
Definition sym.h:243
bool contains(Sym sym) const
Definition sym.h:263
std::optional< V > find(Sym sym) const
Yields nothing if sym is not present - the empty Symbol never is.
Definition sym.h:256
A Symbol just wraps a pointer to Sym::String, so pass Sym itself around as value.
Definition sym.h:30
constexpr uintptr_t raw() const noexcept
Definition sym.h:88
friend constexpr std::strong_ordering operator<=>(char c, Sym s) noexcept
Definition sym.h:122
friend constexpr bool operator==(Sym lhs, const std::convertible_to< std::string_view > auto &rhs) noexcept
Definition sym.h:136
friend constexpr auto operator<=>(Sym s1, Sym s2) noexcept
Definition sym.h:115
constexpr auto rend() const noexcept
Definition sym.h:108
constexpr auto begin() const noexcept
Definition sym.h:103
constexpr char front() const noexcept
Definition sym.h:97
constexpr std::string_view operator*() const noexcept
Definition sym.h:160
constexpr bool empty() const noexcept
Definition sym.h:82
static constexpr size_t Short_String_Mask
Definition sym.h:33
static constexpr size_t Short_String_Bytes
Definition sym.h:32
constexpr auto cend() const noexcept
Definition sym.h:106
friend constexpr bool operator==(char c, Sym s) noexcept
Definition sym.h:124
constexpr size_t size() const noexcept
Definition sym.h:83
constexpr Sym() noexcept=default
constexpr char back() const noexcept
Definition sym.h:98
friend constexpr auto operator<=>(const std::convertible_to< std::string_view > auto &lhs, Sym rhs) noexcept
Definition sym.h:132
friend constexpr bool operator==(Sym s1, Sym s2) noexcept
Definition sym.h:116
friend class SymPool
Definition sym.h:205
constexpr auto crbegin() const noexcept
Definition sym.h:109
constexpr char operator[](size_t i) const noexcept
Definition sym.h:93
friend constexpr bool operator==(Sym s, char c) noexcept
Definition sym.h:123
constexpr auto crend() const noexcept
Definition sym.h:110
friend std::ostream & operator<<(std::ostream &os, Sym sym)
constexpr auto rbegin() const noexcept
Definition sym.h:107
friend constexpr bool operator==(const std::convertible_to< std::string_view > auto &lhs, Sym rhs) noexcept
Definition sym.h:140
constexpr std::string str() const
This involves a copy.
Definition sym.h:164
constexpr auto cbegin() const noexcept
Definition sym.h:105
friend constexpr auto operator<=>(Sym lhs, const std::convertible_to< std::string_view > auto &rhs) noexcept
Definition sym.h:129
constexpr auto end() const noexcept
Definition sym.h:104
constexpr std::string_view view() const noexcept
Definition sym.h:150
friend constexpr std::strong_ordering operator<=>(Sym s, char c) noexcept
Definition sym.h:121
Definition algo.h:17
ankerl::unordered_dense::set< Sym, Sym::Hash, Sym::Eq > SymSet
Definition sym.h:225
ankerl::unordered_dense::map< Sym, V, Sym::Hash, Sym::Eq > SymMap
Definition sym.h:224
Hashes the characters of a string; transparent, so std::string keys may be looked up by std::string_v...
Definition hash.h:46
constexpr bool operator()(Sym a, Sym b) const noexcept
Definition sym.h:184
size_t operator()(Sym s) const noexcept
Definition sym.h:180
void is_avalanching
Definition sym.h:178
constexpr bool operator()(const String *s1, const String *s2) const noexcept
Definition sym.h:58
Hashes the characters, not the pointer - String::Equal compares them, and the two have to agree.
Definition sym.h:64
void is_avalanching
Definition sym.h:65
size_t operator()(const String *s) const noexcept
Definition sym.h:67
constexpr String() noexcept=default
char chars[]
Definition sym.h:49
size_t size
Definition sym.h:40