diff options
Diffstat (limited to 'crates/ra_hir/src/ty')
-rw-r--r-- | crates/ra_hir/src/ty/infer.rs | 1164 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/coerce.rs | 336 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/expr.rs | 658 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/pat.rs | 180 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/unify.rs | 23 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/lower.rs | 39 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests.rs | 22 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits.rs | 2 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits/chalk.rs | 61 |
9 files changed, 1287 insertions, 1198 deletions
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index ca9aefc42..ebaff998e 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs | |||
@@ -14,7 +14,6 @@ | |||
14 | //! the `ena` crate, which is extracted from rustc. | 14 | //! the `ena` crate, which is extracted from rustc. |
15 | 15 | ||
16 | use std::borrow::Cow; | 16 | use std::borrow::Cow; |
17 | use std::iter::{repeat, repeat_with}; | ||
18 | use std::mem; | 17 | use std::mem; |
19 | use std::ops::Index; | 18 | use std::ops::Index; |
20 | use std::sync::Arc; | 19 | use std::sync::Arc; |
@@ -27,33 +26,39 @@ use ra_prof::profile; | |||
27 | use test_utils::tested_by; | 26 | use test_utils::tested_by; |
28 | 27 | ||
29 | use super::{ | 28 | use super::{ |
30 | autoderef, lower, method_resolution, op, primitive, | 29 | lower, primitive, |
31 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | 30 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, |
32 | ApplicationTy, CallableDef, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, | 31 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypableDef, |
33 | Ty, TypableDef, TypeCtor, TypeWalk, | 32 | TypeCtor, TypeWalk, |
34 | }; | 33 | }; |
35 | use crate::{ | 34 | use crate::{ |
36 | adt::VariantDef, | 35 | adt::VariantDef, |
37 | code_model::TypeAlias, | 36 | code_model::TypeAlias, |
38 | db::HirDatabase, | 37 | db::HirDatabase, |
39 | diagnostics::DiagnosticSink, | 38 | diagnostics::DiagnosticSink, |
40 | expr::{ | 39 | expr::{BindingAnnotation, Body, ExprId, PatId}, |
41 | self, Array, BinaryOp, BindingAnnotation, Body, Expr, ExprId, Literal, Pat, PatId, | ||
42 | RecordFieldPat, Statement, UnaryOp, | ||
43 | }, | ||
44 | generics::{GenericParams, HasGenericParams}, | ||
45 | lang_item::LangItemTarget, | ||
46 | name, | 40 | name, |
47 | nameres::Namespace, | 41 | path::known, |
48 | path::{known, GenericArg, GenericArgs}, | ||
49 | resolve::{Resolver, TypeNs}, | 42 | resolve::{Resolver, TypeNs}, |
50 | ty::infer::diagnostics::InferenceDiagnostic, | 43 | ty::infer::diagnostics::InferenceDiagnostic, |
51 | type_ref::{Mutability, TypeRef}, | 44 | type_ref::{Mutability, TypeRef}, |
52 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Name, Path, StructField, | 45 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Path, StructField, |
53 | }; | 46 | }; |
54 | 47 | ||
48 | macro_rules! ty_app { | ||
49 | ($ctor:pat, $param:pat) => { | ||
50 | crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
51 | }; | ||
52 | ($ctor:pat) => { | ||
53 | ty_app!($ctor, _) | ||
54 | }; | ||
55 | } | ||
56 | |||
55 | mod unify; | 57 | mod unify; |
56 | mod path; | 58 | mod path; |
59 | mod expr; | ||
60 | mod pat; | ||
61 | mod coerce; | ||
57 | 62 | ||
58 | /// The entry point of type inference. | 63 | /// The entry point of type inference. |
59 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { | 64 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { |
@@ -197,15 +202,6 @@ struct InferenceContext<'a, D: HirDatabase> { | |||
197 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | 202 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, |
198 | } | 203 | } |
199 | 204 | ||
200 | macro_rules! ty_app { | ||
201 | ($ctor:pat, $param:pat) => { | ||
202 | Ty::Apply(ApplicationTy { ctor: $ctor, parameters: $param }) | ||
203 | }; | ||
204 | ($ctor:pat) => { | ||
205 | ty_app!($ctor, _) | ||
206 | }; | ||
207 | } | ||
208 | |||
209 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | 205 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { |
210 | fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self { | 206 | fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self { |
211 | InferenceContext { | 207 | InferenceContext { |
@@ -221,45 +217,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
221 | } | 217 | } |
222 | } | 218 | } |
223 | 219 | ||
224 | fn init_coerce_unsized_map( | ||
225 | db: &'a D, | ||
226 | resolver: &Resolver, | ||
227 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
228 | let krate = resolver.krate().unwrap(); | ||
229 | let impls = match db.lang_item(krate, "coerce_unsized".into()) { | ||
230 | Some(LangItemTarget::Trait(trait_)) => db.impls_for_trait(krate, trait_), | ||
231 | _ => return FxHashMap::default(), | ||
232 | }; | ||
233 | |||
234 | impls | ||
235 | .iter() | ||
236 | .filter_map(|impl_block| { | ||
237 | // `CoerseUnsized` has one generic parameter for the target type. | ||
238 | let trait_ref = impl_block.target_trait_ref(db)?; | ||
239 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
240 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
241 | |||
242 | match (&cur_from_ty, cur_to_ty) { | ||
243 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
244 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
245 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
246 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
247 | match (ty1, ty2) { | ||
248 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
249 | if p1 != p2 => | ||
250 | { | ||
251 | Some(((*ctor1, *ctor2), i)) | ||
252 | } | ||
253 | _ => None, | ||
254 | } | ||
255 | }) | ||
256 | } | ||
257 | _ => None, | ||
258 | } | ||
259 | }) | ||
260 | .collect() | ||
261 | } | ||
262 | |||
263 | fn resolve_all(mut self) -> InferenceResult { | 220 | fn resolve_all(mut self) -> InferenceResult { |
264 | // FIXME resolve obligations as well (use Guidance if necessary) | 221 | // FIXME resolve obligations as well (use Guidance if necessary) |
265 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | 222 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); |
@@ -457,7 +414,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
457 | // recursive type | 414 | // recursive type |
458 | return tv.fallback_value(); | 415 | return tv.fallback_value(); |
459 | } | 416 | } |
460 | if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { | 417 | if let Some(known_ty) = |
418 | self.var_unification_table.inlined_probe_value(inner).known() | ||
419 | { | ||
461 | // known_ty may contain other variables that are known by now | 420 | // known_ty may contain other variables that are known by now |
462 | tv_stack.push(inner); | 421 | tv_stack.push(inner); |
463 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | 422 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); |
@@ -485,7 +444,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
485 | match &*ty { | 444 | match &*ty { |
486 | Ty::Infer(tv) => { | 445 | Ty::Infer(tv) => { |
487 | let inner = tv.to_inner(); | 446 | let inner = tv.to_inner(); |
488 | match self.var_unification_table.probe_value(inner).known() { | 447 | match self.var_unification_table.inlined_probe_value(inner).known() { |
489 | Some(known_ty) => { | 448 | Some(known_ty) => { |
490 | // The known_ty can't be a type var itself | 449 | // The known_ty can't be a type var itself |
491 | ty = Cow::Owned(known_ty.clone()); | 450 | ty = Cow::Owned(known_ty.clone()); |
@@ -533,7 +492,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
533 | // recursive type | 492 | // recursive type |
534 | return tv.fallback_value(); | 493 | return tv.fallback_value(); |
535 | } | 494 | } |
536 | if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { | 495 | if let Some(known_ty) = |
496 | self.var_unification_table.inlined_probe_value(inner).known() | ||
497 | { | ||
537 | // known_ty may contain other variables that are known by now | 498 | // known_ty may contain other variables that are known by now |
538 | tv_stack.push(inner); | 499 | tv_stack.push(inner); |
539 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | 500 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); |
@@ -559,6 +520,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
559 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | 520 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { |
560 | Some(TypeNs::Adt(Adt::Struct(it))) => it.into(), | 521 | Some(TypeNs::Adt(Adt::Struct(it))) => it.into(), |
561 | Some(TypeNs::Adt(Adt::Union(it))) => it.into(), | 522 | Some(TypeNs::Adt(Adt::Union(it))) => it.into(), |
523 | Some(TypeNs::AdtSelfType(adt)) => adt.into(), | ||
562 | Some(TypeNs::EnumVariant(it)) => it.into(), | 524 | Some(TypeNs::EnumVariant(it)) => it.into(), |
563 | Some(TypeNs::TypeAlias(it)) => it.into(), | 525 | Some(TypeNs::TypeAlias(it)) => it.into(), |
564 | 526 | ||
@@ -594,1080 +556,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
594 | } | 556 | } |
595 | } | 557 | } |
596 | 558 | ||
597 | fn infer_tuple_struct_pat( | ||
598 | &mut self, | ||
599 | path: Option<&Path>, | ||
600 | subpats: &[PatId], | ||
601 | expected: &Ty, | ||
602 | default_bm: BindingMode, | ||
603 | ) -> Ty { | ||
604 | let (ty, def) = self.resolve_variant(path); | ||
605 | |||
606 | self.unify(&ty, expected); | ||
607 | |||
608 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
609 | |||
610 | for (i, &subpat) in subpats.iter().enumerate() { | ||
611 | let expected_ty = def | ||
612 | .and_then(|d| d.field(self.db, &Name::new_tuple_field(i))) | ||
613 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
614 | .subst(&substs); | ||
615 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
616 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
617 | } | ||
618 | |||
619 | ty | ||
620 | } | ||
621 | |||
622 | fn infer_record_pat( | ||
623 | &mut self, | ||
624 | path: Option<&Path>, | ||
625 | subpats: &[RecordFieldPat], | ||
626 | expected: &Ty, | ||
627 | default_bm: BindingMode, | ||
628 | id: PatId, | ||
629 | ) -> Ty { | ||
630 | let (ty, def) = self.resolve_variant(path); | ||
631 | if let Some(variant) = def { | ||
632 | self.write_variant_resolution(id.into(), variant); | ||
633 | } | ||
634 | |||
635 | self.unify(&ty, expected); | ||
636 | |||
637 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
638 | |||
639 | for subpat in subpats { | ||
640 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | ||
641 | let expected_ty = | ||
642 | matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs); | ||
643 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
644 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
645 | } | ||
646 | |||
647 | ty | ||
648 | } | ||
649 | |||
650 | fn infer_pat(&mut self, pat: PatId, mut expected: &Ty, mut default_bm: BindingMode) -> Ty { | ||
651 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
652 | |||
653 | let is_non_ref_pat = match &body[pat] { | ||
654 | Pat::Tuple(..) | ||
655 | | Pat::TupleStruct { .. } | ||
656 | | Pat::Record { .. } | ||
657 | | Pat::Range { .. } | ||
658 | | Pat::Slice { .. } => true, | ||
659 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
660 | Pat::Path(..) | Pat::Lit(..) => true, | ||
661 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
662 | }; | ||
663 | if is_non_ref_pat { | ||
664 | while let Some((inner, mutability)) = expected.as_reference() { | ||
665 | expected = inner; | ||
666 | default_bm = match default_bm { | ||
667 | BindingMode::Move => BindingMode::Ref(mutability), | ||
668 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
669 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
670 | } | ||
671 | } | ||
672 | } else if let Pat::Ref { .. } = &body[pat] { | ||
673 | tested_by!(match_ergonomics_ref); | ||
674 | // When you encounter a `&pat` pattern, reset to Move. | ||
675 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
676 | default_bm = BindingMode::Move; | ||
677 | } | ||
678 | |||
679 | // Lose mutability. | ||
680 | let default_bm = default_bm; | ||
681 | let expected = expected; | ||
682 | |||
683 | let ty = match &body[pat] { | ||
684 | Pat::Tuple(ref args) => { | ||
685 | let expectations = match expected.as_tuple() { | ||
686 | Some(parameters) => &*parameters.0, | ||
687 | _ => &[], | ||
688 | }; | ||
689 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
690 | |||
691 | let inner_tys = args | ||
692 | .iter() | ||
693 | .zip(expectations_iter) | ||
694 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
695 | .collect(); | ||
696 | |||
697 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
698 | } | ||
699 | Pat::Ref { pat, mutability } => { | ||
700 | let expectation = match expected.as_reference() { | ||
701 | Some((inner_ty, exp_mut)) => { | ||
702 | if *mutability != exp_mut { | ||
703 | // FIXME: emit type error? | ||
704 | } | ||
705 | inner_ty | ||
706 | } | ||
707 | _ => &Ty::Unknown, | ||
708 | }; | ||
709 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
710 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
711 | } | ||
712 | Pat::TupleStruct { path: p, args: subpats } => { | ||
713 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
714 | } | ||
715 | Pat::Record { path: p, args: fields } => { | ||
716 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
717 | } | ||
718 | Pat::Path(path) => { | ||
719 | // FIXME use correct resolver for the surrounding expression | ||
720 | let resolver = self.resolver.clone(); | ||
721 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
722 | } | ||
723 | Pat::Bind { mode, name: _, subpat } => { | ||
724 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
725 | default_bm | ||
726 | } else { | ||
727 | BindingMode::convert(*mode) | ||
728 | }; | ||
729 | let inner_ty = if let Some(subpat) = subpat { | ||
730 | self.infer_pat(*subpat, expected, default_bm) | ||
731 | } else { | ||
732 | expected.clone() | ||
733 | }; | ||
734 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
735 | |||
736 | let bound_ty = match mode { | ||
737 | BindingMode::Ref(mutability) => { | ||
738 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
739 | } | ||
740 | BindingMode::Move => inner_ty.clone(), | ||
741 | }; | ||
742 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
743 | self.write_pat_ty(pat, bound_ty); | ||
744 | return inner_ty; | ||
745 | } | ||
746 | _ => Ty::Unknown, | ||
747 | }; | ||
748 | // use a new type variable if we got Ty::Unknown here | ||
749 | let ty = self.insert_type_vars_shallow(ty); | ||
750 | self.unify(&ty, expected); | ||
751 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
752 | self.write_pat_ty(pat, ty.clone()); | ||
753 | ty | ||
754 | } | ||
755 | |||
756 | fn substs_for_method_call( | ||
757 | &mut self, | ||
758 | def_generics: Option<Arc<GenericParams>>, | ||
759 | generic_args: Option<&GenericArgs>, | ||
760 | receiver_ty: &Ty, | ||
761 | ) -> Substs { | ||
762 | let (parent_param_count, param_count) = | ||
763 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
764 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
765 | // Parent arguments are unknown, except for the receiver type | ||
766 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
767 | for param in &parent_generics.params { | ||
768 | if param.name == name::SELF_TYPE { | ||
769 | substs.push(receiver_ty.clone()); | ||
770 | } else { | ||
771 | substs.push(Ty::Unknown); | ||
772 | } | ||
773 | } | ||
774 | } | ||
775 | // handle provided type arguments | ||
776 | if let Some(generic_args) = generic_args { | ||
777 | // if args are provided, it should be all of them, but we can't rely on that | ||
778 | for arg in generic_args.args.iter().take(param_count) { | ||
779 | match arg { | ||
780 | GenericArg::Type(type_ref) => { | ||
781 | let ty = self.make_ty(type_ref); | ||
782 | substs.push(ty); | ||
783 | } | ||
784 | } | ||
785 | } | ||
786 | }; | ||
787 | let supplied_params = substs.len(); | ||
788 | for _ in supplied_params..parent_param_count + param_count { | ||
789 | substs.push(Ty::Unknown); | ||
790 | } | ||
791 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
792 | Substs(substs.into()) | ||
793 | } | ||
794 | |||
795 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
796 | if let Ty::Apply(a_ty) = callable_ty { | ||
797 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
798 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
799 | for predicate in generic_predicates.iter() { | ||
800 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
801 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
802 | self.obligations.push(obligation); | ||
803 | } | ||
804 | } | ||
805 | // add obligation for trait implementation, if this is a trait method | ||
806 | match def { | ||
807 | CallableDef::Function(f) => { | ||
808 | if let Some(trait_) = f.parent_trait(self.db) { | ||
809 | // construct a TraitDef | ||
810 | let substs = a_ty.parameters.prefix( | ||
811 | trait_.generic_params(self.db).count_params_including_parent(), | ||
812 | ); | ||
813 | self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); | ||
814 | } | ||
815 | } | ||
816 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {} | ||
817 | } | ||
818 | } | ||
819 | } | ||
820 | } | ||
821 | |||
822 | fn infer_method_call( | ||
823 | &mut self, | ||
824 | tgt_expr: ExprId, | ||
825 | receiver: ExprId, | ||
826 | args: &[ExprId], | ||
827 | method_name: &Name, | ||
828 | generic_args: Option<&GenericArgs>, | ||
829 | ) -> Ty { | ||
830 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
831 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
832 | let resolved = method_resolution::lookup_method( | ||
833 | &canonicalized_receiver.value, | ||
834 | self.db, | ||
835 | method_name, | ||
836 | &self.resolver, | ||
837 | ); | ||
838 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
839 | Some((ty, func)) => { | ||
840 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
841 | self.write_method_resolution(tgt_expr, func); | ||
842 | ( | ||
843 | ty, | ||
844 | self.db.type_for_def(func.into(), Namespace::Values), | ||
845 | Some(func.generic_params(self.db)), | ||
846 | ) | ||
847 | } | ||
848 | None => (receiver_ty, Ty::Unknown, None), | ||
849 | }; | ||
850 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
851 | let method_ty = method_ty.apply_substs(substs); | ||
852 | let method_ty = self.insert_type_vars(method_ty); | ||
853 | self.register_obligations_for_call(&method_ty); | ||
854 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
855 | Some(sig) => { | ||
856 | if !sig.params().is_empty() { | ||
857 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
858 | } else { | ||
859 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
860 | } | ||
861 | } | ||
862 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
863 | }; | ||
864 | // Apply autoref so the below unification works correctly | ||
865 | // FIXME: return correct autorefs from lookup_method | ||
866 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
867 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
868 | _ => derefed_receiver_ty, | ||
869 | }; | ||
870 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
871 | |||
872 | self.check_call_arguments(args, ¶m_tys); | ||
873 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
874 | ret_ty | ||
875 | } | ||
876 | |||
877 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
878 | /// Return the type after possible coercion. | ||
879 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
880 | let ty = self.infer_expr_inner(expr, &expected); | ||
881 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
882 | self.result | ||
883 | .type_mismatches | ||
884 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
885 | // Return actual type when type mismatch. | ||
886 | // This is needed for diagnostic when return type mismatch. | ||
887 | ty | ||
888 | } else if expected.ty == Ty::Unknown { | ||
889 | ty | ||
890 | } else { | ||
891 | expected.ty.clone() | ||
892 | }; | ||
893 | |||
894 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
895 | } | ||
896 | |||
897 | /// Merge two types from different branches, with possible implicit coerce. | ||
898 | /// | ||
899 | /// Note that it is only possible that one type are coerced to another. | ||
900 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
901 | /// which will simply result in "incompatible types" error. | ||
902 | fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
903 | if self.coerce(ty1, ty2) { | ||
904 | ty2.clone() | ||
905 | } else if self.coerce(ty2, ty1) { | ||
906 | ty1.clone() | ||
907 | } else { | ||
908 | tested_by!(coerce_merge_fail_fallback); | ||
909 | // For incompatible types, we use the latter one as result | ||
910 | // to be better recovery for `if` without `else`. | ||
911 | ty2.clone() | ||
912 | } | ||
913 | } | ||
914 | |||
915 | /// Unify two types, but may coerce the first one to the second one | ||
916 | /// using "implicit coercion rules" if needed. | ||
917 | /// | ||
918 | /// See: https://doc.rust-lang.org/nomicon/coercions.html | ||
919 | fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
920 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
921 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
922 | self.coerce_inner(from_ty, &to_ty) | ||
923 | } | ||
924 | |||
925 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
926 | match (&from_ty, to_ty) { | ||
927 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
928 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
929 | let var = self.new_maybe_never_type_var(); | ||
930 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
931 | return true; | ||
932 | } | ||
933 | (ty_app!(TypeCtor::Never), _) => return true, | ||
934 | |||
935 | // Trivial cases, this should go after `never` check to | ||
936 | // avoid infer result type to be never | ||
937 | _ => { | ||
938 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
939 | return true; | ||
940 | } | ||
941 | } | ||
942 | } | ||
943 | |||
944 | // Pointer weakening and function to pointer | ||
945 | match (&mut from_ty, to_ty) { | ||
946 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
947 | // `&mut T` -> `&T` | ||
948 | // `&mut T` -> `*mut T` | ||
949 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
950 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
951 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
952 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
953 | *c1 = *c2; | ||
954 | } | ||
955 | |||
956 | // Illegal mutablity conversion | ||
957 | ( | ||
958 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
959 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
960 | ) | ||
961 | | ( | ||
962 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
963 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
964 | ) => return false, | ||
965 | |||
966 | // `{function_type}` -> `fn()` | ||
967 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
968 | match from_ty.callable_sig(self.db) { | ||
969 | None => return false, | ||
970 | Some(sig) => { | ||
971 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
972 | from_ty = | ||
973 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
974 | } | ||
975 | } | ||
976 | } | ||
977 | |||
978 | _ => {} | ||
979 | } | ||
980 | |||
981 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
982 | return ret; | ||
983 | } | ||
984 | |||
985 | // Auto Deref if cannot coerce | ||
986 | match (&from_ty, to_ty) { | ||
987 | // FIXME: DerefMut | ||
988 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
989 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
990 | } | ||
991 | |||
992 | // Otherwise, normal unify | ||
993 | _ => self.unify(&from_ty, to_ty), | ||
994 | } | ||
995 | } | ||
996 | |||
997 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
998 | /// | ||
999 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
1000 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
1001 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
1002 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
1003 | _ => return None, | ||
1004 | }; | ||
1005 | |||
1006 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
1007 | |||
1008 | // Check `Unsize` first | ||
1009 | match self.check_unsize_and_coerce( | ||
1010 | st1.0.get(coerce_generic_index)?, | ||
1011 | st2.0.get(coerce_generic_index)?, | ||
1012 | 0, | ||
1013 | ) { | ||
1014 | Some(true) => {} | ||
1015 | ret => return ret, | ||
1016 | } | ||
1017 | |||
1018 | let ret = st1 | ||
1019 | .iter() | ||
1020 | .zip(st2.iter()) | ||
1021 | .enumerate() | ||
1022 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
1023 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
1024 | |||
1025 | Some(ret) | ||
1026 | } | ||
1027 | |||
1028 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
1029 | /// | ||
1030 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
1031 | /// | ||
1032 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
1033 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
1034 | if depth > 1000 { | ||
1035 | panic!("Infinite recursion in coercion"); | ||
1036 | } | ||
1037 | |||
1038 | match (&from_ty, &to_ty) { | ||
1039 | // `[T; N]` -> `[T]` | ||
1040 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
1041 | Some(self.unify(&st1[0], &st2[0])) | ||
1042 | } | ||
1043 | |||
1044 | // `T` -> `dyn Trait` when `T: Trait` | ||
1045 | (_, Ty::Dyn(_)) => { | ||
1046 | // FIXME: Check predicates | ||
1047 | Some(true) | ||
1048 | } | ||
1049 | |||
1050 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
1051 | ( | ||
1052 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
1053 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
1054 | ) => { | ||
1055 | if len1 != len2 || *len1 == 0 { | ||
1056 | return None; | ||
1057 | } | ||
1058 | |||
1059 | match self.check_unsize_and_coerce( | ||
1060 | st1.last().unwrap(), | ||
1061 | st2.last().unwrap(), | ||
1062 | depth + 1, | ||
1063 | ) { | ||
1064 | Some(true) => {} | ||
1065 | ret => return ret, | ||
1066 | } | ||
1067 | |||
1068 | let ret = st1[..st1.len() - 1] | ||
1069 | .iter() | ||
1070 | .zip(&st2[..st2.len() - 1]) | ||
1071 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
1072 | |||
1073 | Some(ret) | ||
1074 | } | ||
1075 | |||
1076 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
1077 | // - T: Unsize<U> | ||
1078 | // - Foo is a struct | ||
1079 | // - Only the last field of Foo has a type involving T | ||
1080 | // - T is not part of the type of any other fields | ||
1081 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
1082 | ( | ||
1083 | ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1), | ||
1084 | ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2), | ||
1085 | ) if struct1 == struct2 => { | ||
1086 | let fields = struct1.fields(self.db); | ||
1087 | let (last_field, prev_fields) = fields.split_last()?; | ||
1088 | |||
1089 | // Get the generic parameter involved in the last field. | ||
1090 | let unsize_generic_index = { | ||
1091 | let mut index = None; | ||
1092 | let mut multiple_param = false; | ||
1093 | last_field.ty(self.db).walk(&mut |ty| match ty { | ||
1094 | &Ty::Param { idx, .. } => { | ||
1095 | if index.is_none() { | ||
1096 | index = Some(idx); | ||
1097 | } else if Some(idx) != index { | ||
1098 | multiple_param = true; | ||
1099 | } | ||
1100 | } | ||
1101 | _ => {} | ||
1102 | }); | ||
1103 | |||
1104 | if multiple_param { | ||
1105 | return None; | ||
1106 | } | ||
1107 | index? | ||
1108 | }; | ||
1109 | |||
1110 | // Check other fields do not involve it. | ||
1111 | let mut multiple_used = false; | ||
1112 | prev_fields.iter().for_each(|field| { | ||
1113 | field.ty(self.db).walk(&mut |ty| match ty { | ||
1114 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
1115 | multiple_used = true | ||
1116 | } | ||
1117 | _ => {} | ||
1118 | }) | ||
1119 | }); | ||
1120 | if multiple_used { | ||
1121 | return None; | ||
1122 | } | ||
1123 | |||
1124 | let unsize_generic_index = unsize_generic_index as usize; | ||
1125 | |||
1126 | // Check `Unsize` first | ||
1127 | match self.check_unsize_and_coerce( | ||
1128 | st1.get(unsize_generic_index)?, | ||
1129 | st2.get(unsize_generic_index)?, | ||
1130 | depth + 1, | ||
1131 | ) { | ||
1132 | Some(true) => {} | ||
1133 | ret => return ret, | ||
1134 | } | ||
1135 | |||
1136 | // Then unify other parameters | ||
1137 | let ret = st1 | ||
1138 | .iter() | ||
1139 | .zip(st2.iter()) | ||
1140 | .enumerate() | ||
1141 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
1142 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
1143 | |||
1144 | Some(ret) | ||
1145 | } | ||
1146 | |||
1147 | _ => None, | ||
1148 | } | ||
1149 | } | ||
1150 | |||
1151 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
1152 | /// | ||
1153 | /// Note that the parameters are already stripped the outer reference. | ||
1154 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
1155 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
1156 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
1157 | // FIXME: Auto DerefMut | ||
1158 | for derefed_ty in | ||
1159 | autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone()) | ||
1160 | { | ||
1161 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
1162 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
1163 | // Stop when constructor matches. | ||
1164 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
1165 | // It will not recurse to `coerce`. | ||
1166 | return self.unify_substs(st1, st2, 0); | ||
1167 | } | ||
1168 | _ => {} | ||
1169 | } | ||
1170 | } | ||
1171 | |||
1172 | false | ||
1173 | } | ||
1174 | |||
1175 | fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
1176 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
1177 | let could_unify = self.unify(&ty, &expected.ty); | ||
1178 | if !could_unify { | ||
1179 | self.result.type_mismatches.insert( | ||
1180 | tgt_expr, | ||
1181 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
1182 | ); | ||
1183 | } | ||
1184 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1185 | ty | ||
1186 | } | ||
1187 | |||
1188 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
1189 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
1190 | let ty = match &body[tgt_expr] { | ||
1191 | Expr::Missing => Ty::Unknown, | ||
1192 | Expr::If { condition, then_branch, else_branch } => { | ||
1193 | // if let is desugared to match, so this is always simple if | ||
1194 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
1195 | |||
1196 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
1197 | let else_ty = match else_branch { | ||
1198 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
1199 | None => Ty::unit(), | ||
1200 | }; | ||
1201 | |||
1202 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
1203 | } | ||
1204 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
1205 | Expr::TryBlock { body } => { | ||
1206 | let _inner = self.infer_expr(*body, expected); | ||
1207 | // FIXME should be std::result::Result<{inner}, _> | ||
1208 | Ty::Unknown | ||
1209 | } | ||
1210 | Expr::Loop { body } => { | ||
1211 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1212 | // FIXME handle break with value | ||
1213 | Ty::simple(TypeCtor::Never) | ||
1214 | } | ||
1215 | Expr::While { condition, body } => { | ||
1216 | // while let is desugared to a match loop, so this is always simple while | ||
1217 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
1218 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1219 | Ty::unit() | ||
1220 | } | ||
1221 | Expr::For { iterable, body, pat } => { | ||
1222 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
1223 | |||
1224 | let pat_ty = match self.resolve_into_iter_item() { | ||
1225 | Some(into_iter_item_alias) => { | ||
1226 | let pat_ty = self.new_type_var(); | ||
1227 | let projection = ProjectionPredicate { | ||
1228 | ty: pat_ty.clone(), | ||
1229 | projection_ty: ProjectionTy { | ||
1230 | associated_ty: into_iter_item_alias, | ||
1231 | parameters: Substs::single(iterable_ty), | ||
1232 | }, | ||
1233 | }; | ||
1234 | self.obligations.push(Obligation::Projection(projection)); | ||
1235 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
1236 | } | ||
1237 | None => Ty::Unknown, | ||
1238 | }; | ||
1239 | |||
1240 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
1241 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1242 | Ty::unit() | ||
1243 | } | ||
1244 | Expr::Lambda { body, args, arg_types } => { | ||
1245 | assert_eq!(args.len(), arg_types.len()); | ||
1246 | |||
1247 | let mut sig_tys = Vec::new(); | ||
1248 | |||
1249 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
1250 | let expected = if let Some(type_ref) = arg_type { | ||
1251 | self.make_ty(type_ref) | ||
1252 | } else { | ||
1253 | Ty::Unknown | ||
1254 | }; | ||
1255 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
1256 | sig_tys.push(arg_ty); | ||
1257 | } | ||
1258 | |||
1259 | // add return type | ||
1260 | let ret_ty = self.new_type_var(); | ||
1261 | sig_tys.push(ret_ty.clone()); | ||
1262 | let sig_ty = Ty::apply( | ||
1263 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
1264 | Substs(sig_tys.into()), | ||
1265 | ); | ||
1266 | let closure_ty = Ty::apply_one( | ||
1267 | TypeCtor::Closure { def: self.body.owner(), expr: tgt_expr }, | ||
1268 | sig_ty, | ||
1269 | ); | ||
1270 | |||
1271 | // Eagerly try to relate the closure type with the expected | ||
1272 | // type, otherwise we often won't have enough information to | ||
1273 | // infer the body. | ||
1274 | self.coerce(&closure_ty, &expected.ty); | ||
1275 | |||
1276 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
1277 | closure_ty | ||
1278 | } | ||
1279 | Expr::Call { callee, args } => { | ||
1280 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
1281 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
1282 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
1283 | None => { | ||
1284 | // Not callable | ||
1285 | // FIXME: report an error | ||
1286 | (Vec::new(), Ty::Unknown) | ||
1287 | } | ||
1288 | }; | ||
1289 | self.register_obligations_for_call(&callee_ty); | ||
1290 | self.check_call_arguments(args, ¶m_tys); | ||
1291 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
1292 | ret_ty | ||
1293 | } | ||
1294 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
1295 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
1296 | Expr::Match { expr, arms } => { | ||
1297 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1298 | |||
1299 | let mut result_ty = self.new_maybe_never_type_var(); | ||
1300 | |||
1301 | for arm in arms { | ||
1302 | for &pat in &arm.pats { | ||
1303 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
1304 | } | ||
1305 | if let Some(guard_expr) = arm.guard { | ||
1306 | self.infer_expr( | ||
1307 | guard_expr, | ||
1308 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
1309 | ); | ||
1310 | } | ||
1311 | |||
1312 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
1313 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
1314 | } | ||
1315 | |||
1316 | result_ty | ||
1317 | } | ||
1318 | Expr::Path(p) => { | ||
1319 | // FIXME this could be more efficient... | ||
1320 | let resolver = expr::resolver_for_expr(self.body.clone(), self.db, tgt_expr); | ||
1321 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
1322 | } | ||
1323 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
1324 | Expr::Break { expr } => { | ||
1325 | if let Some(expr) = expr { | ||
1326 | // FIXME handle break with value | ||
1327 | self.infer_expr(*expr, &Expectation::none()); | ||
1328 | } | ||
1329 | Ty::simple(TypeCtor::Never) | ||
1330 | } | ||
1331 | Expr::Return { expr } => { | ||
1332 | if let Some(expr) = expr { | ||
1333 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
1334 | } | ||
1335 | Ty::simple(TypeCtor::Never) | ||
1336 | } | ||
1337 | Expr::RecordLit { path, fields, spread } => { | ||
1338 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
1339 | if let Some(variant) = def_id { | ||
1340 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
1341 | } | ||
1342 | |||
1343 | self.unify(&ty, &expected.ty); | ||
1344 | |||
1345 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
1346 | for (field_idx, field) in fields.iter().enumerate() { | ||
1347 | let field_ty = def_id | ||
1348 | .and_then(|it| match it.field(self.db, &field.name) { | ||
1349 | Some(field) => Some(field), | ||
1350 | None => { | ||
1351 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
1352 | expr: tgt_expr, | ||
1353 | field: field_idx, | ||
1354 | }); | ||
1355 | None | ||
1356 | } | ||
1357 | }) | ||
1358 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
1359 | .subst(&substs); | ||
1360 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
1361 | } | ||
1362 | if let Some(expr) = spread { | ||
1363 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
1364 | } | ||
1365 | ty | ||
1366 | } | ||
1367 | Expr::Field { expr, name } => { | ||
1368 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1369 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
1370 | let ty = autoderef::autoderef( | ||
1371 | self.db, | ||
1372 | &self.resolver.clone(), | ||
1373 | canonicalized.value.clone(), | ||
1374 | ) | ||
1375 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
1376 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1377 | TypeCtor::Tuple { .. } => name | ||
1378 | .as_tuple_index() | ||
1379 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
1380 | TypeCtor::Adt(Adt::Struct(s)) => s.field(self.db, name).map(|field| { | ||
1381 | self.write_field_resolution(tgt_expr, field); | ||
1382 | field.ty(self.db).subst(&a_ty.parameters) | ||
1383 | }), | ||
1384 | _ => None, | ||
1385 | }, | ||
1386 | _ => None, | ||
1387 | }) | ||
1388 | .unwrap_or(Ty::Unknown); | ||
1389 | let ty = self.insert_type_vars(ty); | ||
1390 | self.normalize_associated_types_in(ty) | ||
1391 | } | ||
1392 | Expr::Await { expr } => { | ||
1393 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1394 | let ty = match self.resolve_future_future_output() { | ||
1395 | Some(future_future_output_alias) => { | ||
1396 | let ty = self.new_type_var(); | ||
1397 | let projection = ProjectionPredicate { | ||
1398 | ty: ty.clone(), | ||
1399 | projection_ty: ProjectionTy { | ||
1400 | associated_ty: future_future_output_alias, | ||
1401 | parameters: Substs::single(inner_ty), | ||
1402 | }, | ||
1403 | }; | ||
1404 | self.obligations.push(Obligation::Projection(projection)); | ||
1405 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
1406 | } | ||
1407 | None => Ty::Unknown, | ||
1408 | }; | ||
1409 | ty | ||
1410 | } | ||
1411 | Expr::Try { expr } => { | ||
1412 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1413 | let ty = match self.resolve_ops_try_ok() { | ||
1414 | Some(ops_try_ok_alias) => { | ||
1415 | let ty = self.new_type_var(); | ||
1416 | let projection = ProjectionPredicate { | ||
1417 | ty: ty.clone(), | ||
1418 | projection_ty: ProjectionTy { | ||
1419 | associated_ty: ops_try_ok_alias, | ||
1420 | parameters: Substs::single(inner_ty), | ||
1421 | }, | ||
1422 | }; | ||
1423 | self.obligations.push(Obligation::Projection(projection)); | ||
1424 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
1425 | } | ||
1426 | None => Ty::Unknown, | ||
1427 | }; | ||
1428 | ty | ||
1429 | } | ||
1430 | Expr::Cast { expr, type_ref } => { | ||
1431 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1432 | let cast_ty = self.make_ty(type_ref); | ||
1433 | // FIXME check the cast... | ||
1434 | cast_ty | ||
1435 | } | ||
1436 | Expr::Ref { expr, mutability } => { | ||
1437 | let expectation = | ||
1438 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
1439 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
1440 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
1441 | // which cannot be coerced | ||
1442 | } | ||
1443 | Expectation::has_type(Ty::clone(exp_inner)) | ||
1444 | } else { | ||
1445 | Expectation::none() | ||
1446 | }; | ||
1447 | // FIXME reference coercions etc. | ||
1448 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
1449 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
1450 | } | ||
1451 | Expr::Box { expr } => { | ||
1452 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1453 | if let Some(box_) = self.resolve_boxed_box() { | ||
1454 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
1455 | } else { | ||
1456 | Ty::Unknown | ||
1457 | } | ||
1458 | } | ||
1459 | Expr::UnaryOp { expr, op } => { | ||
1460 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1461 | match op { | ||
1462 | UnaryOp::Deref => { | ||
1463 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
1464 | if let Some(derefed_ty) = | ||
1465 | autoderef::deref(self.db, &self.resolver, &canonicalized.value) | ||
1466 | { | ||
1467 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
1468 | } else { | ||
1469 | Ty::Unknown | ||
1470 | } | ||
1471 | } | ||
1472 | UnaryOp::Neg => { | ||
1473 | match &inner_ty { | ||
1474 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1475 | TypeCtor::Int(primitive::UncertainIntTy::Unknown) | ||
1476 | | TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
1477 | primitive::IntTy { | ||
1478 | signedness: primitive::Signedness::Signed, | ||
1479 | .. | ||
1480 | }, | ||
1481 | )) | ||
1482 | | TypeCtor::Float(..) => inner_ty, | ||
1483 | _ => Ty::Unknown, | ||
1484 | }, | ||
1485 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
1486 | inner_ty | ||
1487 | } | ||
1488 | // FIXME: resolve ops::Neg trait | ||
1489 | _ => Ty::Unknown, | ||
1490 | } | ||
1491 | } | ||
1492 | UnaryOp::Not => { | ||
1493 | match &inner_ty { | ||
1494 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1495 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
1496 | _ => Ty::Unknown, | ||
1497 | }, | ||
1498 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
1499 | // FIXME: resolve ops::Not trait for inner_ty | ||
1500 | _ => Ty::Unknown, | ||
1501 | } | ||
1502 | } | ||
1503 | } | ||
1504 | } | ||
1505 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
1506 | Some(op) => { | ||
1507 | let lhs_expectation = match op { | ||
1508 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
1509 | _ => Expectation::none(), | ||
1510 | }; | ||
1511 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
1512 | // FIXME: find implementation of trait corresponding to operation | ||
1513 | // symbol and resolve associated `Output` type | ||
1514 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
1515 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
1516 | |||
1517 | // FIXME: similar as above, return ty is often associated trait type | ||
1518 | op::binary_op_return_ty(*op, rhs_ty) | ||
1519 | } | ||
1520 | _ => Ty::Unknown, | ||
1521 | }, | ||
1522 | Expr::Index { base, index } => { | ||
1523 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
1524 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
1525 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
1526 | Ty::Unknown | ||
1527 | } | ||
1528 | Expr::Tuple { exprs } => { | ||
1529 | let mut tys = match &expected.ty { | ||
1530 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
1531 | .iter() | ||
1532 | .cloned() | ||
1533 | .chain(repeat_with(|| self.new_type_var())) | ||
1534 | .take(exprs.len()) | ||
1535 | .collect::<Vec<_>>(), | ||
1536 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
1537 | }; | ||
1538 | |||
1539 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
1540 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
1541 | } | ||
1542 | |||
1543 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
1544 | } | ||
1545 | Expr::Array(array) => { | ||
1546 | let elem_ty = match &expected.ty { | ||
1547 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
1548 | st.as_single().clone() | ||
1549 | } | ||
1550 | _ => self.new_type_var(), | ||
1551 | }; | ||
1552 | |||
1553 | match array { | ||
1554 | Array::ElementList(items) => { | ||
1555 | for expr in items.iter() { | ||
1556 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
1557 | } | ||
1558 | } | ||
1559 | Array::Repeat { initializer, repeat } => { | ||
1560 | self.infer_expr_coerce( | ||
1561 | *initializer, | ||
1562 | &Expectation::has_type(elem_ty.clone()), | ||
1563 | ); | ||
1564 | self.infer_expr( | ||
1565 | *repeat, | ||
1566 | &Expectation::has_type(Ty::simple(TypeCtor::Int( | ||
1567 | primitive::UncertainIntTy::Known(primitive::IntTy::usize()), | ||
1568 | ))), | ||
1569 | ); | ||
1570 | } | ||
1571 | } | ||
1572 | |||
1573 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
1574 | } | ||
1575 | Expr::Literal(lit) => match lit { | ||
1576 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
1577 | Literal::String(..) => { | ||
1578 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
1579 | } | ||
1580 | Literal::ByteString(..) => { | ||
1581 | let byte_type = Ty::simple(TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
1582 | primitive::IntTy::u8(), | ||
1583 | ))); | ||
1584 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
1585 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
1586 | } | ||
1587 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
1588 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int(*ty)), | ||
1589 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float(*ty)), | ||
1590 | }, | ||
1591 | }; | ||
1592 | // use a new type variable if we got Ty::Unknown here | ||
1593 | let ty = self.insert_type_vars_shallow(ty); | ||
1594 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1595 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
1596 | ty | ||
1597 | } | ||
1598 | |||
1599 | fn infer_block( | ||
1600 | &mut self, | ||
1601 | statements: &[Statement], | ||
1602 | tail: Option<ExprId>, | ||
1603 | expected: &Expectation, | ||
1604 | ) -> Ty { | ||
1605 | let mut diverges = false; | ||
1606 | for stmt in statements { | ||
1607 | match stmt { | ||
1608 | Statement::Let { pat, type_ref, initializer } => { | ||
1609 | let decl_ty = | ||
1610 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
1611 | |||
1612 | // Always use the declared type when specified | ||
1613 | let mut ty = decl_ty.clone(); | ||
1614 | |||
1615 | if let Some(expr) = initializer { | ||
1616 | let actual_ty = | ||
1617 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
1618 | if decl_ty == Ty::Unknown { | ||
1619 | ty = actual_ty; | ||
1620 | } | ||
1621 | } | ||
1622 | |||
1623 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1624 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
1625 | } | ||
1626 | Statement::Expr(expr) => { | ||
1627 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
1628 | diverges = true; | ||
1629 | } | ||
1630 | } | ||
1631 | } | ||
1632 | } | ||
1633 | |||
1634 | let ty = if let Some(expr) = tail { | ||
1635 | self.infer_expr_coerce(expr, expected) | ||
1636 | } else { | ||
1637 | self.coerce(&Ty::unit(), &expected.ty); | ||
1638 | Ty::unit() | ||
1639 | }; | ||
1640 | if diverges { | ||
1641 | Ty::simple(TypeCtor::Never) | ||
1642 | } else { | ||
1643 | ty | ||
1644 | } | ||
1645 | } | ||
1646 | |||
1647 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
1648 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
1649 | // We do this in a pretty awful way: first we type-check any arguments | ||
1650 | // that are not closures, then we type-check the closures. This is so | ||
1651 | // that we have more information about the types of arguments when we | ||
1652 | // type-check the functions. This isn't really the right way to do this. | ||
1653 | for &check_closures in &[false, true] { | ||
1654 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
1655 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
1656 | let is_closure = match &self.body[arg] { | ||
1657 | Expr::Lambda { .. } => true, | ||
1658 | _ => false, | ||
1659 | }; | ||
1660 | |||
1661 | if is_closure != check_closures { | ||
1662 | continue; | ||
1663 | } | ||
1664 | |||
1665 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
1666 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
1667 | } | ||
1668 | } | ||
1669 | } | ||
1670 | |||
1671 | fn collect_const(&mut self, data: &ConstData) { | 559 | fn collect_const(&mut self, data: &ConstData) { |
1672 | self.return_ty = self.make_ty(data.type_ref()); | 560 | self.return_ty = self.make_ty(data.type_ref()); |
1673 | } | 561 | } |
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs new file mode 100644 index 000000000..0429a9866 --- /dev/null +++ b/crates/ra_hir/src/ty/infer/coerce.rs | |||
@@ -0,0 +1,336 @@ | |||
1 | //! Coercion logic. Coercions are certain type conversions that can implicitly | ||
2 | //! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions | ||
3 | //! like going from `&Vec<T>` to `&[T]`. | ||
4 | //! | ||
5 | //! See: https://doc.rust-lang.org/nomicon/coercions.html | ||
6 | |||
7 | use rustc_hash::FxHashMap; | ||
8 | |||
9 | use test_utils::tested_by; | ||
10 | |||
11 | use super::{InferTy, InferenceContext, TypeVarValue}; | ||
12 | use crate::{ | ||
13 | db::HirDatabase, | ||
14 | lang_item::LangItemTarget, | ||
15 | resolve::Resolver, | ||
16 | ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk}, | ||
17 | type_ref::Mutability, | ||
18 | Adt, | ||
19 | }; | ||
20 | |||
21 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
22 | /// Unify two types, but may coerce the first one to the second one | ||
23 | /// using "implicit coercion rules" if needed. | ||
24 | pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
25 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
26 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
27 | self.coerce_inner(from_ty, &to_ty) | ||
28 | } | ||
29 | |||
30 | /// Merge two types from different branches, with possible implicit coerce. | ||
31 | /// | ||
32 | /// Note that it is only possible that one type are coerced to another. | ||
33 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
34 | /// which will simply result in "incompatible types" error. | ||
35 | pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
36 | if self.coerce(ty1, ty2) { | ||
37 | ty2.clone() | ||
38 | } else if self.coerce(ty2, ty1) { | ||
39 | ty1.clone() | ||
40 | } else { | ||
41 | tested_by!(coerce_merge_fail_fallback); | ||
42 | // For incompatible types, we use the latter one as result | ||
43 | // to be better recovery for `if` without `else`. | ||
44 | ty2.clone() | ||
45 | } | ||
46 | } | ||
47 | |||
48 | pub(super) fn init_coerce_unsized_map( | ||
49 | db: &'a D, | ||
50 | resolver: &Resolver, | ||
51 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
52 | let krate = resolver.krate().unwrap(); | ||
53 | let impls = match db.lang_item(krate, "coerce_unsized".into()) { | ||
54 | Some(LangItemTarget::Trait(trait_)) => db.impls_for_trait(krate, trait_), | ||
55 | _ => return FxHashMap::default(), | ||
56 | }; | ||
57 | |||
58 | impls | ||
59 | .iter() | ||
60 | .filter_map(|impl_block| { | ||
61 | // `CoerseUnsized` has one generic parameter for the target type. | ||
62 | let trait_ref = impl_block.target_trait_ref(db)?; | ||
63 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
64 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
65 | |||
66 | match (&cur_from_ty, cur_to_ty) { | ||
67 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
68 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
69 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
70 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
71 | match (ty1, ty2) { | ||
72 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
73 | if p1 != p2 => | ||
74 | { | ||
75 | Some(((*ctor1, *ctor2), i)) | ||
76 | } | ||
77 | _ => None, | ||
78 | } | ||
79 | }) | ||
80 | } | ||
81 | _ => None, | ||
82 | } | ||
83 | }) | ||
84 | .collect() | ||
85 | } | ||
86 | |||
87 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
88 | match (&from_ty, to_ty) { | ||
89 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
90 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
91 | let var = self.new_maybe_never_type_var(); | ||
92 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
93 | return true; | ||
94 | } | ||
95 | (ty_app!(TypeCtor::Never), _) => return true, | ||
96 | |||
97 | // Trivial cases, this should go after `never` check to | ||
98 | // avoid infer result type to be never | ||
99 | _ => { | ||
100 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
101 | return true; | ||
102 | } | ||
103 | } | ||
104 | } | ||
105 | |||
106 | // Pointer weakening and function to pointer | ||
107 | match (&mut from_ty, to_ty) { | ||
108 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
109 | // `&mut T` -> `&T` | ||
110 | // `&mut T` -> `*mut T` | ||
111 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
112 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
113 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
114 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
115 | *c1 = *c2; | ||
116 | } | ||
117 | |||
118 | // Illegal mutablity conversion | ||
119 | ( | ||
120 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
121 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
122 | ) | ||
123 | | ( | ||
124 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
125 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
126 | ) => return false, | ||
127 | |||
128 | // `{function_type}` -> `fn()` | ||
129 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
130 | match from_ty.callable_sig(self.db) { | ||
131 | None => return false, | ||
132 | Some(sig) => { | ||
133 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
134 | from_ty = | ||
135 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
136 | } | ||
137 | } | ||
138 | } | ||
139 | |||
140 | _ => {} | ||
141 | } | ||
142 | |||
143 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
144 | return ret; | ||
145 | } | ||
146 | |||
147 | // Auto Deref if cannot coerce | ||
148 | match (&from_ty, to_ty) { | ||
149 | // FIXME: DerefMut | ||
150 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
151 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
152 | } | ||
153 | |||
154 | // Otherwise, normal unify | ||
155 | _ => self.unify(&from_ty, to_ty), | ||
156 | } | ||
157 | } | ||
158 | |||
159 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
160 | /// | ||
161 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
162 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
163 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
164 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
165 | _ => return None, | ||
166 | }; | ||
167 | |||
168 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
169 | |||
170 | // Check `Unsize` first | ||
171 | match self.check_unsize_and_coerce( | ||
172 | st1.0.get(coerce_generic_index)?, | ||
173 | st2.0.get(coerce_generic_index)?, | ||
174 | 0, | ||
175 | ) { | ||
176 | Some(true) => {} | ||
177 | ret => return ret, | ||
178 | } | ||
179 | |||
180 | let ret = st1 | ||
181 | .iter() | ||
182 | .zip(st2.iter()) | ||
183 | .enumerate() | ||
184 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
185 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
186 | |||
187 | Some(ret) | ||
188 | } | ||
189 | |||
190 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
191 | /// | ||
192 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
193 | /// | ||
194 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
195 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
196 | if depth > 1000 { | ||
197 | panic!("Infinite recursion in coercion"); | ||
198 | } | ||
199 | |||
200 | match (&from_ty, &to_ty) { | ||
201 | // `[T; N]` -> `[T]` | ||
202 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
203 | Some(self.unify(&st1[0], &st2[0])) | ||
204 | } | ||
205 | |||
206 | // `T` -> `dyn Trait` when `T: Trait` | ||
207 | (_, Ty::Dyn(_)) => { | ||
208 | // FIXME: Check predicates | ||
209 | Some(true) | ||
210 | } | ||
211 | |||
212 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
213 | ( | ||
214 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
215 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
216 | ) => { | ||
217 | if len1 != len2 || *len1 == 0 { | ||
218 | return None; | ||
219 | } | ||
220 | |||
221 | match self.check_unsize_and_coerce( | ||
222 | st1.last().unwrap(), | ||
223 | st2.last().unwrap(), | ||
224 | depth + 1, | ||
225 | ) { | ||
226 | Some(true) => {} | ||
227 | ret => return ret, | ||
228 | } | ||
229 | |||
230 | let ret = st1[..st1.len() - 1] | ||
231 | .iter() | ||
232 | .zip(&st2[..st2.len() - 1]) | ||
233 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
234 | |||
235 | Some(ret) | ||
236 | } | ||
237 | |||
238 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
239 | // - T: Unsize<U> | ||
240 | // - Foo is a struct | ||
241 | // - Only the last field of Foo has a type involving T | ||
242 | // - T is not part of the type of any other fields | ||
243 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
244 | ( | ||
245 | ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1), | ||
246 | ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2), | ||
247 | ) if struct1 == struct2 => { | ||
248 | let fields = struct1.fields(self.db); | ||
249 | let (last_field, prev_fields) = fields.split_last()?; | ||
250 | |||
251 | // Get the generic parameter involved in the last field. | ||
252 | let unsize_generic_index = { | ||
253 | let mut index = None; | ||
254 | let mut multiple_param = false; | ||
255 | last_field.ty(self.db).walk(&mut |ty| match ty { | ||
256 | &Ty::Param { idx, .. } => { | ||
257 | if index.is_none() { | ||
258 | index = Some(idx); | ||
259 | } else if Some(idx) != index { | ||
260 | multiple_param = true; | ||
261 | } | ||
262 | } | ||
263 | _ => {} | ||
264 | }); | ||
265 | |||
266 | if multiple_param { | ||
267 | return None; | ||
268 | } | ||
269 | index? | ||
270 | }; | ||
271 | |||
272 | // Check other fields do not involve it. | ||
273 | let mut multiple_used = false; | ||
274 | prev_fields.iter().for_each(|field| { | ||
275 | field.ty(self.db).walk(&mut |ty| match ty { | ||
276 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
277 | multiple_used = true | ||
278 | } | ||
279 | _ => {} | ||
280 | }) | ||
281 | }); | ||
282 | if multiple_used { | ||
283 | return None; | ||
284 | } | ||
285 | |||
286 | let unsize_generic_index = unsize_generic_index as usize; | ||
287 | |||
288 | // Check `Unsize` first | ||
289 | match self.check_unsize_and_coerce( | ||
290 | st1.get(unsize_generic_index)?, | ||
291 | st2.get(unsize_generic_index)?, | ||
292 | depth + 1, | ||
293 | ) { | ||
294 | Some(true) => {} | ||
295 | ret => return ret, | ||
296 | } | ||
297 | |||
298 | // Then unify other parameters | ||
299 | let ret = st1 | ||
300 | .iter() | ||
301 | .zip(st2.iter()) | ||
302 | .enumerate() | ||
303 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
304 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
305 | |||
306 | Some(ret) | ||
307 | } | ||
308 | |||
309 | _ => None, | ||
310 | } | ||
311 | } | ||
312 | |||
313 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
314 | /// | ||
315 | /// Note that the parameters are already stripped the outer reference. | ||
316 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
317 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
318 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
319 | // FIXME: Auto DerefMut | ||
320 | for derefed_ty in | ||
321 | autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone()) | ||
322 | { | ||
323 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
324 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
325 | // Stop when constructor matches. | ||
326 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
327 | // It will not recurse to `coerce`. | ||
328 | return self.unify_substs(st1, st2, 0); | ||
329 | } | ||
330 | _ => {} | ||
331 | } | ||
332 | } | ||
333 | |||
334 | false | ||
335 | } | ||
336 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs new file mode 100644 index 000000000..f8807c742 --- /dev/null +++ b/crates/ra_hir/src/ty/infer/expr.rs | |||
@@ -0,0 +1,658 @@ | |||
1 | //! Type inference for expressions. | ||
2 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
7 | use crate::{ | ||
8 | db::HirDatabase, | ||
9 | expr::{self, Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | ||
10 | generics::{GenericParams, HasGenericParams}, | ||
11 | name, | ||
12 | nameres::Namespace, | ||
13 | path::{GenericArg, GenericArgs}, | ||
14 | ty::{ | ||
15 | autoderef, method_resolution, op, primitive, CallableDef, InferTy, Mutability, Obligation, | ||
16 | ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, | ||
17 | }, | ||
18 | Adt, Name, | ||
19 | }; | ||
20 | |||
21 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
22 | pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
23 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
24 | let could_unify = self.unify(&ty, &expected.ty); | ||
25 | if !could_unify { | ||
26 | self.result.type_mismatches.insert( | ||
27 | tgt_expr, | ||
28 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
29 | ); | ||
30 | } | ||
31 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
32 | ty | ||
33 | } | ||
34 | |||
35 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
36 | /// Return the type after possible coercion. | ||
37 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
38 | let ty = self.infer_expr_inner(expr, &expected); | ||
39 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
40 | self.result | ||
41 | .type_mismatches | ||
42 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
43 | // Return actual type when type mismatch. | ||
44 | // This is needed for diagnostic when return type mismatch. | ||
45 | ty | ||
46 | } else if expected.ty == Ty::Unknown { | ||
47 | ty | ||
48 | } else { | ||
49 | expected.ty.clone() | ||
50 | }; | ||
51 | |||
52 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
53 | } | ||
54 | |||
55 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
56 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
57 | let ty = match &body[tgt_expr] { | ||
58 | Expr::Missing => Ty::Unknown, | ||
59 | Expr::If { condition, then_branch, else_branch } => { | ||
60 | // if let is desugared to match, so this is always simple if | ||
61 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
62 | |||
63 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
64 | let else_ty = match else_branch { | ||
65 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
66 | None => Ty::unit(), | ||
67 | }; | ||
68 | |||
69 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
70 | } | ||
71 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
72 | Expr::TryBlock { body } => { | ||
73 | let _inner = self.infer_expr(*body, expected); | ||
74 | // FIXME should be std::result::Result<{inner}, _> | ||
75 | Ty::Unknown | ||
76 | } | ||
77 | Expr::Loop { body } => { | ||
78 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
79 | // FIXME handle break with value | ||
80 | Ty::simple(TypeCtor::Never) | ||
81 | } | ||
82 | Expr::While { condition, body } => { | ||
83 | // while let is desugared to a match loop, so this is always simple while | ||
84 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
85 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
86 | Ty::unit() | ||
87 | } | ||
88 | Expr::For { iterable, body, pat } => { | ||
89 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
90 | |||
91 | let pat_ty = match self.resolve_into_iter_item() { | ||
92 | Some(into_iter_item_alias) => { | ||
93 | let pat_ty = self.new_type_var(); | ||
94 | let projection = ProjectionPredicate { | ||
95 | ty: pat_ty.clone(), | ||
96 | projection_ty: ProjectionTy { | ||
97 | associated_ty: into_iter_item_alias, | ||
98 | parameters: Substs::single(iterable_ty), | ||
99 | }, | ||
100 | }; | ||
101 | self.obligations.push(Obligation::Projection(projection)); | ||
102 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
103 | } | ||
104 | None => Ty::Unknown, | ||
105 | }; | ||
106 | |||
107 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
108 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
109 | Ty::unit() | ||
110 | } | ||
111 | Expr::Lambda { body, args, arg_types } => { | ||
112 | assert_eq!(args.len(), arg_types.len()); | ||
113 | |||
114 | let mut sig_tys = Vec::new(); | ||
115 | |||
116 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
117 | let expected = if let Some(type_ref) = arg_type { | ||
118 | self.make_ty(type_ref) | ||
119 | } else { | ||
120 | Ty::Unknown | ||
121 | }; | ||
122 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
123 | sig_tys.push(arg_ty); | ||
124 | } | ||
125 | |||
126 | // add return type | ||
127 | let ret_ty = self.new_type_var(); | ||
128 | sig_tys.push(ret_ty.clone()); | ||
129 | let sig_ty = Ty::apply( | ||
130 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
131 | Substs(sig_tys.into()), | ||
132 | ); | ||
133 | let closure_ty = Ty::apply_one( | ||
134 | TypeCtor::Closure { def: self.body.owner(), expr: tgt_expr }, | ||
135 | sig_ty, | ||
136 | ); | ||
137 | |||
138 | // Eagerly try to relate the closure type with the expected | ||
139 | // type, otherwise we often won't have enough information to | ||
140 | // infer the body. | ||
141 | self.coerce(&closure_ty, &expected.ty); | ||
142 | |||
143 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
144 | closure_ty | ||
145 | } | ||
146 | Expr::Call { callee, args } => { | ||
147 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
148 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
149 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
150 | None => { | ||
151 | // Not callable | ||
152 | // FIXME: report an error | ||
153 | (Vec::new(), Ty::Unknown) | ||
154 | } | ||
155 | }; | ||
156 | self.register_obligations_for_call(&callee_ty); | ||
157 | self.check_call_arguments(args, ¶m_tys); | ||
158 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
159 | ret_ty | ||
160 | } | ||
161 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
162 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
163 | Expr::Match { expr, arms } => { | ||
164 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
165 | |||
166 | let mut result_ty = self.new_maybe_never_type_var(); | ||
167 | |||
168 | for arm in arms { | ||
169 | for &pat in &arm.pats { | ||
170 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
171 | } | ||
172 | if let Some(guard_expr) = arm.guard { | ||
173 | self.infer_expr( | ||
174 | guard_expr, | ||
175 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
176 | ); | ||
177 | } | ||
178 | |||
179 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
180 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
181 | } | ||
182 | |||
183 | result_ty | ||
184 | } | ||
185 | Expr::Path(p) => { | ||
186 | // FIXME this could be more efficient... | ||
187 | let resolver = expr::resolver_for_expr(self.body.clone(), self.db, tgt_expr); | ||
188 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
189 | } | ||
190 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
191 | Expr::Break { expr } => { | ||
192 | if let Some(expr) = expr { | ||
193 | // FIXME handle break with value | ||
194 | self.infer_expr(*expr, &Expectation::none()); | ||
195 | } | ||
196 | Ty::simple(TypeCtor::Never) | ||
197 | } | ||
198 | Expr::Return { expr } => { | ||
199 | if let Some(expr) = expr { | ||
200 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
201 | } | ||
202 | Ty::simple(TypeCtor::Never) | ||
203 | } | ||
204 | Expr::RecordLit { path, fields, spread } => { | ||
205 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
206 | if let Some(variant) = def_id { | ||
207 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
208 | } | ||
209 | |||
210 | self.unify(&ty, &expected.ty); | ||
211 | |||
212 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
213 | for (field_idx, field) in fields.iter().enumerate() { | ||
214 | let field_ty = def_id | ||
215 | .and_then(|it| match it.field(self.db, &field.name) { | ||
216 | Some(field) => Some(field), | ||
217 | None => { | ||
218 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
219 | expr: tgt_expr, | ||
220 | field: field_idx, | ||
221 | }); | ||
222 | None | ||
223 | } | ||
224 | }) | ||
225 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
226 | .subst(&substs); | ||
227 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
228 | } | ||
229 | if let Some(expr) = spread { | ||
230 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
231 | } | ||
232 | ty | ||
233 | } | ||
234 | Expr::Field { expr, name } => { | ||
235 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
236 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
237 | let ty = autoderef::autoderef( | ||
238 | self.db, | ||
239 | &self.resolver.clone(), | ||
240 | canonicalized.value.clone(), | ||
241 | ) | ||
242 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
243 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
244 | TypeCtor::Tuple { .. } => name | ||
245 | .as_tuple_index() | ||
246 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
247 | TypeCtor::Adt(Adt::Struct(s)) => s.field(self.db, name).map(|field| { | ||
248 | self.write_field_resolution(tgt_expr, field); | ||
249 | field.ty(self.db).subst(&a_ty.parameters) | ||
250 | }), | ||
251 | _ => None, | ||
252 | }, | ||
253 | _ => None, | ||
254 | }) | ||
255 | .unwrap_or(Ty::Unknown); | ||
256 | let ty = self.insert_type_vars(ty); | ||
257 | self.normalize_associated_types_in(ty) | ||
258 | } | ||
259 | Expr::Await { expr } => { | ||
260 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
261 | let ty = match self.resolve_future_future_output() { | ||
262 | Some(future_future_output_alias) => { | ||
263 | let ty = self.new_type_var(); | ||
264 | let projection = ProjectionPredicate { | ||
265 | ty: ty.clone(), | ||
266 | projection_ty: ProjectionTy { | ||
267 | associated_ty: future_future_output_alias, | ||
268 | parameters: Substs::single(inner_ty), | ||
269 | }, | ||
270 | }; | ||
271 | self.obligations.push(Obligation::Projection(projection)); | ||
272 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
273 | } | ||
274 | None => Ty::Unknown, | ||
275 | }; | ||
276 | ty | ||
277 | } | ||
278 | Expr::Try { expr } => { | ||
279 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
280 | let ty = match self.resolve_ops_try_ok() { | ||
281 | Some(ops_try_ok_alias) => { | ||
282 | let ty = self.new_type_var(); | ||
283 | let projection = ProjectionPredicate { | ||
284 | ty: ty.clone(), | ||
285 | projection_ty: ProjectionTy { | ||
286 | associated_ty: ops_try_ok_alias, | ||
287 | parameters: Substs::single(inner_ty), | ||
288 | }, | ||
289 | }; | ||
290 | self.obligations.push(Obligation::Projection(projection)); | ||
291 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
292 | } | ||
293 | None => Ty::Unknown, | ||
294 | }; | ||
295 | ty | ||
296 | } | ||
297 | Expr::Cast { expr, type_ref } => { | ||
298 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
299 | let cast_ty = self.make_ty(type_ref); | ||
300 | // FIXME check the cast... | ||
301 | cast_ty | ||
302 | } | ||
303 | Expr::Ref { expr, mutability } => { | ||
304 | let expectation = | ||
305 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
306 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
307 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
308 | // which cannot be coerced | ||
309 | } | ||
310 | Expectation::has_type(Ty::clone(exp_inner)) | ||
311 | } else { | ||
312 | Expectation::none() | ||
313 | }; | ||
314 | // FIXME reference coercions etc. | ||
315 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
316 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
317 | } | ||
318 | Expr::Box { expr } => { | ||
319 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
320 | if let Some(box_) = self.resolve_boxed_box() { | ||
321 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
322 | } else { | ||
323 | Ty::Unknown | ||
324 | } | ||
325 | } | ||
326 | Expr::UnaryOp { expr, op } => { | ||
327 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
328 | match op { | ||
329 | UnaryOp::Deref => { | ||
330 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
331 | if let Some(derefed_ty) = | ||
332 | autoderef::deref(self.db, &self.resolver, &canonicalized.value) | ||
333 | { | ||
334 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
335 | } else { | ||
336 | Ty::Unknown | ||
337 | } | ||
338 | } | ||
339 | UnaryOp::Neg => { | ||
340 | match &inner_ty { | ||
341 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
342 | TypeCtor::Int(primitive::UncertainIntTy::Unknown) | ||
343 | | TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
344 | primitive::IntTy { | ||
345 | signedness: primitive::Signedness::Signed, | ||
346 | .. | ||
347 | }, | ||
348 | )) | ||
349 | | TypeCtor::Float(..) => inner_ty, | ||
350 | _ => Ty::Unknown, | ||
351 | }, | ||
352 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
353 | inner_ty | ||
354 | } | ||
355 | // FIXME: resolve ops::Neg trait | ||
356 | _ => Ty::Unknown, | ||
357 | } | ||
358 | } | ||
359 | UnaryOp::Not => { | ||
360 | match &inner_ty { | ||
361 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
362 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
363 | _ => Ty::Unknown, | ||
364 | }, | ||
365 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
366 | // FIXME: resolve ops::Not trait for inner_ty | ||
367 | _ => Ty::Unknown, | ||
368 | } | ||
369 | } | ||
370 | } | ||
371 | } | ||
372 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
373 | Some(op) => { | ||
374 | let lhs_expectation = match op { | ||
375 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
376 | _ => Expectation::none(), | ||
377 | }; | ||
378 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
379 | // FIXME: find implementation of trait corresponding to operation | ||
380 | // symbol and resolve associated `Output` type | ||
381 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
382 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
383 | |||
384 | // FIXME: similar as above, return ty is often associated trait type | ||
385 | op::binary_op_return_ty(*op, rhs_ty) | ||
386 | } | ||
387 | _ => Ty::Unknown, | ||
388 | }, | ||
389 | Expr::Index { base, index } => { | ||
390 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
391 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
392 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
393 | Ty::Unknown | ||
394 | } | ||
395 | Expr::Tuple { exprs } => { | ||
396 | let mut tys = match &expected.ty { | ||
397 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
398 | .iter() | ||
399 | .cloned() | ||
400 | .chain(repeat_with(|| self.new_type_var())) | ||
401 | .take(exprs.len()) | ||
402 | .collect::<Vec<_>>(), | ||
403 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
404 | }; | ||
405 | |||
406 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
407 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
408 | } | ||
409 | |||
410 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
411 | } | ||
412 | Expr::Array(array) => { | ||
413 | let elem_ty = match &expected.ty { | ||
414 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
415 | st.as_single().clone() | ||
416 | } | ||
417 | _ => self.new_type_var(), | ||
418 | }; | ||
419 | |||
420 | match array { | ||
421 | Array::ElementList(items) => { | ||
422 | for expr in items.iter() { | ||
423 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
424 | } | ||
425 | } | ||
426 | Array::Repeat { initializer, repeat } => { | ||
427 | self.infer_expr_coerce( | ||
428 | *initializer, | ||
429 | &Expectation::has_type(elem_ty.clone()), | ||
430 | ); | ||
431 | self.infer_expr( | ||
432 | *repeat, | ||
433 | &Expectation::has_type(Ty::simple(TypeCtor::Int( | ||
434 | primitive::UncertainIntTy::Known(primitive::IntTy::usize()), | ||
435 | ))), | ||
436 | ); | ||
437 | } | ||
438 | } | ||
439 | |||
440 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
441 | } | ||
442 | Expr::Literal(lit) => match lit { | ||
443 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
444 | Literal::String(..) => { | ||
445 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
446 | } | ||
447 | Literal::ByteString(..) => { | ||
448 | let byte_type = Ty::simple(TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
449 | primitive::IntTy::u8(), | ||
450 | ))); | ||
451 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
452 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
453 | } | ||
454 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
455 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int(*ty)), | ||
456 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float(*ty)), | ||
457 | }, | ||
458 | }; | ||
459 | // use a new type variable if we got Ty::Unknown here | ||
460 | let ty = self.insert_type_vars_shallow(ty); | ||
461 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
462 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
463 | ty | ||
464 | } | ||
465 | |||
466 | fn infer_block( | ||
467 | &mut self, | ||
468 | statements: &[Statement], | ||
469 | tail: Option<ExprId>, | ||
470 | expected: &Expectation, | ||
471 | ) -> Ty { | ||
472 | let mut diverges = false; | ||
473 | for stmt in statements { | ||
474 | match stmt { | ||
475 | Statement::Let { pat, type_ref, initializer } => { | ||
476 | let decl_ty = | ||
477 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
478 | |||
479 | // Always use the declared type when specified | ||
480 | let mut ty = decl_ty.clone(); | ||
481 | |||
482 | if let Some(expr) = initializer { | ||
483 | let actual_ty = | ||
484 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
485 | if decl_ty == Ty::Unknown { | ||
486 | ty = actual_ty; | ||
487 | } | ||
488 | } | ||
489 | |||
490 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
491 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
492 | } | ||
493 | Statement::Expr(expr) => { | ||
494 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
495 | diverges = true; | ||
496 | } | ||
497 | } | ||
498 | } | ||
499 | } | ||
500 | |||
501 | let ty = if let Some(expr) = tail { | ||
502 | self.infer_expr_coerce(expr, expected) | ||
503 | } else { | ||
504 | self.coerce(&Ty::unit(), &expected.ty); | ||
505 | Ty::unit() | ||
506 | }; | ||
507 | if diverges { | ||
508 | Ty::simple(TypeCtor::Never) | ||
509 | } else { | ||
510 | ty | ||
511 | } | ||
512 | } | ||
513 | |||
514 | fn infer_method_call( | ||
515 | &mut self, | ||
516 | tgt_expr: ExprId, | ||
517 | receiver: ExprId, | ||
518 | args: &[ExprId], | ||
519 | method_name: &Name, | ||
520 | generic_args: Option<&GenericArgs>, | ||
521 | ) -> Ty { | ||
522 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
523 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
524 | let resolved = method_resolution::lookup_method( | ||
525 | &canonicalized_receiver.value, | ||
526 | self.db, | ||
527 | method_name, | ||
528 | &self.resolver, | ||
529 | ); | ||
530 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
531 | Some((ty, func)) => { | ||
532 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
533 | self.write_method_resolution(tgt_expr, func); | ||
534 | ( | ||
535 | ty, | ||
536 | self.db.type_for_def(func.into(), Namespace::Values), | ||
537 | Some(func.generic_params(self.db)), | ||
538 | ) | ||
539 | } | ||
540 | None => (receiver_ty, Ty::Unknown, None), | ||
541 | }; | ||
542 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
543 | let method_ty = method_ty.apply_substs(substs); | ||
544 | let method_ty = self.insert_type_vars(method_ty); | ||
545 | self.register_obligations_for_call(&method_ty); | ||
546 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
547 | Some(sig) => { | ||
548 | if !sig.params().is_empty() { | ||
549 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
550 | } else { | ||
551 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
552 | } | ||
553 | } | ||
554 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
555 | }; | ||
556 | // Apply autoref so the below unification works correctly | ||
557 | // FIXME: return correct autorefs from lookup_method | ||
558 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
559 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
560 | _ => derefed_receiver_ty, | ||
561 | }; | ||
562 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
563 | |||
564 | self.check_call_arguments(args, ¶m_tys); | ||
565 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
566 | ret_ty | ||
567 | } | ||
568 | |||
569 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
570 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
571 | // We do this in a pretty awful way: first we type-check any arguments | ||
572 | // that are not closures, then we type-check the closures. This is so | ||
573 | // that we have more information about the types of arguments when we | ||
574 | // type-check the functions. This isn't really the right way to do this. | ||
575 | for &check_closures in &[false, true] { | ||
576 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
577 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
578 | let is_closure = match &self.body[arg] { | ||
579 | Expr::Lambda { .. } => true, | ||
580 | _ => false, | ||
581 | }; | ||
582 | |||
583 | if is_closure != check_closures { | ||
584 | continue; | ||
585 | } | ||
586 | |||
587 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
588 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
589 | } | ||
590 | } | ||
591 | } | ||
592 | |||
593 | fn substs_for_method_call( | ||
594 | &mut self, | ||
595 | def_generics: Option<Arc<GenericParams>>, | ||
596 | generic_args: Option<&GenericArgs>, | ||
597 | receiver_ty: &Ty, | ||
598 | ) -> Substs { | ||
599 | let (parent_param_count, param_count) = | ||
600 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
601 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
602 | // Parent arguments are unknown, except for the receiver type | ||
603 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
604 | for param in &parent_generics.params { | ||
605 | if param.name == name::SELF_TYPE { | ||
606 | substs.push(receiver_ty.clone()); | ||
607 | } else { | ||
608 | substs.push(Ty::Unknown); | ||
609 | } | ||
610 | } | ||
611 | } | ||
612 | // handle provided type arguments | ||
613 | if let Some(generic_args) = generic_args { | ||
614 | // if args are provided, it should be all of them, but we can't rely on that | ||
615 | for arg in generic_args.args.iter().take(param_count) { | ||
616 | match arg { | ||
617 | GenericArg::Type(type_ref) => { | ||
618 | let ty = self.make_ty(type_ref); | ||
619 | substs.push(ty); | ||
620 | } | ||
621 | } | ||
622 | } | ||
623 | }; | ||
624 | let supplied_params = substs.len(); | ||
625 | for _ in supplied_params..parent_param_count + param_count { | ||
626 | substs.push(Ty::Unknown); | ||
627 | } | ||
628 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
629 | Substs(substs.into()) | ||
630 | } | ||
631 | |||
632 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
633 | if let Ty::Apply(a_ty) = callable_ty { | ||
634 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
635 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
636 | for predicate in generic_predicates.iter() { | ||
637 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
638 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
639 | self.obligations.push(obligation); | ||
640 | } | ||
641 | } | ||
642 | // add obligation for trait implementation, if this is a trait method | ||
643 | match def { | ||
644 | CallableDef::Function(f) => { | ||
645 | if let Some(trait_) = f.parent_trait(self.db) { | ||
646 | // construct a TraitDef | ||
647 | let substs = a_ty.parameters.prefix( | ||
648 | trait_.generic_params(self.db).count_params_including_parent(), | ||
649 | ); | ||
650 | self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); | ||
651 | } | ||
652 | } | ||
653 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {} | ||
654 | } | ||
655 | } | ||
656 | } | ||
657 | } | ||
658 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir/src/ty/infer/pat.rs new file mode 100644 index 000000000..c125ddfbc --- /dev/null +++ b/crates/ra_hir/src/ty/infer/pat.rs | |||
@@ -0,0 +1,180 @@ | |||
1 | //! Type inference for patterns. | ||
2 | |||
3 | use std::iter::repeat; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use test_utils::tested_by; | ||
7 | |||
8 | use super::{BindingMode, InferenceContext}; | ||
9 | use crate::{ | ||
10 | db::HirDatabase, | ||
11 | expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, | ||
12 | ty::{Mutability, Substs, Ty, TypeCtor, TypeWalk}, | ||
13 | Name, Path, | ||
14 | }; | ||
15 | |||
16 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
17 | fn infer_tuple_struct_pat( | ||
18 | &mut self, | ||
19 | path: Option<&Path>, | ||
20 | subpats: &[PatId], | ||
21 | expected: &Ty, | ||
22 | default_bm: BindingMode, | ||
23 | ) -> Ty { | ||
24 | let (ty, def) = self.resolve_variant(path); | ||
25 | |||
26 | self.unify(&ty, expected); | ||
27 | |||
28 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
29 | |||
30 | for (i, &subpat) in subpats.iter().enumerate() { | ||
31 | let expected_ty = def | ||
32 | .and_then(|d| d.field(self.db, &Name::new_tuple_field(i))) | ||
33 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
34 | .subst(&substs); | ||
35 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
36 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
37 | } | ||
38 | |||
39 | ty | ||
40 | } | ||
41 | |||
42 | fn infer_record_pat( | ||
43 | &mut self, | ||
44 | path: Option<&Path>, | ||
45 | subpats: &[RecordFieldPat], | ||
46 | expected: &Ty, | ||
47 | default_bm: BindingMode, | ||
48 | id: PatId, | ||
49 | ) -> Ty { | ||
50 | let (ty, def) = self.resolve_variant(path); | ||
51 | if let Some(variant) = def { | ||
52 | self.write_variant_resolution(id.into(), variant); | ||
53 | } | ||
54 | |||
55 | self.unify(&ty, expected); | ||
56 | |||
57 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
58 | |||
59 | for subpat in subpats { | ||
60 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | ||
61 | let expected_ty = | ||
62 | matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs); | ||
63 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
64 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
65 | } | ||
66 | |||
67 | ty | ||
68 | } | ||
69 | |||
70 | pub(super) fn infer_pat( | ||
71 | &mut self, | ||
72 | pat: PatId, | ||
73 | mut expected: &Ty, | ||
74 | mut default_bm: BindingMode, | ||
75 | ) -> Ty { | ||
76 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
77 | |||
78 | let is_non_ref_pat = match &body[pat] { | ||
79 | Pat::Tuple(..) | ||
80 | | Pat::TupleStruct { .. } | ||
81 | | Pat::Record { .. } | ||
82 | | Pat::Range { .. } | ||
83 | | Pat::Slice { .. } => true, | ||
84 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
85 | Pat::Path(..) | Pat::Lit(..) => true, | ||
86 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
87 | }; | ||
88 | if is_non_ref_pat { | ||
89 | while let Some((inner, mutability)) = expected.as_reference() { | ||
90 | expected = inner; | ||
91 | default_bm = match default_bm { | ||
92 | BindingMode::Move => BindingMode::Ref(mutability), | ||
93 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
94 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
95 | } | ||
96 | } | ||
97 | } else if let Pat::Ref { .. } = &body[pat] { | ||
98 | tested_by!(match_ergonomics_ref); | ||
99 | // When you encounter a `&pat` pattern, reset to Move. | ||
100 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
101 | default_bm = BindingMode::Move; | ||
102 | } | ||
103 | |||
104 | // Lose mutability. | ||
105 | let default_bm = default_bm; | ||
106 | let expected = expected; | ||
107 | |||
108 | let ty = match &body[pat] { | ||
109 | Pat::Tuple(ref args) => { | ||
110 | let expectations = match expected.as_tuple() { | ||
111 | Some(parameters) => &*parameters.0, | ||
112 | _ => &[], | ||
113 | }; | ||
114 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
115 | |||
116 | let inner_tys = args | ||
117 | .iter() | ||
118 | .zip(expectations_iter) | ||
119 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
120 | .collect(); | ||
121 | |||
122 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
123 | } | ||
124 | Pat::Ref { pat, mutability } => { | ||
125 | let expectation = match expected.as_reference() { | ||
126 | Some((inner_ty, exp_mut)) => { | ||
127 | if *mutability != exp_mut { | ||
128 | // FIXME: emit type error? | ||
129 | } | ||
130 | inner_ty | ||
131 | } | ||
132 | _ => &Ty::Unknown, | ||
133 | }; | ||
134 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
135 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
136 | } | ||
137 | Pat::TupleStruct { path: p, args: subpats } => { | ||
138 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
139 | } | ||
140 | Pat::Record { path: p, args: fields } => { | ||
141 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
142 | } | ||
143 | Pat::Path(path) => { | ||
144 | // FIXME use correct resolver for the surrounding expression | ||
145 | let resolver = self.resolver.clone(); | ||
146 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
147 | } | ||
148 | Pat::Bind { mode, name: _, subpat } => { | ||
149 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
150 | default_bm | ||
151 | } else { | ||
152 | BindingMode::convert(*mode) | ||
153 | }; | ||
154 | let inner_ty = if let Some(subpat) = subpat { | ||
155 | self.infer_pat(*subpat, expected, default_bm) | ||
156 | } else { | ||
157 | expected.clone() | ||
158 | }; | ||
159 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
160 | |||
161 | let bound_ty = match mode { | ||
162 | BindingMode::Ref(mutability) => { | ||
163 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
164 | } | ||
165 | BindingMode::Move => inner_ty.clone(), | ||
166 | }; | ||
167 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
168 | self.write_pat_ty(pat, bound_ty); | ||
169 | return inner_ty; | ||
170 | } | ||
171 | _ => Ty::Unknown, | ||
172 | }; | ||
173 | // use a new type variable if we got Ty::Unknown here | ||
174 | let ty = self.insert_type_vars_shallow(ty); | ||
175 | self.unify(&ty, expected); | ||
176 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
177 | self.write_pat_ty(pat, ty.clone()); | ||
178 | ty | ||
179 | } | ||
180 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index d161aa6b3..ca33cc7f8 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs | |||
@@ -6,6 +6,7 @@ use crate::ty::{ | |||
6 | Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, | 6 | Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, |
7 | TypeWalk, | 7 | TypeWalk, |
8 | }; | 8 | }; |
9 | use crate::util::make_mut_slice; | ||
9 | 10 | ||
10 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | 11 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { |
11 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> | 12 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> |
@@ -53,7 +54,9 @@ where | |||
53 | // recursive type | 54 | // recursive type |
54 | return tv.fallback_value(); | 55 | return tv.fallback_value(); |
55 | } | 56 | } |
56 | if let Some(known_ty) = self.ctx.var_unification_table.probe_value(inner).known() { | 57 | if let Some(known_ty) = |
58 | self.ctx.var_unification_table.inlined_probe_value(inner).known() | ||
59 | { | ||
57 | self.var_stack.push(inner); | 60 | self.var_stack.push(inner); |
58 | let result = self.do_canonicalize_ty(known_ty.clone()); | 61 | let result = self.do_canonicalize_ty(known_ty.clone()); |
59 | self.var_stack.pop(); | 62 | self.var_stack.pop(); |
@@ -74,10 +77,11 @@ where | |||
74 | }) | 77 | }) |
75 | } | 78 | } |
76 | 79 | ||
77 | fn do_canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> TraitRef { | 80 | fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { |
78 | let substs = | 81 | for ty in make_mut_slice(&mut trait_ref.substs.0) { |
79 | trait_ref.substs.iter().map(|ty| self.do_canonicalize_ty(ty.clone())).collect(); | 82 | *ty = self.do_canonicalize_ty(ty.clone()); |
80 | TraitRef { trait_: trait_ref.trait_, substs: Substs(substs) } | 83 | } |
84 | trait_ref | ||
81 | } | 85 | } |
82 | 86 | ||
83 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { | 87 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { |
@@ -87,10 +91,11 @@ where | |||
87 | } | 91 | } |
88 | } | 92 | } |
89 | 93 | ||
90 | fn do_canonicalize_projection_ty(&mut self, projection_ty: ProjectionTy) -> ProjectionTy { | 94 | fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { |
91 | let params = | 95 | for ty in make_mut_slice(&mut projection_ty.parameters.0) { |
92 | projection_ty.parameters.iter().map(|ty| self.do_canonicalize_ty(ty.clone())).collect(); | 96 | *ty = self.do_canonicalize_ty(ty.clone()); |
93 | ProjectionTy { associated_ty: projection_ty.associated_ty, parameters: Substs(params) } | 97 | } |
98 | projection_ty | ||
94 | } | 99 | } |
95 | 100 | ||
96 | fn do_canonicalize_projection_predicate( | 101 | fn do_canonicalize_projection_predicate( |
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs index 4b67c82e7..366556134 100644 --- a/crates/ra_hir/src/ty/lower.rs +++ b/crates/ra_hir/src/ty/lower.rs | |||
@@ -22,6 +22,7 @@ use crate::{ | |||
22 | resolve::{Resolver, TypeNs}, | 22 | resolve::{Resolver, TypeNs}, |
23 | ty::Adt, | 23 | ty::Adt, |
24 | type_ref::{TypeBound, TypeRef}, | 24 | type_ref::{TypeBound, TypeRef}, |
25 | util::make_mut_slice, | ||
25 | BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField, | 26 | BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField, |
26 | Trait, TypeAlias, Union, | 27 | Trait, TypeAlias, Union, |
27 | }; | 28 | }; |
@@ -31,11 +32,11 @@ impl Ty { | |||
31 | match type_ref { | 32 | match type_ref { |
32 | TypeRef::Never => Ty::simple(TypeCtor::Never), | 33 | TypeRef::Never => Ty::simple(TypeCtor::Never), |
33 | TypeRef::Tuple(inner) => { | 34 | TypeRef::Tuple(inner) => { |
34 | let inner_tys = | 35 | let inner_tys: Arc<[Ty]> = |
35 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::<Vec<_>>(); | 36 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); |
36 | Ty::apply( | 37 | Ty::apply( |
37 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, | 38 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, |
38 | Substs(inner_tys.into()), | 39 | Substs(inner_tys), |
39 | ) | 40 | ) |
40 | } | 41 | } |
41 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), | 42 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), |
@@ -57,9 +58,7 @@ impl Ty { | |||
57 | } | 58 | } |
58 | TypeRef::Placeholder => Ty::Unknown, | 59 | TypeRef::Placeholder => Ty::Unknown, |
59 | TypeRef::Fn(params) => { | 60 | TypeRef::Fn(params) => { |
60 | let inner_tys = | 61 | let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); |
61 | params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::<Vec<_>>(); | ||
62 | let sig = Substs(inner_tys.into()); | ||
63 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) | 62 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) |
64 | } | 63 | } |
65 | TypeRef::DynTrait(bounds) => { | 64 | TypeRef::DynTrait(bounds) => { |
@@ -69,8 +68,8 @@ impl Ty { | |||
69 | .flat_map(|b| { | 68 | .flat_map(|b| { |
70 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | 69 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) |
71 | }) | 70 | }) |
72 | .collect::<Vec<_>>(); | 71 | .collect(); |
73 | Ty::Dyn(predicates.into()) | 72 | Ty::Dyn(predicates) |
74 | } | 73 | } |
75 | TypeRef::ImplTrait(bounds) => { | 74 | TypeRef::ImplTrait(bounds) => { |
76 | let self_ty = Ty::Bound(0); | 75 | let self_ty = Ty::Bound(0); |
@@ -79,8 +78,8 @@ impl Ty { | |||
79 | .flat_map(|b| { | 78 | .flat_map(|b| { |
80 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | 79 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) |
81 | }) | 80 | }) |
82 | .collect::<Vec<_>>(); | 81 | .collect(); |
83 | Ty::Opaque(predicates.into()) | 82 | Ty::Opaque(predicates) |
84 | } | 83 | } |
85 | TypeRef::Error => Ty::Unknown, | 84 | TypeRef::Error => Ty::Unknown, |
86 | } | 85 | } |
@@ -175,6 +174,7 @@ impl Ty { | |||
175 | Ty::Param { idx, name } | 174 | Ty::Param { idx, name } |
176 | } | 175 | } |
177 | TypeNs::SelfType(impl_block) => impl_block.target_ty(db), | 176 | TypeNs::SelfType(impl_block) => impl_block.target_ty(db), |
177 | TypeNs::AdtSelfType(adt) => adt.ty(db), | ||
178 | 178 | ||
179 | TypeNs::Adt(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), | 179 | TypeNs::Adt(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), |
180 | TypeNs::BuiltinType(it) => { | 180 | TypeNs::BuiltinType(it) => { |
@@ -391,10 +391,7 @@ impl TraitRef { | |||
391 | ) -> Self { | 391 | ) -> Self { |
392 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | 392 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); |
393 | if let Some(self_ty) = explicit_self_ty { | 393 | if let Some(self_ty) = explicit_self_ty { |
394 | // FIXME this could be nicer | 394 | make_mut_slice(&mut substs.0)[0] = self_ty; |
395 | let mut substs_vec = substs.0.to_vec(); | ||
396 | substs_vec[0] = self_ty; | ||
397 | substs.0 = substs_vec.into(); | ||
398 | } | 395 | } |
399 | TraitRef { trait_: resolved, substs } | 396 | TraitRef { trait_: resolved, substs } |
400 | } | 397 | } |
@@ -557,13 +554,12 @@ pub(crate) fn generic_predicates_for_param_query( | |||
557 | param_idx: u32, | 554 | param_idx: u32, |
558 | ) -> Arc<[GenericPredicate]> { | 555 | ) -> Arc<[GenericPredicate]> { |
559 | let resolver = def.resolver(db); | 556 | let resolver = def.resolver(db); |
560 | let predicates = resolver | 557 | resolver |
561 | .where_predicates_in_scope() | 558 | .where_predicates_in_scope() |
562 | // we have to filter out all other predicates *first*, before attempting to lower them | 559 | // we have to filter out all other predicates *first*, before attempting to lower them |
563 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) | 560 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) |
564 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | 561 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) |
565 | .collect::<Vec<_>>(); | 562 | .collect() |
566 | predicates.into() | ||
567 | } | 563 | } |
568 | 564 | ||
569 | pub(crate) fn trait_env( | 565 | pub(crate) fn trait_env( |
@@ -584,11 +580,10 @@ pub(crate) fn generic_predicates_query( | |||
584 | def: GenericDef, | 580 | def: GenericDef, |
585 | ) -> Arc<[GenericPredicate]> { | 581 | ) -> Arc<[GenericPredicate]> { |
586 | let resolver = def.resolver(db); | 582 | let resolver = def.resolver(db); |
587 | let predicates = resolver | 583 | resolver |
588 | .where_predicates_in_scope() | 584 | .where_predicates_in_scope() |
589 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | 585 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) |
590 | .collect::<Vec<_>>(); | 586 | .collect() |
591 | predicates.into() | ||
592 | } | 587 | } |
593 | 588 | ||
594 | /// Resolve the default type params from generics | 589 | /// Resolve the default type params from generics |
@@ -602,9 +597,9 @@ pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDef) -> | |||
602 | .map(|p| { | 597 | .map(|p| { |
603 | p.default.as_ref().map_or(Ty::Unknown, |path| Ty::from_hir_path(db, &resolver, path)) | 598 | p.default.as_ref().map_or(Ty::Unknown, |path| Ty::from_hir_path(db, &resolver, path)) |
604 | }) | 599 | }) |
605 | .collect::<Vec<_>>(); | 600 | .collect(); |
606 | 601 | ||
607 | Substs(defaults.into()) | 602 | Substs(defaults) |
608 | } | 603 | } |
609 | 604 | ||
610 | fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig { | 605 | fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig { |
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index 25dad81eb..c12326643 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs | |||
@@ -3,7 +3,6 @@ use std::sync::Arc; | |||
3 | 3 | ||
4 | use insta::assert_snapshot; | 4 | use insta::assert_snapshot; |
5 | 5 | ||
6 | use ra_cfg::CfgOptions; | ||
7 | use ra_db::{salsa::Database, FilePosition, SourceDatabase}; | 6 | use ra_db::{salsa::Database, FilePosition, SourceDatabase}; |
8 | use ra_syntax::{ | 7 | use ra_syntax::{ |
9 | algo, | 8 | algo, |
@@ -62,7 +61,7 @@ impl S { | |||
62 | "#, | 61 | "#, |
63 | ); | 62 | ); |
64 | db.set_crate_graph_from_fixture(crate_graph! { | 63 | db.set_crate_graph_from_fixture(crate_graph! { |
65 | "main": ("/main.rs", ["foo"], CfgOptions::default().atom("test".into())), | 64 | "main": ("/main.rs", ["foo"], cfg = { "test" }), |
66 | "foo": ("/foo.rs", []), | 65 | "foo": ("/foo.rs", []), |
67 | }); | 66 | }); |
68 | assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos)); | 67 | assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos)); |
@@ -135,6 +134,25 @@ mod boxed { | |||
135 | } | 134 | } |
136 | 135 | ||
137 | #[test] | 136 | #[test] |
137 | fn infer_adt_self() { | ||
138 | let (db, pos) = MockDatabase::with_position( | ||
139 | r#" | ||
140 | //- /main.rs | ||
141 | enum Nat { Succ(Self), Demo(Nat), Zero } | ||
142 | |||
143 | fn test() { | ||
144 | let foo: Nat = Nat::Zero; | ||
145 | if let Nat::Succ(x) = foo { | ||
146 | x<|> | ||
147 | } | ||
148 | } | ||
149 | |||
150 | "#, | ||
151 | ); | ||
152 | assert_eq!("Nat", type_at_pos(&db, pos)); | ||
153 | } | ||
154 | |||
155 | #[test] | ||
138 | fn infer_try() { | 156 | fn infer_try() { |
139 | let (mut db, pos) = MockDatabase::with_position( | 157 | let (mut db, pos) = MockDatabase::with_position( |
140 | r#" | 158 | r#" |
diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index b0f67ae50..0cb5c3798 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs | |||
@@ -89,7 +89,7 @@ pub(crate) fn impls_for_trait_query( | |||
89 | } | 89 | } |
90 | let crate_impl_blocks = db.impls_in_crate(krate); | 90 | let crate_impl_blocks = db.impls_in_crate(krate); |
91 | impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_)); | 91 | impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_)); |
92 | impls.into_iter().collect::<Vec<_>>().into() | 92 | impls.into_iter().collect() |
93 | } | 93 | } |
94 | 94 | ||
95 | /// A set of clauses that we assume to be true. E.g. if we are inside this function: | 95 | /// A set of clauses that we assume to be true. E.g. if we are inside this function: |
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 2642a54bf..00aaf65d9 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs | |||
@@ -126,8 +126,7 @@ impl ToChalk for Substs { | |||
126 | chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), | 126 | chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), |
127 | chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), | 127 | chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), |
128 | }) | 128 | }) |
129 | .collect::<Vec<_>>() | 129 | .collect(); |
130 | .into(); | ||
131 | Substs(tys) | 130 | Substs(tys) |
132 | } | 131 | } |
133 | } | 132 | } |
@@ -491,15 +490,16 @@ pub(crate) fn trait_datum_query( | |||
491 | }, | 490 | }, |
492 | associated_ty_ids: Vec::new(), | 491 | associated_ty_ids: Vec::new(), |
493 | where_clauses: Vec::new(), | 492 | where_clauses: Vec::new(), |
494 | flags: chalk_rust_ir::TraitFlags { | ||
495 | non_enumerable: true, | ||
496 | auto: false, | ||
497 | marker: false, | ||
498 | upstream: true, | ||
499 | fundamental: false, | ||
500 | }, | ||
501 | }; | 493 | }; |
502 | return Arc::new(TraitDatum { binders: make_binders(trait_datum_bound, 1) }); | 494 | |
495 | let flags = chalk_rust_ir::TraitFlags { | ||
496 | auto: false, | ||
497 | marker: false, | ||
498 | upstream: true, | ||
499 | fundamental: false, | ||
500 | non_enumerable: true, | ||
501 | }; | ||
502 | return Arc::new(TraitDatum { binders: make_binders(trait_datum_bound, 1), flags }); | ||
503 | } | 503 | } |
504 | let trait_: Trait = from_chalk(db, trait_id); | 504 | let trait_: Trait = from_chalk(db, trait_id); |
505 | debug!("trait {:?} = {:?}", trait_id, trait_.name(db)); | 505 | debug!("trait {:?} = {:?}", trait_id, trait_.name(db)); |
@@ -525,8 +525,9 @@ pub(crate) fn trait_datum_query( | |||
525 | .map(|type_alias| type_alias.to_chalk(db)) | 525 | .map(|type_alias| type_alias.to_chalk(db)) |
526 | .collect(); | 526 | .collect(); |
527 | let trait_datum_bound = | 527 | let trait_datum_bound = |
528 | chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags, associated_ty_ids }; | 528 | chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, associated_ty_ids }; |
529 | let trait_datum = TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()) }; | 529 | let trait_datum = |
530 | TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()), flags }; | ||
530 | Arc::new(trait_datum) | 531 | Arc::new(trait_datum) |
531 | } | 532 | } |
532 | 533 | ||
@@ -632,18 +633,20 @@ fn impl_block_datum( | |||
632 | }) | 633 | }) |
633 | .collect(); | 634 | .collect(); |
634 | 635 | ||
635 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { | 636 | let polarity = if negative { |
636 | trait_ref: if negative { | 637 | chalk_rust_ir::Polarity::Negative |
637 | chalk_rust_ir::PolarizedTraitRef::Negative(trait_ref) | 638 | } else { |
638 | } else { | 639 | chalk_rust_ir::Polarity::Positive |
639 | chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref) | ||
640 | }, | ||
641 | where_clauses, | ||
642 | associated_ty_values, | ||
643 | impl_type, | ||
644 | }; | 640 | }; |
641 | |||
642 | let impl_datum_bound = | ||
643 | chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses, associated_ty_values }; | ||
645 | debug!("impl_datum: {:?}", impl_datum_bound); | 644 | debug!("impl_datum: {:?}", impl_datum_bound); |
646 | let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()) }; | 645 | let impl_datum = ImplDatum { |
646 | binders: make_binders(impl_datum_bound, bound_vars.len()), | ||
647 | impl_type, | ||
648 | polarity, | ||
649 | }; | ||
647 | Arc::new(impl_datum) | 650 | Arc::new(impl_datum) |
648 | } | 651 | } |
649 | 652 | ||
@@ -653,12 +656,15 @@ fn invalid_impl_datum() -> Arc<ImplDatum> { | |||
653 | parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], | 656 | parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], |
654 | }; | 657 | }; |
655 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { | 658 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { |
656 | trait_ref: chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref), | 659 | trait_ref, |
657 | where_clauses: Vec::new(), | 660 | where_clauses: Vec::new(), |
658 | associated_ty_values: Vec::new(), | 661 | associated_ty_values: Vec::new(), |
662 | }; | ||
663 | let impl_datum = ImplDatum { | ||
664 | binders: make_binders(impl_datum_bound, 1), | ||
659 | impl_type: chalk_rust_ir::ImplType::External, | 665 | impl_type: chalk_rust_ir::ImplType::External, |
666 | polarity: chalk_rust_ir::Polarity::Positive, | ||
660 | }; | 667 | }; |
661 | let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, 1) }; | ||
662 | Arc::new(impl_datum) | 668 | Arc::new(impl_datum) |
663 | } | 669 | } |
664 | 670 | ||
@@ -713,12 +719,15 @@ fn closure_fn_trait_impl_datum( | |||
713 | let impl_type = chalk_rust_ir::ImplType::External; | 719 | let impl_type = chalk_rust_ir::ImplType::External; |
714 | 720 | ||
715 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { | 721 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { |
716 | trait_ref: chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref.to_chalk(db)), | 722 | trait_ref: trait_ref.to_chalk(db), |
717 | where_clauses: Vec::new(), | 723 | where_clauses: Vec::new(), |
718 | associated_ty_values: vec![output_ty_value], | 724 | associated_ty_values: vec![output_ty_value], |
725 | }; | ||
726 | let impl_datum = ImplDatum { | ||
727 | binders: make_binders(impl_datum_bound, num_args as usize + 1), | ||
719 | impl_type, | 728 | impl_type, |
729 | polarity: chalk_rust_ir::Polarity::Positive, | ||
720 | }; | 730 | }; |
721 | let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, num_args as usize + 1) }; | ||
722 | Some(Arc::new(impl_datum)) | 731 | Some(Arc::new(impl_datum)) |
723 | } | 732 | } |
724 | 733 | ||