symbolmap_trait/
lib.rs

1/*!
2A trait for generic implementation of symbol tables. Used by the [`hayami`](https://gitlab.com/rain-lang/hayami) family
3of symbol table crates, which were developed for use in the [`rain` programming language](https://gitlab.com/rain-lang).
4*/
5#![deny(missing_docs, unsafe_code, missing_debug_implementations)]
6use std::borrow::Borrow;
7use std::hash::Hash;
8
9#[cfg(feature = "testing")]
10pub mod testing;
11
12/**
13A trait for a symbol table which can be indexed by a given key.
14
15Behaves like a stack of `HashMap`s.
16*/
17pub trait SymbolMap<K> {
18    /// The value stored in this symbol table
19    type Value;
20    /// Insert a key/value pair into this symbol table at the current level
21    fn insert(&mut self, key: K, value: Self::Value);
22    /// Get the most recent definition of a key in this symbol table
23    fn get<Q>(&self, key: &Q) -> Option<&Self::Value>
24    where
25        Q: ?Sized + Hash + Eq,
26        K: Borrow<Q>;
27    /// Whether this symbol table contains this key
28    #[inline]
29    fn contains_key<Q>(&self, key: &Q) -> bool
30    where
31        Q: ?Sized + Hash + Eq,
32        K: Borrow<Q>,
33    {
34        self.get(key).is_some()
35    }
36    /// Whether this symbol table is empty
37    fn is_empty(&self) -> bool;
38    /// Try to get a mutable reference to the definition of a key in the top level of this symbol table
39    ///
40    /// May fail for arbitrary reasons, to avoid, e.g., re-inserting the key at the top level as mutable.
41    fn try_get_mut<Q>(&mut self, key: &Q) -> Option<&mut Self::Value>
42    where
43        Q: ?Sized + Hash + Eq,
44        K: Borrow<Q>;
45    /// Push a level onto this symbol table
46    fn push(&mut self);
47    /// Pop a level from this symbol table
48    ///
49    /// Note that this is *not* guaranteed to drop all elements stored in the level!
50    fn pop(&mut self);
51    /// Get the current depth of this symbol table
52    fn depth(&self) -> usize;
53}
54
55/**
56A trait for a symbol table which in which entries may be infallibly mutated.
57*/
58pub trait MutSymbolMap<K>: SymbolMap<K> {
59    /// Get a mutable reference to the definition of a key in the top level of this symbol table
60    #[inline(always)]
61    fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut Self::Value>
62    where
63        Q: ?Sized + Hash + Eq,
64        K: Borrow<Q>,
65    {
66        self.try_get_mut(key)
67    }
68}
69
70/**
71A trait for a stack-like symbol table in which a reference to the previous layer may be obtained
72*/
73pub trait SymbolStack<K>: SymbolMap<K> {
74    /// Get the previous layer of this symbol table
75    fn prev(&self) -> Option<&Self>;
76}