diff options
Diffstat (limited to 'crates/ra_hir/src/ty/infer.rs')
-rw-r--r-- | crates/ra_hir/src/ty/infer.rs | 1164 |
1 files changed, 26 insertions, 1138 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 | } |