-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathfresh.rs
52 lines (42 loc) · 1.42 KB
/
fresh.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
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::AtomicUsize;
use crate::Str;
#[derive(Debug, Default)]
pub struct FreshNameGenerator {
id: AtomicUsize,
/// To avoid conflicts with variable names generated in another phase
prefix: &'static str,
}
impl FreshNameGenerator {
pub const fn new(prefix: &'static str) -> Self {
Self {
id: AtomicUsize::new(0),
prefix,
}
}
pub fn fresh_varname(&self) -> Str {
self.id.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let i = self.id.load(std::sync::atomic::Ordering::SeqCst);
Str::from(format!("%v_{}_{i}", self.prefix))
}
pub fn fresh_param_name(&self) -> Str {
self.id.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let i = self.id.load(std::sync::atomic::Ordering::SeqCst);
Str::from(format!("%p_{}_{i}", self.prefix))
}
}
pub static FRESH_GEN: FreshNameGenerator = FreshNameGenerator::new("global");
#[derive(Debug, Clone, Default)]
pub struct SharedFreshNameGenerator(Rc<RefCell<FreshNameGenerator>>);
impl SharedFreshNameGenerator {
pub fn new(prefix: &'static str) -> Self {
Self(Rc::new(RefCell::new(FreshNameGenerator::new(prefix))))
}
pub fn fresh_varname(&self) -> Str {
self.0.borrow_mut().fresh_varname()
}
pub fn fresh_param_name(&self) -> Str {
self.0.borrow_mut().fresh_param_name()
}
}