| @@ -47,9 +47,13 @@ pub struct FnInfer<'a, 'h> { |
| 47 | 47 | pub tyvars: VarScope, |
| 48 | 48 | pub types: BodyTypes, |
| 49 | 49 | pub wanted: Vec<Wanted>, |
| 50 | + /// The effect row the code being checked may perform: the enclosing |
| 51 | + /// function's (or lambda's) row, extended inside `handle` bodies. |
| 52 | + pub effect: Ty, |
| 50 | 53 | } |
| 51 | 54 | |
| 52 | 55 | impl<'a, 'h> FnInfer<'a, 'h> { |
| 56 | + #[allow(clippy::too_many_arguments)] |
| 53 | 57 | pub fn new( |
| 54 | 58 | env: &'a mut Env<'h>, |
| 55 | 59 | ctx: &'a mut InferCtx, |
| @@ -58,6 +62,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 58 | 62 | diags: &'a mut Vec<Diagnostic>, |
| 59 | 63 | mono: &'a HashMap<DefId, Ty>, |
| 60 | 64 | tyvars: VarScope, |
| 65 | + effect: Ty, |
| 61 | 66 | ) -> Self { |
| 62 | 67 | let types = BodyTypes { |
| 63 | 68 | exprs: vec![Ty::Error; body.exprs.len()], |
| @@ -74,6 +79,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 74 | 79 | tyvars, |
| 75 | 80 | types, |
| 76 | 81 | wanted: Vec::new(), |
| 82 | + effect, |
| 77 | 83 | } |
| 78 | 84 | } |
| 79 | 85 | |
| @@ -93,6 +99,7 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 93 | 99 | hir: self.env.hir, |
| 94 | 100 | ctx: Some(self.ctx), |
| 95 | 101 | gen_names: &[], |
| 102 | + rigid_names: &[], |
| 96 | 103 | } |
| 97 | 104 | } |
| 98 | 105 | |
| @@ -169,10 +176,11 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 169 | 176 | pub fn check_expr(&mut self, e: ExprId, expected: &Ty) { |
| 170 | 177 | match &self.body.exprs[e] { |
| 171 | 178 | Expr::Lambda { params, ret, body } => { |
| 172 | | − if let Ty::Fn(eparams, eret, _) = self.ctx.shallow(expected) |
| 179 | + if let Ty::Fn(eparams, eret, eeff) = self.ctx.shallow(expected) |
| 173 | 180 | && eparams.len() == params.len() |
| 174 | 181 | { |
| 175 | | − let ty = self.lambda(params, ret.as_ref(), *body, Some((&eparams, &eret))); |
| 182 | + let ty = |
| 183 | + self.lambda(params, ret.as_ref(), *body, Some((&eparams, &eret, &eeff))); |
| 176 | 184 | self.set(e, ty); |
| 177 | 185 | return; |
| 178 | 186 | } |
| @@ -218,7 +226,10 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 218 | 226 | Expr::Lit(Lit::Int(_)) => WellKnown::con(wk.int, vec![]), |
| 219 | 227 | Expr::Lit(Lit::Float(_)) => WellKnown::con(wk.float, vec![]), |
| 220 | 228 | Expr::Lit(Lit::String(_)) => WellKnown::con(wk.string, vec![]), |
| 221 | | − Expr::Local(l) => self.types.locals[l.index()].clone(), |
| 229 | + Expr::Local(l) => { |
| 230 | + let ty = self.types.locals[l.index()].clone(); |
| 231 | + self.ctx.open(ty) |
| 232 | + } |
| 222 | 233 | Expr::Def(def) => self.instantiate_def(*def, Some(e), range), |
| 223 | 234 | Expr::Call { |
| 224 | 235 | callee, |
| @@ -382,12 +393,13 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 382 | 393 | /// The type of a reference to a definition, instantiating its scheme. |
| 383 | 394 | pub fn instantiate_def(&mut self, def: DefId, site: Option<ExprId>, range: TextRange) -> Ty { |
| 384 | 395 | if let Some(mono) = self.mono.get(&def) { |
| 385 | | − return mono.clone(); |
| 396 | + return mono.clone(); // already open: its effect is a variable |
| 386 | 397 | } |
| 387 | 398 | let Some(scheme) = self.env.schemes.get(&def).cloned() else { |
| 388 | 399 | return Ty::Error; // its own signature failed to check |
| 389 | 400 | }; |
| 390 | 401 | let (ty, constraints) = self.ctx.instantiate(&scheme); |
| 402 | + let ty = self.ctx.open(ty); |
| 391 | 403 | for c in constraints { |
| 392 | 404 | let span = self.span(range); |
| 393 | 405 | self.wanted.push(Wanted { |
| @@ -499,11 +511,14 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 499 | 511 | return Ty::Error; |
| 500 | 512 | }; |
| 501 | 513 | let (params, ret) = match self.ctx.shallow(&callee_ty) { |
| 502 | | − Ty::Fn(params, ret, _) => (params, *ret), |
| 514 | + Ty::Fn(params, ret, eff) => { |
| 515 | + self.perform(&eff, range); |
| 516 | + (params, *ret) |
| 517 | + } |
| 503 | 518 | Ty::Var(_) => { |
| 504 | 519 | let params: Vec<Ty> = slots.iter().map(|_| self.ctx.fresh()).collect(); |
| 505 | 520 | let ret = self.ctx.fresh(); |
| 506 | | − let f = Ty::func(params.clone(), ret.clone()); |
| 521 | + let f = Ty::func_eff(params.clone(), ret.clone(), self.effect.clone()); |
| 507 | 522 | self.unify_at(&callee_ty, &f, self.body.expr_span(callee)); |
| 508 | 523 | (params, ret) |
| 509 | 524 | } |
| @@ -631,35 +646,88 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 631 | 646 | params: &[(PatId, Option<TypeRef>)], |
| 632 | 647 | ret: Option<&TypeRef>, |
| 633 | 648 | body: ExprId, |
| 634 | | − expected: Option<(&[Ty], &Ty)>, |
| 649 | + expected: Option<(&[Ty], &Ty, &Ty)>, |
| 635 | 650 | ) -> Ty { |
| 636 | 651 | let mut param_tys = Vec::new(); |
| 637 | 652 | for (i, (pat, ann)) in params.iter().enumerate() { |
| 638 | 653 | let ty = match (ann, expected) { |
| 639 | | − (Some(t), Some((eps, _))) => { |
| 654 | + (Some(t), Some((eps, _, _))) => { |
| 640 | 655 | let ann = self.lower_annotation(t); |
| 641 | 656 | self.unify_at(&eps[i], &ann, self.body.pat_span(*pat)); |
| 642 | 657 | ann |
| 643 | 658 | } |
| 644 | 659 | (Some(t), None) => self.lower_annotation(t), |
| 645 | | − (None, Some((eps, _))) => eps[i].clone(), |
| 660 | + (None, Some((eps, _, _))) => eps[i].clone(), |
| 646 | 661 | (None, None) => self.ctx.fresh(), |
| 647 | 662 | }; |
| 648 | 663 | self.check_pat(*pat, &ty); |
| 649 | 664 | param_tys.push(ty); |
| 650 | 665 | } |
| 651 | 666 | let ret_ty = match (ret, expected) { |
| 652 | | − (Some(t), Some((_, eret))) => { |
| 667 | + (Some(t), Some((_, eret, _))) => { |
| 653 | 668 | let ann = self.lower_annotation(t); |
| 654 | 669 | self.unify_at(eret, &ann, self.body.expr_span(body)); |
| 655 | 670 | ann |
| 656 | 671 | } |
| 657 | 672 | (Some(t), None) => self.lower_annotation(t), |
| 658 | | − (None, Some((_, eret))) => eret.clone(), |
| 673 | + (None, Some((_, eret, _))) => eret.clone(), |
| 659 | 674 | (None, None) => self.ctx.fresh(), |
| 660 | 675 | }; |
| 676 | + // The body runs when the lambda is called: its effects are the |
| 677 | + // lambda's own, not the enclosing function's. |
| 678 | + let effect = match expected { |
| 679 | + Some((_, _, eeff)) => eeff.clone(), |
| 680 | + None => self.ctx.fresh(), |
| 681 | + }; |
| 682 | + let outer = std::mem::replace(&mut self.effect, effect.clone()); |
| 661 | 683 | self.check_expr(body, &ret_ty); |
| 662 | | − Ty::func(param_tys, ret_ty) |
| 684 | + self.effect = outer; |
| 685 | + Ty::func_eff(param_tys, ret_ty, effect) |
| 686 | + } |
| 687 | + |
| 688 | + /// A call performs `effects`: they must be allowed by the current row. |
| 689 | + fn perform(&mut self, effects: &Ty, range: TextRange) { |
| 690 | + let current = self.effect.clone(); |
| 691 | + if self.ctx.unify(effects, ¤t).is_ok() { |
| 692 | + return; |
| 693 | + } |
| 694 | + let (performed, _) = self.ctx.row_parts(effects); |
| 695 | + let (allowed, tail) = self.ctx.row_parts(¤t); |
| 696 | + let heads: Vec<_> = allowed.iter().map(crate::ty::effect_head).collect(); |
| 697 | + let missing: Vec<String> = performed |
| 698 | + .iter() |
| 699 | + .filter(|l| !heads.contains(&crate::ty::effect_head(l))) |
| 700 | + .map(|l| format!("`{}`", self.show(l))) |
| 701 | + .collect(); |
| 702 | + let allowed_shown = self.show(¤t); |
| 703 | + let span = self.span(range); |
| 704 | + let message = if missing.is_empty() { |
| 705 | + format!( |
| 706 | + "this call's effects `{}` do not fit the allowed `{allowed_shown}`", |
| 707 | + self.show(effects) |
| 708 | + ) |
| 709 | + } else { |
| 710 | + format!( |
| 711 | + "this call performs {} which is not handled here", |
| 712 | + missing.join(", ") |
| 713 | + ) |
| 714 | + }; |
| 715 | + let note = if tail == Ty::RowEmpty && allowed.is_empty() { |
| 716 | + "the enclosing function is declared total; add the effect to its signature (`-> T / <...>`) or handle it".to_owned() |
| 717 | + } else if missing.is_empty() { |
| 718 | + // Same labels, different tails: typically a callback declared |
| 719 | + // with fewer effects than its caller (rows must be equal; there |
| 720 | + // is no `mask` in v0, see ADR 0008). |
| 721 | + format!( |
| 722 | + "effect rows must match exactly: give the callee the caller's row `{allowed_shown}`, e.g. `f: fn() -> T / {allowed_shown}`" |
| 723 | + ) |
| 724 | + } else { |
| 725 | + format!( |
| 726 | + "the effects allowed here are `{allowed_shown}`; add the effect to the signature or handle it" |
| 727 | + ) |
| 728 | + }; |
| 729 | + self.diags |
| 730 | + .push(Diagnostic::error(codes::UNHANDLED_EFFECT, message, span).with_note(note)); |
| 663 | 731 | } |
| 664 | 732 | |
| 665 | 733 | fn binary(&mut self, e: ExprId, op: BinOp, lhs: ExprId, rhs: ExprId, range: TextRange) -> Ty { |
| @@ -697,14 +765,91 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 697 | 765 | } |
| 698 | 766 | } |
| 699 | 767 | |
| 700 | | − /// Handlers are typed structurally in M2; effect rows (what the body |
| 701 | | − /// may perform, what the handler removes) arrive in M3. |
| 768 | + /// `handle { body } with { clauses }` handles one effect `L`: |
| 769 | + /// - the body runs with `<L | outer>`, the clauses with `outer`; |
| 770 | + /// - a `fn` clause produces the operation's result (resumption is |
| 771 | + /// implicit); a `ctl` clause produces the handler's result and may |
| 772 | + /// call `resume: fn(op_result) -> R / outer`; a `final ctl` clause |
| 773 | + /// produces the handler's result and never resumes; |
| 774 | + /// - `return(x)` maps the body's value to the result (identity if |
| 775 | + /// omitted); |
| 776 | + /// - every operation of `L` must be handled. |
| 702 | 777 | fn handle(&mut self, body: ExprId, clauses: &[HandlerClause]) -> Ty { |
| 778 | + let hir = self.env.hir; |
| 779 | + let outer = self.effect.clone(); |
| 780 | + let ops: Vec<DefId> = clauses.iter().filter_map(|c| c.op).collect(); |
| 781 | + let effect_of = |op: DefId| match &hir.def(op).kind { |
| 782 | + DefKind::Op(o) => Some(o.effect), |
| 783 | + _ => None, |
| 784 | + }; |
| 785 | + let handled = ops.first().and_then(|op| effect_of(*op)); |
| 786 | + let range = self.body.expr_span(body); |
| 787 | + let label = match handled { |
| 788 | + Some(effect) => { |
| 789 | + let n = match &hir.def(effect).kind { |
| 790 | + DefKind::Effect(e) => e.params.len(), |
| 791 | + _ => 0, |
| 792 | + }; |
| 793 | + let args = (0..n).map(|_| self.ctx.fresh()).collect(); |
| 794 | + Some((effect, Ty::Con(effect, args))) |
| 795 | + } |
| 796 | + None => { |
| 797 | + if clauses.iter().all(|c| c.is_return) && !clauses.is_empty() { |
| 798 | + self.error( |
| 799 | + codes::MIXED_HANDLER, |
| 800 | + "a handler must handle at least one operation", |
| 801 | + range, |
| 802 | + ); |
| 803 | + } |
| 804 | + None |
| 805 | + } |
| 806 | + }; |
| 807 | + if let Some((effect, _)) = &label { |
| 808 | + for c in clauses |
| 809 | + .iter() |
| 810 | + .filter(|c| c.op.is_some_and(|op| effect_of(op) != Some(*effect))) |
| 811 | + { |
| 812 | + let other = |
| 813 | + c.op.and_then(effect_of) |
| 814 | + .map_or("?", |e| hir.def(e).name.as_str()); |
| 815 | + self.error( |
| 816 | + codes::MIXED_HANDLER, |
| 817 | + format!( |
| 818 | + "one handler handles one effect: this clause is for `{other}`, not `{}`", |
| 819 | + hir.def(*effect).name |
| 820 | + ), |
| 821 | + c.span, |
| 822 | + ); |
| 823 | + } |
| 824 | + if let DefKind::Effect(e) = &hir.def(*effect).kind { |
| 825 | + for op in &e.ops { |
| 826 | + if !ops.contains(op) { |
| 827 | + self.error( |
| 828 | + codes::MISSING_OPERATION, |
| 829 | + format!( |
| 830 | + "this handler for `{}` does not handle operation `{}`", |
| 831 | + hir.def(*effect).name, |
| 832 | + hir.def(*op).name |
| 833 | + ), |
| 834 | + range, |
| 835 | + ); |
| 836 | + } |
| 837 | + } |
| 838 | + } |
| 839 | + } |
| 840 | + |
| 841 | + // The body may perform the handled effect on top of the outer ones. |
| 842 | + let inner = match &label { |
| 843 | + Some((_, l)) => Ty::row(vec![l.clone()], outer.clone()), |
| 844 | + None => outer.clone(), |
| 845 | + }; |
| 846 | + self.effect = inner; |
| 703 | 847 | let body_ty = self.infer_expr(body); |
| 848 | + self.effect = outer.clone(); |
| 849 | + |
| 704 | 850 | let result = self.ctx.fresh(); |
| 705 | | − let has_return = clauses.iter().any(|c| c.is_return); |
| 706 | | − if !has_return { |
| 707 | | − self.coerce(&body_ty, &result, self.body.expr_span(body)); |
| 851 | + if !clauses.iter().any(|c| c.is_return) { |
| 852 | + self.coerce(&body_ty, &result, range); |
| 708 | 853 | } |
| 709 | 854 | for clause in clauses { |
| 710 | 855 | if clause.is_return { |
| @@ -716,38 +861,60 @@ impl<'a, 'h> FnInfer<'a, 'h> { |
| 716 | 861 | clause.span, |
| 717 | 862 | ), |
| 718 | 863 | } |
| 719 | | − } else if let Some(op) = clause.op { |
| 720 | | − let op_ty = self.instantiate_def(op, None, clause.span); |
| 721 | | − match self.ctx.shallow(&op_ty) { |
| 722 | | − Ty::Fn(params, op_ret, _) => { |
| 723 | | − if params.len() != clause.params.len() { |
| 724 | | − self.error( |
| 725 | | − codes::ARITY, |
| 726 | | − format!( |
| 727 | | − "this operation takes {} parameter{}", |
| 728 | | − params.len(), |
| 729 | | − plural(params.len()) |
| 730 | | − ), |
| 731 | | − clause.span, |
| 732 | | − ); |
| 733 | | − } |
| 734 | | − for (p, t) in clause.params.iter().zip(¶ms) { |
| 735 | | − self.check_pat(*p, t); |
| 736 | | − } |
| 737 | | − if let Some(resume) = clause.resume { |
| 738 | | − self.types.locals[resume.index()] = |
| 739 | | − Ty::func(vec![*op_ret], result.clone()); |
| 740 | | − } |
| 741 | | − } |
| 742 | | − _ => { |
| 743 | | − for p in &clause.params { |
| 744 | | − let t = self.ctx.fresh(); |
| 745 | | − self.check_pat(*p, &t); |
| 746 | | − } |
| 864 | + self.check_expr(clause.body, &result); |
| 865 | + continue; |
| 866 | + } |
| 867 | + let Some(op) = clause.op else { |
| 868 | + for p in &clause.params { |
| 869 | + let t = self.ctx.fresh(); |
| 870 | + self.check_pat(*p, &t); |
| 871 | + } |
| 872 | + self.check_expr(clause.body, &result); |
| 873 | + continue; |
| 874 | + }; |
| 875 | + let Some(scheme) = self.env.schemes.get(&op).cloned() else { |
| 876 | + continue; |
| 877 | + }; |
| 878 | + let (op_ty, _) = self.ctx.instantiate(&scheme); |
| 879 | + let Ty::Fn(params, op_ret, op_eff) = op_ty else { |
| 880 | + continue; |
| 881 | + }; |
| 882 | + // Tie the operation's effect arguments to the handled label. |
| 883 | + if let (Some((_, l)), (op_labels, _)) = (&label, self.ctx.row_parts(&op_eff)) |
| 884 | + && let Some(op_label) = op_labels.first() |
| 885 | + { |
| 886 | + let _ = self.ctx.unify(l, op_label); |
| 887 | + } |
| 888 | + if params.len() != clause.params.len() { |
| 889 | + self.error( |
| 890 | + codes::ARITY, |
| 891 | + format!( |
| 892 | + "operation `{}` takes {} parameter{}", |
| 893 | + hir.def(op).name, |
| 894 | + params.len(), |
| 895 | + plural(params.len()) |
| 896 | + ), |
| 897 | + clause.span, |
| 898 | + ); |
| 899 | + } |
| 900 | + for (p, t) in clause.params.iter().zip(¶ms) { |
| 901 | + self.check_pat(*p, t); |
| 902 | + } |
| 903 | + let kind = match &hir.def(op).kind { |
| 904 | + DefKind::Op(o) => o.kind, |
| 905 | + _ => continue, |
| 906 | + }; |
| 907 | + match kind { |
| 908 | + tilc_hir::OpKind::Fn => self.check_expr(clause.body, &op_ret), |
| 909 | + tilc_hir::OpKind::Ctl => { |
| 910 | + if let Some(resume) = clause.resume { |
| 911 | + self.types.locals[resume.index()] = |
| 912 | + Ty::func_eff(vec![*op_ret], result.clone(), outer.clone()); |
| 747 | 913 | } |
| 914 | + self.check_expr(clause.body, &result); |
| 748 | 915 | } |
| 916 | + tilc_hir::OpKind::FinalCtl => self.check_expr(clause.body, &result), |
| 749 | 917 | } |
| 750 | | − self.check_expr(clause.body, &result); |
| 751 | 918 | } |
| 752 | 919 | result |
| 753 | 920 | } |