Skip to main content

lolli_core/
term.rs

1//! Lambda term representation.
2//!
3//! This module provides the [`Term`] enum representing linear lambda terms
4//! extracted from proofs via the Curry-Howard correspondence.
5
6use std::collections::HashSet;
7
8/// Linear λ-terms extracted from proofs.
9///
10/// These terms correspond to the computational content of linear logic proofs
11/// via the Curry-Howard correspondence.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum Term {
14    // Variables
15    /// Variable reference
16    Var(String),
17
18    // Multiplicatives
19    /// Unit value ()
20    Unit,
21    /// Pair (a, b)
22    Pair(Box<Term>, Box<Term>),
23    /// Let pair: let (x, y) = e in e'
24    LetPair(String, String, Box<Term>, Box<Term>),
25
26    // Linear functions
27    /// Abstraction: λx. e
28    Abs(String, Box<Term>),
29    /// Application: e e'
30    App(Box<Term>, Box<Term>),
31
32    // Additives
33    /// Left injection: inl e
34    Inl(Box<Term>),
35    /// Right injection: inr e
36    Inr(Box<Term>),
37    /// Case analysis: case e of inl x => e1 | inr y => e2
38    Case(Box<Term>, String, Box<Term>, String, Box<Term>),
39    /// Trivial value (unit for &)
40    Trivial,
41    /// First projection: fst e
42    Fst(Box<Term>),
43    /// Second projection: snd e
44    Snd(Box<Term>),
45    /// Abort (for 0): absurd e
46    Abort(Box<Term>),
47
48    // Exponentials
49    /// Promote: !e (mark as copyable)
50    Promote(Box<Term>),
51    /// Derelict: use !e as regular e
52    Derelict(Box<Term>),
53    /// Discard: discard e in e'
54    Discard(Box<Term>, Box<Term>),
55    /// Copy: copy e as (x, y) in e'
56    Copy(Box<Term>, String, String, Box<Term>),
57}
58
59impl Term {
60    /// Compute the free variables of this term.
61    pub fn free_vars(&self) -> HashSet<String> {
62        match self {
63            Term::Var(v) => {
64                let mut set = HashSet::new();
65                set.insert(v.clone());
66                set
67            }
68            Term::Unit | Term::Trivial => HashSet::new(),
69            Term::Pair(a, b) | Term::App(a, b) => {
70                let mut fv = a.free_vars();
71                fv.extend(b.free_vars());
72                fv
73            }
74            Term::LetPair(x, y, pair, body) => {
75                let mut fv = pair.free_vars();
76                let mut body_fv = body.free_vars();
77                body_fv.remove(x);
78                body_fv.remove(y);
79                fv.extend(body_fv);
80                fv
81            }
82            Term::Abs(x, body) => {
83                let mut fv = body.free_vars();
84                fv.remove(x);
85                fv
86            }
87            Term::Inl(e) | Term::Inr(e) | Term::Fst(e) | Term::Snd(e) | Term::Abort(e) => {
88                e.free_vars()
89            }
90            Term::Case(scrut, x, left, y, right) => {
91                let mut fv = scrut.free_vars();
92                let mut left_fv = left.free_vars();
93                left_fv.remove(x);
94                let mut right_fv = right.free_vars();
95                right_fv.remove(y);
96                fv.extend(left_fv);
97                fv.extend(right_fv);
98                fv
99            }
100            Term::Promote(e) | Term::Derelict(e) => e.free_vars(),
101            Term::Discard(discarded, body) => {
102                let mut fv = discarded.free_vars();
103                fv.extend(body.free_vars());
104                fv
105            }
106            Term::Copy(src, x, y, body) => {
107                let mut fv = src.free_vars();
108                let mut body_fv = body.free_vars();
109                body_fv.remove(x);
110                body_fv.remove(y);
111                fv.extend(body_fv);
112                fv
113            }
114        }
115    }
116
117    /// Substitute a term for a variable.
118    pub fn substitute(&self, var: &str, replacement: &Term) -> Term {
119        match self {
120            Term::Var(v) if v == var => replacement.clone(),
121            Term::Var(v) => Term::Var(v.clone()),
122            Term::Unit => Term::Unit,
123            Term::Trivial => Term::Trivial,
124            Term::Pair(a, b) => Term::Pair(
125                Box::new(a.substitute(var, replacement)),
126                Box::new(b.substitute(var, replacement)),
127            ),
128            Term::LetPair(x, y, pair, body) => {
129                let new_pair = pair.substitute(var, replacement);
130                let new_body = if x == var || y == var {
131                    body.as_ref().clone()
132                } else {
133                    body.substitute(var, replacement)
134                };
135                Term::LetPair(x.clone(), y.clone(), Box::new(new_pair), Box::new(new_body))
136            }
137            Term::Abs(x, body) if x == var => Term::Abs(x.clone(), body.clone()),
138            Term::Abs(x, body) => {
139                Term::Abs(x.clone(), Box::new(body.substitute(var, replacement)))
140            }
141            Term::App(f, a) => Term::App(
142                Box::new(f.substitute(var, replacement)),
143                Box::new(a.substitute(var, replacement)),
144            ),
145            Term::Inl(e) => Term::Inl(Box::new(e.substitute(var, replacement))),
146            Term::Inr(e) => Term::Inr(Box::new(e.substitute(var, replacement))),
147            Term::Case(scrut, x, left, y, right) => {
148                let new_scrut = scrut.substitute(var, replacement);
149                let new_left = if x == var {
150                    left.as_ref().clone()
151                } else {
152                    left.substitute(var, replacement)
153                };
154                let new_right = if y == var {
155                    right.as_ref().clone()
156                } else {
157                    right.substitute(var, replacement)
158                };
159                Term::Case(
160                    Box::new(new_scrut),
161                    x.clone(),
162                    Box::new(new_left),
163                    y.clone(),
164                    Box::new(new_right),
165                )
166            }
167            Term::Fst(e) => Term::Fst(Box::new(e.substitute(var, replacement))),
168            Term::Snd(e) => Term::Snd(Box::new(e.substitute(var, replacement))),
169            Term::Abort(e) => Term::Abort(Box::new(e.substitute(var, replacement))),
170            Term::Promote(e) => Term::Promote(Box::new(e.substitute(var, replacement))),
171            Term::Derelict(e) => Term::Derelict(Box::new(e.substitute(var, replacement))),
172            Term::Discard(discarded, body) => Term::Discard(
173                Box::new(discarded.substitute(var, replacement)),
174                Box::new(body.substitute(var, replacement)),
175            ),
176            Term::Copy(src, x, y, body) => {
177                let new_src = src.substitute(var, replacement);
178                let new_body = if x == var || y == var {
179                    body.as_ref().clone()
180                } else {
181                    body.substitute(var, replacement)
182                };
183                Term::Copy(Box::new(new_src), x.clone(), y.clone(), Box::new(new_body))
184            }
185        }
186    }
187
188    /// Pretty print the term.
189    pub fn pretty(&self) -> String {
190        match self {
191            Term::Var(v) => v.clone(),
192            Term::Unit => "()".to_string(),
193            Term::Trivial => "⟨⟩".to_string(),
194            Term::Pair(a, b) => format!("({}, {})", a.pretty(), b.pretty()),
195            Term::LetPair(x, y, pair, body) => {
196                format!("let ({}, {}) = {} in {}", x, y, pair.pretty(), body.pretty())
197            }
198            Term::Abs(x, body) => format!("λ{}. {}", x, body.pretty()),
199            Term::App(f, a) => format!("({} {})", f.pretty(), a.pretty()),
200            Term::Inl(e) => format!("inl {}", e.pretty()),
201            Term::Inr(e) => format!("inr {}", e.pretty()),
202            Term::Case(scrut, x, left, y, right) => {
203                format!(
204                    "case {} of {{ inl {} => {} | inr {} => {} }}",
205                    scrut.pretty(),
206                    x,
207                    left.pretty(),
208                    y,
209                    right.pretty()
210                )
211            }
212            Term::Fst(e) => format!("fst {}", e.pretty()),
213            Term::Snd(e) => format!("snd {}", e.pretty()),
214            Term::Abort(e) => format!("absurd {}", e.pretty()),
215            Term::Promote(e) => format!("!{}", e.pretty()),
216            Term::Derelict(e) => format!("derelict {}", e.pretty()),
217            Term::Discard(_, body) => format!("discard in {}", body.pretty()),
218            Term::Copy(src, x, y, body) => {
219                format!("copy {} as ({}, {}) in {}", src.pretty(), x, y, body.pretty())
220            }
221        }
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn test_free_vars() {
231        let t = Term::Abs(
232            "x".to_string(),
233            Box::new(Term::App(
234                Box::new(Term::Var("x".to_string())),
235                Box::new(Term::Var("y".to_string())),
236            )),
237        );
238        let fv = t.free_vars();
239        assert!(!fv.contains("x"));
240        assert!(fv.contains("y"));
241    }
242
243    #[test]
244    fn test_substitute() {
245        let t = Term::Var("x".to_string());
246        let result = t.substitute("x", &Term::Unit);
247        assert_eq!(result, Term::Unit);
248    }
249}