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
|
use crate::semantics::core::var::AlphaVar;
use crate::syntax::{Label, V};
pub(crate) type Binder = Label;
#[derive(Debug, Clone)]
pub(crate) struct NameEnv {
names: Vec<Binder>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct VarEnv {
size: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NzVar {
/// Reverse-debruijn index: counts number of binders from the bottom of the stack.
Bound(usize),
/// Fake fresh variable generated for expression equality checking.
Fresh(usize),
}
impl NameEnv {
pub fn new() -> Self {
NameEnv { names: Vec::new() }
}
pub fn from_binders(names: impl Iterator<Item = Binder>) -> Self {
NameEnv {
names: names.collect(),
}
}
pub fn as_varenv(&self) -> VarEnv {
VarEnv {
size: self.names.len(),
}
}
pub fn insert(&self, x: &Binder) -> Self {
let mut env = self.clone();
env.insert_mut(x);
env
}
pub fn insert_mut(&mut self, x: &Binder) {
self.names.push(x.clone())
}
pub fn remove_mut(&mut self) {
self.names.pop();
}
pub fn unlabel_var(&self, var: &V<Binder>) -> Option<AlphaVar> {
let V(name, idx) = var;
let (idx, _) = self
.names
.iter()
.rev()
.enumerate()
.filter(|(_, n)| *n == name)
.nth(*idx)?;
Some(AlphaVar::new(V((), idx)))
}
pub fn label_var(&self, var: &AlphaVar) -> V<Binder> {
let name = &self.names[self.names.len() - 1 - var.idx()];
let idx = self
.names
.iter()
.rev()
.take(var.idx())
.filter(|n| *n == name)
.count();
V(name.clone(), idx)
}
}
impl VarEnv {
pub fn new() -> Self {
VarEnv { size: 0 }
}
pub fn size(&self) -> usize {
self.size
}
pub fn insert(&self) -> Self {
VarEnv {
size: self.size + 1,
}
}
pub fn lookup(&self, var: &NzVar) -> AlphaVar {
self.lookup_fallible(var).unwrap()
}
pub fn lookup_fallible(&self, var: &NzVar) -> Option<AlphaVar> {
let idx = self.size.checked_sub(var.idx() + 1)?;
Some(AlphaVar::new(V((), idx)))
}
}
impl NzVar {
pub fn new(idx: usize) -> Self {
NzVar::Bound(idx)
}
pub fn fresh() -> Self {
use std::sync::atomic::{AtomicUsize, Ordering};
// Global counter to ensure uniqueness of the generated id.
static FRESH_VAR_COUNTER: AtomicUsize = AtomicUsize::new(0);
let id = FRESH_VAR_COUNTER.fetch_add(1, Ordering::SeqCst);
NzVar::Fresh(id)
}
// Panics on a fresh variable.
pub fn idx(&self) -> usize {
match self {
NzVar::Bound(i) => *i,
NzVar::Fresh(_) => panic!(
"Trying to use a fresh variable outside of equality checking"
),
}
}
}
|