-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathenvironment.rs
401 lines (357 loc) · 14.2 KB
/
environment.rs
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
//! An environment for storing variables with scopes.
use std::cell::RefCell;
use std::collections::{hash_map, HashMap};
use std::hash::Hash;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::rc::Rc;
use crate::metrics::{increment, sample};
/// An environment as a linked-list of hashmaps.
///
/// Each node of the linked-list corresponds to what is called
/// "a layer", where only the current layer can be modified, the
/// previous ones are only accessible for lookup.
///
/// For the generic parameters, `K` is the type for the environment
/// keys, and `V` are their value.
///
/// The linked list is composed of the current layer and the previous layers.
/// The current layer is stored as an `Rc<Hashmap>`. It is inserted in the previous layers
/// by cloning.
/// The insertion is made by trying to get the current layer as mutable using
/// [`Rc::get_mut`]. If it can, it means it is the only owner of this layer
/// in the environment, allowing it to mutate it. If it cannot, it means that
/// the current has been cloned and inserted in the previous environment already,
/// so it can safely be reset as a new hashmap.
/// The previous layers are set in order from the most recent one to the oldest.
#[derive(Debug, PartialEq)]
pub struct Environment<K: Hash + Eq, V: PartialEq> {
current: Rc<HashMap<K, V>>,
previous: RefCell<Option<Rc<Environment<K, V>>>>,
}
impl<K: Hash + Eq, V: PartialEq> Clone for Environment<K, V> {
/// Clone has to create a new environment, while ensuring that previous
/// defined layers are accessible but not modifiable anymore.
/// For that, it checks if the current Environment has already be cloned,
/// and if it wasn't, it sets the `current` has the new head of `previous`.
/// Then a clone is an empty `current` and the clone of `self.previous`.
fn clone(&self) -> Self {
increment!("Environment::clone");
if !self.current.is_empty() && !self.was_cloned() {
sample!(
"Environment.curr_layer_size_at_clone",
self.current.len() as f64
);
self.previous.replace_with(|old| {
Some(Rc::new(Environment {
current: self.current.clone(),
previous: RefCell::new(old.clone()),
}))
});
}
Self {
current: Rc::new(HashMap::new()),
previous: self.previous.clone(),
}
}
}
impl<K: Hash + Eq, V: PartialEq> Default for Environment<K, V> {
fn default() -> Self {
Self {
current: Rc::new(HashMap::new()),
previous: RefCell::new(None),
}
}
}
impl<K: Hash + Eq, V: PartialEq> Environment<K, V> {
/// Creates a new empty Environment.
pub fn new() -> Self {
Self::default()
}
/// Inserts a key-value pair into the Environment.
pub fn insert(&mut self, key: K, value: V) {
increment!("Environment::insert");
if self.was_cloned() {
self.current = Rc::new(HashMap::new());
}
Rc::get_mut(&mut self.current).unwrap().insert(key, value);
}
/// Tries to find the value of a key in the Environment.
pub fn get(&self, key: &K) -> Option<&V> {
increment!("Environment::get");
let mut layer_count = 0;
let r = self.iter_layers().find_map(|hmap| {
sample!("Environment.hashmap_size_get", hmap.len() as f64);
layer_count += 1;
hmap.get(key)
});
sample!("Environment.get_layers_traversed", layer_count as f64);
r
}
/// Creates an iterator that visits all layers from the most recent one to the oldest.
/// The element iterator type is `Rc<HashMap<K, V>>`.
pub fn iter_layers<'slf>(&'slf self) -> EnvLayerIter<'slf, K, V> {
EnvLayerIter {
env: if !self.was_cloned() {
Some(NonNull::from(self))
} else {
// if was cloned, current is the same as first of previous (that cannot be empty
// then)
self.previous
.borrow()
.as_ref()
// SAFETY: created from Rc, so cannot be null
.map(|prev| unsafe { NonNull::new_unchecked(Rc::as_ptr(prev) as *mut _) })
},
_marker: PhantomData,
}
}
/// Creates an iterator that visits all elements from the Environment, from the oldest layer to
/// the most recent one. It uses this order, so calling `collect` on this iterator to create a
/// hashmap would have the same values as the Environment. The element iterator type is `(&'env
/// K, &'env V)`, with `'env` being the lifetime of the Environment.
pub fn iter_elems(&self) -> EnvElemIter<'_, K, V> {
let mut env: Vec<NonNull<HashMap<K, V>>> = self
.iter_layers()
// SAFETY: Rc::as_ptr never returnes null
.map(|hmap| unsafe { NonNull::new_unchecked(Rc::as_ptr(hmap) as *mut _) })
.collect();
// SAFETY: by design, env cannot be empty, and coming from an Rc, it is well aligned and initialized
let current_map = unsafe { env.pop().unwrap().as_ref() }.iter();
EnvElemIter { env, current_map }
}
/// Creates an iterator that visits all elements from the Environment, from the current layer to
/// the oldest one. If values are present multiple times, only the most recent one appears.
/// [`iter_elems`] should be preferred, since it does not need to create an intermediary
/// hashmap. The element iterator type is `(&'env K, &'env V)`, with `'env` being the lifetime
/// of the Environment.
///
/// [`iter_elems`]: Environment::iter_elems
///
pub fn iter(&self) -> EnvIter<'_, K, V> {
EnvIter {
collapsed_map: self.iter_elems().collect::<HashMap<_, _>>().into_iter(),
}
}
/// Checks if `current` has been cloned. If it has, it is present both in current and in
/// previous, making it Rc strong count bigger than 1.
fn was_cloned(&self) -> bool {
Rc::strong_count(&self.current) > 1
}
/// Checks quickly if two environments are obviously equal (when their components are
/// physically equal as pointers or obviously equal such as being both empty).
pub(crate) fn ptr_eq(this: &Self, that: &Self) -> bool {
let prev_layers_eq = match (&*this.previous.borrow(), &*that.previous.borrow()) {
(Some(ptr_this), Some(ptr_that)) => Rc::ptr_eq(ptr_this, ptr_that),
(None, None) => true,
_ => false,
};
let curr_layers_eq = (this.current.is_empty() && that.current.is_empty())
|| Rc::ptr_eq(&this.current, &that.current);
prev_layers_eq && curr_layers_eq
}
}
impl<K: Hash + Eq, V: PartialEq> FromIterator<(K, V)> for Environment<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
Self {
current: Rc::new(HashMap::from_iter(iter)),
previous: RefCell::new(None),
}
}
}
impl<K: Hash + Eq, V: PartialEq> Extend<(K, V)> for Environment<K, V> {
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
// if can mut. borrow current, then we just extend, otherwise it means
// it was cloned, and we recreate a new map from iter for current
match Rc::get_mut(&mut self.current) {
Some(current) => current.extend(iter),
None => self.current = Rc::new(HashMap::from_iter(iter)),
}
}
}
/// An iterator over the layers of `Environment`.
///
/// Created by the [`iter_layers`] method on [`Environment`].
///
/// [`iter_layers`]: Environment::iter_layers
///
pub struct EnvLayerIter<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> {
env: Option<NonNull<Environment<K, V>>>,
_marker: PhantomData<&'a Environment<K, V>>,
}
impl<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> Iterator for EnvLayerIter<'a, K, V> {
type Item = &'a Rc<HashMap<K, V>>;
fn next(&mut self) -> Option<Self::Item> {
// SAFETY: NonNull being in an option, we know it cannot be null and can be dereferenceable
self.env.map(|env| unsafe {
let res = &env.as_ref().current;
self.env = env
.as_ref()
.previous
.borrow()
.as_ref()
// SAFETY: can safely create NonNull from Rc
.map(|prev| NonNull::new_unchecked(Rc::as_ptr(prev) as *mut _));
res
})
}
}
/// An iterator over all the elements inside the `Environment`, from the oldest layer to the current
/// one.
///
/// Created by the [`Environment::iter_elems`] method.
///
pub struct EnvElemIter<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> {
env: Vec<NonNull<HashMap<K, V>>>,
current_map: std::collections::hash_map::Iter<'a, K, V>,
}
impl<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> Iterator for EnvElemIter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.current_map.next() {
Some(res) => return Some(res),
None => self.current_map = unsafe { self.env.pop()?.as_ref() }.iter(),
}
}
}
}
/// An iterator over the elements of an `Environment`, from current layer to oldest one.
/// Keys are guaranteed to appear only once, with actual value.
///
/// Created by the [`iter`] method on [`Environment`].
///
/// [`iter`]: Environment::iter
///
pub struct EnvIter<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> {
collapsed_map: hash_map::IntoIter<&'a K, &'a V>,
}
impl<'a, K: 'a + Hash + Eq, V: 'a + PartialEq> Iterator for EnvIter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.collapsed_map.next()
}
}
#[cfg(test)]
mod tests {
use super::*;
impl<K: Hash + Eq, V: PartialEq> Environment<K, V> {
pub fn depth(&self) -> usize {
1 + self.previous.borrow().as_ref().map_or(0, |p| p.depth())
}
}
#[test]
fn test_env_base() {
let mut env_base = Environment::new();
env_base.insert(1, 'a');
assert_eq!(env_base.get(&1), Some(&'a'));
assert_eq!(env_base.get(&5), None);
assert_eq!(env_base.depth(), 1);
}
#[test]
fn test_clone() {
let mut env_base = Environment::new();
env_base.insert(1, 'a');
let mut env2 = env_base.clone();
env2.insert(2, 'b');
assert_eq!(env2.get(&1), Some(&'a'));
assert_eq!(env2.get(&2), Some(&'b'));
env_base.insert(3, 'c');
assert_eq!(env2.get(&3), None);
assert_eq!(env_base.get(&3), Some(&'c'));
env_base.insert(2, 'z');
assert_eq!(env_base.get(&2), Some(&'z'));
assert_eq!(env_base.depth(), 2);
assert_eq!(env2.depth(), 2);
}
#[test]
fn test_deepness() {
let mut env_base = Environment::<u8, char>::new();
assert_eq!(env_base.depth(), 1);
let mut env2 = env_base.clone();
assert_eq!(env_base.depth(), 1);
assert_eq!(env_base.depth(), 1);
env2.insert(1, 'a');
let env3 = env2.clone();
assert_eq!(env_base.depth(), 1);
assert_eq!(env2.depth(), 2);
assert_eq!(env3.depth(), 2);
let env4 = env_base.clone();
assert_eq!(env_base.depth(), 1);
assert_eq!(env4.depth(), 1);
env_base.insert(1, 'z');
assert_eq!(env_base.depth(), 1);
assert_eq!(env2.depth(), 2);
assert_eq!(env3.depth(), 2);
assert_eq!(env4.depth(), 1);
let env5 = env_base.clone();
assert_eq!(env_base.depth(), 2);
assert_eq!(env2.depth(), 2);
assert_eq!(env3.depth(), 2);
assert_eq!(env4.depth(), 1);
assert_eq!(env5.depth(), 2);
}
#[test]
fn test_iter_layer() {
let mut env_base = Environment::<u8, char>::new();
assert_eq!(env_base.iter_layers().count(), 1);
env_base.insert(1, 'a');
assert_eq!(env_base.iter_layers().count(), 1);
assert_eq!(env_base.iter_layers().next().unwrap().get(&1), Some(&'a'));
assert_eq!(env_base.iter_layers().nth(1), None);
let _ = env_base.clone();
assert_eq!(env_base.iter_layers().count(), 1);
env_base.insert(2, 'b');
assert_eq!(env_base.iter_layers().count(), 2);
let _ = env_base.clone();
let mut iter = env_base.iter_layers();
let map1 = iter.next().unwrap();
assert_eq!(map1.get(&2), Some(&'b'));
assert_eq!(map1.get(&1), None);
let map2 = iter.next().unwrap();
assert_eq!(map2.get(&1), Some(&'a'));
assert_eq!(map2.get(&2), None);
assert!(iter.next().is_none());
}
#[test]
fn test_iter_elem() {
let env_base = Environment::<u8, char>::new();
assert!(env_base.iter_elems().next().is_none());
let mut env_base = Environment::new();
env_base.insert(1, 'a');
env_base.insert(2, 'b');
let mut iter_elems = env_base.iter_elems();
assert!(iter_elems.next().is_some());
assert!(iter_elems.next().is_some());
assert!(iter_elems.next().is_none());
assert!({
let mut vec: Vec<_> = env_base.iter_elems().collect();
vec.sort_unstable();
vec == vec![(&1, &'a'), (&2, &'b')]
});
let mut env2 = env_base.clone();
env_base.insert(1, 'z');
env2.insert(1, 'y');
assert_eq!(env_base.iter_elems().count(), 3);
assert_eq!(env2.iter_elems().count(), 3);
assert_eq!(env_base.iter_elems().nth(2), Some((&1, &'z')));
assert_eq!(env2.iter_elems().nth(2), Some((&1, &'y')));
let mut iter_elems_base = env_base.iter_elems();
let _ = iter_elems_base.next();
let mut iter_elems2 = env2.iter_elems();
let _ = iter_elems_base.next();
let _ = iter_elems2.next();
let mut env_base = Environment::new();
env_base.insert(1, 'a');
env_base.insert(2, 'b');
let _ = env_base.clone();
env_base.insert(1, 'z');
env_base.insert(3, 'c');
let hmap: HashMap<_, _> = env_base.iter_elems().collect();
assert_eq!(hmap.len(), 3);
assert_eq!(hmap[&1], &'z');
assert_eq!(hmap[&2], &'b');
assert_eq!(hmap[&3], &'c');
}
}