| @@ -132,21 +132,50 @@ impl VarScope { |
| 132 | 132 | } |
| 133 | 133 | } |
| 134 | 134 | |
| 135 | | −/// An implementation of a trait for a named type (written or derived). |
| 135 | +/// An implementation of a trait (written or derived). |
| 136 | 136 | #[derive(Clone, Debug)] |
| 137 | 137 | pub struct ImplInfo { |
| 138 | 138 | /// The `impl` item; `None` for `@derive`d impls. |
| 139 | 139 | pub def: Option<DefId>, |
| 140 | 140 | pub trait_: DefId, |
| 141 | | − pub head: DefId, |
| 141 | + /// The named type at the head of each trait argument: `[Int, List]` |
| 142 | + /// for `impl Convert<Int, List<a>>`. Two impls of a trait overlap |
| 143 | + /// exactly when their heads are equal (ADR 0018). |
| 144 | + pub heads: Vec<DefId>, |
| 142 | 145 | /// The impl's type variables, bound as `Gen(i)`. |
| 143 | 146 | pub var_names: Vec<String>, |
| 144 | | − /// The implementing type is `Con(head, args)`; args are `Gen(0..n)`. |
| 147 | + /// The trait's arguments, one per trait parameter: `Con(head, vars)`, |
| 148 | + /// with the impl's variables as `Gen(i)`, each used once. |
| 145 | 149 | pub args: Vec<Ty>, |
| 146 | 150 | pub constraints: Vec<Constraint>, |
| 147 | 151 | pub span: Span, |
| 148 | 152 | } |
| 149 | 153 | |
| 154 | +impl ImplInfo { |
| 155 | + /// The types the impl's variables stand for, if its arguments match |
| 156 | + /// `args`. Impl arguments are named types applied to distinct |
| 157 | + /// variables, so matching is one-way and needs no unification. |
| 158 | + pub fn match_args(&self, args: &[Ty]) -> Option<Vec<Ty>> { |
| 159 | + if self.args.len() != args.len() { |
| 160 | + return None; |
| 161 | + } |
| 162 | + let mut subst = vec![None; self.var_names.len()]; |
| 163 | + for (pattern, ty) in self.args.iter().zip(args) { |
| 164 | + let (Ty::Con(p, pargs), Ty::Con(t, targs)) = (pattern, ty) else { |
| 165 | + return None; |
| 166 | + }; |
| 167 | + if p != t || pargs.len() != targs.len() { |
| 168 | + return None; |
| 169 | + } |
| 170 | + for (pa, ta) in pargs.iter().zip(targs) { |
| 171 | + let Ty::Gen(i) = pa else { return None }; |
| 172 | + subst[*i as usize] = Some(ta.clone()); |
| 173 | + } |
| 174 | + } |
| 175 | + subst.into_iter().collect() |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 150 | 179 | #[derive(Clone, Copy, PartialEq)] |
| 151 | 180 | enum AliasState { |
| 152 | 181 | InProgress, |
| @@ -456,13 +485,14 @@ impl<'h> Env<'h> { |
| 456 | 485 | self.alias_bodies.entry(def).or_insert(result).clone() |
| 457 | 486 | } |
| 458 | 487 | |
| 459 | | − /// Lower a `where` clause entry: `Trait<T>`. |
| 488 | + /// Lower a `where` clause entry: `Trait<T, ...>`, one type per trait |
| 489 | + /// parameter. |
| 460 | 490 | pub fn lower_constraint( |
| 461 | 491 | &mut self, |
| 462 | 492 | tref: &TypeRef, |
| 463 | 493 | file: FileId, |
| 464 | 494 | scope: &mut VarScope, |
| 465 | | − ictx: Option<&mut InferCtx>, |
| 495 | + mut ictx: Option<&mut InferCtx>, |
| 466 | 496 | diags: &mut Vec<Diagnostic>, |
| 467 | 497 | ) -> Option<Constraint> { |
| 468 | 498 | let TypeRef::Def { def, args, span } = tref else { |
| @@ -478,19 +508,38 @@ impl<'h> Env<'h> { |
| 478 | 508 | } |
| 479 | 509 | return None; |
| 480 | 510 | }; |
| 481 | | − if !matches!(self.hir.def(*def).kind, DefKind::Trait(_)) || args.len() != 1 { |
| 511 | + let data = self.hir.def(*def); |
| 512 | + let DefKind::Trait(t) = &data.kind else { |
| 482 | 513 | diags.push(Diagnostic::error( |
| 483 | 514 | codes::NOT_A_CONSTRAINT, |
| 484 | 515 | format!( |
| 485 | | − "expected a trait applied to one type, such as `Show<a>`, found `{}`", |
| 486 | | − self.hir.def(*def).name |
| 516 | + "expected a trait applied to types, such as `Show<a>`, found `{}`", |
| 517 | + data.name |
| 518 | + ), |
| 519 | + Span { file, range: *span }, |
| 520 | + )); |
| 521 | + return None; |
| 522 | + }; |
| 523 | + if args.len() != t.params.len() { |
| 524 | + diags.push(Diagnostic::error( |
| 525 | + codes::NOT_A_CONSTRAINT, |
| 526 | + format!( |
| 527 | + "trait `{}` takes {} type argument{}, but {} {} given", |
| 528 | + data.name, |
| 529 | + t.params.len(), |
| 530 | + if t.params.len() == 1 { "" } else { "s" }, |
| 531 | + args.len(), |
| 532 | + if args.len() == 1 { "was" } else { "were" } |
| 487 | 533 | ), |
| 488 | 534 | Span { file, range: *span }, |
| 489 | 535 | )); |
| 490 | 536 | return None; |
| 491 | 537 | } |
| 492 | | − let ty = self.lower_ty(&args[0], file, scope, ictx, diags); |
| 493 | | − Some(Constraint { trait_: *def, ty }) |
| 538 | + let args = args |
| 539 | + .iter() |
| 540 | + .map(|a| self.lower_ty(a, file, scope, ictx.as_deref_mut(), diags)) |
| 541 | + .collect(); |
| 542 | + Some(Constraint { trait_: *def, args }) |
| 494 | 543 | } |
| 495 | 544 | |
| 496 | 545 | /// Whether a signature is complete (all parameter and result types). |
| @@ -542,6 +591,47 @@ impl<'h> Env<'h> { |
| 542 | 591 | } |
| 543 | 592 | } |
| 544 | 593 | |
| 594 | + /// Every type variable of a scheme's constraints must appear in its |
| 595 | + /// type: the type arguments of a call are the only way to choose an |
| 596 | + /// impl (no functional dependencies, ADR 0018), so a variable that |
| 597 | + /// appears only in a constraint would make every call ambiguous. |
| 598 | + fn check_determined(&self, def: DefId, scheme: &Scheme, diags: &mut Vec<Diagnostic>) { |
| 599 | + let mut in_type = Vec::new(); |
| 600 | + scheme.ty.visit(&mut |t| { |
| 601 | + if let Ty::Gen(i) = t { |
| 602 | + in_type.push(*i); |
| 603 | + } |
| 604 | + }); |
| 605 | + let data = self.hir.def(def); |
| 606 | + let in_trait = matches!(&data.kind, DefKind::Fn(f) |
| 607 | + if f.owner.is_some_and(|o| matches!(self.hir.def(o).kind, DefKind::Trait(_)))); |
| 608 | + let mut reported = Vec::new(); |
| 609 | + for (k, c) in scheme.constraints.iter().enumerate() { |
| 610 | + for arg in &c.args { |
| 611 | + arg.visit(&mut |t| { |
| 612 | + let Ty::Gen(i) = t else { return }; |
| 613 | + if in_type.contains(i) || reported.contains(i) { |
| 614 | + return; |
| 615 | + } |
| 616 | + reported.push(*i); |
| 617 | + let var = &scheme.vars[*i as usize]; |
| 618 | + let message = if in_trait && k == 0 { |
| 619 | + format!( |
| 620 | + "method `{}` does not mention the trait's type parameter `{var}`, so no call can determine which impl to use", |
| 621 | + data.name |
| 622 | + ) |
| 623 | + } else { |
| 624 | + format!( |
| 625 | + "type variable `{var}` appears only in the `where` clause of `{}`, so no call can determine it", |
| 626 | + data.name |
| 627 | + ) |
| 628 | + }; |
| 629 | + diags.push(Diagnostic::error(codes::AMBIGUOUS, message, data.span)); |
| 630 | + }); |
| 631 | + } |
| 632 | + } |
| 633 | + } |
| 634 | + |
| 545 | 635 | /// Schemes of everything with a declared type: constructors, annotated |
| 546 | 636 | /// functions, trait methods, effect operations. |
| 547 | 637 | pub fn declare_schemes(&mut self, diags: &mut Vec<Diagnostic>) { |
| @@ -595,18 +685,25 @@ impl<'h> Env<'h> { |
| 595 | 685 | DefKind::Fn(f) => match f.owner.map(|o| &self.hir.def(o).kind) { |
| 596 | 686 | Some(DefKind::Trait(t)) => { |
| 597 | 687 | let owner = f.owner.expect("matched Some"); |
| 598 | | − if t.params.len() != 1 { |
| 599 | | − continue; // reported by check_traits |
| 688 | + if !trait_params_valid(t) { |
| 689 | + continue; // reported by collect_impls |
| 600 | 690 | } |
| 691 | + // The trait's own constraint comes first: its |
| 692 | + // dictionary holds the method (ADR 0007). |
| 601 | 693 | let constraint = Constraint { |
| 602 | 694 | trait_: owner, |
| 603 | | − ty: Ty::Gen(0), |
| 695 | + args: (0..t.params.len() as u32).map(Ty::Gen).collect(), |
| 604 | 696 | }; |
| 605 | | − self.sig_scheme(&f.sig, file, &t.params, vec![constraint], diags) |
| 697 | + let scheme = |
| 698 | + self.sig_scheme(&f.sig, file, &t.params, vec![constraint], diags); |
| 699 | + self.check_determined(id, &scheme, diags); |
| 700 | + scheme |
| 606 | 701 | } |
| 607 | 702 | Some(DefKind::Impl(_)) => continue, // checked against the trait |
| 608 | 703 | _ if Env::is_annotated(&f.sig) => { |
| 609 | | − self.sig_scheme(&f.sig, file, &[], Vec::new(), diags) |
| 704 | + let scheme = self.sig_scheme(&f.sig, file, &[], Vec::new(), diags); |
| 705 | + self.check_determined(id, &scheme, diags); |
| 706 | + scheme |
| 610 | 707 | } |
| 611 | 708 | _ => continue, // inferred |
| 612 | 709 | }, |
| @@ -643,14 +740,17 @@ impl<'h> Env<'h> { |
| 643 | 740 | } |
| 644 | 741 | |
| 645 | 742 | /// Validate traits and collect impls (written and derived), enforcing |
| 646 | | − /// coherence: one impl per (trait, type), in the trait's or the type's |
| 647 | | − /// module. |
| 743 | + /// coherence (ADR 0018): one impl per trait and tuple of head types, in |
| 744 | + /// the module of the trait or of one of the head types. |
| 648 | 745 | pub fn collect_impls(&mut self, diags: &mut Vec<Diagnostic>) { |
| 649 | 746 | for (id, data) in self.hir.defs.iter() { |
| 650 | 747 | match &data.kind { |
| 651 | | − DefKind::Trait(t) if t.params.len() != 1 => diags.push(Diagnostic::error( |
| 748 | + DefKind::Trait(t) if !trait_params_valid(t) => diags.push(Diagnostic::error( |
| 652 | 749 | codes::TRAIT_PARAMS, |
| 653 | | − format!("trait `{}` must have exactly one type parameter (v0 traits are single-parameter)", data.name), |
| 750 | + format!( |
| 751 | + "trait `{}` must have at least one type parameter, and its parameters must be distinct", |
| 752 | + data.name |
| 753 | + ), |
| 654 | 754 | data.span, |
| 655 | 755 | )), |
| 656 | 756 | DefKind::Impl(i) => { |
| @@ -671,15 +771,15 @@ impl<'h> Env<'h> { |
| 671 | 771 | )); |
| 672 | 772 | continue; |
| 673 | 773 | }; |
| 674 | | − let args: Vec<Ty> = (0..t.params.len() as u32).map(Ty::Gen).collect(); |
| 675 | | − let constraints = args.iter().map(|a| Constraint { trait_, ty: a.clone() }).collect(); |
| 774 | + let vars: Vec<Ty> = (0..t.params.len() as u32).map(Ty::Gen).collect(); |
| 775 | + let constraints = vars.iter().map(|v| Constraint::single(trait_, v.clone())).collect(); |
| 676 | 776 | self.add_impl( |
| 677 | 777 | ImplInfo { |
| 678 | 778 | def: None, |
| 679 | 779 | trait_, |
| 680 | | − head: id, |
| 780 | + heads: vec![id], |
| 681 | 781 | var_names: t.params.clone(), |
| 682 | | − args, |
| 782 | + args: vec![Ty::Con(id, vars)], |
| 683 | 783 | constraints, |
| 684 | 784 | span: data.span, |
| 685 | 785 | }, |
| @@ -693,6 +793,9 @@ impl<'h> Env<'h> { |
| 693 | 793 | } |
| 694 | 794 | } |
| 695 | 795 | |
| 796 | + /// Check an impl's shape (Haskell 98, generalized to several |
| 797 | + /// parameters): every trait argument is a named type applied to type |
| 798 | + /// variables, and no variable appears twice in the whole head. |
| 696 | 799 | fn impl_info( |
| 697 | 800 | &mut self, |
| 698 | 801 | id: DefId, |
| @@ -705,7 +808,7 @@ impl<'h> Env<'h> { |
| 705 | 808 | let shape_error = |diags: &mut Vec<Diagnostic>| { |
| 706 | 809 | diags.push(Diagnostic::error( |
| 707 | 810 | codes::IMPL_SHAPE, |
| 708 | | − "an impl must be `impl Trait<Type<a, b, ...>>`: a trait applied to a named type whose arguments are distinct type variables", |
| 811 | + "an impl must be `impl Trait<Type<a, b, ...>, ...>`: a trait applied to named types whose arguments are distinct type variables", |
| 709 | 812 | span, |
| 710 | 813 | )); |
| 711 | 814 | }; |
| @@ -720,38 +823,60 @@ impl<'h> Env<'h> { |
| 720 | 823 | } |
| 721 | 824 | return None; |
| 722 | 825 | }; |
| 723 | | − if !matches!(self.hir.def(*trait_).kind, DefKind::Trait(_)) || trait_args.len() != 1 { |
| 724 | | − shape_error(diags); |
| 725 | | − return None; |
| 726 | | − } |
| 727 | | − let TypeRef::Def { |
| 728 | | − def: head, |
| 729 | | − args: head_args, |
| 730 | | − .. |
| 731 | | − } = &trait_args[0] |
| 732 | | − else { |
| 826 | + let DefKind::Trait(t) = &self.hir.def(*trait_).kind else { |
| 733 | 827 | shape_error(diags); |
| 734 | 828 | return None; |
| 735 | 829 | }; |
| 830 | + if trait_args.len() != t.params.len() { |
| 831 | + diags.push(Diagnostic::error( |
| 832 | + codes::IMPL_SHAPE, |
| 833 | + format!( |
| 834 | + "trait `{}` takes {} type argument{}, but the impl gives {}", |
| 835 | + self.hir.def(*trait_).name, |
| 836 | + t.params.len(), |
| 837 | + if t.params.len() == 1 { "" } else { "s" }, |
| 838 | + trait_args.len() |
| 839 | + ), |
| 840 | + span, |
| 841 | + )); |
| 842 | + return None; |
| 843 | + } |
| 736 | 844 | let mut var_names = Vec::new(); |
| 737 | | − for a in head_args { |
| 738 | | − match a { |
| 739 | | − TypeRef::Var { name, .. } if !var_names.contains(name) => { |
| 740 | | − var_names.push(name.clone()) |
| 845 | + let mut heads = Vec::new(); |
| 846 | + let mut args = Vec::new(); |
| 847 | + for arg in trait_args { |
| 848 | + let TypeRef::Def { |
| 849 | + def: head, |
| 850 | + args: head_args, |
| 851 | + .. |
| 852 | + } = arg |
| 853 | + else { |
| 854 | + shape_error(diags); |
| 855 | + return None; |
| 856 | + }; |
| 857 | + let mut vars = Vec::new(); |
| 858 | + for a in head_args { |
| 859 | + match a { |
| 860 | + TypeRef::Var { name, .. } if !var_names.contains(name) => { |
| 861 | + vars.push(Ty::Gen(var_names.len() as u32)); |
| 862 | + var_names.push(name.clone()); |
| 863 | + } |
| 864 | + _ => { |
| 865 | + shape_error(diags); |
| 866 | + return None; |
| 867 | + } |
| 741 | 868 | } |
| 869 | + } |
| 870 | + match &self.hir.def(*head).kind { |
| 871 | + DefKind::Type(t) |
| 872 | + if !matches!(t.body, TypeBody::Alias(_)) && t.params.len() == vars.len() => {} |
| 742 | 873 | _ => { |
| 743 | 874 | shape_error(diags); |
| 744 | 875 | return None; |
| 745 | 876 | } |
| 746 | 877 | } |
| 747 | | − } |
| 748 | | − match &self.hir.def(*head).kind { |
| 749 | | − DefKind::Type(t) |
| 750 | | − if !matches!(t.body, TypeBody::Alias(_)) && t.params.len() == var_names.len() => {} |
| 751 | | − _ => { |
| 752 | | − shape_error(diags); |
| 753 | | − return None; |
| 754 | | − } |
| 878 | + heads.push(*head); |
| 879 | + args.push(Ty::Con(*head, vars)); |
| 755 | 880 | } |
| 756 | 881 | let mut scope = VarScope::with_params(VarMode::Gen, &var_names); |
| 757 | 882 | let constraints = constraints |
| @@ -771,26 +896,48 @@ impl<'h> Env<'h> { |
| 771 | 896 | Some(ImplInfo { |
| 772 | 897 | def: Some(id), |
| 773 | 898 | trait_: *trait_, |
| 774 | | − head: *head, |
| 775 | | − args: (0..var_names.len() as u32).map(Ty::Gen).collect(), |
| 899 | + heads, |
| 776 | 900 | var_names, |
| 901 | + args, |
| 777 | 902 | constraints, |
| 778 | 903 | span, |
| 779 | 904 | }) |
| 780 | 905 | } |
| 781 | 906 | |
| 907 | + /// `Color` for an impl of `Show<Color>`, `Int, String` for one of |
| 908 | + /// `Convert<Int, String>`. |
| 909 | + fn heads_shown(&self, info: &ImplInfo) -> String { |
| 910 | + let heads: Vec<&str> = info |
| 911 | + .heads |
| 912 | + .iter() |
| 913 | + .map(|h| self.hir.def(*h).name.as_str()) |
| 914 | + .collect(); |
| 915 | + heads.join(", ") |
| 916 | + } |
| 917 | + |
| 918 | + /// Coherence (ADR 0018). An impl lives in the module of its trait or |
| 919 | + /// of one of its head types. Since the impl names all of them, two |
| 920 | + /// modules defining the same impl would have to import each other, and |
| 921 | + /// the whole program is checked at once, so duplicates are always |
| 922 | + /// found here. |
| 782 | 923 | fn add_impl(&mut self, info: ImplInfo, diags: &mut Vec<Diagnostic>) { |
| 783 | 924 | let hir = self.hir; |
| 784 | 925 | let module = info |
| 785 | 926 | .def |
| 786 | | − .map_or(hir.def(info.head).module, |d| hir.def(d).module); |
| 787 | | − if module != hir.def(info.trait_).module && module != hir.def(info.head).module { |
| 927 | + .map_or(hir.def(info.heads[0]).module, |d| hir.def(d).module); |
| 928 | + let homes = std::iter::once(info.trait_).chain(info.heads.iter().copied()); |
| 929 | + if !homes.map(|d| hir.def(d).module).any(|m| m == module) { |
| 930 | + let one_of = if info.heads.len() == 1 { |
| 931 | + "of the type" |
| 932 | + } else { |
| 933 | + "of one of the types" |
| 934 | + }; |
| 788 | 935 | diags.push(Diagnostic::error( |
| 789 | 936 | codes::ORPHAN_IMPL, |
| 790 | 937 | format!( |
| 791 | | − "impl of `{}` for `{}` must be in the module of the trait or of the type", |
| 938 | + "impl of `{}` for `{}` must be in the module of the trait or {one_of}", |
| 792 | 939 | hir.def(info.trait_).name, |
| 793 | | − hir.def(info.head).name |
| 940 | + self.heads_shown(&info) |
| 794 | 941 | ), |
| 795 | 942 | info.span, |
| 796 | 943 | )); |
| @@ -799,7 +946,7 @@ impl<'h> Env<'h> { |
| 799 | 946 | if let Some(existing) = self |
| 800 | 947 | .impls |
| 801 | 948 | .iter() |
| 802 | | − .find(|i| i.trait_ == info.trait_ && i.head == info.head) |
| 949 | + .find(|i| i.trait_ == info.trait_ && i.heads == info.heads) |
| 803 | 950 | { |
| 804 | 951 | diags.push( |
| 805 | 952 | Diagnostic::error( |
| @@ -807,7 +954,7 @@ impl<'h> Env<'h> { |
| 807 | 954 | format!( |
| 808 | 955 | "`{}` is implemented more than once for `{}`", |
| 809 | 956 | hir.def(info.trait_).name, |
| 810 | | − hir.def(info.head).name |
| 957 | + self.heads_shown(&info) |
| 811 | 958 | ), |
| 812 | 959 | info.span, |
| 813 | 960 | ) |
| @@ -818,9 +965,28 @@ impl<'h> Env<'h> { |
| 818 | 965 | self.impls.push(info); |
| 819 | 966 | } |
| 820 | 967 | |
| 821 | | − pub fn find_impl(&self, trait_: DefId, head: DefId) -> Option<usize> { |
| 822 | | − self.impls |
| 823 | | − .iter() |
| 824 | | − .position(|i| i.trait_ == trait_ && i.head == head) |
| 968 | + /// The impl of `trait_` whose arguments match `args`, and the types |
| 969 | + /// its variables stand for. |
| 970 | + pub fn find_impl(&self, trait_: DefId, args: &[Ty]) -> Option<(usize, Vec<Ty>)> { |
| 971 | + find_impl(&self.impls, trait_, args) |
| 825 | 972 | } |
| 826 | 973 | } |
| 974 | + |
| 975 | +/// A trait has at least one type parameter, and they are distinct. |
| 976 | +fn trait_params_valid(t: &tilc_hir::TraitDef) -> bool { |
| 977 | + !t.params.is_empty() |
| 978 | + && t.params |
| 979 | + .iter() |
| 980 | + .enumerate() |
| 981 | + .all(|(i, p)| !t.params[..i].contains(p)) |
| 982 | +} |
| 983 | + |
| 984 | +/// The impl of `trait_` whose arguments match `args` (at most one, by |
| 985 | +/// coherence), and the types its variables stand for. |
| 986 | +pub fn find_impl(impls: &[ImplInfo], trait_: DefId, args: &[Ty]) -> Option<(usize, Vec<Ty>)> { |
| 987 | + impls |
| 988 | + .iter() |
| 989 | + .enumerate() |
| 990 | + .filter(|(_, i)| i.trait_ == trait_) |
| 991 | + .find_map(|(index, i)| i.match_args(args).map(|subst| (index, subst))) |
| 992 | +} |