Skip to main content

lolli_codegen/
codegen.rs

1//! Rust code generation from linear lambda terms.
2//!
3//! This module translates extracted terms into Rust code.
4
5use lolli_core::{Formula, Term, TwoSidedSequent};
6use crate::types::TypeGenerator;
7
8/// Rust code generator.
9///
10/// Translates linear lambda terms into Rust code, preserving
11/// linear ownership semantics through Rust's move semantics.
12pub struct RustCodegen {
13    /// Current indentation level
14    indent: usize,
15    /// Type generator
16    types: TypeGenerator,
17    /// Variable counter for fresh names
18    var_counter: usize,
19}
20
21impl Default for RustCodegen {
22    fn default() -> Self {
23        Self::new()
24    }
25}
26
27impl RustCodegen {
28    /// Create a new code generator.
29    pub fn new() -> Self {
30        Self {
31            indent: 0,
32            types: TypeGenerator::new(),
33            var_counter: 0,
34        }
35    }
36
37    /// Generate a fresh variable name.
38    pub fn fresh_var(&mut self) -> String {
39        let v = format!("_v{}", self.var_counter);
40        self.var_counter += 1;
41        v
42    }
43
44    /// Get current indentation string.
45    fn indent_str(&self) -> String {
46        "    ".repeat(self.indent)
47    }
48
49    /// Generate a Rust type from a formula.
50    pub fn formula_to_type(&self, formula: &Formula) -> String {
51        self.types.generate(formula)
52    }
53
54    /// Generate Rust code from a term.
55    pub fn term_to_code(&mut self, term: &Term) -> String {
56        match term {
57            Term::Var(v) => v.clone(),
58
59            Term::Unit => "()".to_string(),
60
61            Term::Trivial => "Top".to_string(),
62
63            Term::Pair(a, b) => {
64                format!("({}, {})", self.term_to_code(a), self.term_to_code(b))
65            }
66
67            Term::LetPair(x, y, pair, body) => {
68                let pair_code = self.term_to_code(pair);
69                let body_code = self.term_to_code(body);
70                format!("{{ let ({}, {}) = {}; {} }}", x, y, pair_code, body_code)
71            }
72
73            Term::Abs(x, body) => {
74                let body_code = self.term_to_code(body);
75                format!("|{}| {}", x, body_code)
76            }
77
78            Term::App(f, a) => {
79                let f_code = self.term_to_code(f);
80                let a_code = self.term_to_code(a);
81                // Handle the case where f is a closure
82                if matches!(f.as_ref(), Term::Abs(_, _)) {
83                    format!("({})({})", f_code, a_code)
84                } else {
85                    format!("{}({})", f_code, a_code)
86                }
87            }
88
89            Term::Inl(a) => {
90                format!("Either::Left({})", self.term_to_code(a))
91            }
92
93            Term::Inr(b) => {
94                format!("Either::Right({})", self.term_to_code(b))
95            }
96
97            Term::Case(scrut, x, left, y, right) => {
98                let scrut_code = self.term_to_code(scrut);
99                let left_code = self.term_to_code(left);
100                let right_code = self.term_to_code(right);
101                format!(
102                    "match {} {{ Either::Left({}) => {}, Either::Right({}) => {} }}",
103                    scrut_code, x, left_code, y, right_code
104                )
105            }
106
107            Term::Fst(p) => {
108                let p_code = self.term_to_code(p);
109                format!("{}.0", p_code)
110            }
111
112            Term::Snd(p) => {
113                let p_code = self.term_to_code(p);
114                format!("{}.1", p_code)
115            }
116
117            Term::Abort(e) => {
118                let e_code = self.term_to_code(e);
119                format!("match {} {{}}", e_code)
120            }
121
122            Term::Promote(a) => {
123                format!("Rc::new({})", self.term_to_code(a))
124            }
125
126            Term::Derelict(e) => {
127                let e_code = self.term_to_code(e);
128                format!("Rc::try_unwrap({}).unwrap_or_else(|rc| (*rc).clone())", e_code)
129            }
130
131            Term::Discard(_, body) => {
132                // In Rust, dropping is implicit
133                // We could add drop(_discarded) but it's not necessary
134                self.term_to_code(body)
135            }
136
137            Term::Copy(src, x, y, body) => {
138                let src_code = self.term_to_code(src);
139                let body_code = self.term_to_code(body);
140                format!(
141                    "{{ let {} = Rc::clone(&{}); let {} = {}; {} }}",
142                    x, src_code, y, src_code, body_code
143                )
144            }
145        }
146    }
147
148    /// Generate a complete function from a sequent and term.
149    pub fn generate_function(&mut self, name: &str, sequent: &TwoSidedSequent, term: &Term) -> String {
150        let mut lines = Vec::new();
151
152        // Generate function signature
153        let mut args = Vec::new();
154        for (i, formula) in sequent.antecedent.iter().enumerate() {
155            let arg_name = format!("arg{}", i);
156            let arg_type = self.types.generate(formula);
157            args.push(format!("{}: {}", arg_name, arg_type));
158        }
159
160        let return_type = self.types.generate_return(&sequent.succedent);
161
162        lines.push(format!(
163            "fn {}({}) -> {} {{",
164            name,
165            args.join(", "),
166            return_type
167        ));
168
169        // Generate function body
170        self.indent += 1;
171        let body = self.term_to_code(term);
172        lines.push(format!("{}{}", self.indent_str(), body));
173        self.indent -= 1;
174
175        lines.push("}".to_string());
176
177        lines.join("\n")
178    }
179
180    /// Generate a complete module with necessary imports and type definitions.
181    pub fn generate_module(&mut self, name: &str, sequent: &TwoSidedSequent, term: &Term) -> String {
182        let mut lines = Vec::new();
183
184        // Module documentation
185        lines.push(format!("//! Generated from sequent: {}", sequent.pretty()));
186        lines.push("//!".to_string());
187        lines.push("//! This code was generated by lolli-codegen from a linear logic proof.".to_string());
188        lines.push("".to_string());
189
190        // Imports
191        lines.push("use std::rc::Rc;".to_string());
192        lines.push("".to_string());
193
194        // Include prelude types
195        lines.push(crate::PRELUDE.to_string());
196        lines.push("".to_string());
197
198        // Generate the main function
199        lines.push(self.generate_function(name, sequent, term));
200
201        lines.join("\n")
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn test_var() {
211        let mut codegen = RustCodegen::new();
212        let term = Term::Var("x".to_string());
213        assert_eq!(codegen.term_to_code(&term), "x");
214    }
215
216    #[test]
217    fn test_unit() {
218        let mut codegen = RustCodegen::new();
219        assert_eq!(codegen.term_to_code(&Term::Unit), "()");
220    }
221
222    #[test]
223    fn test_pair() {
224        let mut codegen = RustCodegen::new();
225        let term = Term::Pair(
226            Box::new(Term::Var("x".to_string())),
227            Box::new(Term::Var("y".to_string())),
228        );
229        assert_eq!(codegen.term_to_code(&term), "(x, y)");
230    }
231
232    #[test]
233    fn test_let_pair() {
234        let mut codegen = RustCodegen::new();
235        let term = Term::LetPair(
236            "a".to_string(),
237            "b".to_string(),
238            Box::new(Term::Var("p".to_string())),
239            Box::new(Term::Var("a".to_string())),
240        );
241        assert_eq!(codegen.term_to_code(&term), "{ let (a, b) = p; a }");
242    }
243
244    #[test]
245    fn test_abs() {
246        let mut codegen = RustCodegen::new();
247        let term = Term::Abs(
248            "x".to_string(),
249            Box::new(Term::Var("x".to_string())),
250        );
251        assert_eq!(codegen.term_to_code(&term), "|x| x");
252    }
253
254    #[test]
255    fn test_app() {
256        let mut codegen = RustCodegen::new();
257        let term = Term::App(
258            Box::new(Term::Var("f".to_string())),
259            Box::new(Term::Var("x".to_string())),
260        );
261        assert_eq!(codegen.term_to_code(&term), "f(x)");
262    }
263
264    #[test]
265    fn test_inl_inr() {
266        let mut codegen = RustCodegen::new();
267
268        let inl = Term::Inl(Box::new(Term::Var("x".to_string())));
269        assert_eq!(codegen.term_to_code(&inl), "Either::Left(x)");
270
271        let inr = Term::Inr(Box::new(Term::Var("y".to_string())));
272        assert_eq!(codegen.term_to_code(&inr), "Either::Right(y)");
273    }
274
275    #[test]
276    fn test_case() {
277        let mut codegen = RustCodegen::new();
278        let term = Term::Case(
279            Box::new(Term::Var("e".to_string())),
280            "x".to_string(),
281            Box::new(Term::Var("x".to_string())),
282            "y".to_string(),
283            Box::new(Term::Var("y".to_string())),
284        );
285        assert_eq!(
286            codegen.term_to_code(&term),
287            "match e { Either::Left(x) => x, Either::Right(y) => y }"
288        );
289    }
290
291    #[test]
292    fn test_fst_snd() {
293        let mut codegen = RustCodegen::new();
294
295        let fst = Term::Fst(Box::new(Term::Var("p".to_string())));
296        assert_eq!(codegen.term_to_code(&fst), "p.0");
297
298        let snd = Term::Snd(Box::new(Term::Var("p".to_string())));
299        assert_eq!(codegen.term_to_code(&snd), "p.1");
300    }
301
302    #[test]
303    fn test_promote() {
304        let mut codegen = RustCodegen::new();
305        let term = Term::Promote(Box::new(Term::Var("x".to_string())));
306        assert_eq!(codegen.term_to_code(&term), "Rc::new(x)");
307    }
308
309    #[test]
310    fn test_copy() {
311        let mut codegen = RustCodegen::new();
312        let term = Term::Copy(
313            Box::new(Term::Var("r".to_string())),
314            "x".to_string(),
315            "y".to_string(),
316            Box::new(Term::Pair(
317                Box::new(Term::Var("x".to_string())),
318                Box::new(Term::Var("y".to_string())),
319            )),
320        );
321        let code = codegen.term_to_code(&term);
322        assert!(code.contains("Rc::clone"));
323    }
324
325    #[test]
326    fn test_generate_function() {
327        let mut codegen = RustCodegen::new();
328        let sequent = TwoSidedSequent::new(
329            vec![Formula::atom("A"), Formula::atom("B")],
330            vec![Formula::tensor(Formula::atom("A"), Formula::atom("B"))],
331        );
332        let term = Term::Pair(
333            Box::new(Term::Var("arg0".to_string())),
334            Box::new(Term::Var("arg1".to_string())),
335        );
336
337        let code = codegen.generate_function("make_pair", &sequent, &term);
338        assert!(code.contains("fn make_pair(arg0: A, arg1: B) -> (A, B)"));
339        assert!(code.contains("(arg0, arg1)"));
340    }
341}