1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Types for "symbols", an optimized string-like type that ensures only one
//! underlying copy of each unique string exists.

use std::fmt::{Debug, Display};
use std::ops::{Add, Deref};
use std::sync::OnceLock;
use std::{array, iter};

use refuse::{CollectionGuard, Trace};
use refuse_pool::{RefString, RootString};
use serde::de::Visitor;
use serde::{Deserialize, Serialize};

use crate::runtime::value::ValueFreed;

/// A garbage-collected weak reference to a [`Symbol`].
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Trace)]
pub struct SymbolRef(RefString);

impl SymbolRef {
    /// Loads the underlying string value of this symbol.
    ///
    /// Returns `None` if the underlying symbol has been freed by the garbage
    /// collector.
    #[must_use]
    pub fn load<'guard>(&self, guard: &'guard CollectionGuard<'_>) -> Option<&'guard str> {
        self.0.load(guard)
    }

    /// Tries to loads the underlying string value of this symbol.
    ///
    /// # Errors
    ///
    /// Returns [`ValueFreed`] if the underlying symbol has been freed by the
    /// garbage collector.
    pub fn try_load<'guard>(
        &self,
        guard: &'guard CollectionGuard<'_>,
    ) -> Result<&'guard str, ValueFreed> {
        self.load(guard).ok_or(ValueFreed)
    }

    /// Upgrades this weak reference to a reference-counted [`Symbol`].
    ///
    ///
    /// Returns `None` if the underlying symbol has been freed by the garbage
    /// collector.
    #[must_use]
    pub fn upgrade(&self, guard: &CollectionGuard<'_>) -> Option<Symbol> {
        self.0.as_root(guard).map(Symbol)
    }

    /// Tries to upgrade this weak reference to a reference-counted [`Symbol`].
    ///
    /// # Errors
    ///
    /// Returns [`ValueFreed`] if the underlying symbol has been freed by the
    /// garbage collector.
    pub fn try_upgrade(&self, guard: &CollectionGuard<'_>) -> Result<Symbol, ValueFreed> {
        self.upgrade(guard).ok_or(ValueFreed)
    }
}

impl kempt::Sort<SymbolRef> for Symbol {
    fn compare(&self, other: &SymbolRef) -> std::cmp::Ordering {
        self.0.downgrade_any().cmp(&other.0.as_any())
    }
}

/// A reference-counted, cheap-to-compare String type.
///
/// Symbols are optimized to be able to cheaply compare and hash without needing
/// to analyze the underlying string contents. This is done by ensuring that all
/// instances of the same underlying string data point to the same [`Symbol`].
#[derive(Clone, Trace)]
pub struct Symbol(RootString);

impl Symbol {
    /// Returns a weak reference to this symbol.
    #[must_use]
    pub const fn downgrade(&self) -> SymbolRef {
        SymbolRef(self.0.downgrade())
    }
}

impl Eq for Symbol {}

impl PartialEq for Symbol {
    fn eq(&self, other: &Self) -> bool {
        self.0.downgrade() == other.0.downgrade()
    }
}

impl Ord for Symbol {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.downgrade().cmp(&other.0.downgrade())
    }
}

impl PartialOrd for Symbol {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl std::hash::Hash for Symbol {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.downgrade().hash(state);
    }
}

macro_rules! static_symbols {
    ($($name:ident => $string:literal),+ $(,)?) => {
        impl Symbol {
            $(
                #[doc = concat!("Returns the symbol for \"", $string, "\".")]
                pub fn $name() -> &'static Self {
                static S: OnceLock<Symbol> = OnceLock::new();
                S.get_or_init(|| Symbol::from($string))
            })+
        }
    };
}

static_symbols!(
    empty => "",
    and_symbol => "and",
    break_symbol => "break",
    catch_symbol => "catch",
    continue_symbol => "continue",
    else_symbol => "else",
    enum_symbol => "enum",
    false_symbol => "false",
    for_symbol => "for",
    fn_symbol => "fn",
    get_symbol => "get",
    if_symbol => "if",
    impl_symbol => "impl",
    in_symbol => "in",
    it_symbol => "it",
    iterate_symbol => "iterate",
    len_symbol => "len",
    let_symbol => "let",
    loop_symbol => "loop",
    match_symbol => "match",
    captures_symbol => "captures",
    mod_symbol => "mod",
    next_symbol => "next",
    new_symbol => "new",
    nil_symbol => "nil",
    not_symbol => "not",
    nth_symbol => "nth",
    or_symbol => "or",
    pub_symbol => "pub",
    return_symbol => "return",
    self_symbol => "self",
    set_symbol => "set",
    sigil_symbol => "$",
    struct_symbol => "struct",
    super_symbol => "super",
    then_symbol => "then",
    throw_symbol => "throw",
    true_symbol => "true",
    try_symbol => "try",
    var_symbol => "var",
    while_symbol => "while",
    xor_symbol => "xor",
);

macro_rules! impl_froms {
    ($type:ty, $inner:ty) => {
        impl From<String> for $type {
            fn from(value: String) -> Self {
                Self(<$inner>::from(value))
            }
        }
        impl From<&'_ $type> for $type {
            fn from(value: &'_ $type) -> Self {
                value.clone()
            }
        }

        impl From<&'_ String> for $type {
            fn from(value: &'_ String) -> Self {
                Self(<$inner>::from(value))
            }
        }

        impl From<&'_ str> for $type {
            fn from(value: &'_ str) -> Self {
                Self(<$inner>::from(value))
            }
        }
    };
}

impl_froms!(Symbol, RootString);
impl_froms!(SymbolRef, RefString);

impl From<&'_ Symbol> for SymbolRef {
    fn from(value: &'_ Symbol) -> Self {
        value.downgrade()
    }
}

impl From<Symbol> for SymbolRef {
    fn from(value: Symbol) -> Self {
        value.downgrade()
    }
}

/// A type that can be optionally be converted to a [`Symbol`].
pub trait IntoOptionSymbol {
    /// Returns this type as an optional symbol.
    fn into_symbol(self) -> Option<Symbol>;
}

impl<T> IntoOptionSymbol for T
where
    T: Into<Symbol>,
{
    fn into_symbol(self) -> Option<Symbol> {
        Some(self.into())
    }
}

impl IntoOptionSymbol for Option<Symbol> {
    fn into_symbol(self) -> Option<Symbol> {
        self
    }
}

impl PartialEq<&'_ str> for Symbol {
    fn eq(&self, other: &&'_ str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<str> for Symbol {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<SymbolRef> for Symbol {
    fn eq(&self, other: &SymbolRef) -> bool {
        self.0 == other.0
    }
}

impl PartialEq<Symbol> for SymbolRef {
    fn eq(&self, other: &Symbol) -> bool {
        self.0 == other.0
    }
}

impl From<bool> for Symbol {
    fn from(bool: bool) -> Self {
        if bool {
            Symbol::true_symbol().clone()
        } else {
            Symbol::false_symbol().clone()
        }
    }
}

impl From<bool> for SymbolRef {
    fn from(bool: bool) -> Self {
        if bool {
            Symbol::true_symbol().downgrade()
        } else {
            Symbol::false_symbol().downgrade()
        }
    }
}

impl Deref for Symbol {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Debug for Symbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for Symbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<'a, 'b> Add<&'a Symbol> for &'b Symbol {
    type Output = Symbol;

    fn add(self, rhs: &'a Symbol) -> Self::Output {
        Symbol::from(self + &**rhs)
    }
}

impl<'a, 'b> Add<&'a str> for &'b Symbol {
    type Output = String;

    fn add(self, rhs: &'a str) -> Self::Output {
        let mut out = String::with_capacity(self.len() + rhs.len());
        out.push_str(self);
        out.push_str(rhs);
        out
    }
}

impl<'a, 'b> Add<&'a Symbol> for &'b str {
    type Output = String;

    fn add(self, rhs: &'a Symbol) -> Self::Output {
        let mut out = String::with_capacity(self.len() + rhs.len());
        out.push_str(self);
        out.push_str(rhs);
        out
    }
}

impl<'a, 'b> Add<&'a String> for &'b Symbol {
    type Output = String;

    fn add(self, rhs: &'a String) -> Self::Output {
        self + rhs.as_str()
    }
}

impl Serialize for Symbol {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self)
    }
}

impl<'de> Deserialize<'de> for Symbol {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(SymbolVisitor)
    }
}

struct SymbolVisitor;

impl<'de> Visitor<'de> for SymbolVisitor {
    type Value = Symbol;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "an Symbol")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Symbol::from(v))
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Symbol::from(v))
    }
}

/// A [`Symbol`] that is initialized once and retains a reference to the
/// [`Symbol`].
///
/// This type is designed to be used as a `static`, allowing usages of common
/// symbols to never be garbage collected.
pub struct StaticSymbol(OnceLock<Symbol>, &'static str);

impl StaticSymbol {
    /// Returns a new static symbol from a static string.
    #[must_use]
    pub const fn new(symbol: &'static str) -> Self {
        Self(OnceLock::new(), symbol)
    }
}

impl Debug for StaticSymbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for StaticSymbol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.1, f)
    }
}

impl Deref for StaticSymbol {
    type Target = Symbol;

    fn deref(&self) -> &Self::Target {
        self.0.get_or_init(|| Symbol::from(self.1))
    }
}

impl<'a> From<&'a StaticSymbol> for SymbolRef {
    fn from(value: &'a StaticSymbol) -> Self {
        value.downgrade()
    }
}

/// A type that contains a list of symbols.
pub trait SymbolList {
    /// The iterator used for [`into_symbols`](Self::into_symbols).
    type Iterator: Iterator<Item = Symbol>;

    /// Returns `self` as an iterator over its contained symbols.
    fn into_symbols(self) -> Self::Iterator;
}

/// An iterator over an array of types that implement [`Into<Symbol>`].
pub struct ArraySymbolsIntoIter<T: Into<Symbol>, const N: usize>(array::IntoIter<T, N>);

impl<T: Into<Symbol>, const N: usize> Iterator for ArraySymbolsIntoIter<T, N> {
    type Item = Symbol;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(T::into)
    }
}

impl<T: Into<Symbol>, const N: usize> SymbolList for [T; N] {
    type Iterator = ArraySymbolsIntoIter<T, N>;

    fn into_symbols(self) -> Self::Iterator {
        ArraySymbolsIntoIter(self.into_iter())
    }
}

impl SymbolList for Symbol {
    type Iterator = iter::Once<Symbol>;

    fn into_symbols(self) -> Self::Iterator {
        iter::once(self)
    }
}

impl SymbolList for &'_ Symbol {
    type Iterator = iter::Once<Symbol>;

    fn into_symbols(self) -> Self::Iterator {
        self.clone().into_symbols()
    }
}

impl SymbolList for &'_ str {
    type Iterator = iter::Once<Symbol>;

    fn into_symbols(self) -> Self::Iterator {
        Symbol::from(self).into_symbols()
    }
}