-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathtree_builder.rs
More file actions
43 lines (38 loc) · 1.19 KB
/
Copy pathtree_builder.rs
File metadata and controls
43 lines (38 loc) · 1.19 KB
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
use std::cell::Cell;
use std::collections::BTreeMap;
/// Tracks fresh identifier generation during a single tree-building operation.
/// All occurrences of the same `$name` within one build share the same generated value.
pub struct FreshScope {
counter: Cell<u32>,
resolved: std::cell::RefCell<BTreeMap<String, String>>,
}
impl Default for FreshScope {
fn default() -> Self {
Self::new()
}
}
impl FreshScope {
pub fn new() -> Self {
Self {
counter: Cell::new(0),
resolved: std::cell::RefCell::new(BTreeMap::new()),
}
}
pub fn resolve(&self, name: &str) -> String {
self.resolved
.borrow_mut()
.entry(name.to_string())
.or_insert_with(|| {
let id = self.counter.get();
self.counter.set(id + 1);
format!("${name}-{id}")
})
.clone()
}
/// Clear resolved names but keep the counter. Called between rule
/// applications so that `$tmp` in different rules gets different values
/// while the counter increases monotonically.
pub fn next_scope(&self) {
self.resolved.borrow_mut().clear();
}
}