seqc/unification.rs
1//! Type unification for Seq
2//!
3//! Implements Hindley-Milner style unification with support for:
4//! - Type variables (T, U, V)
5//! - Row variables (..a, ..rest)
6//! - Concrete types (Int, Bool, String)
7
8use crate::types::{Effect, StackType, Type};
9use std::collections::HashMap;
10
11/// Substitutions for type variables
12pub type TypeSubst = HashMap<String, Type>;
13
14/// Substitutions for row variables (stack type variables)
15pub type RowSubst = HashMap<String, StackType>;
16
17/// Combined substitution environment
18#[derive(Debug, Clone, PartialEq)]
19pub struct Subst {
20 pub types: TypeSubst,
21 pub rows: RowSubst,
22}
23
24impl Subst {
25 /// Create an empty substitution
26 pub fn empty() -> Self {
27 Subst {
28 types: HashMap::new(),
29 rows: HashMap::new(),
30 }
31 }
32
33 /// Apply substitutions to a Type
34 pub fn apply_type(&self, ty: &Type) -> Type {
35 match ty {
36 Type::Var(name) => self.types.get(name).cloned().unwrap_or(ty.clone()),
37 _ => ty.clone(),
38 }
39 }
40
41 /// Apply substitutions to a StackType
42 pub fn apply_stack(&self, stack: &StackType) -> StackType {
43 match stack {
44 StackType::Empty => StackType::Empty,
45 StackType::Cons { rest, top } => {
46 let new_rest = self.apply_stack(rest);
47 let new_top = self.apply_type(top);
48 StackType::Cons {
49 rest: Box::new(new_rest),
50 top: new_top,
51 }
52 }
53 StackType::RowVar(name) => self.rows.get(name).cloned().unwrap_or(stack.clone()),
54 }
55 }
56
57 /// Compose two substitutions (apply other after self)
58 /// Result: (other ∘ self) where self is applied first, then other
59 pub fn compose(&self, other: &Subst) -> Subst {
60 let mut types = HashMap::new();
61 let mut rows = HashMap::new();
62
63 // Apply other to all of self's type substitutions
64 for (k, v) in &self.types {
65 types.insert(k.clone(), other.apply_type(v));
66 }
67
68 // Add other's type substitutions (applying self to other's values)
69 for (k, v) in &other.types {
70 let v_subst = self.apply_type(v);
71 types.insert(k.clone(), v_subst);
72 }
73
74 // Apply other to all of self's row substitutions
75 for (k, v) in &self.rows {
76 rows.insert(k.clone(), other.apply_stack(v));
77 }
78
79 // Add other's row substitutions (applying self to other's values)
80 for (k, v) in &other.rows {
81 let v_subst = self.apply_stack(v);
82 rows.insert(k.clone(), v_subst);
83 }
84
85 Subst { types, rows }
86 }
87}
88
89/// Check if a type variable occurs in a type (for occurs check)
90///
91/// Prevents infinite types like: T = List<T>
92///
93/// NOTE: Currently we only have simple types (Int, String, Bool).
94/// When parametric types are added (e.g., List<T>, Option<T>), this function
95/// must be extended to recursively check type arguments:
96///
97/// ```ignore
98/// Type::Named { name: _, args } => {
99/// args.iter().any(|arg| occurs_in_type(var, arg))
100/// }
101/// ```
102fn occurs_in_type(var: &str, ty: &Type) -> bool {
103 match ty {
104 Type::Var(name) => name == var,
105 // Concrete types contain no type variables
106 Type::Int
107 | Type::Float
108 | Type::Bool
109 | Type::String
110 | Type::Symbol
111 | Type::Channel
112 | Type::Socket
113 | Type::Union(_)
114 | Type::Variant => false,
115 Type::Quotation(effect) => {
116 // Check if var occurs in quotation's input or output stack types
117 occurs_in_stack(var, &effect.inputs) || occurs_in_stack(var, &effect.outputs)
118 }
119 Type::Closure { effect, captures } => {
120 // Check if var occurs in closure's effect or any captured types
121 occurs_in_stack(var, &effect.inputs)
122 || occurs_in_stack(var, &effect.outputs)
123 || captures.iter().any(|t| occurs_in_type(var, t))
124 }
125 }
126}
127
128/// Check if a row variable occurs in a stack type (for occurs check)
129fn occurs_in_stack(var: &str, stack: &StackType) -> bool {
130 match stack {
131 StackType::Empty => false,
132 StackType::RowVar(name) => name == var,
133 StackType::Cons { rest, top: _ } => {
134 // Row variables only occur in stack positions, not in type positions
135 // So we only need to check the rest of the stack
136 occurs_in_stack(var, rest)
137 }
138 }
139}
140
141/// Unify two stack effects: unify inputs, then outputs under the resulting
142/// substitution, and compose. Shared by the Quotation/Closure arms of
143/// `unify_types` (captures are an implementation detail, ignored here).
144fn unify_effects(e1: &Effect, e2: &Effect) -> Result<Subst, String> {
145 let s_in = unify_stacks(&e1.inputs, &e2.inputs)?;
146 let out1 = s_in.apply_stack(&e1.outputs);
147 let out2 = s_in.apply_stack(&e2.outputs);
148 let s_out = unify_stacks(&out1, &out2)?;
149 Ok(s_in.compose(&s_out))
150}
151
152/// Unify two types, returning a substitution or an error
153pub fn unify_types(t1: &Type, t2: &Type) -> Result<Subst, String> {
154 match (t1, t2) {
155 // Same concrete types unify
156 (Type::Int, Type::Int)
157 | (Type::Float, Type::Float)
158 | (Type::Bool, Type::Bool)
159 | (Type::String, Type::String)
160 | (Type::Symbol, Type::Symbol)
161 | (Type::Channel, Type::Channel)
162 | (Type::Socket, Type::Socket) => Ok(Subst::empty()),
163
164 // Union types unify if they have the same name
165 (Type::Union(name1), Type::Union(name2)) => {
166 if name1 == name2 {
167 Ok(Subst::empty())
168 } else {
169 Err(format!(
170 "Type mismatch: cannot unify Union({}) with Union({})",
171 name1, name2
172 ))
173 }
174 }
175
176 // Variant matches itself
177 (Type::Variant, Type::Variant) => Ok(Subst::empty()),
178
179 // Union <: Variant relaxation — a named union value is a variant.
180 // This lets `variant.*` builtins (typed against `Variant`) accept
181 // user values typed as `Union(name)` without losing union safety
182 // elsewhere: the rule applies only when one side is the bare
183 // `Variant` placeholder. Mirrors the Closure <: Quotation rule
184 // below; the symmetric form is a minor unsoundness in the reverse
185 // direction (a `Variant` flowing back into a `Union(name)` slot)
186 // that we accept for now.
187 //
188 // TODO: tighten to a directional rule once the typechecker tracks
189 // which side of a unification is "expected" vs "actual". Today a
190 // `Variant` (e.g. the result of `variant.append`) silently
191 // satisfies a `Union(name)` constraint without checking the tag —
192 // intended pragmatic loophole, not a permanent stance.
193 (Type::Union(_), Type::Variant) | (Type::Variant, Type::Union(_)) => Ok(Subst::empty()),
194
195 // Type variable unifies with anything (with occurs check)
196 (Type::Var(name), ty) | (ty, Type::Var(name)) => {
197 // If unifying a variable with itself, no substitution needed
198 if matches!(ty, Type::Var(ty_name) if ty_name == name) {
199 return Ok(Subst::empty());
200 }
201
202 // Occurs check: prevent infinite types
203 if occurs_in_type(name, ty) {
204 return Err(format!(
205 "Occurs check failed: cannot unify {:?} with {:?} (would create infinite type)",
206 Type::Var(name.clone()),
207 ty
208 ));
209 }
210
211 let mut subst = Subst::empty();
212 subst.types.insert(name.clone(), ty.clone());
213 Ok(subst)
214 }
215
216 // Quotation types unify if their effects unify
217 (Type::Quotation(effect1), Type::Quotation(effect2)) => unify_effects(effect1, effect2),
218
219 // Closure types unify if their effects unify. Captures are an
220 // implementation detail determined by the type checker, not part of
221 // the user-visible type.
222 (
223 Type::Closure {
224 effect: effect1, ..
225 },
226 Type::Closure {
227 effect: effect2, ..
228 },
229 ) => unify_effects(effect1, effect2),
230
231 // Closure <: Quotation (subtyping): a Closure can be used where a
232 // Quotation is expected; the runtime dispatches appropriately.
233 (Type::Quotation(quot_effect), Type::Closure { effect, .. })
234 | (Type::Closure { effect, .. }, Type::Quotation(quot_effect)) => {
235 unify_effects(quot_effect, effect)
236 }
237
238 // Different concrete types don't unify
239 _ => Err(format!("Type mismatch: cannot unify {} with {}", t1, t2)),
240 }
241}
242
243/// Unify two stack types, returning a substitution or an error
244pub fn unify_stacks(s1: &StackType, s2: &StackType) -> Result<Subst, String> {
245 match (s1, s2) {
246 // Empty stacks unify
247 (StackType::Empty, StackType::Empty) => Ok(Subst::empty()),
248
249 // Row variable unifies with any stack (with occurs check)
250 (StackType::RowVar(name), stack) | (stack, StackType::RowVar(name)) => {
251 // If unifying a row var with itself, no substitution needed
252 if matches!(stack, StackType::RowVar(stack_name) if stack_name == name) {
253 return Ok(Subst::empty());
254 }
255
256 // Occurs check: prevent infinite stack types
257 if occurs_in_stack(name, stack) {
258 return Err(format!(
259 "Occurs check failed: cannot unify {} with {} (would create infinite stack type)",
260 StackType::RowVar(name.clone()),
261 stack
262 ));
263 }
264
265 let mut subst = Subst::empty();
266 subst.rows.insert(name.clone(), stack.clone());
267 Ok(subst)
268 }
269
270 // Cons cells unify if tops and rests unify
271 (
272 StackType::Cons {
273 rest: rest1,
274 top: top1,
275 },
276 StackType::Cons {
277 rest: rest2,
278 top: top2,
279 },
280 ) => {
281 // Unify the tops
282 let s_top = unify_types(top1, top2)?;
283
284 // Apply substitution to rests and unify
285 let rest1_subst = s_top.apply_stack(rest1);
286 let rest2_subst = s_top.apply_stack(rest2);
287 let s_rest = unify_stacks(&rest1_subst, &rest2_subst)?;
288
289 // Compose substitutions
290 Ok(s_top.compose(&s_rest))
291 }
292
293 // Empty doesn't unify with Cons
294 _ => Err(format!(
295 "Stack shape mismatch: cannot unify {} with {}",
296 s1, s2
297 )),
298 }
299}
300
301#[cfg(test)]
302mod tests;