| @@ -14,7 +14,7 @@ use tilc_span::{FileId, Span, TextRange}; |
| 14 | 14 | |
| 15 | 15 | use crate::codes; |
| 16 | 16 | use crate::env::{Env, VarMode, VarScope, WellKnown}; |
| 17 | | −use crate::ty::{Constraint, InferCtx, Printer, Ty, UnifyError}; |
| 17 | +use crate::ty::{Constraint, InferCtx, Printer, Ty, UnifyError, effect_head}; |
| 18 | 18 | |
| 19 | 19 | /// A constraint to solve after the body is inferred. |
| 20 | 20 | #[derive(Clone, Debug)] |
| @@ -26,6 +26,36 @@ pub struct Wanted { |
| 26 | 26 | pub site: Option<ExprId>, |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | +/// A capability argument of a function name used as a value (ADR 0010). |
| 30 | +#[derive(Clone, Debug, PartialEq)] |
| 31 | +pub enum CapArg { |
| 32 | + /// Captured where the value is made: this instance. |
| 33 | + Inst(Ty), |
| 34 | + /// The wrapper's `k`-th capability parameter (the value is used where |
| 35 | + /// an arrow with capabilities supplied by callers is expected). |
| 36 | + Param(usize), |
| 37 | +} |
| 38 | + |
| 39 | +/// Which capabilities each site passes or receives (ADR 0010), for Core |
| 40 | +/// lowering. Capabilities are identified by their instance type. |
| 41 | +#[derive(Clone, Debug, Default)] |
| 42 | +pub struct CapSites { |
| 43 | + /// Per callee expression of a call: the capabilities passed, in the |
| 44 | + /// callee's order (a function's own labels, or a closure's `Bound` |
| 45 | + /// labels ordered by effect). |
| 46 | + pub calls: HashMap<ExprId, Vec<Ty>>, |
| 47 | + /// Per lambda: the capabilities it receives, ordered like the `Bound` |
| 48 | + /// labels of its type. |
| 49 | + pub lambdas: HashMap<ExprId, Vec<Ty>>, |
| 50 | + /// Per `handle` or `region` body: the instance it introduces. |
| 51 | + pub binders: HashMap<ExprId, Ty>, |
| 52 | + /// Per function or operation name used as a value: the capabilities of |
| 53 | + /// its own row. |
| 54 | + pub values: HashMap<ExprId, Vec<CapArg>>, |
| 55 | + /// The function's own capability parameters. |
| 56 | + pub own: Vec<Ty>, |
| 57 | +} |
| 58 | + |
| 29 | 59 | /// Types computed for one body (zonked at the end). |
| 30 | 60 | #[derive(Debug, Default)] |
| 31 | 61 | pub struct BodyTypes { |
| @@ -50,6 +80,13 @@ pub struct FnInfer<'a, 'h> { |
| 50 | 80 | /// The effect row the code being checked may perform: the enclosing |
| 51 | 81 | /// function's (or lambda's) row, extended inside `handle` bodies. |
| 52 | 82 | pub effect: Ty, |
| 83 | + /// The `effect` rows of the enclosing scopes of lambdas, outermost |
| 84 | + /// first: the rest of the lexical capability environment (ADR 0010). |
| 85 | + pub scopes: Vec<Ty>, |
| 86 | + pub caps: CapSites, |
| 87 | + /// Calls to functions of the same group, whose rows are not complete |
| 88 | + /// yet: their capabilities are read at the end. |
| 89 | + pub mono_calls: Vec<(ExprId, Ty)>, |
| 53 | 90 | } |
| 54 | 91 | |
| 55 | 92 | impl<'a, 'h> FnInfer<'a, 'h> { |
| @@ -64,7 +101,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 64 | 101 | tyvars: VarScope, |
| 65 | 102 | effect: Ty, |
| 66 | 103 | ) -> Self { |
| 67 | | − ctx.st_effect = env.wk.st; |
| 104 | + ctx.instanced = env.instanced_effects(); |
| 68 | 105 | let types = BodyTypes { |
| 69 | 106 | exprs: vec![Ty::Error; body.exprs.len()], |
| 70 | 107 | pats: vec![Ty::Error; body.pats.len()], |
| @@ -81,6 +118,9 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 81 | 118 | types, |
| 82 | 119 | wanted: Vec::new(), |
| 83 | 120 | effect, |
| 121 | + scopes: Vec::new(), |
| 122 | + caps: CapSites::default(), |
| 123 | + mono_calls: Vec::new(), |
| 84 | 124 | } |
| 85 | 125 | } |
| 86 | 126 | |
| @@ -143,6 +183,12 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 143 | 183 | let (exp, act) = (self.show(expected), self.show(actual)); |
| 144 | 184 | let span = self.span(range); |
| 145 | 185 | let d = match e { |
| 186 | + UnifyError::Mismatch if exp == act => Diagnostic::error( |
| 187 | + codes::TYPE_MISMATCH, |
| 188 | + format!("type mismatch: `{exp}` here uses a different handler than expected"), |
| 189 | + span, |
| 190 | + ) |
| 191 | + .with_note("a function receives the handlers of its declared effects from its caller, but a lambda stored in a variable uses the handlers in scope where it was written (ADR 0010); write the lambda directly as the argument"), |
| 146 | 192 | UnifyError::Mismatch => Diagnostic::error( |
| 147 | 193 | codes::TYPE_MISMATCH, |
| 148 | 194 | format!("type mismatch: expected `{exp}`, found `{act}`"), |
| @@ -154,11 +200,45 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 154 | 200 | format!("this would need an infinite type: `{exp}` contains itself in `{act}`"), |
| 155 | 201 | span, |
| 156 | 202 | ), |
| 203 | + UnifyError::Escape(r) => self.escape_error(r, range), |
| 204 | + UnifyError::Receives(effect) => self.receives_error(effect, range), |
| 157 | 205 | }; |
| 158 | 206 | self.diags.push(d); |
| 159 | 207 | } |
| 160 | 208 | } |
| 161 | 209 | |
| 210 | + /// A region or handler instance would be visible outside its scope. |
| 211 | + fn escape_error(&self, r: u32, range: TextRange) -> Diagnostic { |
| 212 | + let name = self.ctx.rigid_name(r); |
| 213 | + let span = self.span(range); |
| 214 | + if name == "region" { |
| 215 | + Diagnostic::error( |
| 216 | + codes::REGION_ESCAPE, |
| 217 | + "a reference created in this region would escape it through a variable defined outside the region", |
| 218 | + span, |
| 219 | + ) |
| 220 | + } else { |
| 221 | + Diagnostic::error( |
| 222 | + codes::HANDLER_ESCAPE, |
| 223 | + format!("this would let the {name} be used outside its scope"), |
| 224 | + span, |
| 225 | + ) |
| 226 | + .with_note("a handler can only be used inside its `handle` body; a function that calls a callback inside its own handler must declare the callback's type with that effect, e.g. `action: fn() -> a / <log | e>`") |
| 227 | + } |
| 228 | + } |
| 229 | + |
| 230 | + /// A function that receives a handler from its caller used where its |
| 231 | + /// callers would not supply it. |
| 232 | + fn receives_error(&self, effect: DefId, range: TextRange) -> Diagnostic { |
| 233 | + let name = &self.env.hir.def(effect).name; |
| 234 | + Diagnostic::error( |
| 235 | + codes::TYPE_MISMATCH, |
| 236 | + format!("this function receives the `{name}` handler from its caller, but it is used where callers do not supply one"), |
| 237 | + self.span(range), |
| 238 | + ) |
| 239 | + .with_note("a lambda stored in a variable uses the handlers in scope where it was written, and a function value whose declared type lists an effect can only be called, or passed where the same type is declared; write a lambda here, e.g. `fn(x) { f(x) }` (ADR 0010)") |
| 240 | + } |
| 241 | + |
| 162 | 242 | fn error(&mut self, code: &'static str, message: impl Into<String>, range: TextRange) { |
| 163 | 243 | let span = self.span(range); |
| 164 | 244 | self.diags.push(Diagnostic::error(code, message, span)); |
| @@ -180,12 +260,26 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 180 | 260 | if let Ty::Fn(eparams, eret, eeff) = self.ctx.shallow(expected) |
| 181 | 261 | && eparams.len() == params.len() |
| 182 | 262 | { |
| 183 | | − let ty = |
| 184 | | − self.lambda(params, ret.as_ref(), *body, Some((&eparams, &eret, &eeff))); |
| 263 | + let ty = self.lambda( |
| 264 | + e, |
| 265 | + params, |
| 266 | + ret.as_ref(), |
| 267 | + *body, |
| 268 | + Some((&eparams, &eret, &eeff)), |
| 269 | + ); |
| 185 | 270 | self.set(e, ty); |
| 186 | 271 | return; |
| 187 | 272 | } |
| 188 | 273 | } |
| 274 | + Expr::Def(def) => { |
| 275 | + if let Ty::Fn(..) = self.ctx.shallow(expected) { |
| 276 | + let range = self.body.expr_span(e); |
| 277 | + let ty = self.def_value(e, *def, Some(expected), range); |
| 278 | + self.set(e, ty.clone()); |
| 279 | + self.coerce(&ty, expected, range); |
| 280 | + return; |
| 281 | + } |
| 282 | + } |
| 189 | 283 | Expr::Block { |
| 190 | 284 | stmts, |
| 191 | 285 | tail: Some(tail), |
| @@ -231,7 +325,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 231 | 325 | let ty = self.types.locals[l.index()].clone(); |
| 232 | 326 | self.ctx.open(ty) |
| 233 | 327 | } |
| 234 | | − Expr::Def(def) => self.instantiate_def(*def, Some(e), range), |
| 328 | + Expr::Def(def) => self.def_value(e, *def, None, range), |
| 235 | 329 | Expr::Call { |
| 236 | 330 | callee, |
| 237 | 331 | args, |
| @@ -275,7 +369,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 275 | 369 | } |
| 276 | 370 | } |
| 277 | 371 | } |
| 278 | | − Expr::Lambda { params, ret, body } => self.lambda(params, ret.as_ref(), *body, None), |
| 372 | + Expr::Lambda { params, ret, body } => self.lambda(e, params, ret.as_ref(), *body, None), |
| 279 | 373 | Expr::Block { stmts, tail } => { |
| 280 | 374 | self.stmts(stmts); |
| 281 | 375 | match tail { |
| @@ -382,17 +476,18 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 382 | 476 | } |
| 383 | 477 | } |
| 384 | 478 | |
| 385 | | − /// `region { body }` handles `alloc<h>` and `st<h>` for a fresh rigid |
| 386 | | − /// region `h`. The |
| 387 | | − /// result, and every variable that existed before the region, must not |
| 388 | | − /// mention `h`: no reference created inside can escape (like Haskell's |
| 389 | | − /// `runST`, checked at this construct instead of with rank-2 types). |
| 479 | + /// `region { body }` handles `alloc<h>` and `st<h>` for a fresh region |
| 480 | + /// `h`, which is also their instance (ADR 0010). Neither the result nor |
| 481 | + /// any variable from outside may mention `h`: no reference created |
| 482 | + /// inside can escape (like Haskell's `runST`, checked at this construct |
| 483 | + /// instead of with rank-2 types; the level check in unification covers |
| 484 | + /// variables). |
| 390 | 485 | fn region(&mut self, body: ExprId, range: TextRange) -> Ty { |
| 391 | 486 | let (Some(st), Some(alloc)) = (self.wk().st, self.wk().alloc) else { |
| 392 | 487 | return self.infer_expr(body); |
| 393 | 488 | }; |
| 394 | | − let h = self.ctx.fresh_region(); |
| 395 | | − let vars_before = self.ctx.var_count(); |
| 489 | + self.ctx.enter(); |
| 490 | + let h = self.ctx.fresh_scoped("region"); |
| 396 | 491 | let outer = self.effect.clone(); |
| 397 | 492 | let labels = vec![ |
| 398 | 493 | Ty::Con(alloc, vec![h.clone()]), |
| @@ -401,12 +496,10 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 401 | 496 | self.effect = Ty::row(labels, outer.clone()); |
| 402 | 497 | let ty = self.infer_expr(body); |
| 403 | 498 | self.effect = outer; |
| 404 | | − let mentions_h = |ctx: &InferCtx, t: &Ty| { |
| 405 | | − let mut found = false; |
| 406 | | − ctx.zonk(t).visit(&mut |x| found |= *x == h); |
| 407 | | − found |
| 408 | | − }; |
| 409 | | − if mentions_h(self.ctx, &ty) { |
| 499 | + self.ctx.leave(); |
| 500 | + self.caps.binders.insert(body, h.clone()); |
| 501 | + let Ty::Rigid(r) = h else { unreachable!() }; |
| 502 | + if self.ctx.mentions_rigid(&ty, r) { |
| 410 | 503 | let shown = self.show(&ty); |
| 411 | 504 | self.diags.push( |
| 412 | 505 | Diagnostic::error( |
| @@ -418,14 +511,6 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 418 | 511 | ); |
| 419 | 512 | return Ty::Error; |
| 420 | 513 | } |
| 421 | | − if (0..vars_before).any(|v| mentions_h(self.ctx, &Ty::Var(v))) { |
| 422 | | − self.error( |
| 423 | | − codes::REGION_ESCAPE, |
| 424 | | − "a reference created in this region would escape it through a variable defined outside the region", |
| 425 | | − range, |
| 426 | | − ); |
| 427 | | − return Ty::Error; |
| 428 | | − } |
| 429 | 514 | ty |
| 430 | 515 | } |
| 431 | 516 | |
| @@ -627,27 +712,56 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 627 | 712 | spread: Option<ExprId>, |
| 628 | 713 | range: TextRange, |
| 629 | 714 | ) -> Ty { |
| 630 | | − let callee_ty = self.infer_expr(callee); |
| 715 | + // A named function called directly receives its capabilities as |
| 716 | + // arguments; used as a value, it would capture them instead. |
| 717 | + let callee_ty = match &self.body.exprs[callee] { |
| 718 | + Expr::Def(def) => { |
| 719 | + let ty = self.instantiate_def(*def, Some(callee), self.body.expr_span(callee)); |
| 720 | + self.set(callee, ty) |
| 721 | + } |
| 722 | + _ => self.infer_expr(callee), |
| 723 | + }; |
| 631 | 724 | let Some(slots) = self.order_args(callee, args, range) else { |
| 632 | 725 | for a in args { |
| 633 | 726 | self.infer_expr(a.expr); |
| 634 | 727 | } |
| 635 | 728 | return Ty::Error; |
| 636 | 729 | }; |
| 637 | | − let mut pending_effects = None; |
| 730 | + let pending_effects; |
| 638 | 731 | let (params, ret) = match self.ctx.shallow(&callee_ty) { |
| 639 | 732 | Ty::Fn(params, ret, eff) => { |
| 733 | + // Capabilities the callee's callers supply get fresh |
| 734 | + // instances, resolved below like any other label. |
| 735 | + let (eff, opened) = self.open_bound(&eff); |
| 736 | + let hir = self.env.hir; |
| 737 | + match &self.body.exprs[callee] { |
| 738 | + Expr::Def(def) if self.mono.contains_key(def) => { |
| 739 | + self.mono_calls.push((callee, eff.clone())); |
| 740 | + } |
| 741 | + Expr::Def(def) |
| 742 | + if matches!(hir.def(*def).kind, DefKind::Fn(_) | DefKind::Op(_)) => |
| 743 | + { |
| 744 | + let own = self.row_instances(&eff); |
| 745 | + self.caps.calls.insert(callee, own); |
| 746 | + } |
| 747 | + _ => { |
| 748 | + self.caps.calls.insert(callee, opened); |
| 749 | + } |
| 750 | + } |
| 640 | 751 | // Performed after the arguments are checked (below): they |
| 641 | 752 | // run first, and they may pin the callee's type variables |
| 642 | 753 | // (e.g. which region a reference belongs to). |
| 643 | | − pending_effects = Some(*eff); |
| 754 | + pending_effects = Some(eff); |
| 644 | 755 | (params, *ret) |
| 645 | 756 | } |
| 646 | 757 | Ty::Var(_) => { |
| 647 | 758 | let params: Vec<Ty> = slots.iter().map(|_| self.ctx.fresh()).collect(); |
| 648 | 759 | let ret = self.ctx.fresh(); |
| 649 | | − let f = Ty::func_eff(params.clone(), ret.clone(), self.effect.clone()); |
| 760 | + let row = self.ctx.fresh(); |
| 761 | + let f = Ty::func_eff(params.clone(), ret.clone(), row.clone()); |
| 650 | 762 | self.unify_at(&callee_ty, &f, self.body.expr_span(callee)); |
| 763 | + self.caps.calls.insert(callee, Vec::new()); |
| 764 | + pending_effects = Some(row); |
| 651 | 765 | (params, ret) |
| 652 | 766 | } |
| 653 | 767 | Ty::Error => { |
| @@ -774,6 +888,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 774 | 888 | |
| 775 | 889 | fn lambda( |
| 776 | 890 | &mut self, |
| 891 | + e: ExprId, |
| 777 | 892 | params: &[(PatId, Option<TypeRef>)], |
| 778 | 893 | ret: Option<&TypeRef>, |
| 779 | 894 | body: ExprId, |
| @@ -805,60 +920,303 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 805 | 920 | (None, None) => self.ctx.fresh(), |
| 806 | 921 | }; |
| 807 | 922 | // The body runs when the lambda is called: its effects are the |
| 808 | | − // lambda's own, not the enclosing function's. |
| 923 | + // lambda's own, not the enclosing function's. Capabilities its |
| 924 | + // callers supply (`Bound` labels of the expected type) become |
| 925 | + // scoped instances inside the body (ADR 0010). |
| 809 | 926 | let effect = match expected { |
| 810 | 927 | Some((_, _, eeff)) => eeff.clone(), |
| 811 | 928 | None => self.ctx.fresh(), |
| 812 | 929 | }; |
| 813 | | − let outer = std::mem::replace(&mut self.effect, effect.clone()); |
| 930 | + self.ctx.enter(); |
| 931 | + let (labels, tail) = self.ctx.row_labels(&effect); |
| 932 | + let mut received: Vec<((DefId, u32), Ty)> = Vec::new(); |
| 933 | + let inner_labels = labels |
| 934 | + .into_iter() |
| 935 | + .map(|l| match (&l, self.ctx.instance(&l)) { |
| 936 | + (Ty::Con(d, args), Some(Ty::Bound(k))) => { |
| 937 | + let name = format!("`{}` capability", self.env.hir.def(*d).name); |
| 938 | + let cap = self.ctx.fresh_scoped(&name); |
| 939 | + received.push(((*d, k), cap.clone())); |
| 940 | + let mut args = args.clone(); |
| 941 | + *args.last_mut().expect("has an instance") = cap; |
| 942 | + Ty::Con(*d, args) |
| 943 | + } |
| 944 | + _ => l, |
| 945 | + }) |
| 946 | + .collect(); |
| 947 | + let inner = if received.is_empty() { |
| 948 | + effect.clone() |
| 949 | + } else { |
| 950 | + Ty::row(inner_labels, tail) |
| 951 | + }; |
| 952 | + let outer = std::mem::replace(&mut self.effect, inner); |
| 953 | + self.scopes.push(outer); |
| 814 | 954 | self.check_expr(body, &ret_ty); |
| 815 | | − self.effect = outer; |
| 955 | + self.effect = self.scopes.pop().expect("pushed"); |
| 956 | + self.ctx.leave(); |
| 957 | + received.sort_by_key(|(k, _)| *k); |
| 958 | + self.caps |
| 959 | + .lambdas |
| 960 | + .insert(e, received.into_iter().map(|(_, c)| c).collect()); |
| 816 | 961 | Ty::func_eff(param_tys, ret_ty, effect) |
| 817 | 962 | } |
| 818 | 963 | |
| 819 | | − /// A call performs `effects`: they must be allowed by the current row. |
| 964 | + /// Replace the `Bound` instances of a callee's row (capabilities the |
| 965 | + /// caller supplies) with fresh variables. Returns the new row and the |
| 966 | + /// variables, ordered by effect and occurrence. |
| 967 | + fn open_bound(&mut self, eff: &Ty) -> (Ty, Vec<Ty>) { |
| 968 | + let (labels, tail) = self.ctx.row_labels(eff); |
| 969 | + let mut opened: Vec<((DefId, u32), Ty)> = Vec::new(); |
| 970 | + let labels: Vec<Ty> = labels |
| 971 | + .into_iter() |
| 972 | + .map(|l| match (&l, self.ctx.instance(&l)) { |
| 973 | + (Ty::Con(d, args), Some(Ty::Bound(k))) => { |
| 974 | + let v = self.ctx.fresh(); |
| 975 | + opened.push(((*d, k), v.clone())); |
| 976 | + let mut args = args.clone(); |
| 977 | + *args.last_mut().expect("has an instance") = v; |
| 978 | + Ty::Con(*d, args) |
| 979 | + } |
| 980 | + _ => l, |
| 981 | + }) |
| 982 | + .collect(); |
| 983 | + if opened.is_empty() { |
| 984 | + return (eff.clone(), Vec::new()); |
| 985 | + } |
| 986 | + opened.sort_by_key(|(k, _)| *k); |
| 987 | + ( |
| 988 | + Ty::row(labels, tail), |
| 989 | + opened.into_iter().map(|(_, v)| v).collect(), |
| 990 | + ) |
| 991 | + } |
| 992 | + |
| 993 | + /// Instances of the labels of a row (up to its tail), in order. |
| 994 | + fn row_instances(&self, row: &Ty) -> Vec<Ty> { |
| 995 | + let (labels, _) = self.ctx.row_labels(row); |
| 996 | + labels.iter().filter_map(|l| self.ctx.instance(l)).collect() |
| 997 | + } |
| 998 | + |
| 999 | + /// A function or operation used as a value captures the capabilities of |
| 1000 | + /// its own row where it is used, except those an expected arrow says |
| 1001 | + /// its callers supply: those become parameters of a wrapper. |
| 1002 | + fn def_value(&mut self, e: ExprId, def: DefId, expected: Option<&Ty>, range: TextRange) -> Ty { |
| 1003 | + let ty = self.instantiate_def(def, Some(e), range); |
| 1004 | + let hir = self.env.hir; |
| 1005 | + if !matches!(hir.def(def).kind, DefKind::Fn(_) | DefKind::Op(_)) |
| 1006 | + || self.mono.contains_key(&def) |
| 1007 | + { |
| 1008 | + return ty; |
| 1009 | + } |
| 1010 | + let Ty::Fn(_, _, eff) = self.ctx.shallow(&ty) else { |
| 1011 | + return ty; |
| 1012 | + }; |
| 1013 | + // Capabilities the expected arrow's callers supply, by effect. |
| 1014 | + let mut supplied: Vec<(DefId, u32)> = Vec::new(); |
| 1015 | + if let Some(Ty::Fn(_, _, eeff)) = expected.map(|t| self.ctx.shallow(t)) { |
| 1016 | + for l in self.ctx.row_labels(&eeff).0 { |
| 1017 | + if let (Ty::Con(d, _), Some(Ty::Bound(k))) = (&l, self.ctx.instance(&l)) { |
| 1018 | + supplied.push((*d, k)); |
| 1019 | + } |
| 1020 | + } |
| 1021 | + supplied.sort(); |
| 1022 | + } |
| 1023 | + let mut seen: Vec<DefId> = Vec::new(); |
| 1024 | + let mut args = Vec::new(); |
| 1025 | + for l in self.ctx.row_labels(&eff).0 { |
| 1026 | + let (Some(head), Some(inst)) = (effect_head(&l), self.ctx.instance(&l)) else { |
| 1027 | + continue; |
| 1028 | + }; |
| 1029 | + let k = seen.iter().filter(|d| **d == head).count() as u32; |
| 1030 | + seen.push(head); |
| 1031 | + match (supplied.iter().position(|s| *s == (head, k)), &inst) { |
| 1032 | + (Some(pos), Ty::Var(v)) => { |
| 1033 | + self.ctx.bind_bound(*v, k); |
| 1034 | + args.push(CapArg::Param(pos)); |
| 1035 | + } |
| 1036 | + _ => { |
| 1037 | + self.resolve(&l, range); |
| 1038 | + args.push(CapArg::Inst(inst)); |
| 1039 | + } |
| 1040 | + } |
| 1041 | + } |
| 1042 | + self.caps.values.insert(e, args); |
| 1043 | + ty |
| 1044 | + } |
| 1045 | + |
| 1046 | + /// Resolve a label against the lexical capability environment (ADR |
| 1047 | + /// 0010) and unify it with the label found. Returns the label found, or |
| 1048 | + /// `None` after reporting why there is none. |
| 1049 | + /// |
| 1050 | + /// - A known instance (a handler, region or capability in scope) must |
| 1051 | + /// be in scope; an unknown one takes the nearest label of the effect. |
| 1052 | + /// - Type arguments never choose: they must agree with the label found. |
| 1053 | + /// - A label found outside the current lambda is added to the rows of |
| 1054 | + /// the lambdas in between; one found nowhere is added to the |
| 1055 | + /// function's own row if that is inferred. |
| 1056 | + fn resolve(&mut self, label: &Ty, range: TextRange) -> Option<Ty> { |
| 1057 | + let head = effect_head(label)?; |
| 1058 | + let inst = self.ctx.instance(label); |
| 1059 | + let mut rows = vec![self.effect.clone()]; |
| 1060 | + rows.extend(self.scopes.iter().rev().cloned()); |
| 1061 | + let find = |this: &Self, same_instance: bool| { |
| 1062 | + rows.iter().enumerate().find_map(|(depth, row)| { |
| 1063 | + this.ctx.row_labels(row).0.into_iter().find_map(|l| { |
| 1064 | + let ok = effect_head(&l) == Some(head) |
| 1065 | + && (!same_instance || this.ctx.instance(&l) == inst); |
| 1066 | + ok.then_some((depth, l)) |
| 1067 | + }) |
| 1068 | + }) |
| 1069 | + }; |
| 1070 | + let known = matches!(inst, Some(Ty::Rigid(_))); |
| 1071 | + let mut found = match inst { |
| 1072 | + Some(Ty::Var(_) | Ty::Rigid(_)) => find(self, true), |
| 1073 | + _ => None, |
| 1074 | + }; |
| 1075 | + if found.is_none() && known { |
| 1076 | + let name = self.env.hir.def(head).name.clone(); |
| 1077 | + self.error( |
| 1078 | + codes::HANDLER_ESCAPE, |
| 1079 | + format!("the `{name}` handler this refers to is not in scope here"), |
| 1080 | + range, |
| 1081 | + ); |
| 1082 | + return None; |
| 1083 | + } |
| 1084 | + if found.is_none() { |
| 1085 | + found = find(self, false); |
| 1086 | + } |
| 1087 | + let (depth, found) = match found { |
| 1088 | + Some(f) => f, |
| 1089 | + None => { |
| 1090 | + let outermost = rows.len() - 1; |
| 1091 | + if !self.ctx.extend_row(&rows[outermost], label.clone()) { |
| 1092 | + return None; |
| 1093 | + } |
| 1094 | + (outermost, label.clone()) |
| 1095 | + } |
| 1096 | + }; |
| 1097 | + for row in &rows[..depth] { |
| 1098 | + if !self.ctx.extend_row(row, found.clone()) { |
| 1099 | + let name = self.env.hir.def(head).name.clone(); |
| 1100 | + self.error( |
| 1101 | + codes::UNHANDLED_EFFECT, |
| 1102 | + format!("this function cannot use the `{name}` handler of the code around it: its effects are fixed by the type it is expected to have"), |
| 1103 | + range, |
| 1104 | + ); |
| 1105 | + return None; |
| 1106 | + } |
| 1107 | + } |
| 1108 | + if let Err(e) = self.ctx.unify(label, &found) { |
| 1109 | + let d = match e { |
| 1110 | + UnifyError::Escape(r) => self.escape_error(r, range), |
| 1111 | + UnifyError::Receives(effect) => self.receives_error(effect, range), |
| 1112 | + _ => { |
| 1113 | + let (want, have) = (self.show(label), self.show(&found)); |
| 1114 | + Diagnostic::error( |
| 1115 | + codes::TYPE_MISMATCH, |
| 1116 | + format!("this performs `{want}`, but the nearest handler for it is `{have}`"), |
| 1117 | + self.span(range), |
| 1118 | + ) |
| 1119 | + .with_note("an operation goes to the nearest enclosing handler of its effect; type arguments do not choose another one (ADR 0010)") |
| 1120 | + } |
| 1121 | + }; |
| 1122 | + self.diags.push(d); |
| 1123 | + } |
| 1124 | + Some(found) |
| 1125 | + } |
| 1126 | + |
| 1127 | + /// A call performs `effects`: each label must resolve in the lexical |
| 1128 | + /// capability environment, and the callee's row must be *included* in |
| 1129 | + /// the current one (ADR 0010; sound because operations are routed by |
| 1130 | + /// instance). A callee's row variable becomes the current row minus |
| 1131 | + /// the labels matched. |
| 820 | 1132 | fn perform(&mut self, effects: &Ty, range: TextRange) { |
| 821 | | − let current = self.effect.clone(); |
| 822 | | − if self.ctx.unify(effects, ¤t).is_ok() { |
| 1133 | + let (labels, tail) = self.ctx.row_labels(effects); |
| 1134 | + let mut matched = Vec::new(); |
| 1135 | + let mut missing = Vec::new(); |
| 1136 | + for l in &labels { |
| 1137 | + match self.resolve(l, range) { |
| 1138 | + Some(found) => matched.push(self.ctx.zonk(&found)), |
| 1139 | + None => missing.push(l.clone()), |
| 1140 | + } |
| 1141 | + } |
| 1142 | + if !missing.is_empty() { |
| 1143 | + self.unhandled(&missing, range); |
| 823 | 1144 | return; |
| 824 | 1145 | } |
| 825 | | − let (performed, _) = self.ctx.row_parts(effects); |
| 826 | | − let (allowed, tail) = self.ctx.row_parts(¤t); |
| 827 | | − let heads: Vec<_> = allowed.iter().map(crate::ty::effect_head).collect(); |
| 828 | | − let missing: Vec<String> = performed |
| 1146 | + let (current, current_tail) = self.ctx.row_labels(&self.effect); |
| 1147 | + match (&tail, self.ctx.shallow(¤t_tail)) { |
| 1148 | + (Ty::RowEmpty | Ty::Error, _) => {} |
| 1149 | + (t, ct) if *t == ct => {} |
| 1150 | + (Ty::Var(_), _) => { |
| 1151 | + let mut rest = Vec::new(); |
| 1152 | + for l in current { |
| 1153 | + let z = self.ctx.zonk(&l); |
| 1154 | + match matched.iter().position(|m| *m == z) { |
| 1155 | + Some(i) => { |
| 1156 | + matched.remove(i); |
| 1157 | + } |
| 1158 | + None => rest.push(l), |
| 1159 | + } |
| 1160 | + } |
| 1161 | + let remainder = Ty::row(rest, current_tail); |
| 1162 | + if let Err(e) = self.ctx.unify(&tail, &remainder) { |
| 1163 | + let d = match e { |
| 1164 | + UnifyError::Escape(r) => self.escape_error(r, range), |
| 1165 | + UnifyError::Receives(effect) => self.receives_error(effect, range), |
| 1166 | + _ => Diagnostic::error( |
| 1167 | + codes::UNHANDLED_EFFECT, |
| 1168 | + format!( |
| 1169 | + "this call's effects `{}` do not fit the allowed `{}`", |
| 1170 | + self.show(effects), |
| 1171 | + self.show(&self.effect) |
| 1172 | + ), |
| 1173 | + self.span(range), |
| 1174 | + ), |
| 1175 | + }; |
| 1176 | + self.diags.push(d); |
| 1177 | + } |
| 1178 | + } |
| 1179 | + _ => { |
| 1180 | + let (callee, allowed) = (self.show(&tail), self.show(&self.effect)); |
| 1181 | + self.diags.push( |
| 1182 | + Diagnostic::error( |
| 1183 | + codes::UNHANDLED_EFFECT, |
| 1184 | + format!("this call may perform the effects `<{callee}>`, which are not allowed here"), |
| 1185 | + self.span(range), |
| 1186 | + ) |
| 1187 | + .with_note(format!("the effects allowed here are `{allowed}`")), |
| 1188 | + ); |
| 1189 | + } |
| 1190 | + } |
| 1191 | + } |
| 1192 | + |
| 1193 | + fn unhandled(&mut self, missing: &[Ty], range: TextRange) { |
| 1194 | + let shown: Vec<String> = missing |
| 829 | 1195 | .iter() |
| 830 | | − .filter(|l| !heads.contains(&crate::ty::effect_head(l))) |
| 831 | 1196 | .map(|l| format!("`{}`", self.show(l))) |
| 832 | 1197 | .collect(); |
| 1198 | + let current = self.effect.clone(); |
| 1199 | + let (allowed, tail) = self.ctx.row_parts(¤t); |
| 833 | 1200 | let allowed_shown = self.show(¤t); |
| 834 | | − let span = self.span(range); |
| 835 | | − let message = if missing.is_empty() { |
| 836 | | − format!( |
| 837 | | − "this call's effects `{}` do not fit the allowed `{allowed_shown}`", |
| 838 | | − self.show(effects) |
| 839 | | − ) |
| 840 | | − } else { |
| 841 | | − format!( |
| 842 | | − "this call performs {} which is not handled here", |
| 843 | | − missing.join(", ") |
| 844 | | − ) |
| 845 | | − }; |
| 846 | 1201 | let note = if tail == Ty::RowEmpty && allowed.is_empty() { |
| 847 | 1202 | "the enclosing function is declared total; add the effect to its signature (`-> T / <...>`) or handle it".to_owned() |
| 848 | | − } else if missing.is_empty() { |
| 849 | | − // Same labels, different tails: typically a callback declared |
| 850 | | − // with fewer effects than its caller (rows must be equal; there |
| 851 | | − // is no `mask` in v0, see ADR 0008). |
| 852 | | − format!( |
| 853 | | − "effect rows must match exactly: give the callee the caller's row `{allowed_shown}`, e.g. `f: fn() -> T / {allowed_shown}`" |
| 854 | | − ) |
| 855 | 1203 | } else { |
| 856 | 1204 | format!( |
| 857 | 1205 | "the effects allowed here are `{allowed_shown}`; add the effect to the signature or handle it" |
| 858 | 1206 | ) |
| 859 | 1207 | }; |
| 860 | | − self.diags |
| 861 | | − .push(Diagnostic::error(codes::UNHANDLED_EFFECT, message, span).with_note(note)); |
| 1208 | + let span = self.span(range); |
| 1209 | + self.diags.push( |
| 1210 | + Diagnostic::error( |
| 1211 | + codes::UNHANDLED_EFFECT, |
| 1212 | + format!( |
| 1213 | + "this call performs {} which is not handled here", |
| 1214 | + shown.join(", ") |
| 1215 | + ), |
| 1216 | + span, |
| 1217 | + ) |
| 1218 | + .with_note(note), |
| 1219 | + ); |
| 862 | 1220 | } |
| 863 | 1221 | |
| 864 | 1222 | fn binary(&mut self, e: ExprId, op: BinOp, lhs: ExprId, rhs: ExprId, range: TextRange) -> Ty { |
| @@ -928,7 +1286,13 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 928 | 1286 | DefKind::Effect(e) => e.params.len(), |
| 929 | 1287 | _ => 0, |
| 930 | 1288 | }; |
| 931 | | − let args = (0..n).map(|_| self.ctx.fresh()).collect(); |
| 1289 | + let mut args: Vec<Ty> = (0..n).map(|_| self.ctx.fresh()).collect(); |
| 1290 | + // Each handler is a new instance of its effect (ADR 0010). |
| 1291 | + self.ctx.enter(); |
| 1292 | + if self.env.implicit_instance(effect) { |
| 1293 | + let name = format!("`{}` handler", hir.def(effect).name); |
| 1294 | + args.push(self.ctx.fresh_scoped(&name)); |
| 1295 | + } |
| 932 | 1296 | Some((effect, Ty::Con(effect, args))) |
| 933 | 1297 | } |
| 934 | 1298 | None => { |
| @@ -984,6 +1348,13 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 984 | 1348 | self.effect = inner; |
| 985 | 1349 | let body_ty = self.infer_expr(body); |
| 986 | 1350 | self.effect = outer.clone(); |
| 1351 | + let instance = label.as_ref().and_then(|(_, l)| self.ctx.instance(l)); |
| 1352 | + if label.is_some() { |
| 1353 | + self.ctx.leave(); |
| 1354 | + } |
| 1355 | + if let Some(i) = &instance { |
| 1356 | + self.caps.binders.insert(body, i.clone()); |
| 1357 | + } |
| 987 | 1358 | |
| 988 | 1359 | let result = self.ctx.fresh(); |
| 989 | 1360 | if !clauses.iter().any(|c| c.is_return) { |
| @@ -1054,6 +1425,18 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 1054 | 1425 | tilc_hir::OpKind::FinalCtl => self.check_expr(clause.body, &result), |
| 1055 | 1426 | } |
| 1056 | 1427 | } |
| 1428 | + // The handler exists only while its body runs (ADR 0010). |
| 1429 | + if let Some(Ty::Rigid(r)) = instance |
| 1430 | + && self.ctx.mentions_rigid(&result, r) |
| 1431 | + { |
| 1432 | + let shown = self.show(&result); |
| 1433 | + self.error( |
| 1434 | + codes::HANDLER_ESCAPE, |
| 1435 | + format!("this handler's value would use the handler after it ends: it has type `{shown}`"), |
| 1436 | + range, |
| 1437 | + ); |
| 1438 | + return Ty::Error; |
| 1439 | + } |
| 1057 | 1440 | result |
| 1058 | 1441 | } |
| 1059 | 1442 | |