Skip to main content

lolli_codegen/
types.rs

1//! Type generation from linear logic formulas.
2//!
3//! This module translates linear logic formulas into Rust types.
4
5use lolli_core::Formula;
6
7/// Generates Rust types from linear logic formulas.
8pub struct TypeGenerator {
9    /// Use explicit lifetime annotations
10    pub use_lifetimes: bool,
11}
12
13impl Default for TypeGenerator {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl TypeGenerator {
20    /// Create a new type generator.
21    pub fn new() -> Self {
22        Self {
23            use_lifetimes: false,
24        }
25    }
26
27    /// Generate a Rust type from a formula.
28    pub fn generate(&self, formula: &Formula) -> String {
29        match formula {
30            // Atoms become type parameters or concrete types
31            Formula::Atom(name) => name.clone(),
32            Formula::NegAtom(name) => format!("{}Dual", name),
33
34            // Tensor is a tuple - both values consumed together
35            Formula::Tensor(a, b) => {
36                format!("({}, {})", self.generate(a), self.generate(b))
37            }
38
39            // Par is the dual of tensor - continuation-style
40            Formula::Par(a, b) => {
41                format!("Par<{}, {}>", self.generate(a), self.generate(b))
42            }
43
44            // Linear implication is FnOnce - exactly one use
45            Formula::Lolli(a, b) => {
46                format!("impl FnOnce({}) -> {}", self.generate(a), self.generate(b))
47            }
48
49            // With is a lazy pair - can project to either
50            Formula::With(a, b) => {
51                format!("With<{}, {}>", self.generate(a), self.generate(b))
52            }
53
54            // Plus is a sum type - Either
55            Formula::Plus(a, b) => {
56                format!("Either<{}, {}>", self.generate(a), self.generate(b))
57            }
58
59            // Bang is Rc - can be cloned/dropped
60            Formula::OfCourse(a) => {
61                format!("Rc<{}>", self.generate(a))
62            }
63
64            // Why-not is demand for a bang
65            Formula::WhyNot(a) => {
66                format!("Demand<{}>", self.generate(a))
67            }
68
69            // Multiplicative units
70            Formula::One => "()".to_string(),
71            Formula::Bottom => "!".to_string(), // Never type
72
73            // Additive units
74            Formula::Top => "Top".to_string(), // Unit for &
75            Formula::Zero => "Void".to_string(), // Empty type
76        }
77    }
78
79    /// Generate a type with explicit ownership annotation.
80    pub fn generate_owned(&self, formula: &Formula) -> String {
81        let ty = self.generate(formula);
82        // Linear types are always owned (moved)
83        ty
84    }
85
86    /// Generate a type signature for a function argument.
87    pub fn generate_arg(&self, formula: &Formula, name: &str) -> String {
88        let ty = self.generate(formula);
89        format!("{}: {}", name, ty)
90    }
91
92    /// Generate a return type.
93    pub fn generate_return(&self, formulas: &[Formula]) -> String {
94        match formulas.len() {
95            0 => "()".to_string(),
96            1 => self.generate(&formulas[0]),
97            _ => {
98                let types: Vec<String> = formulas.iter().map(|f| self.generate(f)).collect();
99                format!("({})", types.join(", "))
100            }
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn test_atoms() {
111        let gen = TypeGenerator::new();
112        assert_eq!(gen.generate(&Formula::atom("A")), "A");
113        assert_eq!(gen.generate(&Formula::neg_atom("A")), "ADual");
114    }
115
116    #[test]
117    fn test_tensor() {
118        let gen = TypeGenerator::new();
119        let tensor = Formula::tensor(Formula::atom("A"), Formula::atom("B"));
120        assert_eq!(gen.generate(&tensor), "(A, B)");
121    }
122
123    #[test]
124    fn test_lolli() {
125        let gen = TypeGenerator::new();
126        let lolli = Formula::lolli(Formula::atom("A"), Formula::atom("B"));
127        assert_eq!(gen.generate(&lolli), "impl FnOnce(A) -> B");
128    }
129
130    #[test]
131    fn test_plus() {
132        let gen = TypeGenerator::new();
133        let plus = Formula::plus(Formula::atom("A"), Formula::atom("B"));
134        assert_eq!(gen.generate(&plus), "Either<A, B>");
135    }
136
137    #[test]
138    fn test_with() {
139        let gen = TypeGenerator::new();
140        let with = Formula::with(Formula::atom("A"), Formula::atom("B"));
141        assert_eq!(gen.generate(&with), "With<A, B>");
142    }
143
144    #[test]
145    fn test_exponentials() {
146        let gen = TypeGenerator::new();
147        let bang = Formula::of_course(Formula::atom("A"));
148        assert_eq!(gen.generate(&bang), "Rc<A>");
149
150        let whynot = Formula::why_not(Formula::atom("A"));
151        assert_eq!(gen.generate(&whynot), "Demand<A>");
152    }
153
154    #[test]
155    fn test_units() {
156        let gen = TypeGenerator::new();
157        assert_eq!(gen.generate(&Formula::One), "()");
158        assert_eq!(gen.generate(&Formula::Bottom), "!");
159        assert_eq!(gen.generate(&Formula::Top), "Top");
160        assert_eq!(gen.generate(&Formula::Zero), "Void");
161    }
162
163    #[test]
164    fn test_complex() {
165        let gen = TypeGenerator::new();
166        // !A ⊗ B ⊸ C
167        let formula = Formula::lolli(
168            Formula::tensor(
169                Formula::of_course(Formula::atom("A")),
170                Formula::atom("B"),
171            ),
172            Formula::atom("C"),
173        );
174        assert_eq!(gen.generate(&formula), "impl FnOnce((Rc<A>, B)) -> C");
175    }
176
177    #[test]
178    fn test_return_type() {
179        let gen = TypeGenerator::new();
180
181        assert_eq!(gen.generate_return(&[]), "()");
182        assert_eq!(gen.generate_return(&[Formula::atom("A")]), "A");
183        assert_eq!(
184            gen.generate_return(&[Formula::atom("A"), Formula::atom("B")]),
185            "(A, B)"
186        );
187    }
188}