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
|
use crate::chomp::ast::Variable;
use super::Type;
#[derive(Debug, Default)]
pub struct Context {
vars: Vec<Type>,
unguard_points: Vec<usize>,
}
impl Context {
pub fn new() -> Self {
Self::default()
}
pub fn depth(&self) -> usize {
self.vars.len()
}
pub fn with_unguard<F: FnOnce(&mut Self) -> R, R>(&mut self, f: F) -> R {
self.unguard_points.push(self.vars.len());
let res = f(self);
self.unguard_points.pop();
res
}
pub fn get_variable_type(&self, var: Variable) -> Result<&Type, GetVariableError> {
self.vars
.iter()
.nth_back(var.index)
.ok_or(GetVariableError::FreeVariable)
.and_then(|ty| {
if self.unguard_points.last().unwrap_or(&0) + var.index >= self.vars.len() {
Ok(ty)
} else {
Err(GetVariableError::GuardedVariable)
}
})
}
pub fn with_variable_type<F: FnOnce(&mut Self) -> R, R>(&mut self, ty: Type, f: F) -> R {
self.vars.push(ty);
let res = f(self);
self.vars.pop();
res
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GetVariableError {
FreeVariable,
GuardedVariable,
}
|