diff options
author | Aleksey Kladov <[email protected]> | 2019-11-27 14:46:02 +0000 |
---|---|---|
committer | Aleksey Kladov <[email protected]> | 2019-11-27 18:16:00 +0000 |
commit | a87579500a2c35597071efd0ad6983927f0c1815 (patch) | |
tree | 9805b3dcbf8d767b2fc0623f42794068f3660d44 /crates/ra_hir_ty/src | |
parent | 368653081558ab389c6543d6b5027859e26beb3b (diff) |
Move Ty
Diffstat (limited to 'crates/ra_hir_ty/src')
23 files changed, 12282 insertions, 2 deletions
diff --git a/crates/ra_hir_ty/src/autoderef.rs b/crates/ra_hir_ty/src/autoderef.rs new file mode 100644 index 000000000..9d1d4e48c --- /dev/null +++ b/crates/ra_hir_ty/src/autoderef.rs | |||
@@ -0,0 +1,108 @@ | |||
1 | //! In certain situations, rust automatically inserts derefs as necessary: for | ||
2 | //! example, field accesses `foo.bar` still work when `foo` is actually a | ||
3 | //! reference to a type with the field `bar`. This is an approximation of the | ||
4 | //! logic in rustc (which lives in librustc_typeck/check/autoderef.rs). | ||
5 | |||
6 | use std::iter::successors; | ||
7 | |||
8 | use hir_def::lang_item::LangItemTarget; | ||
9 | use hir_expand::name; | ||
10 | use log::{info, warn}; | ||
11 | use ra_db::CrateId; | ||
12 | |||
13 | use crate::db::HirDatabase; | ||
14 | |||
15 | use super::{ | ||
16 | traits::{InEnvironment, Solution}, | ||
17 | Canonical, Substs, Ty, TypeWalk, | ||
18 | }; | ||
19 | |||
20 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | ||
21 | |||
22 | pub fn autoderef<'a>( | ||
23 | db: &'a impl HirDatabase, | ||
24 | krate: Option<CrateId>, | ||
25 | ty: InEnvironment<Canonical<Ty>>, | ||
26 | ) -> impl Iterator<Item = Canonical<Ty>> + 'a { | ||
27 | let InEnvironment { value: ty, environment } = ty; | ||
28 | successors(Some(ty), move |ty| { | ||
29 | deref(db, krate?, InEnvironment { value: ty, environment: environment.clone() }) | ||
30 | }) | ||
31 | .take(AUTODEREF_RECURSION_LIMIT) | ||
32 | } | ||
33 | |||
34 | pub(crate) fn deref( | ||
35 | db: &impl HirDatabase, | ||
36 | krate: CrateId, | ||
37 | ty: InEnvironment<&Canonical<Ty>>, | ||
38 | ) -> Option<Canonical<Ty>> { | ||
39 | if let Some(derefed) = ty.value.value.builtin_deref() { | ||
40 | Some(Canonical { value: derefed, num_vars: ty.value.num_vars }) | ||
41 | } else { | ||
42 | deref_by_trait(db, krate, ty) | ||
43 | } | ||
44 | } | ||
45 | |||
46 | fn deref_by_trait( | ||
47 | db: &impl HirDatabase, | ||
48 | krate: CrateId, | ||
49 | ty: InEnvironment<&Canonical<Ty>>, | ||
50 | ) -> Option<Canonical<Ty>> { | ||
51 | let deref_trait = match db.lang_item(krate.into(), "deref".into())? { | ||
52 | LangItemTarget::TraitId(it) => it, | ||
53 | _ => return None, | ||
54 | }; | ||
55 | let target = db.trait_data(deref_trait).associated_type_by_name(&name::TARGET_TYPE)?; | ||
56 | |||
57 | let generic_params = db.generic_params(target.into()); | ||
58 | if generic_params.count_params_including_parent() != 1 { | ||
59 | // the Target type + Deref trait should only have one generic parameter, | ||
60 | // namely Deref's Self type | ||
61 | return None; | ||
62 | } | ||
63 | |||
64 | // FIXME make the Canonical handling nicer | ||
65 | |||
66 | let parameters = Substs::build_for_generics(&generic_params) | ||
67 | .push(ty.value.value.clone().shift_bound_vars(1)) | ||
68 | .build(); | ||
69 | |||
70 | let projection = super::traits::ProjectionPredicate { | ||
71 | ty: Ty::Bound(0), | ||
72 | projection_ty: super::ProjectionTy { associated_ty: target, parameters }, | ||
73 | }; | ||
74 | |||
75 | let obligation = super::Obligation::Projection(projection); | ||
76 | |||
77 | let in_env = InEnvironment { value: obligation, environment: ty.environment }; | ||
78 | |||
79 | let canonical = super::Canonical { num_vars: 1 + ty.value.num_vars, value: in_env }; | ||
80 | |||
81 | let solution = db.trait_solve(krate.into(), canonical)?; | ||
82 | |||
83 | match &solution { | ||
84 | Solution::Unique(vars) => { | ||
85 | // FIXME: vars may contain solutions for any inference variables | ||
86 | // that happened to be inside ty. To correctly handle these, we | ||
87 | // would have to pass the solution up to the inference context, but | ||
88 | // that requires a larger refactoring (especially if the deref | ||
89 | // happens during method resolution). So for the moment, we just | ||
90 | // check that we're not in the situation we're we would actually | ||
91 | // need to handle the values of the additional variables, i.e. | ||
92 | // they're just being 'passed through'. In the 'standard' case where | ||
93 | // we have `impl<T> Deref for Foo<T> { Target = T }`, that should be | ||
94 | // the case. | ||
95 | for i in 1..vars.0.num_vars { | ||
96 | if vars.0.value[i] != Ty::Bound((i - 1) as u32) { | ||
97 | warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution); | ||
98 | return None; | ||
99 | } | ||
100 | } | ||
101 | Some(Canonical { value: vars.0.value[0].clone(), num_vars: vars.0.num_vars }) | ||
102 | } | ||
103 | Solution::Ambig(_) => { | ||
104 | info!("Ambiguous solution for derefing {:?}: {:?}", ty.value, solution); | ||
105 | None | ||
106 | } | ||
107 | } | ||
108 | } | ||
diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs new file mode 100644 index 000000000..aa2659c4b --- /dev/null +++ b/crates/ra_hir_ty/src/db.rs | |||
@@ -0,0 +1,116 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_def::{ | ||
6 | db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId, | ||
7 | }; | ||
8 | use ra_arena::map::ArenaMap; | ||
9 | use ra_db::{salsa, CrateId}; | ||
10 | |||
11 | use crate::{ | ||
12 | method_resolution::CrateImplBlocks, | ||
13 | traits::{AssocTyValue, Impl}, | ||
14 | CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor, | ||
15 | ValueTyDefId, | ||
16 | }; | ||
17 | |||
18 | #[salsa::query_group(HirDatabaseStorage)] | ||
19 | #[salsa::requires(salsa::Database)] | ||
20 | pub trait HirDatabase: DefDatabase { | ||
21 | #[salsa::invoke(crate::infer_query)] | ||
22 | fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>; | ||
23 | |||
24 | #[salsa::invoke(crate::lower::ty_query)] | ||
25 | fn ty(&self, def: TyDefId) -> Ty; | ||
26 | |||
27 | #[salsa::invoke(crate::lower::value_ty_query)] | ||
28 | fn value_ty(&self, def: ValueTyDefId) -> Ty; | ||
29 | |||
30 | #[salsa::invoke(crate::lower::field_types_query)] | ||
31 | fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>; | ||
32 | |||
33 | #[salsa::invoke(crate::callable_item_sig)] | ||
34 | fn callable_item_signature(&self, def: CallableDef) -> FnSig; | ||
35 | |||
36 | #[salsa::invoke(crate::lower::generic_predicates_for_param_query)] | ||
37 | fn generic_predicates_for_param( | ||
38 | &self, | ||
39 | def: GenericDefId, | ||
40 | param_idx: u32, | ||
41 | ) -> Arc<[GenericPredicate]>; | ||
42 | |||
43 | #[salsa::invoke(crate::lower::generic_predicates_query)] | ||
44 | fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>; | ||
45 | |||
46 | #[salsa::invoke(crate::lower::generic_defaults_query)] | ||
47 | fn generic_defaults(&self, def: GenericDefId) -> Substs; | ||
48 | |||
49 | #[salsa::invoke(crate::method_resolution::CrateImplBlocks::impls_in_crate_query)] | ||
50 | fn impls_in_crate(&self, krate: CrateId) -> Arc<CrateImplBlocks>; | ||
51 | |||
52 | #[salsa::invoke(crate::traits::impls_for_trait_query)] | ||
53 | fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>; | ||
54 | |||
55 | /// This provides the Chalk trait solver instance. Because Chalk always | ||
56 | /// works from a specific crate, this query is keyed on the crate; and | ||
57 | /// because Chalk does its own internal caching, the solver is wrapped in a | ||
58 | /// Mutex and the query does an untracked read internally, to make sure the | ||
59 | /// cached state is thrown away when input facts change. | ||
60 | #[salsa::invoke(crate::traits::trait_solver_query)] | ||
61 | fn trait_solver(&self, krate: CrateId) -> crate::traits::TraitSolver; | ||
62 | |||
63 | // Interned IDs for Chalk integration | ||
64 | #[salsa::interned] | ||
65 | fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId; | ||
66 | #[salsa::interned] | ||
67 | fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId; | ||
68 | #[salsa::interned] | ||
69 | fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId; | ||
70 | |||
71 | #[salsa::invoke(crate::traits::chalk::associated_ty_data_query)] | ||
72 | fn associated_ty_data( | ||
73 | &self, | ||
74 | id: chalk_ir::TypeId, | ||
75 | ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>; | ||
76 | |||
77 | #[salsa::invoke(crate::traits::chalk::trait_datum_query)] | ||
78 | fn trait_datum( | ||
79 | &self, | ||
80 | krate: CrateId, | ||
81 | trait_id: chalk_ir::TraitId, | ||
82 | ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>; | ||
83 | |||
84 | #[salsa::invoke(crate::traits::chalk::struct_datum_query)] | ||
85 | fn struct_datum( | ||
86 | &self, | ||
87 | krate: CrateId, | ||
88 | struct_id: chalk_ir::StructId, | ||
89 | ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>; | ||
90 | |||
91 | #[salsa::invoke(crate::traits::chalk::impl_datum_query)] | ||
92 | fn impl_datum( | ||
93 | &self, | ||
94 | krate: CrateId, | ||
95 | impl_id: chalk_ir::ImplId, | ||
96 | ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>; | ||
97 | |||
98 | #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)] | ||
99 | fn associated_ty_value( | ||
100 | &self, | ||
101 | krate: CrateId, | ||
102 | id: chalk_rust_ir::AssociatedTyValueId, | ||
103 | ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>; | ||
104 | |||
105 | #[salsa::invoke(crate::traits::trait_solve_query)] | ||
106 | fn trait_solve( | ||
107 | &self, | ||
108 | krate: CrateId, | ||
109 | goal: crate::Canonical<crate::InEnvironment<crate::Obligation>>, | ||
110 | ) -> Option<crate::traits::Solution>; | ||
111 | } | ||
112 | |||
113 | #[test] | ||
114 | fn hir_database_is_object_safe() { | ||
115 | fn _assert_object_safe(_: &dyn HirDatabase) {} | ||
116 | } | ||
diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs new file mode 100644 index 000000000..4a13fac23 --- /dev/null +++ b/crates/ra_hir_ty/src/diagnostics.rs | |||
@@ -0,0 +1,91 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::any::Any; | ||
4 | |||
5 | use hir_expand::{db::AstDatabase, name::Name, HirFileId, Source}; | ||
6 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; | ||
7 | |||
8 | pub use hir_def::diagnostics::UnresolvedModule; | ||
9 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; | ||
10 | |||
11 | #[derive(Debug)] | ||
12 | pub struct NoSuchField { | ||
13 | pub file: HirFileId, | ||
14 | pub field: AstPtr<ast::RecordField>, | ||
15 | } | ||
16 | |||
17 | impl Diagnostic for NoSuchField { | ||
18 | fn message(&self) -> String { | ||
19 | "no such field".to_string() | ||
20 | } | ||
21 | |||
22 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
23 | Source { file_id: self.file, value: self.field.into() } | ||
24 | } | ||
25 | |||
26 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
27 | self | ||
28 | } | ||
29 | } | ||
30 | |||
31 | #[derive(Debug)] | ||
32 | pub struct MissingFields { | ||
33 | pub file: HirFileId, | ||
34 | pub field_list: AstPtr<ast::RecordFieldList>, | ||
35 | pub missed_fields: Vec<Name>, | ||
36 | } | ||
37 | |||
38 | impl Diagnostic for MissingFields { | ||
39 | fn message(&self) -> String { | ||
40 | use std::fmt::Write; | ||
41 | let mut message = String::from("Missing structure fields:\n"); | ||
42 | for field in &self.missed_fields { | ||
43 | write!(message, "- {}\n", field).unwrap(); | ||
44 | } | ||
45 | message | ||
46 | } | ||
47 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
48 | Source { file_id: self.file, value: self.field_list.into() } | ||
49 | } | ||
50 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
51 | self | ||
52 | } | ||
53 | } | ||
54 | |||
55 | impl AstDiagnostic for MissingFields { | ||
56 | type AST = ast::RecordFieldList; | ||
57 | |||
58 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
59 | let root = db.parse_or_expand(self.source().file_id).unwrap(); | ||
60 | let node = self.source().value.to_node(&root); | ||
61 | ast::RecordFieldList::cast(node).unwrap() | ||
62 | } | ||
63 | } | ||
64 | |||
65 | #[derive(Debug)] | ||
66 | pub struct MissingOkInTailExpr { | ||
67 | pub file: HirFileId, | ||
68 | pub expr: AstPtr<ast::Expr>, | ||
69 | } | ||
70 | |||
71 | impl Diagnostic for MissingOkInTailExpr { | ||
72 | fn message(&self) -> String { | ||
73 | "wrap return expression in Ok".to_string() | ||
74 | } | ||
75 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
76 | Source { file_id: self.file, value: self.expr.into() } | ||
77 | } | ||
78 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
79 | self | ||
80 | } | ||
81 | } | ||
82 | |||
83 | impl AstDiagnostic for MissingOkInTailExpr { | ||
84 | type AST = ast::Expr; | ||
85 | |||
86 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
87 | let root = db.parse_or_expand(self.file).unwrap(); | ||
88 | let node = self.source().value.to_node(&root); | ||
89 | ast::Expr::cast(node).unwrap() | ||
90 | } | ||
91 | } | ||
diff --git a/crates/ra_hir_ty/src/display.rs b/crates/ra_hir_ty/src/display.rs new file mode 100644 index 000000000..9bb3ece6c --- /dev/null +++ b/crates/ra_hir_ty/src/display.rs | |||
@@ -0,0 +1,93 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | use crate::db::HirDatabase; | ||
6 | |||
7 | pub struct HirFormatter<'a, 'b, DB> { | ||
8 | pub db: &'a DB, | ||
9 | fmt: &'a mut fmt::Formatter<'b>, | ||
10 | buf: String, | ||
11 | curr_size: usize, | ||
12 | max_size: Option<usize>, | ||
13 | } | ||
14 | |||
15 | pub trait HirDisplay { | ||
16 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; | ||
17 | |||
18 | fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> | ||
19 | where | ||
20 | Self: Sized, | ||
21 | { | ||
22 | HirDisplayWrapper(db, self, None) | ||
23 | } | ||
24 | |||
25 | fn display_truncated<'a, DB>( | ||
26 | &'a self, | ||
27 | db: &'a DB, | ||
28 | max_size: Option<usize>, | ||
29 | ) -> HirDisplayWrapper<'a, DB, Self> | ||
30 | where | ||
31 | Self: Sized, | ||
32 | { | ||
33 | HirDisplayWrapper(db, self, max_size) | ||
34 | } | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> | ||
38 | where | ||
39 | DB: HirDatabase, | ||
40 | { | ||
41 | pub fn write_joined<T: HirDisplay>( | ||
42 | &mut self, | ||
43 | iter: impl IntoIterator<Item = T>, | ||
44 | sep: &str, | ||
45 | ) -> fmt::Result { | ||
46 | let mut first = true; | ||
47 | for e in iter { | ||
48 | if !first { | ||
49 | write!(self, "{}", sep)?; | ||
50 | } | ||
51 | first = false; | ||
52 | e.hir_fmt(self)?; | ||
53 | } | ||
54 | Ok(()) | ||
55 | } | ||
56 | |||
57 | /// This allows using the `write!` macro directly with a `HirFormatter`. | ||
58 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | ||
59 | // We write to a buffer first to track output size | ||
60 | self.buf.clear(); | ||
61 | fmt::write(&mut self.buf, args)?; | ||
62 | self.curr_size += self.buf.len(); | ||
63 | |||
64 | // Then we write to the internal formatter from the buffer | ||
65 | self.fmt.write_str(&self.buf) | ||
66 | } | ||
67 | |||
68 | pub fn should_truncate(&self) -> bool { | ||
69 | if let Some(max_size) = self.max_size { | ||
70 | self.curr_size >= max_size | ||
71 | } else { | ||
72 | false | ||
73 | } | ||
74 | } | ||
75 | } | ||
76 | |||
77 | pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>); | ||
78 | |||
79 | impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> | ||
80 | where | ||
81 | DB: HirDatabase, | ||
82 | T: HirDisplay, | ||
83 | { | ||
84 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
85 | self.1.hir_fmt(&mut HirFormatter { | ||
86 | db: self.0, | ||
87 | fmt: f, | ||
88 | buf: String::with_capacity(20), | ||
89 | curr_size: 0, | ||
90 | max_size: self.2, | ||
91 | }) | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs new file mode 100644 index 000000000..5c65f9370 --- /dev/null +++ b/crates/ra_hir_ty/src/expr.rs | |||
@@ -0,0 +1,151 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_def::{ | ||
6 | path::{known, Path}, | ||
7 | resolver::HasResolver, | ||
8 | AdtId, FunctionId, | ||
9 | }; | ||
10 | use hir_expand::{diagnostics::DiagnosticSink, name::Name}; | ||
11 | use ra_syntax::ast; | ||
12 | use ra_syntax::AstPtr; | ||
13 | use rustc_hash::FxHashSet; | ||
14 | |||
15 | use crate::{ | ||
16 | db::HirDatabase, | ||
17 | diagnostics::{MissingFields, MissingOkInTailExpr}, | ||
18 | ApplicationTy, InferenceResult, Ty, TypeCtor, | ||
19 | }; | ||
20 | |||
21 | pub use hir_def::{ | ||
22 | body::{ | ||
23 | scope::{ExprScopes, ScopeEntry, ScopeId}, | ||
24 | Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource, | ||
25 | }, | ||
26 | expr::{ | ||
27 | ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp, | ||
28 | MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp, | ||
29 | }, | ||
30 | }; | ||
31 | |||
32 | pub struct ExprValidator<'a, 'b: 'a> { | ||
33 | func: FunctionId, | ||
34 | infer: Arc<InferenceResult>, | ||
35 | sink: &'a mut DiagnosticSink<'b>, | ||
36 | } | ||
37 | |||
38 | impl<'a, 'b> ExprValidator<'a, 'b> { | ||
39 | pub fn new( | ||
40 | func: FunctionId, | ||
41 | infer: Arc<InferenceResult>, | ||
42 | sink: &'a mut DiagnosticSink<'b>, | ||
43 | ) -> ExprValidator<'a, 'b> { | ||
44 | ExprValidator { func, infer, sink } | ||
45 | } | ||
46 | |||
47 | pub fn validate_body(&mut self, db: &impl HirDatabase) { | ||
48 | let body = db.body(self.func.into()); | ||
49 | |||
50 | for e in body.exprs.iter() { | ||
51 | if let (id, Expr::RecordLit { path, fields, spread }) = e { | ||
52 | self.validate_record_literal(id, path, fields, *spread, db); | ||
53 | } | ||
54 | } | ||
55 | |||
56 | let body_expr = &body[body.body_expr]; | ||
57 | if let Expr::Block { statements: _, tail: Some(t) } = body_expr { | ||
58 | self.validate_results_in_tail_expr(body.body_expr, *t, db); | ||
59 | } | ||
60 | } | ||
61 | |||
62 | fn validate_record_literal( | ||
63 | &mut self, | ||
64 | id: ExprId, | ||
65 | _path: &Option<Path>, | ||
66 | fields: &[RecordLitField], | ||
67 | spread: Option<ExprId>, | ||
68 | db: &impl HirDatabase, | ||
69 | ) { | ||
70 | if spread.is_some() { | ||
71 | return; | ||
72 | } | ||
73 | |||
74 | let struct_def = match self.infer[id].as_adt() { | ||
75 | Some((AdtId::StructId(s), _)) => s, | ||
76 | _ => return, | ||
77 | }; | ||
78 | let struct_data = db.struct_data(struct_def); | ||
79 | |||
80 | let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); | ||
81 | let missed_fields: Vec<Name> = struct_data | ||
82 | .variant_data | ||
83 | .fields() | ||
84 | .iter() | ||
85 | .filter_map(|(_f, d)| { | ||
86 | let name = d.name.clone(); | ||
87 | if lit_fields.contains(&name) { | ||
88 | None | ||
89 | } else { | ||
90 | Some(name) | ||
91 | } | ||
92 | }) | ||
93 | .collect(); | ||
94 | if missed_fields.is_empty() { | ||
95 | return; | ||
96 | } | ||
97 | let (_, source_map) = db.body_with_source_map(self.func.into()); | ||
98 | |||
99 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
100 | if let Some(expr) = source_ptr.value.a() { | ||
101 | let root = source_ptr.file_syntax(db); | ||
102 | if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) { | ||
103 | if let Some(field_list) = record_lit.record_field_list() { | ||
104 | self.sink.push(MissingFields { | ||
105 | file: source_ptr.file_id, | ||
106 | field_list: AstPtr::new(&field_list), | ||
107 | missed_fields, | ||
108 | }) | ||
109 | } | ||
110 | } | ||
111 | } | ||
112 | } | ||
113 | } | ||
114 | |||
115 | fn validate_results_in_tail_expr( | ||
116 | &mut self, | ||
117 | body_id: ExprId, | ||
118 | id: ExprId, | ||
119 | db: &impl HirDatabase, | ||
120 | ) { | ||
121 | // the mismatch will be on the whole block currently | ||
122 | let mismatch = match self.infer.type_mismatch_for_expr(body_id) { | ||
123 | Some(m) => m, | ||
124 | None => return, | ||
125 | }; | ||
126 | |||
127 | let std_result_path = known::std_result_result(); | ||
128 | |||
129 | let resolver = self.func.resolver(db); | ||
130 | let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { | ||
131 | Some(it) => it, | ||
132 | _ => return, | ||
133 | }; | ||
134 | |||
135 | let std_result_ctor = TypeCtor::Adt(AdtId::EnumId(std_result_enum)); | ||
136 | let params = match &mismatch.expected { | ||
137 | Ty::Apply(ApplicationTy { ctor, parameters }) if ctor == &std_result_ctor => parameters, | ||
138 | _ => return, | ||
139 | }; | ||
140 | |||
141 | if params.len() == 2 && ¶ms[0] == &mismatch.actual { | ||
142 | let (_, source_map) = db.body_with_source_map(self.func.into()); | ||
143 | |||
144 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
145 | if let Some(expr) = source_ptr.value.a() { | ||
146 | self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr }); | ||
147 | } | ||
148 | } | ||
149 | } | ||
150 | } | ||
151 | } | ||
diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs new file mode 100644 index 000000000..1e9f4b208 --- /dev/null +++ b/crates/ra_hir_ty/src/infer.rs | |||
@@ -0,0 +1,723 @@ | |||
1 | //! Type inference, i.e. the process of walking through the code and determining | ||
2 | //! the type of each expression and pattern. | ||
3 | //! | ||
4 | //! For type inference, compare the implementations in rustc (the various | ||
5 | //! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and | ||
6 | //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for | ||
7 | //! inference here is the `infer` function, which infers the types of all | ||
8 | //! expressions in a given function. | ||
9 | //! | ||
10 | //! During inference, types (i.e. the `Ty` struct) can contain type 'variables' | ||
11 | //! which represent currently unknown types; as we walk through the expressions, | ||
12 | //! we might determine that certain variables need to be equal to each other, or | ||
13 | //! to certain types. To record this, we use the union-find implementation from | ||
14 | //! the `ena` crate, which is extracted from rustc. | ||
15 | |||
16 | use std::borrow::Cow; | ||
17 | use std::mem; | ||
18 | use std::ops::Index; | ||
19 | use std::sync::Arc; | ||
20 | |||
21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; | ||
22 | use rustc_hash::FxHashMap; | ||
23 | |||
24 | use hir_def::{ | ||
25 | body::Body, | ||
26 | data::{ConstData, FunctionData}, | ||
27 | expr::{BindingAnnotation, ExprId, PatId}, | ||
28 | path::{known, Path}, | ||
29 | resolver::{HasResolver, Resolver, TypeNs}, | ||
30 | type_ref::{Mutability, TypeRef}, | ||
31 | AdtId, AssocItemId, DefWithBodyId, FunctionId, StructFieldId, TypeAliasId, VariantId, | ||
32 | }; | ||
33 | use hir_expand::{diagnostics::DiagnosticSink, name}; | ||
34 | use ra_arena::map::ArenaMap; | ||
35 | use ra_prof::profile; | ||
36 | use test_utils::tested_by; | ||
37 | |||
38 | use super::{ | ||
39 | primitive::{FloatTy, IntTy}, | ||
40 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | ||
41 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor, | ||
42 | TypeWalk, Uncertain, | ||
43 | }; | ||
44 | use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic}; | ||
45 | |||
46 | macro_rules! ty_app { | ||
47 | ($ctor:pat, $param:pat) => { | ||
48 | crate::Ty::Apply(crate::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
49 | }; | ||
50 | ($ctor:pat) => { | ||
51 | ty_app!($ctor, _) | ||
52 | }; | ||
53 | } | ||
54 | |||
55 | mod unify; | ||
56 | mod path; | ||
57 | mod expr; | ||
58 | mod pat; | ||
59 | mod coerce; | ||
60 | |||
61 | /// The entry point of type inference. | ||
62 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> { | ||
63 | let _p = profile("infer_query"); | ||
64 | let resolver = def.resolver(db); | ||
65 | let mut ctx = InferenceContext::new(db, def, resolver); | ||
66 | |||
67 | match def { | ||
68 | DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)), | ||
69 | DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)), | ||
70 | DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)), | ||
71 | } | ||
72 | |||
73 | ctx.infer_body(); | ||
74 | |||
75 | Arc::new(ctx.resolve_all()) | ||
76 | } | ||
77 | |||
78 | #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] | ||
79 | enum ExprOrPatId { | ||
80 | ExprId(ExprId), | ||
81 | PatId(PatId), | ||
82 | } | ||
83 | |||
84 | impl_froms!(ExprOrPatId: ExprId, PatId); | ||
85 | |||
86 | /// Binding modes inferred for patterns. | ||
87 | /// https://doc.rust-lang.org/reference/patterns.html#binding-modes | ||
88 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | ||
89 | enum BindingMode { | ||
90 | Move, | ||
91 | Ref(Mutability), | ||
92 | } | ||
93 | |||
94 | impl BindingMode { | ||
95 | pub fn convert(annotation: BindingAnnotation) -> BindingMode { | ||
96 | match annotation { | ||
97 | BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, | ||
98 | BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), | ||
99 | BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut), | ||
100 | } | ||
101 | } | ||
102 | } | ||
103 | |||
104 | impl Default for BindingMode { | ||
105 | fn default() -> Self { | ||
106 | BindingMode::Move | ||
107 | } | ||
108 | } | ||
109 | |||
110 | /// A mismatch between an expected and an inferred type. | ||
111 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
112 | pub struct TypeMismatch { | ||
113 | pub expected: Ty, | ||
114 | pub actual: Ty, | ||
115 | } | ||
116 | |||
117 | /// The result of type inference: A mapping from expressions and patterns to types. | ||
118 | #[derive(Clone, PartialEq, Eq, Debug, Default)] | ||
119 | pub struct InferenceResult { | ||
120 | /// For each method call expr, records the function it resolves to. | ||
121 | method_resolutions: FxHashMap<ExprId, FunctionId>, | ||
122 | /// For each field access expr, records the field it resolves to. | ||
123 | field_resolutions: FxHashMap<ExprId, StructFieldId>, | ||
124 | /// For each field in record literal, records the field it resolves to. | ||
125 | record_field_resolutions: FxHashMap<ExprId, StructFieldId>, | ||
126 | /// For each struct literal, records the variant it resolves to. | ||
127 | variant_resolutions: FxHashMap<ExprOrPatId, VariantId>, | ||
128 | /// For each associated item record what it resolves to | ||
129 | assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>, | ||
130 | diagnostics: Vec<InferenceDiagnostic>, | ||
131 | pub type_of_expr: ArenaMap<ExprId, Ty>, | ||
132 | pub type_of_pat: ArenaMap<PatId, Ty>, | ||
133 | pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>, | ||
134 | } | ||
135 | |||
136 | impl InferenceResult { | ||
137 | pub fn method_resolution(&self, expr: ExprId) -> Option<FunctionId> { | ||
138 | self.method_resolutions.get(&expr).copied() | ||
139 | } | ||
140 | pub fn field_resolution(&self, expr: ExprId) -> Option<StructFieldId> { | ||
141 | self.field_resolutions.get(&expr).copied() | ||
142 | } | ||
143 | pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructFieldId> { | ||
144 | self.record_field_resolutions.get(&expr).copied() | ||
145 | } | ||
146 | pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> { | ||
147 | self.variant_resolutions.get(&id.into()).copied() | ||
148 | } | ||
149 | pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> { | ||
150 | self.variant_resolutions.get(&id.into()).copied() | ||
151 | } | ||
152 | pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> { | ||
153 | self.assoc_resolutions.get(&id.into()).copied() | ||
154 | } | ||
155 | pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> { | ||
156 | self.assoc_resolutions.get(&id.into()).copied() | ||
157 | } | ||
158 | pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { | ||
159 | self.type_mismatches.get(expr) | ||
160 | } | ||
161 | pub fn add_diagnostics( | ||
162 | &self, | ||
163 | db: &impl HirDatabase, | ||
164 | owner: FunctionId, | ||
165 | sink: &mut DiagnosticSink, | ||
166 | ) { | ||
167 | self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink)) | ||
168 | } | ||
169 | } | ||
170 | |||
171 | impl Index<ExprId> for InferenceResult { | ||
172 | type Output = Ty; | ||
173 | |||
174 | fn index(&self, expr: ExprId) -> &Ty { | ||
175 | self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) | ||
176 | } | ||
177 | } | ||
178 | |||
179 | impl Index<PatId> for InferenceResult { | ||
180 | type Output = Ty; | ||
181 | |||
182 | fn index(&self, pat: PatId) -> &Ty { | ||
183 | self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) | ||
184 | } | ||
185 | } | ||
186 | |||
187 | /// The inference context contains all information needed during type inference. | ||
188 | #[derive(Clone, Debug)] | ||
189 | struct InferenceContext<'a, D: HirDatabase> { | ||
190 | db: &'a D, | ||
191 | owner: DefWithBodyId, | ||
192 | body: Arc<Body>, | ||
193 | resolver: Resolver, | ||
194 | var_unification_table: InPlaceUnificationTable<TypeVarId>, | ||
195 | trait_env: Arc<TraitEnvironment>, | ||
196 | obligations: Vec<Obligation>, | ||
197 | result: InferenceResult, | ||
198 | /// The return type of the function being inferred. | ||
199 | return_ty: Ty, | ||
200 | |||
201 | /// Impls of `CoerceUnsized` used in coercion. | ||
202 | /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index | ||
203 | // FIXME: Use trait solver for this. | ||
204 | // Chalk seems unable to work well with builtin impl of `Unsize` now. | ||
205 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | ||
206 | } | ||
207 | |||
208 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
209 | fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self { | ||
210 | InferenceContext { | ||
211 | result: InferenceResult::default(), | ||
212 | var_unification_table: InPlaceUnificationTable::new(), | ||
213 | obligations: Vec::default(), | ||
214 | return_ty: Ty::Unknown, // set in collect_fn_signature | ||
215 | trait_env: TraitEnvironment::lower(db, &resolver), | ||
216 | coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver), | ||
217 | db, | ||
218 | owner, | ||
219 | body: db.body(owner.into()), | ||
220 | resolver, | ||
221 | } | ||
222 | } | ||
223 | |||
224 | fn resolve_all(mut self) -> InferenceResult { | ||
225 | // FIXME resolve obligations as well (use Guidance if necessary) | ||
226 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | ||
227 | let mut tv_stack = Vec::new(); | ||
228 | for ty in result.type_of_expr.values_mut() { | ||
229 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
230 | *ty = resolved; | ||
231 | } | ||
232 | for ty in result.type_of_pat.values_mut() { | ||
233 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
234 | *ty = resolved; | ||
235 | } | ||
236 | result | ||
237 | } | ||
238 | |||
239 | fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) { | ||
240 | self.result.type_of_expr.insert(expr, ty); | ||
241 | } | ||
242 | |||
243 | fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId) { | ||
244 | self.result.method_resolutions.insert(expr, func); | ||
245 | } | ||
246 | |||
247 | fn write_field_resolution(&mut self, expr: ExprId, field: StructFieldId) { | ||
248 | self.result.field_resolutions.insert(expr, field); | ||
249 | } | ||
250 | |||
251 | fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) { | ||
252 | self.result.variant_resolutions.insert(id, variant); | ||
253 | } | ||
254 | |||
255 | fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) { | ||
256 | self.result.assoc_resolutions.insert(id, item.into()); | ||
257 | } | ||
258 | |||
259 | fn write_pat_ty(&mut self, pat: PatId, ty: Ty) { | ||
260 | self.result.type_of_pat.insert(pat, ty); | ||
261 | } | ||
262 | |||
263 | fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) { | ||
264 | self.result.diagnostics.push(diagnostic); | ||
265 | } | ||
266 | |||
267 | fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { | ||
268 | let ty = Ty::from_hir( | ||
269 | self.db, | ||
270 | // FIXME use right resolver for block | ||
271 | &self.resolver, | ||
272 | type_ref, | ||
273 | ); | ||
274 | let ty = self.insert_type_vars(ty); | ||
275 | self.normalize_associated_types_in(ty) | ||
276 | } | ||
277 | |||
278 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { | ||
279 | substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) | ||
280 | } | ||
281 | |||
282 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
283 | self.unify_inner(ty1, ty2, 0) | ||
284 | } | ||
285 | |||
286 | fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { | ||
287 | if depth > 1000 { | ||
288 | // prevent stackoverflows | ||
289 | panic!("infinite recursion in unification"); | ||
290 | } | ||
291 | if ty1 == ty2 { | ||
292 | return true; | ||
293 | } | ||
294 | // try to resolve type vars first | ||
295 | let ty1 = self.resolve_ty_shallow(ty1); | ||
296 | let ty2 = self.resolve_ty_shallow(ty2); | ||
297 | match (&*ty1, &*ty2) { | ||
298 | (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { | ||
299 | self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) | ||
300 | } | ||
301 | _ => self.unify_inner_trivial(&ty1, &ty2), | ||
302 | } | ||
303 | } | ||
304 | |||
305 | fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
306 | match (ty1, ty2) { | ||
307 | (Ty::Unknown, _) | (_, Ty::Unknown) => true, | ||
308 | |||
309 | (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) | ||
310 | | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) | ||
311 | | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) | ||
312 | | ( | ||
313 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), | ||
314 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), | ||
315 | ) => { | ||
316 | // both type vars are unknown since we tried to resolve them | ||
317 | self.var_unification_table.union(*tv1, *tv2); | ||
318 | true | ||
319 | } | ||
320 | |||
321 | // The order of MaybeNeverTypeVar matters here. | ||
322 | // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. | ||
323 | // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. | ||
324 | (Ty::Infer(InferTy::TypeVar(tv)), other) | ||
325 | | (other, Ty::Infer(InferTy::TypeVar(tv))) | ||
326 | | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) | ||
327 | | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) | ||
328 | | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) | ||
329 | | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) | ||
330 | | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) | ||
331 | | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { | ||
332 | // the type var is unknown since we tried to resolve it | ||
333 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); | ||
334 | true | ||
335 | } | ||
336 | |||
337 | _ => false, | ||
338 | } | ||
339 | } | ||
340 | |||
341 | fn new_type_var(&mut self) -> Ty { | ||
342 | Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
343 | } | ||
344 | |||
345 | fn new_integer_var(&mut self) -> Ty { | ||
346 | Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
347 | } | ||
348 | |||
349 | fn new_float_var(&mut self) -> Ty { | ||
350 | Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
351 | } | ||
352 | |||
353 | fn new_maybe_never_type_var(&mut self) -> Ty { | ||
354 | Ty::Infer(InferTy::MaybeNeverTypeVar( | ||
355 | self.var_unification_table.new_key(TypeVarValue::Unknown), | ||
356 | )) | ||
357 | } | ||
358 | |||
359 | /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. | ||
360 | fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { | ||
361 | match ty { | ||
362 | Ty::Unknown => self.new_type_var(), | ||
363 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => { | ||
364 | self.new_integer_var() | ||
365 | } | ||
366 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => { | ||
367 | self.new_float_var() | ||
368 | } | ||
369 | _ => ty, | ||
370 | } | ||
371 | } | ||
372 | |||
373 | fn insert_type_vars(&mut self, ty: Ty) -> Ty { | ||
374 | ty.fold(&mut |ty| self.insert_type_vars_shallow(ty)) | ||
375 | } | ||
376 | |||
377 | fn resolve_obligations_as_possible(&mut self) { | ||
378 | let obligations = mem::replace(&mut self.obligations, Vec::new()); | ||
379 | for obligation in obligations { | ||
380 | let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone()); | ||
381 | let canonicalized = self.canonicalizer().canonicalize_obligation(in_env); | ||
382 | let solution = self | ||
383 | .db | ||
384 | .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone()); | ||
385 | |||
386 | match solution { | ||
387 | Some(Solution::Unique(substs)) => { | ||
388 | canonicalized.apply_solution(self, substs.0); | ||
389 | } | ||
390 | Some(Solution::Ambig(Guidance::Definite(substs))) => { | ||
391 | canonicalized.apply_solution(self, substs.0); | ||
392 | self.obligations.push(obligation); | ||
393 | } | ||
394 | Some(_) => { | ||
395 | // FIXME use this when trying to resolve everything at the end | ||
396 | self.obligations.push(obligation); | ||
397 | } | ||
398 | None => { | ||
399 | // FIXME obligation cannot be fulfilled => diagnostic | ||
400 | } | ||
401 | }; | ||
402 | } | ||
403 | } | ||
404 | |||
405 | /// Resolves the type as far as currently possible, replacing type variables | ||
406 | /// by their known types. All types returned by the infer_* functions should | ||
407 | /// be resolved as far as possible, i.e. contain no type variables with | ||
408 | /// known type. | ||
409 | fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
410 | self.resolve_obligations_as_possible(); | ||
411 | |||
412 | ty.fold(&mut |ty| match ty { | ||
413 | Ty::Infer(tv) => { | ||
414 | let inner = tv.to_inner(); | ||
415 | if tv_stack.contains(&inner) { | ||
416 | tested_by!(type_var_cycles_resolve_as_possible); | ||
417 | // recursive type | ||
418 | return tv.fallback_value(); | ||
419 | } | ||
420 | if let Some(known_ty) = | ||
421 | self.var_unification_table.inlined_probe_value(inner).known() | ||
422 | { | ||
423 | // known_ty may contain other variables that are known by now | ||
424 | tv_stack.push(inner); | ||
425 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | ||
426 | tv_stack.pop(); | ||
427 | result | ||
428 | } else { | ||
429 | ty | ||
430 | } | ||
431 | } | ||
432 | _ => ty, | ||
433 | }) | ||
434 | } | ||
435 | |||
436 | /// If `ty` is a type variable with known type, returns that type; | ||
437 | /// otherwise, return ty. | ||
438 | fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { | ||
439 | let mut ty = Cow::Borrowed(ty); | ||
440 | // The type variable could resolve to a int/float variable. Hence try | ||
441 | // resolving up to three times; each type of variable shouldn't occur | ||
442 | // more than once | ||
443 | for i in 0..3 { | ||
444 | if i > 0 { | ||
445 | tested_by!(type_var_resolves_to_int_var); | ||
446 | } | ||
447 | match &*ty { | ||
448 | Ty::Infer(tv) => { | ||
449 | let inner = tv.to_inner(); | ||
450 | match self.var_unification_table.inlined_probe_value(inner).known() { | ||
451 | Some(known_ty) => { | ||
452 | // The known_ty can't be a type var itself | ||
453 | ty = Cow::Owned(known_ty.clone()); | ||
454 | } | ||
455 | _ => return ty, | ||
456 | } | ||
457 | } | ||
458 | _ => return ty, | ||
459 | } | ||
460 | } | ||
461 | log::error!("Inference variable still not resolved: {:?}", ty); | ||
462 | ty | ||
463 | } | ||
464 | |||
465 | /// Recurses through the given type, normalizing associated types mentioned | ||
466 | /// in it by replacing them by type variables and registering obligations to | ||
467 | /// resolve later. This should be done once for every type we get from some | ||
468 | /// type annotation (e.g. from a let type annotation, field type or function | ||
469 | /// call). `make_ty` handles this already, but e.g. for field types we need | ||
470 | /// to do it as well. | ||
471 | fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { | ||
472 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
473 | ty.fold(&mut |ty| match ty { | ||
474 | Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), | ||
475 | _ => ty, | ||
476 | }) | ||
477 | } | ||
478 | |||
479 | fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { | ||
480 | let var = self.new_type_var(); | ||
481 | let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() }; | ||
482 | let obligation = Obligation::Projection(predicate); | ||
483 | self.obligations.push(obligation); | ||
484 | var | ||
485 | } | ||
486 | |||
487 | /// Resolves the type completely; type variables without known type are | ||
488 | /// replaced by Ty::Unknown. | ||
489 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
490 | ty.fold(&mut |ty| match ty { | ||
491 | Ty::Infer(tv) => { | ||
492 | let inner = tv.to_inner(); | ||
493 | if tv_stack.contains(&inner) { | ||
494 | tested_by!(type_var_cycles_resolve_completely); | ||
495 | // recursive type | ||
496 | return tv.fallback_value(); | ||
497 | } | ||
498 | if let Some(known_ty) = | ||
499 | self.var_unification_table.inlined_probe_value(inner).known() | ||
500 | { | ||
501 | // known_ty may contain other variables that are known by now | ||
502 | tv_stack.push(inner); | ||
503 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | ||
504 | tv_stack.pop(); | ||
505 | result | ||
506 | } else { | ||
507 | tv.fallback_value() | ||
508 | } | ||
509 | } | ||
510 | _ => ty, | ||
511 | }) | ||
512 | } | ||
513 | |||
514 | fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) { | ||
515 | let path = match path { | ||
516 | Some(path) => path, | ||
517 | None => return (Ty::Unknown, None), | ||
518 | }; | ||
519 | let resolver = &self.resolver; | ||
520 | // FIXME: this should resolve assoc items as well, see this example: | ||
521 | // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 | ||
522 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | ||
523 | Some(TypeNs::AdtId(AdtId::StructId(strukt))) => { | ||
524 | let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into()); | ||
525 | let ty = self.db.ty(strukt.into()); | ||
526 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
527 | (ty, Some(strukt.into())) | ||
528 | } | ||
529 | Some(TypeNs::EnumVariantId(var)) => { | ||
530 | let substs = Ty::substs_from_path(self.db, resolver, path, var.into()); | ||
531 | let ty = self.db.ty(var.parent.into()); | ||
532 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
533 | (ty, Some(var.into())) | ||
534 | } | ||
535 | Some(_) | None => (Ty::Unknown, None), | ||
536 | } | ||
537 | } | ||
538 | |||
539 | fn collect_const(&mut self, data: &ConstData) { | ||
540 | self.return_ty = self.make_ty(&data.type_ref); | ||
541 | } | ||
542 | |||
543 | fn collect_fn(&mut self, data: &FunctionData) { | ||
544 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
545 | for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { | ||
546 | let ty = self.make_ty(type_ref); | ||
547 | |||
548 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
549 | } | ||
550 | self.return_ty = self.make_ty(&data.ret_type); | ||
551 | } | ||
552 | |||
553 | fn infer_body(&mut self) { | ||
554 | self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone())); | ||
555 | } | ||
556 | |||
557 | fn resolve_into_iter_item(&self) -> Option<TypeAliasId> { | ||
558 | let path = known::std_iter_into_iterator(); | ||
559 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
560 | self.db.trait_data(trait_).associated_type_by_name(&name::ITEM_TYPE) | ||
561 | } | ||
562 | |||
563 | fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> { | ||
564 | let path = known::std_ops_try(); | ||
565 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
566 | self.db.trait_data(trait_).associated_type_by_name(&name::OK_TYPE) | ||
567 | } | ||
568 | |||
569 | fn resolve_future_future_output(&self) -> Option<TypeAliasId> { | ||
570 | let path = known::std_future_future(); | ||
571 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
572 | self.db.trait_data(trait_).associated_type_by_name(&name::OUTPUT_TYPE) | ||
573 | } | ||
574 | |||
575 | fn resolve_boxed_box(&self) -> Option<AdtId> { | ||
576 | let path = known::std_boxed_box(); | ||
577 | let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; | ||
578 | Some(struct_.into()) | ||
579 | } | ||
580 | } | ||
581 | |||
582 | /// The ID of a type variable. | ||
583 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | ||
584 | pub struct TypeVarId(pub(super) u32); | ||
585 | |||
586 | impl UnifyKey for TypeVarId { | ||
587 | type Value = TypeVarValue; | ||
588 | |||
589 | fn index(&self) -> u32 { | ||
590 | self.0 | ||
591 | } | ||
592 | |||
593 | fn from_index(i: u32) -> Self { | ||
594 | TypeVarId(i) | ||
595 | } | ||
596 | |||
597 | fn tag() -> &'static str { | ||
598 | "TypeVarId" | ||
599 | } | ||
600 | } | ||
601 | |||
602 | /// The value of a type variable: either we already know the type, or we don't | ||
603 | /// know it yet. | ||
604 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
605 | pub enum TypeVarValue { | ||
606 | Known(Ty), | ||
607 | Unknown, | ||
608 | } | ||
609 | |||
610 | impl TypeVarValue { | ||
611 | fn known(&self) -> Option<&Ty> { | ||
612 | match self { | ||
613 | TypeVarValue::Known(ty) => Some(ty), | ||
614 | TypeVarValue::Unknown => None, | ||
615 | } | ||
616 | } | ||
617 | } | ||
618 | |||
619 | impl UnifyValue for TypeVarValue { | ||
620 | type Error = NoError; | ||
621 | |||
622 | fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> { | ||
623 | match (value1, value2) { | ||
624 | // We should never equate two type variables, both of which have | ||
625 | // known types. Instead, we recursively equate those types. | ||
626 | (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!( | ||
627 | "equating two type variables, both of which have known types: {:?} and {:?}", | ||
628 | t1, t2 | ||
629 | ), | ||
630 | |||
631 | // If one side is known, prefer that one. | ||
632 | (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()), | ||
633 | (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()), | ||
634 | |||
635 | (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown), | ||
636 | } | ||
637 | } | ||
638 | } | ||
639 | |||
640 | /// The kinds of placeholders we need during type inference. There's separate | ||
641 | /// values for general types, and for integer and float variables. The latter | ||
642 | /// two are used for inference of literal values (e.g. `100` could be one of | ||
643 | /// several integer types). | ||
644 | #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] | ||
645 | pub enum InferTy { | ||
646 | TypeVar(TypeVarId), | ||
647 | IntVar(TypeVarId), | ||
648 | FloatVar(TypeVarId), | ||
649 | MaybeNeverTypeVar(TypeVarId), | ||
650 | } | ||
651 | |||
652 | impl InferTy { | ||
653 | fn to_inner(self) -> TypeVarId { | ||
654 | match self { | ||
655 | InferTy::TypeVar(ty) | ||
656 | | InferTy::IntVar(ty) | ||
657 | | InferTy::FloatVar(ty) | ||
658 | | InferTy::MaybeNeverTypeVar(ty) => ty, | ||
659 | } | ||
660 | } | ||
661 | |||
662 | fn fallback_value(self) -> Ty { | ||
663 | match self { | ||
664 | InferTy::TypeVar(..) => Ty::Unknown, | ||
665 | InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))), | ||
666 | InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))), | ||
667 | InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never), | ||
668 | } | ||
669 | } | ||
670 | } | ||
671 | |||
672 | /// When inferring an expression, we propagate downward whatever type hint we | ||
673 | /// are able in the form of an `Expectation`. | ||
674 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
675 | struct Expectation { | ||
676 | ty: Ty, | ||
677 | // FIXME: In some cases, we need to be aware whether the expectation is that | ||
678 | // the type match exactly what we passed, or whether it just needs to be | ||
679 | // coercible to the expected type. See Expectation::rvalue_hint in rustc. | ||
680 | } | ||
681 | |||
682 | impl Expectation { | ||
683 | /// The expectation that the type of the expression needs to equal the given | ||
684 | /// type. | ||
685 | fn has_type(ty: Ty) -> Self { | ||
686 | Expectation { ty } | ||
687 | } | ||
688 | |||
689 | /// This expresses no expectation on the type. | ||
690 | fn none() -> Self { | ||
691 | Expectation { ty: Ty::Unknown } | ||
692 | } | ||
693 | } | ||
694 | |||
695 | mod diagnostics { | ||
696 | use hir_def::{expr::ExprId, FunctionId, HasSource, Lookup}; | ||
697 | use hir_expand::diagnostics::DiagnosticSink; | ||
698 | |||
699 | use crate::{db::HirDatabase, diagnostics::NoSuchField}; | ||
700 | |||
701 | #[derive(Debug, PartialEq, Eq, Clone)] | ||
702 | pub(super) enum InferenceDiagnostic { | ||
703 | NoSuchField { expr: ExprId, field: usize }, | ||
704 | } | ||
705 | |||
706 | impl InferenceDiagnostic { | ||
707 | pub(super) fn add_to( | ||
708 | &self, | ||
709 | db: &impl HirDatabase, | ||
710 | owner: FunctionId, | ||
711 | sink: &mut DiagnosticSink, | ||
712 | ) { | ||
713 | match self { | ||
714 | InferenceDiagnostic::NoSuchField { expr, field } => { | ||
715 | let file = owner.lookup(db).source(db).file_id; | ||
716 | let (_, source_map) = db.body_with_source_map(owner.into()); | ||
717 | let field = source_map.field_syntax(*expr, *field); | ||
718 | sink.push(NoSuchField { file, field }) | ||
719 | } | ||
720 | } | ||
721 | } | ||
722 | } | ||
723 | } | ||
diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs new file mode 100644 index 000000000..d66a21932 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/coerce.rs | |||
@@ -0,0 +1,354 @@ | |||
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 hir_def::{ | ||
8 | lang_item::LangItemTarget, | ||
9 | resolver::{HasResolver, Resolver}, | ||
10 | type_ref::Mutability, | ||
11 | AdtId, | ||
12 | }; | ||
13 | use rustc_hash::FxHashMap; | ||
14 | use test_utils::tested_by; | ||
15 | |||
16 | use crate::{autoderef, db::HirDatabase, Substs, TraitRef, Ty, TypeCtor, TypeWalk}; | ||
17 | |||
18 | use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue}; | ||
19 | |||
20 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
21 | /// Unify two types, but may coerce the first one to the second one | ||
22 | /// using "implicit coercion rules" if needed. | ||
23 | pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
24 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
25 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
26 | self.coerce_inner(from_ty, &to_ty) | ||
27 | } | ||
28 | |||
29 | /// Merge two types from different branches, with possible implicit coerce. | ||
30 | /// | ||
31 | /// Note that it is only possible that one type are coerced to another. | ||
32 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
33 | /// which will simply result in "incompatible types" error. | ||
34 | pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
35 | if self.coerce(ty1, ty2) { | ||
36 | ty2.clone() | ||
37 | } else if self.coerce(ty2, ty1) { | ||
38 | ty1.clone() | ||
39 | } else { | ||
40 | tested_by!(coerce_merge_fail_fallback); | ||
41 | // For incompatible types, we use the latter one as result | ||
42 | // to be better recovery for `if` without `else`. | ||
43 | ty2.clone() | ||
44 | } | ||
45 | } | ||
46 | |||
47 | pub(super) fn init_coerce_unsized_map( | ||
48 | db: &'a D, | ||
49 | resolver: &Resolver, | ||
50 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
51 | let krate = resolver.krate().unwrap(); | ||
52 | let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) { | ||
53 | Some(LangItemTarget::TraitId(trait_)) => { | ||
54 | db.impls_for_trait(krate.into(), trait_.into()) | ||
55 | } | ||
56 | _ => return FxHashMap::default(), | ||
57 | }; | ||
58 | |||
59 | impls | ||
60 | .iter() | ||
61 | .filter_map(|&impl_id| { | ||
62 | let impl_data = db.impl_data(impl_id); | ||
63 | let resolver = impl_id.resolver(db); | ||
64 | let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); | ||
65 | |||
66 | // `CoerseUnsized` has one generic parameter for the target type. | ||
67 | let trait_ref = TraitRef::from_hir( | ||
68 | db, | ||
69 | &resolver, | ||
70 | impl_data.target_trait.as_ref()?, | ||
71 | Some(target_ty), | ||
72 | )?; | ||
73 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
74 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
75 | |||
76 | match (&cur_from_ty, cur_to_ty) { | ||
77 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
78 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
79 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
80 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
81 | match (ty1, ty2) { | ||
82 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
83 | if p1 != p2 => | ||
84 | { | ||
85 | Some(((*ctor1, *ctor2), i)) | ||
86 | } | ||
87 | _ => None, | ||
88 | } | ||
89 | }) | ||
90 | } | ||
91 | _ => None, | ||
92 | } | ||
93 | }) | ||
94 | .collect() | ||
95 | } | ||
96 | |||
97 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
98 | match (&from_ty, to_ty) { | ||
99 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
100 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
101 | let var = self.new_maybe_never_type_var(); | ||
102 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
103 | return true; | ||
104 | } | ||
105 | (ty_app!(TypeCtor::Never), _) => return true, | ||
106 | |||
107 | // Trivial cases, this should go after `never` check to | ||
108 | // avoid infer result type to be never | ||
109 | _ => { | ||
110 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
111 | return true; | ||
112 | } | ||
113 | } | ||
114 | } | ||
115 | |||
116 | // Pointer weakening and function to pointer | ||
117 | match (&mut from_ty, to_ty) { | ||
118 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
119 | // `&mut T` -> `&T` | ||
120 | // `&mut T` -> `*mut T` | ||
121 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
122 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
123 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
124 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
125 | *c1 = *c2; | ||
126 | } | ||
127 | |||
128 | // Illegal mutablity conversion | ||
129 | ( | ||
130 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
131 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
132 | ) | ||
133 | | ( | ||
134 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
135 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
136 | ) => return false, | ||
137 | |||
138 | // `{function_type}` -> `fn()` | ||
139 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
140 | match from_ty.callable_sig(self.db) { | ||
141 | None => return false, | ||
142 | Some(sig) => { | ||
143 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
144 | from_ty = | ||
145 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
146 | } | ||
147 | } | ||
148 | } | ||
149 | |||
150 | _ => {} | ||
151 | } | ||
152 | |||
153 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
154 | return ret; | ||
155 | } | ||
156 | |||
157 | // Auto Deref if cannot coerce | ||
158 | match (&from_ty, to_ty) { | ||
159 | // FIXME: DerefMut | ||
160 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
161 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
162 | } | ||
163 | |||
164 | // Otherwise, normal unify | ||
165 | _ => self.unify(&from_ty, to_ty), | ||
166 | } | ||
167 | } | ||
168 | |||
169 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
170 | /// | ||
171 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
172 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
173 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
174 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
175 | _ => return None, | ||
176 | }; | ||
177 | |||
178 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
179 | |||
180 | // Check `Unsize` first | ||
181 | match self.check_unsize_and_coerce( | ||
182 | st1.0.get(coerce_generic_index)?, | ||
183 | st2.0.get(coerce_generic_index)?, | ||
184 | 0, | ||
185 | ) { | ||
186 | Some(true) => {} | ||
187 | ret => return ret, | ||
188 | } | ||
189 | |||
190 | let ret = st1 | ||
191 | .iter() | ||
192 | .zip(st2.iter()) | ||
193 | .enumerate() | ||
194 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
195 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
196 | |||
197 | Some(ret) | ||
198 | } | ||
199 | |||
200 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
201 | /// | ||
202 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
203 | /// | ||
204 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
205 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
206 | if depth > 1000 { | ||
207 | panic!("Infinite recursion in coercion"); | ||
208 | } | ||
209 | |||
210 | match (&from_ty, &to_ty) { | ||
211 | // `[T; N]` -> `[T]` | ||
212 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
213 | Some(self.unify(&st1[0], &st2[0])) | ||
214 | } | ||
215 | |||
216 | // `T` -> `dyn Trait` when `T: Trait` | ||
217 | (_, Ty::Dyn(_)) => { | ||
218 | // FIXME: Check predicates | ||
219 | Some(true) | ||
220 | } | ||
221 | |||
222 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
223 | ( | ||
224 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
225 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
226 | ) => { | ||
227 | if len1 != len2 || *len1 == 0 { | ||
228 | return None; | ||
229 | } | ||
230 | |||
231 | match self.check_unsize_and_coerce( | ||
232 | st1.last().unwrap(), | ||
233 | st2.last().unwrap(), | ||
234 | depth + 1, | ||
235 | ) { | ||
236 | Some(true) => {} | ||
237 | ret => return ret, | ||
238 | } | ||
239 | |||
240 | let ret = st1[..st1.len() - 1] | ||
241 | .iter() | ||
242 | .zip(&st2[..st2.len() - 1]) | ||
243 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
244 | |||
245 | Some(ret) | ||
246 | } | ||
247 | |||
248 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
249 | // - T: Unsize<U> | ||
250 | // - Foo is a struct | ||
251 | // - Only the last field of Foo has a type involving T | ||
252 | // - T is not part of the type of any other fields | ||
253 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
254 | ( | ||
255 | ty_app!(TypeCtor::Adt(AdtId::StructId(struct1)), st1), | ||
256 | ty_app!(TypeCtor::Adt(AdtId::StructId(struct2)), st2), | ||
257 | ) if struct1 == struct2 => { | ||
258 | let field_tys = self.db.field_types((*struct1).into()); | ||
259 | let struct_data = self.db.struct_data(*struct1); | ||
260 | |||
261 | let mut fields = struct_data.variant_data.fields().iter(); | ||
262 | let (last_field_id, _data) = fields.next_back()?; | ||
263 | |||
264 | // Get the generic parameter involved in the last field. | ||
265 | let unsize_generic_index = { | ||
266 | let mut index = None; | ||
267 | let mut multiple_param = false; | ||
268 | field_tys[last_field_id].walk(&mut |ty| match ty { | ||
269 | &Ty::Param { idx, .. } => { | ||
270 | if index.is_none() { | ||
271 | index = Some(idx); | ||
272 | } else if Some(idx) != index { | ||
273 | multiple_param = true; | ||
274 | } | ||
275 | } | ||
276 | _ => {} | ||
277 | }); | ||
278 | |||
279 | if multiple_param { | ||
280 | return None; | ||
281 | } | ||
282 | index? | ||
283 | }; | ||
284 | |||
285 | // Check other fields do not involve it. | ||
286 | let mut multiple_used = false; | ||
287 | fields.for_each(|(field_id, _data)| { | ||
288 | field_tys[field_id].walk(&mut |ty| match ty { | ||
289 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
290 | multiple_used = true | ||
291 | } | ||
292 | _ => {} | ||
293 | }) | ||
294 | }); | ||
295 | if multiple_used { | ||
296 | return None; | ||
297 | } | ||
298 | |||
299 | let unsize_generic_index = unsize_generic_index as usize; | ||
300 | |||
301 | // Check `Unsize` first | ||
302 | match self.check_unsize_and_coerce( | ||
303 | st1.get(unsize_generic_index)?, | ||
304 | st2.get(unsize_generic_index)?, | ||
305 | depth + 1, | ||
306 | ) { | ||
307 | Some(true) => {} | ||
308 | ret => return ret, | ||
309 | } | ||
310 | |||
311 | // Then unify other parameters | ||
312 | let ret = st1 | ||
313 | .iter() | ||
314 | .zip(st2.iter()) | ||
315 | .enumerate() | ||
316 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
317 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
318 | |||
319 | Some(ret) | ||
320 | } | ||
321 | |||
322 | _ => None, | ||
323 | } | ||
324 | } | ||
325 | |||
326 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
327 | /// | ||
328 | /// Note that the parameters are already stripped the outer reference. | ||
329 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
330 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
331 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
332 | // FIXME: Auto DerefMut | ||
333 | for derefed_ty in autoderef::autoderef( | ||
334 | self.db, | ||
335 | self.resolver.krate(), | ||
336 | InEnvironment { | ||
337 | value: canonicalized.value.clone(), | ||
338 | environment: self.trait_env.clone(), | ||
339 | }, | ||
340 | ) { | ||
341 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
342 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
343 | // Stop when constructor matches. | ||
344 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
345 | // It will not recurse to `coerce`. | ||
346 | return self.unify_substs(st1, st2, 0); | ||
347 | } | ||
348 | _ => {} | ||
349 | } | ||
350 | } | ||
351 | |||
352 | false | ||
353 | } | ||
354 | } | ||
diff --git a/crates/ra_hir_ty/src/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs new file mode 100644 index 000000000..2f9ca4bbb --- /dev/null +++ b/crates/ra_hir_ty/src/infer/expr.rs | |||
@@ -0,0 +1,686 @@ | |||
1 | //! Type inference for expressions. | ||
2 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | builtin_type::Signedness, | ||
8 | expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | ||
9 | generics::GenericParams, | ||
10 | path::{GenericArg, GenericArgs}, | ||
11 | resolver::resolver_for_expr, | ||
12 | AdtId, ContainerId, Lookup, StructFieldId, | ||
13 | }; | ||
14 | use hir_expand::name::{self, Name}; | ||
15 | |||
16 | use crate::{ | ||
17 | autoderef, db::HirDatabase, method_resolution, op, traits::InEnvironment, utils::variant_data, | ||
18 | CallableDef, InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs, | ||
19 | TraitRef, Ty, TypeCtor, TypeWalk, Uncertain, | ||
20 | }; | ||
21 | |||
22 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
23 | |||
24 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
25 | pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
26 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
27 | let could_unify = self.unify(&ty, &expected.ty); | ||
28 | if !could_unify { | ||
29 | self.result.type_mismatches.insert( | ||
30 | tgt_expr, | ||
31 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
32 | ); | ||
33 | } | ||
34 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
35 | ty | ||
36 | } | ||
37 | |||
38 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
39 | /// Return the type after possible coercion. | ||
40 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
41 | let ty = self.infer_expr_inner(expr, &expected); | ||
42 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
43 | self.result | ||
44 | .type_mismatches | ||
45 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
46 | // Return actual type when type mismatch. | ||
47 | // This is needed for diagnostic when return type mismatch. | ||
48 | ty | ||
49 | } else if expected.ty == Ty::Unknown { | ||
50 | ty | ||
51 | } else { | ||
52 | expected.ty.clone() | ||
53 | }; | ||
54 | |||
55 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
56 | } | ||
57 | |||
58 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
59 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
60 | let ty = match &body[tgt_expr] { | ||
61 | Expr::Missing => Ty::Unknown, | ||
62 | Expr::If { condition, then_branch, else_branch } => { | ||
63 | // if let is desugared to match, so this is always simple if | ||
64 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
65 | |||
66 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
67 | let else_ty = match else_branch { | ||
68 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
69 | None => Ty::unit(), | ||
70 | }; | ||
71 | |||
72 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
73 | } | ||
74 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
75 | Expr::TryBlock { body } => { | ||
76 | let _inner = self.infer_expr(*body, expected); | ||
77 | // FIXME should be std::result::Result<{inner}, _> | ||
78 | Ty::Unknown | ||
79 | } | ||
80 | Expr::Loop { body } => { | ||
81 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
82 | // FIXME handle break with value | ||
83 | Ty::simple(TypeCtor::Never) | ||
84 | } | ||
85 | Expr::While { condition, body } => { | ||
86 | // while let is desugared to a match loop, so this is always simple while | ||
87 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
88 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
89 | Ty::unit() | ||
90 | } | ||
91 | Expr::For { iterable, body, pat } => { | ||
92 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
93 | |||
94 | let pat_ty = match self.resolve_into_iter_item() { | ||
95 | Some(into_iter_item_alias) => { | ||
96 | let pat_ty = self.new_type_var(); | ||
97 | let projection = ProjectionPredicate { | ||
98 | ty: pat_ty.clone(), | ||
99 | projection_ty: ProjectionTy { | ||
100 | associated_ty: into_iter_item_alias, | ||
101 | parameters: Substs::single(iterable_ty), | ||
102 | }, | ||
103 | }; | ||
104 | self.obligations.push(Obligation::Projection(projection)); | ||
105 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
106 | } | ||
107 | None => Ty::Unknown, | ||
108 | }; | ||
109 | |||
110 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
111 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
112 | Ty::unit() | ||
113 | } | ||
114 | Expr::Lambda { body, args, arg_types } => { | ||
115 | assert_eq!(args.len(), arg_types.len()); | ||
116 | |||
117 | let mut sig_tys = Vec::new(); | ||
118 | |||
119 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
120 | let expected = if let Some(type_ref) = arg_type { | ||
121 | self.make_ty(type_ref) | ||
122 | } else { | ||
123 | Ty::Unknown | ||
124 | }; | ||
125 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
126 | sig_tys.push(arg_ty); | ||
127 | } | ||
128 | |||
129 | // add return type | ||
130 | let ret_ty = self.new_type_var(); | ||
131 | sig_tys.push(ret_ty.clone()); | ||
132 | let sig_ty = Ty::apply( | ||
133 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
134 | Substs(sig_tys.into()), | ||
135 | ); | ||
136 | let closure_ty = Ty::apply_one( | ||
137 | TypeCtor::Closure { def: self.owner.into(), expr: tgt_expr }, | ||
138 | sig_ty, | ||
139 | ); | ||
140 | |||
141 | // Eagerly try to relate the closure type with the expected | ||
142 | // type, otherwise we often won't have enough information to | ||
143 | // infer the body. | ||
144 | self.coerce(&closure_ty, &expected.ty); | ||
145 | |||
146 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
147 | closure_ty | ||
148 | } | ||
149 | Expr::Call { callee, args } => { | ||
150 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
151 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
152 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
153 | None => { | ||
154 | // Not callable | ||
155 | // FIXME: report an error | ||
156 | (Vec::new(), Ty::Unknown) | ||
157 | } | ||
158 | }; | ||
159 | self.register_obligations_for_call(&callee_ty); | ||
160 | self.check_call_arguments(args, ¶m_tys); | ||
161 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
162 | ret_ty | ||
163 | } | ||
164 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
165 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
166 | Expr::Match { expr, arms } => { | ||
167 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
168 | |||
169 | let mut result_ty = self.new_maybe_never_type_var(); | ||
170 | |||
171 | for arm in arms { | ||
172 | for &pat in &arm.pats { | ||
173 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
174 | } | ||
175 | if let Some(guard_expr) = arm.guard { | ||
176 | self.infer_expr( | ||
177 | guard_expr, | ||
178 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
179 | ); | ||
180 | } | ||
181 | |||
182 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
183 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
184 | } | ||
185 | |||
186 | result_ty | ||
187 | } | ||
188 | Expr::Path(p) => { | ||
189 | // FIXME this could be more efficient... | ||
190 | let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr); | ||
191 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
192 | } | ||
193 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
194 | Expr::Break { expr } => { | ||
195 | if let Some(expr) = expr { | ||
196 | // FIXME handle break with value | ||
197 | self.infer_expr(*expr, &Expectation::none()); | ||
198 | } | ||
199 | Ty::simple(TypeCtor::Never) | ||
200 | } | ||
201 | Expr::Return { expr } => { | ||
202 | if let Some(expr) = expr { | ||
203 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
204 | } | ||
205 | Ty::simple(TypeCtor::Never) | ||
206 | } | ||
207 | Expr::RecordLit { path, fields, spread } => { | ||
208 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
209 | if let Some(variant) = def_id { | ||
210 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
211 | } | ||
212 | |||
213 | self.unify(&ty, &expected.ty); | ||
214 | |||
215 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
216 | let field_types = | ||
217 | def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
218 | let variant_data = def_id.map(|it| variant_data(self.db, it)); | ||
219 | for (field_idx, field) in fields.iter().enumerate() { | ||
220 | let field_def = | ||
221 | variant_data.as_ref().and_then(|it| match it.field(&field.name) { | ||
222 | Some(local_id) => { | ||
223 | Some(StructFieldId { parent: def_id.unwrap(), local_id }) | ||
224 | } | ||
225 | None => { | ||
226 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
227 | expr: tgt_expr, | ||
228 | field: field_idx, | ||
229 | }); | ||
230 | None | ||
231 | } | ||
232 | }); | ||
233 | if let Some(field_def) = field_def { | ||
234 | self.result.record_field_resolutions.insert(field.expr, field_def); | ||
235 | } | ||
236 | let field_ty = field_def | ||
237 | .map_or(Ty::Unknown, |it| field_types[it.local_id].clone()) | ||
238 | .subst(&substs); | ||
239 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
240 | } | ||
241 | if let Some(expr) = spread { | ||
242 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
243 | } | ||
244 | ty | ||
245 | } | ||
246 | Expr::Field { expr, name } => { | ||
247 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
248 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
249 | let ty = autoderef::autoderef( | ||
250 | self.db, | ||
251 | self.resolver.krate(), | ||
252 | InEnvironment { | ||
253 | value: canonicalized.value.clone(), | ||
254 | environment: self.trait_env.clone(), | ||
255 | }, | ||
256 | ) | ||
257 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
258 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
259 | TypeCtor::Tuple { .. } => name | ||
260 | .as_tuple_index() | ||
261 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
262 | TypeCtor::Adt(AdtId::StructId(s)) => { | ||
263 | self.db.struct_data(s).variant_data.field(name).map(|local_id| { | ||
264 | let field = StructFieldId { parent: s.into(), local_id }.into(); | ||
265 | self.write_field_resolution(tgt_expr, field); | ||
266 | self.db.field_types(s.into())[field.local_id] | ||
267 | .clone() | ||
268 | .subst(&a_ty.parameters) | ||
269 | }) | ||
270 | } | ||
271 | // FIXME: | ||
272 | TypeCtor::Adt(AdtId::UnionId(_)) => None, | ||
273 | _ => None, | ||
274 | }, | ||
275 | _ => None, | ||
276 | }) | ||
277 | .unwrap_or(Ty::Unknown); | ||
278 | let ty = self.insert_type_vars(ty); | ||
279 | self.normalize_associated_types_in(ty) | ||
280 | } | ||
281 | Expr::Await { expr } => { | ||
282 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
283 | let ty = match self.resolve_future_future_output() { | ||
284 | Some(future_future_output_alias) => { | ||
285 | let ty = self.new_type_var(); | ||
286 | let projection = ProjectionPredicate { | ||
287 | ty: ty.clone(), | ||
288 | projection_ty: ProjectionTy { | ||
289 | associated_ty: future_future_output_alias, | ||
290 | parameters: Substs::single(inner_ty), | ||
291 | }, | ||
292 | }; | ||
293 | self.obligations.push(Obligation::Projection(projection)); | ||
294 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
295 | } | ||
296 | None => Ty::Unknown, | ||
297 | }; | ||
298 | ty | ||
299 | } | ||
300 | Expr::Try { expr } => { | ||
301 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
302 | let ty = match self.resolve_ops_try_ok() { | ||
303 | Some(ops_try_ok_alias) => { | ||
304 | let ty = self.new_type_var(); | ||
305 | let projection = ProjectionPredicate { | ||
306 | ty: ty.clone(), | ||
307 | projection_ty: ProjectionTy { | ||
308 | associated_ty: ops_try_ok_alias, | ||
309 | parameters: Substs::single(inner_ty), | ||
310 | }, | ||
311 | }; | ||
312 | self.obligations.push(Obligation::Projection(projection)); | ||
313 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
314 | } | ||
315 | None => Ty::Unknown, | ||
316 | }; | ||
317 | ty | ||
318 | } | ||
319 | Expr::Cast { expr, type_ref } => { | ||
320 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
321 | let cast_ty = self.make_ty(type_ref); | ||
322 | // FIXME check the cast... | ||
323 | cast_ty | ||
324 | } | ||
325 | Expr::Ref { expr, mutability } => { | ||
326 | let expectation = | ||
327 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
328 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
329 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
330 | // which cannot be coerced | ||
331 | } | ||
332 | Expectation::has_type(Ty::clone(exp_inner)) | ||
333 | } else { | ||
334 | Expectation::none() | ||
335 | }; | ||
336 | // FIXME reference coercions etc. | ||
337 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
338 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
339 | } | ||
340 | Expr::Box { expr } => { | ||
341 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
342 | if let Some(box_) = self.resolve_boxed_box() { | ||
343 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
344 | } else { | ||
345 | Ty::Unknown | ||
346 | } | ||
347 | } | ||
348 | Expr::UnaryOp { expr, op } => { | ||
349 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
350 | match op { | ||
351 | UnaryOp::Deref => match self.resolver.krate() { | ||
352 | Some(krate) => { | ||
353 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
354 | match autoderef::deref( | ||
355 | self.db, | ||
356 | krate, | ||
357 | InEnvironment { | ||
358 | value: &canonicalized.value, | ||
359 | environment: self.trait_env.clone(), | ||
360 | }, | ||
361 | ) { | ||
362 | Some(derefed_ty) => { | ||
363 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
364 | } | ||
365 | None => Ty::Unknown, | ||
366 | } | ||
367 | } | ||
368 | None => Ty::Unknown, | ||
369 | }, | ||
370 | UnaryOp::Neg => { | ||
371 | match &inner_ty { | ||
372 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
373 | TypeCtor::Int(Uncertain::Unknown) | ||
374 | | TypeCtor::Int(Uncertain::Known(IntTy { | ||
375 | signedness: Signedness::Signed, | ||
376 | .. | ||
377 | })) | ||
378 | | TypeCtor::Float(..) => inner_ty, | ||
379 | _ => Ty::Unknown, | ||
380 | }, | ||
381 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
382 | inner_ty | ||
383 | } | ||
384 | // FIXME: resolve ops::Neg trait | ||
385 | _ => Ty::Unknown, | ||
386 | } | ||
387 | } | ||
388 | UnaryOp::Not => { | ||
389 | match &inner_ty { | ||
390 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
391 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
392 | _ => Ty::Unknown, | ||
393 | }, | ||
394 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
395 | // FIXME: resolve ops::Not trait for inner_ty | ||
396 | _ => Ty::Unknown, | ||
397 | } | ||
398 | } | ||
399 | } | ||
400 | } | ||
401 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
402 | Some(op) => { | ||
403 | let lhs_expectation = match op { | ||
404 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
405 | _ => Expectation::none(), | ||
406 | }; | ||
407 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
408 | // FIXME: find implementation of trait corresponding to operation | ||
409 | // symbol and resolve associated `Output` type | ||
410 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
411 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
412 | |||
413 | // FIXME: similar as above, return ty is often associated trait type | ||
414 | op::binary_op_return_ty(*op, rhs_ty) | ||
415 | } | ||
416 | _ => Ty::Unknown, | ||
417 | }, | ||
418 | Expr::Index { base, index } => { | ||
419 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
420 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
421 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
422 | Ty::Unknown | ||
423 | } | ||
424 | Expr::Tuple { exprs } => { | ||
425 | let mut tys = match &expected.ty { | ||
426 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
427 | .iter() | ||
428 | .cloned() | ||
429 | .chain(repeat_with(|| self.new_type_var())) | ||
430 | .take(exprs.len()) | ||
431 | .collect::<Vec<_>>(), | ||
432 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
433 | }; | ||
434 | |||
435 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
436 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
437 | } | ||
438 | |||
439 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
440 | } | ||
441 | Expr::Array(array) => { | ||
442 | let elem_ty = match &expected.ty { | ||
443 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
444 | st.as_single().clone() | ||
445 | } | ||
446 | _ => self.new_type_var(), | ||
447 | }; | ||
448 | |||
449 | match array { | ||
450 | Array::ElementList(items) => { | ||
451 | for expr in items.iter() { | ||
452 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
453 | } | ||
454 | } | ||
455 | Array::Repeat { initializer, repeat } => { | ||
456 | self.infer_expr_coerce( | ||
457 | *initializer, | ||
458 | &Expectation::has_type(elem_ty.clone()), | ||
459 | ); | ||
460 | self.infer_expr( | ||
461 | *repeat, | ||
462 | &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known( | ||
463 | IntTy::usize(), | ||
464 | )))), | ||
465 | ); | ||
466 | } | ||
467 | } | ||
468 | |||
469 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
470 | } | ||
471 | Expr::Literal(lit) => match lit { | ||
472 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
473 | Literal::String(..) => { | ||
474 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
475 | } | ||
476 | Literal::ByteString(..) => { | ||
477 | let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8()))); | ||
478 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
479 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
480 | } | ||
481 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
482 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())), | ||
483 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())), | ||
484 | }, | ||
485 | }; | ||
486 | // use a new type variable if we got Ty::Unknown here | ||
487 | let ty = self.insert_type_vars_shallow(ty); | ||
488 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
489 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
490 | ty | ||
491 | } | ||
492 | |||
493 | fn infer_block( | ||
494 | &mut self, | ||
495 | statements: &[Statement], | ||
496 | tail: Option<ExprId>, | ||
497 | expected: &Expectation, | ||
498 | ) -> Ty { | ||
499 | let mut diverges = false; | ||
500 | for stmt in statements { | ||
501 | match stmt { | ||
502 | Statement::Let { pat, type_ref, initializer } => { | ||
503 | let decl_ty = | ||
504 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
505 | |||
506 | // Always use the declared type when specified | ||
507 | let mut ty = decl_ty.clone(); | ||
508 | |||
509 | if let Some(expr) = initializer { | ||
510 | let actual_ty = | ||
511 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
512 | if decl_ty == Ty::Unknown { | ||
513 | ty = actual_ty; | ||
514 | } | ||
515 | } | ||
516 | |||
517 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
518 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
519 | } | ||
520 | Statement::Expr(expr) => { | ||
521 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
522 | diverges = true; | ||
523 | } | ||
524 | } | ||
525 | } | ||
526 | } | ||
527 | |||
528 | let ty = if let Some(expr) = tail { | ||
529 | self.infer_expr_coerce(expr, expected) | ||
530 | } else { | ||
531 | self.coerce(&Ty::unit(), &expected.ty); | ||
532 | Ty::unit() | ||
533 | }; | ||
534 | if diverges { | ||
535 | Ty::simple(TypeCtor::Never) | ||
536 | } else { | ||
537 | ty | ||
538 | } | ||
539 | } | ||
540 | |||
541 | fn infer_method_call( | ||
542 | &mut self, | ||
543 | tgt_expr: ExprId, | ||
544 | receiver: ExprId, | ||
545 | args: &[ExprId], | ||
546 | method_name: &Name, | ||
547 | generic_args: Option<&GenericArgs>, | ||
548 | ) -> Ty { | ||
549 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
550 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
551 | let resolved = method_resolution::lookup_method( | ||
552 | &canonicalized_receiver.value, | ||
553 | self.db, | ||
554 | method_name, | ||
555 | &self.resolver, | ||
556 | ); | ||
557 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
558 | Some((ty, func)) => { | ||
559 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
560 | self.write_method_resolution(tgt_expr, func); | ||
561 | (ty, self.db.value_ty(func.into()), Some(self.db.generic_params(func.into()))) | ||
562 | } | ||
563 | None => (receiver_ty, Ty::Unknown, None), | ||
564 | }; | ||
565 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
566 | let method_ty = method_ty.apply_substs(substs); | ||
567 | let method_ty = self.insert_type_vars(method_ty); | ||
568 | self.register_obligations_for_call(&method_ty); | ||
569 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
570 | Some(sig) => { | ||
571 | if !sig.params().is_empty() { | ||
572 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
573 | } else { | ||
574 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
575 | } | ||
576 | } | ||
577 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
578 | }; | ||
579 | // Apply autoref so the below unification works correctly | ||
580 | // FIXME: return correct autorefs from lookup_method | ||
581 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
582 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
583 | _ => derefed_receiver_ty, | ||
584 | }; | ||
585 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
586 | |||
587 | self.check_call_arguments(args, ¶m_tys); | ||
588 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
589 | ret_ty | ||
590 | } | ||
591 | |||
592 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
593 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
594 | // We do this in a pretty awful way: first we type-check any arguments | ||
595 | // that are not closures, then we type-check the closures. This is so | ||
596 | // that we have more information about the types of arguments when we | ||
597 | // type-check the functions. This isn't really the right way to do this. | ||
598 | for &check_closures in &[false, true] { | ||
599 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
600 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
601 | let is_closure = match &self.body[arg] { | ||
602 | Expr::Lambda { .. } => true, | ||
603 | _ => false, | ||
604 | }; | ||
605 | |||
606 | if is_closure != check_closures { | ||
607 | continue; | ||
608 | } | ||
609 | |||
610 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
611 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
612 | } | ||
613 | } | ||
614 | } | ||
615 | |||
616 | fn substs_for_method_call( | ||
617 | &mut self, | ||
618 | def_generics: Option<Arc<GenericParams>>, | ||
619 | generic_args: Option<&GenericArgs>, | ||
620 | receiver_ty: &Ty, | ||
621 | ) -> Substs { | ||
622 | let (parent_param_count, param_count) = | ||
623 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
624 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
625 | // Parent arguments are unknown, except for the receiver type | ||
626 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
627 | for param in &parent_generics.params { | ||
628 | if param.name == name::SELF_TYPE { | ||
629 | substs.push(receiver_ty.clone()); | ||
630 | } else { | ||
631 | substs.push(Ty::Unknown); | ||
632 | } | ||
633 | } | ||
634 | } | ||
635 | // handle provided type arguments | ||
636 | if let Some(generic_args) = generic_args { | ||
637 | // if args are provided, it should be all of them, but we can't rely on that | ||
638 | for arg in generic_args.args.iter().take(param_count) { | ||
639 | match arg { | ||
640 | GenericArg::Type(type_ref) => { | ||
641 | let ty = self.make_ty(type_ref); | ||
642 | substs.push(ty); | ||
643 | } | ||
644 | } | ||
645 | } | ||
646 | }; | ||
647 | let supplied_params = substs.len(); | ||
648 | for _ in supplied_params..parent_param_count + param_count { | ||
649 | substs.push(Ty::Unknown); | ||
650 | } | ||
651 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
652 | Substs(substs.into()) | ||
653 | } | ||
654 | |||
655 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
656 | if let Ty::Apply(a_ty) = callable_ty { | ||
657 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
658 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
659 | for predicate in generic_predicates.iter() { | ||
660 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
661 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
662 | self.obligations.push(obligation); | ||
663 | } | ||
664 | } | ||
665 | // add obligation for trait implementation, if this is a trait method | ||
666 | match def { | ||
667 | CallableDef::FunctionId(f) => { | ||
668 | if let ContainerId::TraitId(trait_) = f.lookup(self.db).container { | ||
669 | // construct a TraitDef | ||
670 | let substs = a_ty.parameters.prefix( | ||
671 | self.db | ||
672 | .generic_params(trait_.into()) | ||
673 | .count_params_including_parent(), | ||
674 | ); | ||
675 | self.obligations.push(Obligation::Trait(TraitRef { | ||
676 | trait_: trait_.into(), | ||
677 | substs, | ||
678 | })); | ||
679 | } | ||
680 | } | ||
681 | CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {} | ||
682 | } | ||
683 | } | ||
684 | } | ||
685 | } | ||
686 | } | ||
diff --git a/crates/ra_hir_ty/src/infer/pat.rs b/crates/ra_hir_ty/src/infer/pat.rs new file mode 100644 index 000000000..1ebb36239 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/pat.rs | |||
@@ -0,0 +1,186 @@ | |||
1 | //! Type inference for patterns. | ||
2 | |||
3 | use std::iter::repeat; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, | ||
8 | path::Path, | ||
9 | type_ref::Mutability, | ||
10 | }; | ||
11 | use hir_expand::name::Name; | ||
12 | use test_utils::tested_by; | ||
13 | |||
14 | use super::{BindingMode, InferenceContext}; | ||
15 | use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk}; | ||
16 | |||
17 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
18 | fn infer_tuple_struct_pat( | ||
19 | &mut self, | ||
20 | path: Option<&Path>, | ||
21 | subpats: &[PatId], | ||
22 | expected: &Ty, | ||
23 | default_bm: BindingMode, | ||
24 | ) -> Ty { | ||
25 | let (ty, def) = self.resolve_variant(path); | ||
26 | let var_data = def.map(|it| variant_data(self.db, it)); | ||
27 | self.unify(&ty, expected); | ||
28 | |||
29 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
30 | |||
31 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
32 | |||
33 | for (i, &subpat) in subpats.iter().enumerate() { | ||
34 | let expected_ty = var_data | ||
35 | .as_ref() | ||
36 | .and_then(|d| d.field(&Name::new_tuple_field(i))) | ||
37 | .map_or(Ty::Unknown, |field| field_tys[field].clone()) | ||
38 | .subst(&substs); | ||
39 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
40 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
41 | } | ||
42 | |||
43 | ty | ||
44 | } | ||
45 | |||
46 | fn infer_record_pat( | ||
47 | &mut self, | ||
48 | path: Option<&Path>, | ||
49 | subpats: &[RecordFieldPat], | ||
50 | expected: &Ty, | ||
51 | default_bm: BindingMode, | ||
52 | id: PatId, | ||
53 | ) -> Ty { | ||
54 | let (ty, def) = self.resolve_variant(path); | ||
55 | let var_data = def.map(|it| variant_data(self.db, it)); | ||
56 | if let Some(variant) = def { | ||
57 | self.write_variant_resolution(id.into(), variant); | ||
58 | } | ||
59 | |||
60 | self.unify(&ty, expected); | ||
61 | |||
62 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
63 | |||
64 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
65 | for subpat in subpats { | ||
66 | let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name)); | ||
67 | let expected_ty = | ||
68 | matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs); | ||
69 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
70 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
71 | } | ||
72 | |||
73 | ty | ||
74 | } | ||
75 | |||
76 | pub(super) fn infer_pat( | ||
77 | &mut self, | ||
78 | pat: PatId, | ||
79 | mut expected: &Ty, | ||
80 | mut default_bm: BindingMode, | ||
81 | ) -> Ty { | ||
82 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
83 | |||
84 | let is_non_ref_pat = match &body[pat] { | ||
85 | Pat::Tuple(..) | ||
86 | | Pat::TupleStruct { .. } | ||
87 | | Pat::Record { .. } | ||
88 | | Pat::Range { .. } | ||
89 | | Pat::Slice { .. } => true, | ||
90 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
91 | Pat::Path(..) | Pat::Lit(..) => true, | ||
92 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
93 | }; | ||
94 | if is_non_ref_pat { | ||
95 | while let Some((inner, mutability)) = expected.as_reference() { | ||
96 | expected = inner; | ||
97 | default_bm = match default_bm { | ||
98 | BindingMode::Move => BindingMode::Ref(mutability), | ||
99 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
100 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
101 | } | ||
102 | } | ||
103 | } else if let Pat::Ref { .. } = &body[pat] { | ||
104 | tested_by!(match_ergonomics_ref); | ||
105 | // When you encounter a `&pat` pattern, reset to Move. | ||
106 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
107 | default_bm = BindingMode::Move; | ||
108 | } | ||
109 | |||
110 | // Lose mutability. | ||
111 | let default_bm = default_bm; | ||
112 | let expected = expected; | ||
113 | |||
114 | let ty = match &body[pat] { | ||
115 | Pat::Tuple(ref args) => { | ||
116 | let expectations = match expected.as_tuple() { | ||
117 | Some(parameters) => &*parameters.0, | ||
118 | _ => &[], | ||
119 | }; | ||
120 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
121 | |||
122 | let inner_tys = args | ||
123 | .iter() | ||
124 | .zip(expectations_iter) | ||
125 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
126 | .collect(); | ||
127 | |||
128 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
129 | } | ||
130 | Pat::Ref { pat, mutability } => { | ||
131 | let expectation = match expected.as_reference() { | ||
132 | Some((inner_ty, exp_mut)) => { | ||
133 | if *mutability != exp_mut { | ||
134 | // FIXME: emit type error? | ||
135 | } | ||
136 | inner_ty | ||
137 | } | ||
138 | _ => &Ty::Unknown, | ||
139 | }; | ||
140 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
141 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
142 | } | ||
143 | Pat::TupleStruct { path: p, args: subpats } => { | ||
144 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
145 | } | ||
146 | Pat::Record { path: p, args: fields } => { | ||
147 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
148 | } | ||
149 | Pat::Path(path) => { | ||
150 | // FIXME use correct resolver for the surrounding expression | ||
151 | let resolver = self.resolver.clone(); | ||
152 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
153 | } | ||
154 | Pat::Bind { mode, name: _, subpat } => { | ||
155 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
156 | default_bm | ||
157 | } else { | ||
158 | BindingMode::convert(*mode) | ||
159 | }; | ||
160 | let inner_ty = if let Some(subpat) = subpat { | ||
161 | self.infer_pat(*subpat, expected, default_bm) | ||
162 | } else { | ||
163 | expected.clone() | ||
164 | }; | ||
165 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
166 | |||
167 | let bound_ty = match mode { | ||
168 | BindingMode::Ref(mutability) => { | ||
169 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
170 | } | ||
171 | BindingMode::Move => inner_ty.clone(), | ||
172 | }; | ||
173 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
174 | self.write_pat_ty(pat, bound_ty); | ||
175 | return inner_ty; | ||
176 | } | ||
177 | _ => Ty::Unknown, | ||
178 | }; | ||
179 | // use a new type variable if we got Ty::Unknown here | ||
180 | let ty = self.insert_type_vars_shallow(ty); | ||
181 | self.unify(&ty, expected); | ||
182 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
183 | self.write_pat_ty(pat, ty.clone()); | ||
184 | ty | ||
185 | } | ||
186 | } | ||
diff --git a/crates/ra_hir_ty/src/infer/path.rs b/crates/ra_hir_ty/src/infer/path.rs new file mode 100644 index 000000000..e6676e1aa --- /dev/null +++ b/crates/ra_hir_ty/src/infer/path.rs | |||
@@ -0,0 +1,270 @@ | |||
1 | //! Path expression resolution. | ||
2 | |||
3 | use hir_def::{ | ||
4 | path::{Path, PathKind, PathSegment}, | ||
5 | resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, | ||
6 | AssocItemId, ContainerId, Lookup, | ||
7 | }; | ||
8 | use hir_expand::name::Name; | ||
9 | |||
10 | use crate::{db::HirDatabase, method_resolution, Substs, Ty, TypeWalk, ValueTyDefId}; | ||
11 | |||
12 | use super::{ExprOrPatId, InferenceContext, TraitRef}; | ||
13 | |||
14 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
15 | pub(super) fn infer_path( | ||
16 | &mut self, | ||
17 | resolver: &Resolver, | ||
18 | path: &Path, | ||
19 | id: ExprOrPatId, | ||
20 | ) -> Option<Ty> { | ||
21 | let ty = self.resolve_value_path(resolver, path, id)?; | ||
22 | let ty = self.insert_type_vars(ty); | ||
23 | let ty = self.normalize_associated_types_in(ty); | ||
24 | Some(ty) | ||
25 | } | ||
26 | |||
27 | fn resolve_value_path( | ||
28 | &mut self, | ||
29 | resolver: &Resolver, | ||
30 | path: &Path, | ||
31 | id: ExprOrPatId, | ||
32 | ) -> Option<Ty> { | ||
33 | let (value, self_subst) = if let PathKind::Type(type_ref) = &path.kind { | ||
34 | if path.segments.is_empty() { | ||
35 | // This can't actually happen syntax-wise | ||
36 | return None; | ||
37 | } | ||
38 | let ty = self.make_ty(type_ref); | ||
39 | let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1]; | ||
40 | let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); | ||
41 | self.resolve_ty_assoc_item( | ||
42 | ty, | ||
43 | &path.segments.last().expect("path had at least one segment").name, | ||
44 | id, | ||
45 | )? | ||
46 | } else { | ||
47 | let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?; | ||
48 | |||
49 | match value_or_partial { | ||
50 | ResolveValueResult::ValueNs(it) => (it, None), | ||
51 | ResolveValueResult::Partial(def, remaining_index) => { | ||
52 | self.resolve_assoc_item(def, path, remaining_index, id)? | ||
53 | } | ||
54 | } | ||
55 | }; | ||
56 | |||
57 | let typable: ValueTyDefId = match value { | ||
58 | ValueNs::LocalBinding(pat) => { | ||
59 | let ty = self.result.type_of_pat.get(pat)?.clone(); | ||
60 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
61 | return Some(ty); | ||
62 | } | ||
63 | ValueNs::FunctionId(it) => it.into(), | ||
64 | ValueNs::ConstId(it) => it.into(), | ||
65 | ValueNs::StaticId(it) => it.into(), | ||
66 | ValueNs::StructId(it) => it.into(), | ||
67 | ValueNs::EnumVariantId(it) => it.into(), | ||
68 | }; | ||
69 | |||
70 | let mut ty = self.db.value_ty(typable); | ||
71 | if let Some(self_subst) = self_subst { | ||
72 | ty = ty.subst(&self_subst); | ||
73 | } | ||
74 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); | ||
75 | let ty = ty.subst(&substs); | ||
76 | Some(ty) | ||
77 | } | ||
78 | |||
79 | fn resolve_assoc_item( | ||
80 | &mut self, | ||
81 | def: TypeNs, | ||
82 | path: &Path, | ||
83 | remaining_index: usize, | ||
84 | id: ExprOrPatId, | ||
85 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
86 | assert!(remaining_index < path.segments.len()); | ||
87 | // there may be more intermediate segments between the resolved one and | ||
88 | // the end. Only the last segment needs to be resolved to a value; from | ||
89 | // the segments before that, we need to get either a type or a trait ref. | ||
90 | |||
91 | let resolved_segment = &path.segments[remaining_index - 1]; | ||
92 | let remaining_segments = &path.segments[remaining_index..]; | ||
93 | let is_before_last = remaining_segments.len() == 1; | ||
94 | |||
95 | match (def, is_before_last) { | ||
96 | (TypeNs::TraitId(trait_), true) => { | ||
97 | let segment = | ||
98 | remaining_segments.last().expect("there should be at least one segment here"); | ||
99 | let trait_ref = TraitRef::from_resolved_path( | ||
100 | self.db, | ||
101 | &self.resolver, | ||
102 | trait_.into(), | ||
103 | resolved_segment, | ||
104 | None, | ||
105 | ); | ||
106 | self.resolve_trait_assoc_item(trait_ref, segment, id) | ||
107 | } | ||
108 | (def, _) => { | ||
109 | // Either we already have a type (e.g. `Vec::new`), or we have a | ||
110 | // trait but it's not the last segment, so the next segment | ||
111 | // should resolve to an associated type of that trait (e.g. `<T | ||
112 | // as Iterator>::Item::default`) | ||
113 | let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1]; | ||
114 | let ty = Ty::from_partly_resolved_hir_path( | ||
115 | self.db, | ||
116 | &self.resolver, | ||
117 | def, | ||
118 | resolved_segment, | ||
119 | remaining_segments_for_ty, | ||
120 | ); | ||
121 | if let Ty::Unknown = ty { | ||
122 | return None; | ||
123 | } | ||
124 | |||
125 | let ty = self.insert_type_vars(ty); | ||
126 | let ty = self.normalize_associated_types_in(ty); | ||
127 | |||
128 | let segment = | ||
129 | remaining_segments.last().expect("there should be at least one segment here"); | ||
130 | |||
131 | self.resolve_ty_assoc_item(ty, &segment.name, id) | ||
132 | } | ||
133 | } | ||
134 | } | ||
135 | |||
136 | fn resolve_trait_assoc_item( | ||
137 | &mut self, | ||
138 | trait_ref: TraitRef, | ||
139 | segment: &PathSegment, | ||
140 | id: ExprOrPatId, | ||
141 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
142 | let trait_ = trait_ref.trait_; | ||
143 | let item = self | ||
144 | .db | ||
145 | .trait_data(trait_) | ||
146 | .items | ||
147 | .iter() | ||
148 | .map(|(_name, id)| (*id).into()) | ||
149 | .find_map(|item| match item { | ||
150 | AssocItemId::FunctionId(func) => { | ||
151 | if segment.name == self.db.function_data(func).name { | ||
152 | Some(AssocItemId::FunctionId(func)) | ||
153 | } else { | ||
154 | None | ||
155 | } | ||
156 | } | ||
157 | |||
158 | AssocItemId::ConstId(konst) => { | ||
159 | if self.db.const_data(konst).name.as_ref().map_or(false, |n| n == &segment.name) | ||
160 | { | ||
161 | Some(AssocItemId::ConstId(konst)) | ||
162 | } else { | ||
163 | None | ||
164 | } | ||
165 | } | ||
166 | AssocItemId::TypeAliasId(_) => None, | ||
167 | })?; | ||
168 | let def = match item { | ||
169 | AssocItemId::FunctionId(f) => ValueNs::FunctionId(f), | ||
170 | AssocItemId::ConstId(c) => ValueNs::ConstId(c), | ||
171 | AssocItemId::TypeAliasId(_) => unreachable!(), | ||
172 | }; | ||
173 | let substs = Substs::build_for_def(self.db, item) | ||
174 | .use_parent_substs(&trait_ref.substs) | ||
175 | .fill_with_params() | ||
176 | .build(); | ||
177 | |||
178 | self.write_assoc_resolution(id, item); | ||
179 | Some((def, Some(substs))) | ||
180 | } | ||
181 | |||
182 | fn resolve_ty_assoc_item( | ||
183 | &mut self, | ||
184 | ty: Ty, | ||
185 | name: &Name, | ||
186 | id: ExprOrPatId, | ||
187 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
188 | if let Ty::Unknown = ty { | ||
189 | return None; | ||
190 | } | ||
191 | |||
192 | let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); | ||
193 | |||
194 | method_resolution::iterate_method_candidates( | ||
195 | &canonical_ty.value, | ||
196 | self.db, | ||
197 | &self.resolver.clone(), | ||
198 | Some(name), | ||
199 | method_resolution::LookupMode::Path, | ||
200 | move |_ty, item| { | ||
201 | let (def, container) = match item { | ||
202 | AssocItemId::FunctionId(f) => { | ||
203 | (ValueNs::FunctionId(f), f.lookup(self.db).container) | ||
204 | } | ||
205 | AssocItemId::ConstId(c) => (ValueNs::ConstId(c), c.lookup(self.db).container), | ||
206 | AssocItemId::TypeAliasId(_) => unreachable!(), | ||
207 | }; | ||
208 | let substs = match container { | ||
209 | ContainerId::ImplId(_) => self.find_self_types(&def, ty.clone()), | ||
210 | ContainerId::TraitId(trait_) => { | ||
211 | // we're picking this method | ||
212 | let trait_substs = Substs::build_for_def(self.db, trait_) | ||
213 | .push(ty.clone()) | ||
214 | .fill(std::iter::repeat_with(|| self.new_type_var())) | ||
215 | .build(); | ||
216 | let substs = Substs::build_for_def(self.db, item) | ||
217 | .use_parent_substs(&trait_substs) | ||
218 | .fill_with_params() | ||
219 | .build(); | ||
220 | self.obligations.push(super::Obligation::Trait(TraitRef { | ||
221 | trait_, | ||
222 | substs: trait_substs, | ||
223 | })); | ||
224 | Some(substs) | ||
225 | } | ||
226 | ContainerId::ModuleId(_) => None, | ||
227 | }; | ||
228 | |||
229 | self.write_assoc_resolution(id, item.into()); | ||
230 | Some((def, substs)) | ||
231 | }, | ||
232 | ) | ||
233 | } | ||
234 | |||
235 | fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option<Substs> { | ||
236 | if let ValueNs::FunctionId(func) = *def { | ||
237 | // We only do the infer if parent has generic params | ||
238 | let gen = self.db.generic_params(func.into()); | ||
239 | if gen.count_parent_params() == 0 { | ||
240 | return None; | ||
241 | } | ||
242 | |||
243 | let impl_id = match func.lookup(self.db).container { | ||
244 | ContainerId::ImplId(it) => it, | ||
245 | _ => return None, | ||
246 | }; | ||
247 | let resolver = impl_id.resolver(self.db); | ||
248 | let impl_data = self.db.impl_data(impl_id); | ||
249 | let impl_block = Ty::from_hir(self.db, &resolver, &impl_data.target_type); | ||
250 | let impl_block_substs = impl_block.substs()?; | ||
251 | let actual_substs = actual_def_ty.substs()?; | ||
252 | |||
253 | let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; | ||
254 | |||
255 | // The following code *link up* the function actual parma type | ||
256 | // and impl_block type param index | ||
257 | impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { | ||
258 | if let Ty::Param { idx, .. } = param { | ||
259 | if let Some(s) = new_substs.get_mut(*idx as usize) { | ||
260 | *s = pty.clone(); | ||
261 | } | ||
262 | } | ||
263 | }); | ||
264 | |||
265 | Some(Substs(new_substs.into())) | ||
266 | } else { | ||
267 | None | ||
268 | } | ||
269 | } | ||
270 | } | ||
diff --git a/crates/ra_hir_ty/src/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs new file mode 100644 index 000000000..f3a875678 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/unify.rs | |||
@@ -0,0 +1,162 @@ | |||
1 | //! Unification and canonicalization logic. | ||
2 | |||
3 | use super::{InferenceContext, Obligation}; | ||
4 | use crate::{ | ||
5 | db::HirDatabase, utils::make_mut_slice, Canonical, InEnvironment, InferTy, ProjectionPredicate, | ||
6 | ProjectionTy, Substs, TraitRef, Ty, TypeWalk, | ||
7 | }; | ||
8 | |||
9 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
10 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> | ||
11 | where | ||
12 | 'a: 'b, | ||
13 | { | ||
14 | Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } | ||
15 | } | ||
16 | } | ||
17 | |||
18 | pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> | ||
19 | where | ||
20 | 'a: 'b, | ||
21 | { | ||
22 | ctx: &'b mut InferenceContext<'a, D>, | ||
23 | free_vars: Vec<InferTy>, | ||
24 | /// A stack of type variables that is used to detect recursive types (which | ||
25 | /// are an error, but we need to protect against them to avoid stack | ||
26 | /// overflows). | ||
27 | var_stack: Vec<super::TypeVarId>, | ||
28 | } | ||
29 | |||
30 | pub(super) struct Canonicalized<T> { | ||
31 | pub value: Canonical<T>, | ||
32 | free_vars: Vec<InferTy>, | ||
33 | } | ||
34 | |||
35 | impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> | ||
36 | where | ||
37 | 'a: 'b, | ||
38 | { | ||
39 | fn add(&mut self, free_var: InferTy) -> usize { | ||
40 | self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { | ||
41 | let next_index = self.free_vars.len(); | ||
42 | self.free_vars.push(free_var); | ||
43 | next_index | ||
44 | }) | ||
45 | } | ||
46 | |||
47 | fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { | ||
48 | ty.fold(&mut |ty| match ty { | ||
49 | Ty::Infer(tv) => { | ||
50 | let inner = tv.to_inner(); | ||
51 | if self.var_stack.contains(&inner) { | ||
52 | // recursive type | ||
53 | return tv.fallback_value(); | ||
54 | } | ||
55 | if let Some(known_ty) = | ||
56 | self.ctx.var_unification_table.inlined_probe_value(inner).known() | ||
57 | { | ||
58 | self.var_stack.push(inner); | ||
59 | let result = self.do_canonicalize_ty(known_ty.clone()); | ||
60 | self.var_stack.pop(); | ||
61 | result | ||
62 | } else { | ||
63 | let root = self.ctx.var_unification_table.find(inner); | ||
64 | let free_var = match tv { | ||
65 | InferTy::TypeVar(_) => InferTy::TypeVar(root), | ||
66 | InferTy::IntVar(_) => InferTy::IntVar(root), | ||
67 | InferTy::FloatVar(_) => InferTy::FloatVar(root), | ||
68 | InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root), | ||
69 | }; | ||
70 | let position = self.add(free_var); | ||
71 | Ty::Bound(position as u32) | ||
72 | } | ||
73 | } | ||
74 | _ => ty, | ||
75 | }) | ||
76 | } | ||
77 | |||
78 | fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { | ||
79 | for ty in make_mut_slice(&mut trait_ref.substs.0) { | ||
80 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
81 | } | ||
82 | trait_ref | ||
83 | } | ||
84 | |||
85 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { | ||
86 | Canonicalized { | ||
87 | value: Canonical { value: result, num_vars: self.free_vars.len() }, | ||
88 | free_vars: self.free_vars, | ||
89 | } | ||
90 | } | ||
91 | |||
92 | fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { | ||
93 | for ty in make_mut_slice(&mut projection_ty.parameters.0) { | ||
94 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
95 | } | ||
96 | projection_ty | ||
97 | } | ||
98 | |||
99 | fn do_canonicalize_projection_predicate( | ||
100 | &mut self, | ||
101 | projection: ProjectionPredicate, | ||
102 | ) -> ProjectionPredicate { | ||
103 | let ty = self.do_canonicalize_ty(projection.ty); | ||
104 | let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty); | ||
105 | |||
106 | ProjectionPredicate { ty, projection_ty } | ||
107 | } | ||
108 | |||
109 | // FIXME: add some point, we need to introduce a `Fold` trait that abstracts | ||
110 | // over all the things that can be canonicalized (like Chalk and rustc have) | ||
111 | |||
112 | pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized<Ty> { | ||
113 | let result = self.do_canonicalize_ty(ty); | ||
114 | self.into_canonicalized(result) | ||
115 | } | ||
116 | |||
117 | pub(crate) fn canonicalize_obligation( | ||
118 | mut self, | ||
119 | obligation: InEnvironment<Obligation>, | ||
120 | ) -> Canonicalized<InEnvironment<Obligation>> { | ||
121 | let result = match obligation.value { | ||
122 | Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)), | ||
123 | Obligation::Projection(pr) => { | ||
124 | Obligation::Projection(self.do_canonicalize_projection_predicate(pr)) | ||
125 | } | ||
126 | }; | ||
127 | self.into_canonicalized(InEnvironment { | ||
128 | value: result, | ||
129 | environment: obligation.environment, | ||
130 | }) | ||
131 | } | ||
132 | } | ||
133 | |||
134 | impl<T> Canonicalized<T> { | ||
135 | pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { | ||
136 | ty.walk_mut_binders( | ||
137 | &mut |ty, binders| match ty { | ||
138 | &mut Ty::Bound(idx) => { | ||
139 | if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { | ||
140 | *ty = Ty::Infer(self.free_vars[idx as usize - binders]); | ||
141 | } | ||
142 | } | ||
143 | _ => {} | ||
144 | }, | ||
145 | 0, | ||
146 | ); | ||
147 | ty | ||
148 | } | ||
149 | |||
150 | pub fn apply_solution( | ||
151 | &self, | ||
152 | ctx: &mut InferenceContext<'_, impl HirDatabase>, | ||
153 | solution: Canonical<Vec<Ty>>, | ||
154 | ) { | ||
155 | // the solution may contain new variables, which we need to convert to new inference vars | ||
156 | let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect()); | ||
157 | for (i, ty) in solution.value.into_iter().enumerate() { | ||
158 | let var = self.free_vars[i]; | ||
159 | ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); | ||
160 | } | ||
161 | } | ||
162 | } | ||
diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index 28859ba63..f25846326 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs | |||
@@ -1,4 +1,1134 @@ | |||
1 | //! Work in Progress: everything related to types, type inference and trait | 1 | //! The type system. We currently use this to infer types for completion, hover |
2 | //! solving. | 2 | //! information and various assists. |
3 | 3 | ||
4 | macro_rules! impl_froms { | ||
5 | ($e:ident: $($v:ident $(($($sv:ident),*))?),*) => { | ||
6 | $( | ||
7 | impl From<$v> for $e { | ||
8 | fn from(it: $v) -> $e { | ||
9 | $e::$v(it) | ||
10 | } | ||
11 | } | ||
12 | $($( | ||
13 | impl From<$sv> for $e { | ||
14 | fn from(it: $sv) -> $e { | ||
15 | $e::$v($v::$sv(it)) | ||
16 | } | ||
17 | } | ||
18 | )*)? | ||
19 | )* | ||
20 | } | ||
21 | } | ||
22 | |||
23 | mod autoderef; | ||
4 | pub mod primitive; | 24 | pub mod primitive; |
25 | pub mod traits; | ||
26 | pub mod method_resolution; | ||
27 | mod op; | ||
28 | mod lower; | ||
29 | mod infer; | ||
30 | pub mod display; | ||
31 | pub(crate) mod utils; | ||
32 | pub mod db; | ||
33 | pub mod diagnostics; | ||
34 | pub mod expr; | ||
35 | |||
36 | #[cfg(test)] | ||
37 | mod tests; | ||
38 | #[cfg(test)] | ||
39 | mod test_db; | ||
40 | mod marks; | ||
41 | |||
42 | use std::ops::Deref; | ||
43 | use std::sync::Arc; | ||
44 | use std::{fmt, iter, mem}; | ||
45 | |||
46 | use hir_def::{ | ||
47 | expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId, | ||
48 | GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, | ||
49 | }; | ||
50 | use hir_expand::name::Name; | ||
51 | use ra_db::{impl_intern_key, salsa, CrateId}; | ||
52 | |||
53 | use crate::{ | ||
54 | db::HirDatabase, | ||
55 | primitive::{FloatTy, IntTy, Uncertain}, | ||
56 | utils::make_mut_slice, | ||
57 | }; | ||
58 | use display::{HirDisplay, HirFormatter}; | ||
59 | |||
60 | pub use autoderef::autoderef; | ||
61 | pub use infer::{infer_query, InferTy, InferenceResult}; | ||
62 | pub use lower::CallableDef; | ||
63 | pub use lower::{callable_item_sig, TyDefId, ValueTyDefId}; | ||
64 | pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; | ||
65 | |||
66 | /// A type constructor or type name: this might be something like the primitive | ||
67 | /// type `bool`, a struct like `Vec`, or things like function pointers or | ||
68 | /// tuples. | ||
69 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] | ||
70 | pub enum TypeCtor { | ||
71 | /// The primitive boolean type. Written as `bool`. | ||
72 | Bool, | ||
73 | |||
74 | /// The primitive character type; holds a Unicode scalar value | ||
75 | /// (a non-surrogate code point). Written as `char`. | ||
76 | Char, | ||
77 | |||
78 | /// A primitive integer type. For example, `i32`. | ||
79 | Int(Uncertain<IntTy>), | ||
80 | |||
81 | /// A primitive floating-point type. For example, `f64`. | ||
82 | Float(Uncertain<FloatTy>), | ||
83 | |||
84 | /// Structures, enumerations and unions. | ||
85 | Adt(AdtId), | ||
86 | |||
87 | /// The pointee of a string slice. Written as `str`. | ||
88 | Str, | ||
89 | |||
90 | /// The pointee of an array slice. Written as `[T]`. | ||
91 | Slice, | ||
92 | |||
93 | /// An array with the given length. Written as `[T; n]`. | ||
94 | Array, | ||
95 | |||
96 | /// A raw pointer. Written as `*mut T` or `*const T` | ||
97 | RawPtr(Mutability), | ||
98 | |||
99 | /// A reference; a pointer with an associated lifetime. Written as | ||
100 | /// `&'a mut T` or `&'a T`. | ||
101 | Ref(Mutability), | ||
102 | |||
103 | /// The anonymous type of a function declaration/definition. Each | ||
104 | /// function has a unique type, which is output (for a function | ||
105 | /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. | ||
106 | /// | ||
107 | /// This includes tuple struct / enum variant constructors as well. | ||
108 | /// | ||
109 | /// For example the type of `bar` here: | ||
110 | /// | ||
111 | /// ``` | ||
112 | /// fn foo() -> i32 { 1 } | ||
113 | /// let bar = foo; // bar: fn() -> i32 {foo} | ||
114 | /// ``` | ||
115 | FnDef(CallableDef), | ||
116 | |||
117 | /// A pointer to a function. Written as `fn() -> i32`. | ||
118 | /// | ||
119 | /// For example the type of `bar` here: | ||
120 | /// | ||
121 | /// ``` | ||
122 | /// fn foo() -> i32 { 1 } | ||
123 | /// let bar: fn() -> i32 = foo; | ||
124 | /// ``` | ||
125 | FnPtr { num_args: u16 }, | ||
126 | |||
127 | /// The never type `!`. | ||
128 | Never, | ||
129 | |||
130 | /// A tuple type. For example, `(i32, bool)`. | ||
131 | Tuple { cardinality: u16 }, | ||
132 | |||
133 | /// Represents an associated item like `Iterator::Item`. This is used | ||
134 | /// when we have tried to normalize a projection like `T::Item` but | ||
135 | /// couldn't find a better representation. In that case, we generate | ||
136 | /// an **application type** like `(Iterator::Item)<T>`. | ||
137 | AssociatedType(TypeAliasId), | ||
138 | |||
139 | /// The type of a specific closure. | ||
140 | /// | ||
141 | /// The closure signature is stored in a `FnPtr` type in the first type | ||
142 | /// parameter. | ||
143 | Closure { def: DefWithBodyId, expr: ExprId }, | ||
144 | } | ||
145 | |||
146 | /// This exists just for Chalk, because Chalk just has a single `StructId` where | ||
147 | /// we have different kinds of ADTs, primitive types and special type | ||
148 | /// constructors like tuples and function pointers. | ||
149 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
150 | pub struct TypeCtorId(salsa::InternId); | ||
151 | impl_intern_key!(TypeCtorId); | ||
152 | |||
153 | impl TypeCtor { | ||
154 | pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { | ||
155 | match self { | ||
156 | TypeCtor::Bool | ||
157 | | TypeCtor::Char | ||
158 | | TypeCtor::Int(_) | ||
159 | | TypeCtor::Float(_) | ||
160 | | TypeCtor::Str | ||
161 | | TypeCtor::Never => 0, | ||
162 | TypeCtor::Slice | ||
163 | | TypeCtor::Array | ||
164 | | TypeCtor::RawPtr(_) | ||
165 | | TypeCtor::Ref(_) | ||
166 | | TypeCtor::Closure { .. } // 1 param representing the signature of the closure | ||
167 | => 1, | ||
168 | TypeCtor::Adt(adt) => { | ||
169 | let generic_params = db.generic_params(AdtId::from(adt).into()); | ||
170 | generic_params.count_params_including_parent() | ||
171 | } | ||
172 | TypeCtor::FnDef(callable) => { | ||
173 | let generic_params = db.generic_params(callable.into()); | ||
174 | generic_params.count_params_including_parent() | ||
175 | } | ||
176 | TypeCtor::AssociatedType(type_alias) => { | ||
177 | let generic_params = db.generic_params(type_alias.into()); | ||
178 | generic_params.count_params_including_parent() | ||
179 | } | ||
180 | TypeCtor::FnPtr { num_args } => num_args as usize + 1, | ||
181 | TypeCtor::Tuple { cardinality } => cardinality as usize, | ||
182 | } | ||
183 | } | ||
184 | |||
185 | pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> { | ||
186 | match self { | ||
187 | TypeCtor::Bool | ||
188 | | TypeCtor::Char | ||
189 | | TypeCtor::Int(_) | ||
190 | | TypeCtor::Float(_) | ||
191 | | TypeCtor::Str | ||
192 | | TypeCtor::Never | ||
193 | | TypeCtor::Slice | ||
194 | | TypeCtor::Array | ||
195 | | TypeCtor::RawPtr(_) | ||
196 | | TypeCtor::Ref(_) | ||
197 | | TypeCtor::FnPtr { .. } | ||
198 | | TypeCtor::Tuple { .. } => None, | ||
199 | // Closure's krate is irrelevant for coherence I would think? | ||
200 | TypeCtor::Closure { .. } => None, | ||
201 | TypeCtor::Adt(adt) => Some(adt.module(db).krate), | ||
202 | TypeCtor::FnDef(callable) => Some(callable.krate(db)), | ||
203 | TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate), | ||
204 | } | ||
205 | } | ||
206 | |||
207 | pub fn as_generic_def(self) -> Option<GenericDefId> { | ||
208 | match self { | ||
209 | TypeCtor::Bool | ||
210 | | TypeCtor::Char | ||
211 | | TypeCtor::Int(_) | ||
212 | | TypeCtor::Float(_) | ||
213 | | TypeCtor::Str | ||
214 | | TypeCtor::Never | ||
215 | | TypeCtor::Slice | ||
216 | | TypeCtor::Array | ||
217 | | TypeCtor::RawPtr(_) | ||
218 | | TypeCtor::Ref(_) | ||
219 | | TypeCtor::FnPtr { .. } | ||
220 | | TypeCtor::Tuple { .. } | ||
221 | | TypeCtor::Closure { .. } => None, | ||
222 | TypeCtor::Adt(adt) => Some(adt.into()), | ||
223 | TypeCtor::FnDef(callable) => Some(callable.into()), | ||
224 | TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()), | ||
225 | } | ||
226 | } | ||
227 | } | ||
228 | |||
229 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
230 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
231 | /// several other things. | ||
232 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
233 | pub struct ApplicationTy { | ||
234 | pub ctor: TypeCtor, | ||
235 | pub parameters: Substs, | ||
236 | } | ||
237 | |||
238 | /// A "projection" type corresponds to an (unnormalized) | ||
239 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
240 | /// trait and all its parameters are fully known. | ||
241 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
242 | pub struct ProjectionTy { | ||
243 | pub associated_ty: TypeAliasId, | ||
244 | pub parameters: Substs, | ||
245 | } | ||
246 | |||
247 | impl ProjectionTy { | ||
248 | pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { | ||
249 | TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() } | ||
250 | } | ||
251 | |||
252 | fn trait_(&self, db: &impl HirDatabase) -> TraitId { | ||
253 | match self.associated_ty.lookup(db).container { | ||
254 | ContainerId::TraitId(it) => it, | ||
255 | _ => panic!("projection ty without parent trait"), | ||
256 | } | ||
257 | } | ||
258 | } | ||
259 | |||
260 | impl TypeWalk for ProjectionTy { | ||
261 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
262 | self.parameters.walk(f); | ||
263 | } | ||
264 | |||
265 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
266 | self.parameters.walk_mut_binders(f, binders); | ||
267 | } | ||
268 | } | ||
269 | |||
270 | /// A type. | ||
271 | /// | ||
272 | /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents | ||
273 | /// the same thing (but in a different way). | ||
274 | /// | ||
275 | /// This should be cheap to clone. | ||
276 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
277 | pub enum Ty { | ||
278 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
279 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
280 | /// several other things. | ||
281 | Apply(ApplicationTy), | ||
282 | |||
283 | /// A "projection" type corresponds to an (unnormalized) | ||
284 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
285 | /// trait and all its parameters are fully known. | ||
286 | Projection(ProjectionTy), | ||
287 | |||
288 | /// A type parameter; for example, `T` in `fn f<T>(x: T) {} | ||
289 | Param { | ||
290 | /// The index of the parameter (starting with parameters from the | ||
291 | /// surrounding impl, then the current function). | ||
292 | idx: u32, | ||
293 | /// The name of the parameter, for displaying. | ||
294 | // FIXME get rid of this | ||
295 | name: Name, | ||
296 | }, | ||
297 | |||
298 | /// A bound type variable. Used during trait resolution to represent Chalk | ||
299 | /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. | ||
300 | Bound(u32), | ||
301 | |||
302 | /// A type variable used during type checking. Not to be confused with a | ||
303 | /// type parameter. | ||
304 | Infer(InferTy), | ||
305 | |||
306 | /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). | ||
307 | /// | ||
308 | /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)` | ||
309 | /// represents the `Self` type inside the bounds. This is currently | ||
310 | /// implicit; Chalk has the `Binders` struct to make it explicit, but it | ||
311 | /// didn't seem worth the overhead yet. | ||
312 | Dyn(Arc<[GenericPredicate]>), | ||
313 | |||
314 | /// An opaque type (`impl Trait`). | ||
315 | /// | ||
316 | /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for | ||
317 | /// more. | ||
318 | Opaque(Arc<[GenericPredicate]>), | ||
319 | |||
320 | /// A placeholder for a type which could not be computed; this is propagated | ||
321 | /// to avoid useless error messages. Doubles as a placeholder where type | ||
322 | /// variables are inserted before type checking, since we want to try to | ||
323 | /// infer a better type here anyway -- for the IDE use case, we want to try | ||
324 | /// to infer as much as possible even in the presence of type errors. | ||
325 | Unknown, | ||
326 | } | ||
327 | |||
328 | /// A list of substitutions for generic parameters. | ||
329 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
330 | pub struct Substs(Arc<[Ty]>); | ||
331 | |||
332 | impl TypeWalk for Substs { | ||
333 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
334 | for t in self.0.iter() { | ||
335 | t.walk(f); | ||
336 | } | ||
337 | } | ||
338 | |||
339 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
340 | for t in make_mut_slice(&mut self.0) { | ||
341 | t.walk_mut_binders(f, binders); | ||
342 | } | ||
343 | } | ||
344 | } | ||
345 | |||
346 | impl Substs { | ||
347 | pub fn empty() -> Substs { | ||
348 | Substs(Arc::new([])) | ||
349 | } | ||
350 | |||
351 | pub fn single(ty: Ty) -> Substs { | ||
352 | Substs(Arc::new([ty])) | ||
353 | } | ||
354 | |||
355 | pub fn prefix(&self, n: usize) -> Substs { | ||
356 | Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) | ||
357 | } | ||
358 | |||
359 | pub fn as_single(&self) -> &Ty { | ||
360 | if self.0.len() != 1 { | ||
361 | panic!("expected substs of len 1, got {:?}", self); | ||
362 | } | ||
363 | &self.0[0] | ||
364 | } | ||
365 | |||
366 | /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). | ||
367 | pub fn identity(generic_params: &GenericParams) -> Substs { | ||
368 | Substs( | ||
369 | generic_params | ||
370 | .params_including_parent() | ||
371 | .into_iter() | ||
372 | .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) | ||
373 | .collect(), | ||
374 | ) | ||
375 | } | ||
376 | |||
377 | /// Return Substs that replace each parameter by a bound variable. | ||
378 | pub fn bound_vars(generic_params: &GenericParams) -> Substs { | ||
379 | Substs( | ||
380 | generic_params | ||
381 | .params_including_parent() | ||
382 | .into_iter() | ||
383 | .map(|p| Ty::Bound(p.idx)) | ||
384 | .collect(), | ||
385 | ) | ||
386 | } | ||
387 | |||
388 | pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder { | ||
389 | let def = def.into(); | ||
390 | let params = db.generic_params(def); | ||
391 | let param_count = params.count_params_including_parent(); | ||
392 | Substs::builder(param_count) | ||
393 | } | ||
394 | |||
395 | pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder { | ||
396 | Substs::builder(generic_params.count_params_including_parent()) | ||
397 | } | ||
398 | |||
399 | pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { | ||
400 | Substs::builder(type_ctor.num_ty_params(db)) | ||
401 | } | ||
402 | |||
403 | fn builder(param_count: usize) -> SubstsBuilder { | ||
404 | SubstsBuilder { vec: Vec::with_capacity(param_count), param_count } | ||
405 | } | ||
406 | } | ||
407 | |||
408 | #[derive(Debug, Clone)] | ||
409 | pub struct SubstsBuilder { | ||
410 | vec: Vec<Ty>, | ||
411 | param_count: usize, | ||
412 | } | ||
413 | |||
414 | impl SubstsBuilder { | ||
415 | pub fn build(self) -> Substs { | ||
416 | assert_eq!(self.vec.len(), self.param_count); | ||
417 | Substs(self.vec.into()) | ||
418 | } | ||
419 | |||
420 | pub fn push(mut self, ty: Ty) -> Self { | ||
421 | self.vec.push(ty); | ||
422 | self | ||
423 | } | ||
424 | |||
425 | fn remaining(&self) -> usize { | ||
426 | self.param_count - self.vec.len() | ||
427 | } | ||
428 | |||
429 | pub fn fill_with_bound_vars(self, starting_from: u32) -> Self { | ||
430 | self.fill((starting_from..).map(Ty::Bound)) | ||
431 | } | ||
432 | |||
433 | pub fn fill_with_params(self) -> Self { | ||
434 | let start = self.vec.len() as u32; | ||
435 | self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() })) | ||
436 | } | ||
437 | |||
438 | pub fn fill_with_unknown(self) -> Self { | ||
439 | self.fill(iter::repeat(Ty::Unknown)) | ||
440 | } | ||
441 | |||
442 | pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { | ||
443 | self.vec.extend(filler.take(self.remaining())); | ||
444 | assert_eq!(self.remaining(), 0); | ||
445 | self | ||
446 | } | ||
447 | |||
448 | pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { | ||
449 | assert!(self.vec.is_empty()); | ||
450 | assert!(parent_substs.len() <= self.param_count); | ||
451 | self.vec.extend(parent_substs.iter().cloned()); | ||
452 | self | ||
453 | } | ||
454 | } | ||
455 | |||
456 | impl Deref for Substs { | ||
457 | type Target = [Ty]; | ||
458 | |||
459 | fn deref(&self) -> &[Ty] { | ||
460 | &self.0 | ||
461 | } | ||
462 | } | ||
463 | |||
464 | /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. | ||
465 | /// Name to be bikeshedded: TraitBound? TraitImplements? | ||
466 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
467 | pub struct TraitRef { | ||
468 | /// FIXME name? | ||
469 | pub trait_: TraitId, | ||
470 | pub substs: Substs, | ||
471 | } | ||
472 | |||
473 | impl TraitRef { | ||
474 | pub fn self_ty(&self) -> &Ty { | ||
475 | &self.substs[0] | ||
476 | } | ||
477 | } | ||
478 | |||
479 | impl TypeWalk for TraitRef { | ||
480 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
481 | self.substs.walk(f); | ||
482 | } | ||
483 | |||
484 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
485 | self.substs.walk_mut_binders(f, binders); | ||
486 | } | ||
487 | } | ||
488 | |||
489 | /// Like `generics::WherePredicate`, but with resolved types: A condition on the | ||
490 | /// parameters of a generic item. | ||
491 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
492 | pub enum GenericPredicate { | ||
493 | /// The given trait needs to be implemented for its type parameters. | ||
494 | Implemented(TraitRef), | ||
495 | /// An associated type bindings like in `Iterator<Item = T>`. | ||
496 | Projection(ProjectionPredicate), | ||
497 | /// We couldn't resolve the trait reference. (If some type parameters can't | ||
498 | /// be resolved, they will just be Unknown). | ||
499 | Error, | ||
500 | } | ||
501 | |||
502 | impl GenericPredicate { | ||
503 | pub fn is_error(&self) -> bool { | ||
504 | match self { | ||
505 | GenericPredicate::Error => true, | ||
506 | _ => false, | ||
507 | } | ||
508 | } | ||
509 | |||
510 | pub fn is_implemented(&self) -> bool { | ||
511 | match self { | ||
512 | GenericPredicate::Implemented(_) => true, | ||
513 | _ => false, | ||
514 | } | ||
515 | } | ||
516 | |||
517 | pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { | ||
518 | match self { | ||
519 | GenericPredicate::Implemented(tr) => Some(tr.clone()), | ||
520 | GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), | ||
521 | GenericPredicate::Error => None, | ||
522 | } | ||
523 | } | ||
524 | } | ||
525 | |||
526 | impl TypeWalk for GenericPredicate { | ||
527 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
528 | match self { | ||
529 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f), | ||
530 | GenericPredicate::Projection(projection_pred) => projection_pred.walk(f), | ||
531 | GenericPredicate::Error => {} | ||
532 | } | ||
533 | } | ||
534 | |||
535 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
536 | match self { | ||
537 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), | ||
538 | GenericPredicate::Projection(projection_pred) => { | ||
539 | projection_pred.walk_mut_binders(f, binders) | ||
540 | } | ||
541 | GenericPredicate::Error => {} | ||
542 | } | ||
543 | } | ||
544 | } | ||
545 | |||
546 | /// Basically a claim (currently not validated / checked) that the contained | ||
547 | /// type / trait ref contains no inference variables; any inference variables it | ||
548 | /// contained have been replaced by bound variables, and `num_vars` tells us how | ||
549 | /// many there are. This is used to erase irrelevant differences between types | ||
550 | /// before using them in queries. | ||
551 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
552 | pub struct Canonical<T> { | ||
553 | pub value: T, | ||
554 | pub num_vars: usize, | ||
555 | } | ||
556 | |||
557 | /// A function signature as seen by type inference: Several parameter types and | ||
558 | /// one return type. | ||
559 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
560 | pub struct FnSig { | ||
561 | params_and_return: Arc<[Ty]>, | ||
562 | } | ||
563 | |||
564 | impl FnSig { | ||
565 | pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig { | ||
566 | params.push(ret); | ||
567 | FnSig { params_and_return: params.into() } | ||
568 | } | ||
569 | |||
570 | pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig { | ||
571 | FnSig { params_and_return: Arc::clone(&substs.0) } | ||
572 | } | ||
573 | |||
574 | pub fn params(&self) -> &[Ty] { | ||
575 | &self.params_and_return[0..self.params_and_return.len() - 1] | ||
576 | } | ||
577 | |||
578 | pub fn ret(&self) -> &Ty { | ||
579 | &self.params_and_return[self.params_and_return.len() - 1] | ||
580 | } | ||
581 | } | ||
582 | |||
583 | impl TypeWalk for FnSig { | ||
584 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
585 | for t in self.params_and_return.iter() { | ||
586 | t.walk(f); | ||
587 | } | ||
588 | } | ||
589 | |||
590 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
591 | for t in make_mut_slice(&mut self.params_and_return) { | ||
592 | t.walk_mut_binders(f, binders); | ||
593 | } | ||
594 | } | ||
595 | } | ||
596 | |||
597 | impl Ty { | ||
598 | pub fn simple(ctor: TypeCtor) -> Ty { | ||
599 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() }) | ||
600 | } | ||
601 | pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty { | ||
602 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) }) | ||
603 | } | ||
604 | pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty { | ||
605 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
606 | } | ||
607 | pub fn unit() -> Self { | ||
608 | Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) | ||
609 | } | ||
610 | |||
611 | pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { | ||
612 | match self { | ||
613 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => { | ||
614 | Some((parameters.as_single(), *mutability)) | ||
615 | } | ||
616 | _ => None, | ||
617 | } | ||
618 | } | ||
619 | |||
620 | pub fn as_adt(&self) -> Option<(AdtId, &Substs)> { | ||
621 | match self { | ||
622 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => { | ||
623 | Some((*adt_def, parameters)) | ||
624 | } | ||
625 | _ => None, | ||
626 | } | ||
627 | } | ||
628 | |||
629 | pub fn as_tuple(&self) -> Option<&Substs> { | ||
630 | match self { | ||
631 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { | ||
632 | Some(parameters) | ||
633 | } | ||
634 | _ => None, | ||
635 | } | ||
636 | } | ||
637 | |||
638 | pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> { | ||
639 | match self { | ||
640 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => { | ||
641 | Some((*callable_def, parameters)) | ||
642 | } | ||
643 | _ => None, | ||
644 | } | ||
645 | } | ||
646 | |||
647 | fn builtin_deref(&self) -> Option<Ty> { | ||
648 | match self { | ||
649 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
650 | TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
651 | TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
652 | _ => None, | ||
653 | }, | ||
654 | _ => None, | ||
655 | } | ||
656 | } | ||
657 | |||
658 | fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> { | ||
659 | match self { | ||
660 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
661 | TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), | ||
662 | TypeCtor::FnDef(def) => { | ||
663 | let sig = db.callable_item_signature(def); | ||
664 | Some(sig.subst(&a_ty.parameters)) | ||
665 | } | ||
666 | TypeCtor::Closure { .. } => { | ||
667 | let sig_param = &a_ty.parameters[0]; | ||
668 | sig_param.callable_sig(db) | ||
669 | } | ||
670 | _ => None, | ||
671 | }, | ||
672 | _ => None, | ||
673 | } | ||
674 | } | ||
675 | |||
676 | /// If this is a type with type parameters (an ADT or function), replaces | ||
677 | /// the `Substs` for these type parameters with the given ones. (So e.g. if | ||
678 | /// `self` is `Option<_>` and the substs contain `u32`, we'll have | ||
679 | /// `Option<u32>` afterwards.) | ||
680 | pub fn apply_substs(self, substs: Substs) -> Ty { | ||
681 | match self { | ||
682 | Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => { | ||
683 | assert_eq!(previous_substs.len(), substs.len()); | ||
684 | Ty::Apply(ApplicationTy { ctor, parameters: substs }) | ||
685 | } | ||
686 | _ => self, | ||
687 | } | ||
688 | } | ||
689 | |||
690 | /// Returns the type parameters of this type if it has some (i.e. is an ADT | ||
691 | /// or function); so if `self` is `Option<u32>`, this returns the `u32`. | ||
692 | pub fn substs(&self) -> Option<Substs> { | ||
693 | match self { | ||
694 | Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), | ||
695 | _ => None, | ||
696 | } | ||
697 | } | ||
698 | |||
699 | /// If this is an `impl Trait` or `dyn Trait`, returns that trait. | ||
700 | pub fn inherent_trait(&self) -> Option<TraitId> { | ||
701 | match self { | ||
702 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
703 | predicates.iter().find_map(|pred| match pred { | ||
704 | GenericPredicate::Implemented(tr) => Some(tr.trait_), | ||
705 | _ => None, | ||
706 | }) | ||
707 | } | ||
708 | _ => None, | ||
709 | } | ||
710 | } | ||
711 | } | ||
712 | |||
713 | /// This allows walking structures that contain types to do something with those | ||
714 | /// types, similar to Chalk's `Fold` trait. | ||
715 | pub trait TypeWalk { | ||
716 | fn walk(&self, f: &mut impl FnMut(&Ty)); | ||
717 | fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { | ||
718 | self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); | ||
719 | } | ||
720 | /// Walk the type, counting entered binders. | ||
721 | /// | ||
722 | /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers | ||
723 | /// to the innermost binder, 1 to the next, etc.. So when we want to | ||
724 | /// substitute a certain bound variable, we can't just walk the whole type | ||
725 | /// and blindly replace each instance of a certain index; when we 'enter' | ||
726 | /// things that introduce new bound variables, we have to keep track of | ||
727 | /// that. Currently, the only thing that introduces bound variables on our | ||
728 | /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound | ||
729 | /// variable for the self type. | ||
730 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); | ||
731 | |||
732 | fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self | ||
733 | where | ||
734 | Self: Sized, | ||
735 | { | ||
736 | self.walk_mut(&mut |ty_mut| { | ||
737 | let ty = mem::replace(ty_mut, Ty::Unknown); | ||
738 | *ty_mut = f(ty); | ||
739 | }); | ||
740 | self | ||
741 | } | ||
742 | |||
743 | /// Replaces type parameters in this type using the given `Substs`. (So e.g. | ||
744 | /// if `self` is `&[T]`, where type parameter T has index 0, and the | ||
745 | /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.) | ||
746 | fn subst(self, substs: &Substs) -> Self | ||
747 | where | ||
748 | Self: Sized, | ||
749 | { | ||
750 | self.fold(&mut |ty| match ty { | ||
751 | Ty::Param { idx, name } => { | ||
752 | substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) | ||
753 | } | ||
754 | ty => ty, | ||
755 | }) | ||
756 | } | ||
757 | |||
758 | /// Substitutes `Ty::Bound` vars (as opposed to type parameters). | ||
759 | fn subst_bound_vars(mut self, substs: &Substs) -> Self | ||
760 | where | ||
761 | Self: Sized, | ||
762 | { | ||
763 | self.walk_mut_binders( | ||
764 | &mut |ty, binders| match ty { | ||
765 | &mut Ty::Bound(idx) => { | ||
766 | if idx as usize >= binders && (idx as usize - binders) < substs.len() { | ||
767 | *ty = substs.0[idx as usize - binders].clone(); | ||
768 | } | ||
769 | } | ||
770 | _ => {} | ||
771 | }, | ||
772 | 0, | ||
773 | ); | ||
774 | self | ||
775 | } | ||
776 | |||
777 | /// Shifts up `Ty::Bound` vars by `n`. | ||
778 | fn shift_bound_vars(self, n: i32) -> Self | ||
779 | where | ||
780 | Self: Sized, | ||
781 | { | ||
782 | self.fold(&mut |ty| match ty { | ||
783 | Ty::Bound(idx) => { | ||
784 | assert!(idx as i32 >= -n); | ||
785 | Ty::Bound((idx as i32 + n) as u32) | ||
786 | } | ||
787 | ty => ty, | ||
788 | }) | ||
789 | } | ||
790 | } | ||
791 | |||
792 | impl TypeWalk for Ty { | ||
793 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
794 | match self { | ||
795 | Ty::Apply(a_ty) => { | ||
796 | for t in a_ty.parameters.iter() { | ||
797 | t.walk(f); | ||
798 | } | ||
799 | } | ||
800 | Ty::Projection(p_ty) => { | ||
801 | for t in p_ty.parameters.iter() { | ||
802 | t.walk(f); | ||
803 | } | ||
804 | } | ||
805 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
806 | for p in predicates.iter() { | ||
807 | p.walk(f); | ||
808 | } | ||
809 | } | ||
810 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
811 | } | ||
812 | f(self); | ||
813 | } | ||
814 | |||
815 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
816 | match self { | ||
817 | Ty::Apply(a_ty) => { | ||
818 | a_ty.parameters.walk_mut_binders(f, binders); | ||
819 | } | ||
820 | Ty::Projection(p_ty) => { | ||
821 | p_ty.parameters.walk_mut_binders(f, binders); | ||
822 | } | ||
823 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
824 | for p in make_mut_slice(predicates) { | ||
825 | p.walk_mut_binders(f, binders + 1); | ||
826 | } | ||
827 | } | ||
828 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
829 | } | ||
830 | f(self, binders); | ||
831 | } | ||
832 | } | ||
833 | |||
834 | impl HirDisplay for &Ty { | ||
835 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
836 | HirDisplay::hir_fmt(*self, f) | ||
837 | } | ||
838 | } | ||
839 | |||
840 | impl HirDisplay for ApplicationTy { | ||
841 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
842 | if f.should_truncate() { | ||
843 | return write!(f, "…"); | ||
844 | } | ||
845 | |||
846 | match self.ctor { | ||
847 | TypeCtor::Bool => write!(f, "bool")?, | ||
848 | TypeCtor::Char => write!(f, "char")?, | ||
849 | TypeCtor::Int(t) => write!(f, "{}", t)?, | ||
850 | TypeCtor::Float(t) => write!(f, "{}", t)?, | ||
851 | TypeCtor::Str => write!(f, "str")?, | ||
852 | TypeCtor::Slice => { | ||
853 | let t = self.parameters.as_single(); | ||
854 | write!(f, "[{}]", t.display(f.db))?; | ||
855 | } | ||
856 | TypeCtor::Array => { | ||
857 | let t = self.parameters.as_single(); | ||
858 | write!(f, "[{};_]", t.display(f.db))?; | ||
859 | } | ||
860 | TypeCtor::RawPtr(m) => { | ||
861 | let t = self.parameters.as_single(); | ||
862 | write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?; | ||
863 | } | ||
864 | TypeCtor::Ref(m) => { | ||
865 | let t = self.parameters.as_single(); | ||
866 | write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; | ||
867 | } | ||
868 | TypeCtor::Never => write!(f, "!")?, | ||
869 | TypeCtor::Tuple { .. } => { | ||
870 | let ts = &self.parameters; | ||
871 | if ts.len() == 1 { | ||
872 | write!(f, "({},)", ts[0].display(f.db))?; | ||
873 | } else { | ||
874 | write!(f, "(")?; | ||
875 | f.write_joined(&*ts.0, ", ")?; | ||
876 | write!(f, ")")?; | ||
877 | } | ||
878 | } | ||
879 | TypeCtor::FnPtr { .. } => { | ||
880 | let sig = FnSig::from_fn_ptr_substs(&self.parameters); | ||
881 | write!(f, "fn(")?; | ||
882 | f.write_joined(sig.params(), ", ")?; | ||
883 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
884 | } | ||
885 | TypeCtor::FnDef(def) => { | ||
886 | let sig = f.db.callable_item_signature(def); | ||
887 | let name = match def { | ||
888 | CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), | ||
889 | CallableDef::StructId(s) => { | ||
890 | f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing) | ||
891 | } | ||
892 | CallableDef::EnumVariantId(e) => { | ||
893 | let enum_data = f.db.enum_data(e.parent); | ||
894 | enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing) | ||
895 | } | ||
896 | }; | ||
897 | match def { | ||
898 | CallableDef::FunctionId(_) => write!(f, "fn {}", name)?, | ||
899 | CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => { | ||
900 | write!(f, "{}", name)? | ||
901 | } | ||
902 | } | ||
903 | if self.parameters.len() > 0 { | ||
904 | write!(f, "<")?; | ||
905 | f.write_joined(&*self.parameters.0, ", ")?; | ||
906 | write!(f, ">")?; | ||
907 | } | ||
908 | write!(f, "(")?; | ||
909 | f.write_joined(sig.params(), ", ")?; | ||
910 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
911 | } | ||
912 | TypeCtor::Adt(def_id) => { | ||
913 | let name = match def_id { | ||
914 | AdtId::StructId(it) => f.db.struct_data(it).name.clone(), | ||
915 | AdtId::UnionId(it) => f.db.union_data(it).name.clone(), | ||
916 | AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), | ||
917 | } | ||
918 | .unwrap_or_else(Name::missing); | ||
919 | write!(f, "{}", name)?; | ||
920 | if self.parameters.len() > 0 { | ||
921 | write!(f, "<")?; | ||
922 | f.write_joined(&*self.parameters.0, ", ")?; | ||
923 | write!(f, ">")?; | ||
924 | } | ||
925 | } | ||
926 | TypeCtor::AssociatedType(type_alias) => { | ||
927 | let trait_ = match type_alias.lookup(f.db).container { | ||
928 | ContainerId::TraitId(it) => it, | ||
929 | _ => panic!("not an associated type"), | ||
930 | }; | ||
931 | let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing); | ||
932 | let name = f.db.type_alias_data(type_alias).name.clone(); | ||
933 | write!(f, "{}::{}", trait_name, name)?; | ||
934 | if self.parameters.len() > 0 { | ||
935 | write!(f, "<")?; | ||
936 | f.write_joined(&*self.parameters.0, ", ")?; | ||
937 | write!(f, ">")?; | ||
938 | } | ||
939 | } | ||
940 | TypeCtor::Closure { .. } => { | ||
941 | let sig = self.parameters[0] | ||
942 | .callable_sig(f.db) | ||
943 | .expect("first closure parameter should contain signature"); | ||
944 | write!(f, "|")?; | ||
945 | f.write_joined(sig.params(), ", ")?; | ||
946 | write!(f, "| -> {}", sig.ret().display(f.db))?; | ||
947 | } | ||
948 | } | ||
949 | Ok(()) | ||
950 | } | ||
951 | } | ||
952 | |||
953 | impl HirDisplay for ProjectionTy { | ||
954 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
955 | if f.should_truncate() { | ||
956 | return write!(f, "…"); | ||
957 | } | ||
958 | |||
959 | let trait_name = | ||
960 | f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing); | ||
961 | write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; | ||
962 | if self.parameters.len() > 1 { | ||
963 | write!(f, "<")?; | ||
964 | f.write_joined(&self.parameters[1..], ", ")?; | ||
965 | write!(f, ">")?; | ||
966 | } | ||
967 | write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; | ||
968 | Ok(()) | ||
969 | } | ||
970 | } | ||
971 | |||
972 | impl HirDisplay for Ty { | ||
973 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
974 | if f.should_truncate() { | ||
975 | return write!(f, "…"); | ||
976 | } | ||
977 | |||
978 | match self { | ||
979 | Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, | ||
980 | Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, | ||
981 | Ty::Param { name, .. } => write!(f, "{}", name)?, | ||
982 | Ty::Bound(idx) => write!(f, "?{}", idx)?, | ||
983 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
984 | match self { | ||
985 | Ty::Dyn(_) => write!(f, "dyn ")?, | ||
986 | Ty::Opaque(_) => write!(f, "impl ")?, | ||
987 | _ => unreachable!(), | ||
988 | }; | ||
989 | // Note: This code is written to produce nice results (i.e. | ||
990 | // corresponding to surface Rust) for types that can occur in | ||
991 | // actual Rust. It will have weird results if the predicates | ||
992 | // aren't as expected (i.e. self types = $0, projection | ||
993 | // predicates for a certain trait come after the Implemented | ||
994 | // predicate for that trait). | ||
995 | let mut first = true; | ||
996 | let mut angle_open = false; | ||
997 | for p in predicates.iter() { | ||
998 | match p { | ||
999 | GenericPredicate::Implemented(trait_ref) => { | ||
1000 | if angle_open { | ||
1001 | write!(f, ">")?; | ||
1002 | } | ||
1003 | if !first { | ||
1004 | write!(f, " + ")?; | ||
1005 | } | ||
1006 | // We assume that the self type is $0 (i.e. the | ||
1007 | // existential) here, which is the only thing that's | ||
1008 | // possible in actual Rust, and hence don't print it | ||
1009 | write!( | ||
1010 | f, | ||
1011 | "{}", | ||
1012 | f.db.trait_data(trait_ref.trait_) | ||
1013 | .name | ||
1014 | .clone() | ||
1015 | .unwrap_or_else(Name::missing) | ||
1016 | )?; | ||
1017 | if trait_ref.substs.len() > 1 { | ||
1018 | write!(f, "<")?; | ||
1019 | f.write_joined(&trait_ref.substs[1..], ", ")?; | ||
1020 | // there might be assoc type bindings, so we leave the angle brackets open | ||
1021 | angle_open = true; | ||
1022 | } | ||
1023 | } | ||
1024 | GenericPredicate::Projection(projection_pred) => { | ||
1025 | // in types in actual Rust, these will always come | ||
1026 | // after the corresponding Implemented predicate | ||
1027 | if angle_open { | ||
1028 | write!(f, ", ")?; | ||
1029 | } else { | ||
1030 | write!(f, "<")?; | ||
1031 | angle_open = true; | ||
1032 | } | ||
1033 | let name = | ||
1034 | f.db.type_alias_data(projection_pred.projection_ty.associated_ty) | ||
1035 | .name | ||
1036 | .clone(); | ||
1037 | write!(f, "{} = ", name)?; | ||
1038 | projection_pred.ty.hir_fmt(f)?; | ||
1039 | } | ||
1040 | GenericPredicate::Error => { | ||
1041 | if angle_open { | ||
1042 | // impl Trait<X, {error}> | ||
1043 | write!(f, ", ")?; | ||
1044 | } else if !first { | ||
1045 | // impl Trait + {error} | ||
1046 | write!(f, " + ")?; | ||
1047 | } | ||
1048 | p.hir_fmt(f)?; | ||
1049 | } | ||
1050 | } | ||
1051 | first = false; | ||
1052 | } | ||
1053 | if angle_open { | ||
1054 | write!(f, ">")?; | ||
1055 | } | ||
1056 | } | ||
1057 | Ty::Unknown => write!(f, "{{unknown}}")?, | ||
1058 | Ty::Infer(..) => write!(f, "_")?, | ||
1059 | } | ||
1060 | Ok(()) | ||
1061 | } | ||
1062 | } | ||
1063 | |||
1064 | impl TraitRef { | ||
1065 | fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { | ||
1066 | if f.should_truncate() { | ||
1067 | return write!(f, "…"); | ||
1068 | } | ||
1069 | |||
1070 | self.substs[0].hir_fmt(f)?; | ||
1071 | if use_as { | ||
1072 | write!(f, " as ")?; | ||
1073 | } else { | ||
1074 | write!(f, ": ")?; | ||
1075 | } | ||
1076 | write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?; | ||
1077 | if self.substs.len() > 1 { | ||
1078 | write!(f, "<")?; | ||
1079 | f.write_joined(&self.substs[1..], ", ")?; | ||
1080 | write!(f, ">")?; | ||
1081 | } | ||
1082 | Ok(()) | ||
1083 | } | ||
1084 | } | ||
1085 | |||
1086 | impl HirDisplay for TraitRef { | ||
1087 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1088 | self.hir_fmt_ext(f, false) | ||
1089 | } | ||
1090 | } | ||
1091 | |||
1092 | impl HirDisplay for &GenericPredicate { | ||
1093 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1094 | HirDisplay::hir_fmt(*self, f) | ||
1095 | } | ||
1096 | } | ||
1097 | |||
1098 | impl HirDisplay for GenericPredicate { | ||
1099 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1100 | if f.should_truncate() { | ||
1101 | return write!(f, "…"); | ||
1102 | } | ||
1103 | |||
1104 | match self { | ||
1105 | GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?, | ||
1106 | GenericPredicate::Projection(projection_pred) => { | ||
1107 | write!(f, "<")?; | ||
1108 | projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; | ||
1109 | write!( | ||
1110 | f, | ||
1111 | ">::{} = {}", | ||
1112 | f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, | ||
1113 | projection_pred.ty.display(f.db) | ||
1114 | )?; | ||
1115 | } | ||
1116 | GenericPredicate::Error => write!(f, "{{error}}")?, | ||
1117 | } | ||
1118 | Ok(()) | ||
1119 | } | ||
1120 | } | ||
1121 | |||
1122 | impl HirDisplay for Obligation { | ||
1123 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1124 | match self { | ||
1125 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), | ||
1126 | Obligation::Projection(proj) => write!( | ||
1127 | f, | ||
1128 | "Normalize({} => {})", | ||
1129 | proj.projection_ty.display(f.db), | ||
1130 | proj.ty.display(f.db) | ||
1131 | ), | ||
1132 | } | ||
1133 | } | ||
1134 | } | ||
diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs new file mode 100644 index 000000000..53d955a12 --- /dev/null +++ b/crates/ra_hir_ty/src/lower.rs | |||
@@ -0,0 +1,753 @@ | |||
1 | //! Methods for lowering the HIR to types. There are two main cases here: | ||
2 | //! | ||
3 | //! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a | ||
4 | //! type: The entry point for this is `Ty::from_hir`. | ||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | ||
6 | //! | ||
7 | //! This usually involves resolving names, collecting generic arguments etc. | ||
8 | use std::iter; | ||
9 | use std::sync::Arc; | ||
10 | |||
11 | use hir_def::{ | ||
12 | builtin_type::BuiltinType, | ||
13 | generics::WherePredicate, | ||
14 | path::{GenericArg, Path, PathKind, PathSegment}, | ||
15 | resolver::{HasResolver, Resolver, TypeNs}, | ||
16 | type_ref::{TypeBound, TypeRef}, | ||
17 | AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, | ||
18 | LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, | ||
19 | }; | ||
20 | use ra_arena::map::ArenaMap; | ||
21 | use ra_db::CrateId; | ||
22 | |||
23 | use super::{ | ||
24 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, | ||
25 | Ty, TypeCtor, TypeWalk, | ||
26 | }; | ||
27 | use crate::{ | ||
28 | db::HirDatabase, | ||
29 | primitive::{FloatTy, IntTy}, | ||
30 | utils::make_mut_slice, | ||
31 | utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data}, | ||
32 | }; | ||
33 | |||
34 | impl Ty { | ||
35 | pub fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { | ||
36 | match type_ref { | ||
37 | TypeRef::Never => Ty::simple(TypeCtor::Never), | ||
38 | TypeRef::Tuple(inner) => { | ||
39 | let inner_tys: Arc<[Ty]> = | ||
40 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); | ||
41 | Ty::apply( | ||
42 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, | ||
43 | Substs(inner_tys), | ||
44 | ) | ||
45 | } | ||
46 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), | ||
47 | TypeRef::RawPtr(inner, mutability) => { | ||
48 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
49 | Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) | ||
50 | } | ||
51 | TypeRef::Array(inner) => { | ||
52 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
53 | Ty::apply_one(TypeCtor::Array, inner_ty) | ||
54 | } | ||
55 | TypeRef::Slice(inner) => { | ||
56 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
57 | Ty::apply_one(TypeCtor::Slice, inner_ty) | ||
58 | } | ||
59 | TypeRef::Reference(inner, mutability) => { | ||
60 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
61 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
62 | } | ||
63 | TypeRef::Placeholder => Ty::Unknown, | ||
64 | TypeRef::Fn(params) => { | ||
65 | let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); | ||
66 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) | ||
67 | } | ||
68 | TypeRef::DynTrait(bounds) => { | ||
69 | let self_ty = Ty::Bound(0); | ||
70 | let predicates = bounds | ||
71 | .iter() | ||
72 | .flat_map(|b| { | ||
73 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
74 | }) | ||
75 | .collect(); | ||
76 | Ty::Dyn(predicates) | ||
77 | } | ||
78 | TypeRef::ImplTrait(bounds) => { | ||
79 | let self_ty = Ty::Bound(0); | ||
80 | let predicates = bounds | ||
81 | .iter() | ||
82 | .flat_map(|b| { | ||
83 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
84 | }) | ||
85 | .collect(); | ||
86 | Ty::Opaque(predicates) | ||
87 | } | ||
88 | TypeRef::Error => Ty::Unknown, | ||
89 | } | ||
90 | } | ||
91 | |||
92 | /// This is only for `generic_predicates_for_param`, where we can't just | ||
93 | /// lower the self types of the predicates since that could lead to cycles. | ||
94 | /// So we just check here if the `type_ref` resolves to a generic param, and which. | ||
95 | fn from_hir_only_param( | ||
96 | db: &impl HirDatabase, | ||
97 | resolver: &Resolver, | ||
98 | type_ref: &TypeRef, | ||
99 | ) -> Option<u32> { | ||
100 | let path = match type_ref { | ||
101 | TypeRef::Path(path) => path, | ||
102 | _ => return None, | ||
103 | }; | ||
104 | if let PathKind::Type(_) = &path.kind { | ||
105 | return None; | ||
106 | } | ||
107 | if path.segments.len() > 1 { | ||
108 | return None; | ||
109 | } | ||
110 | let resolution = match resolver.resolve_path_in_type_ns(db, path) { | ||
111 | Some((it, None)) => it, | ||
112 | _ => return None, | ||
113 | }; | ||
114 | if let TypeNs::GenericParam(idx) = resolution { | ||
115 | Some(idx) | ||
116 | } else { | ||
117 | None | ||
118 | } | ||
119 | } | ||
120 | |||
121 | pub(crate) fn from_type_relative_path( | ||
122 | db: &impl HirDatabase, | ||
123 | resolver: &Resolver, | ||
124 | ty: Ty, | ||
125 | remaining_segments: &[PathSegment], | ||
126 | ) -> Ty { | ||
127 | if remaining_segments.len() == 1 { | ||
128 | // resolve unselected assoc types | ||
129 | let segment = &remaining_segments[0]; | ||
130 | Ty::select_associated_type(db, resolver, ty, segment) | ||
131 | } else if remaining_segments.len() > 1 { | ||
132 | // FIXME report error (ambiguous associated type) | ||
133 | Ty::Unknown | ||
134 | } else { | ||
135 | ty | ||
136 | } | ||
137 | } | ||
138 | |||
139 | pub(crate) fn from_partly_resolved_hir_path( | ||
140 | db: &impl HirDatabase, | ||
141 | resolver: &Resolver, | ||
142 | resolution: TypeNs, | ||
143 | resolved_segment: &PathSegment, | ||
144 | remaining_segments: &[PathSegment], | ||
145 | ) -> Ty { | ||
146 | let ty = match resolution { | ||
147 | TypeNs::TraitId(trait_) => { | ||
148 | let trait_ref = | ||
149 | TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None); | ||
150 | return if remaining_segments.len() == 1 { | ||
151 | let segment = &remaining_segments[0]; | ||
152 | let associated_ty = associated_type_by_name_including_super_traits( | ||
153 | db, | ||
154 | trait_ref.trait_, | ||
155 | &segment.name, | ||
156 | ); | ||
157 | match associated_ty { | ||
158 | Some(associated_ty) => { | ||
159 | // FIXME handle type parameters on the segment | ||
160 | Ty::Projection(ProjectionTy { | ||
161 | associated_ty, | ||
162 | parameters: trait_ref.substs, | ||
163 | }) | ||
164 | } | ||
165 | None => { | ||
166 | // FIXME: report error (associated type not found) | ||
167 | Ty::Unknown | ||
168 | } | ||
169 | } | ||
170 | } else if remaining_segments.len() > 1 { | ||
171 | // FIXME report error (ambiguous associated type) | ||
172 | Ty::Unknown | ||
173 | } else { | ||
174 | Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) | ||
175 | }; | ||
176 | } | ||
177 | TypeNs::GenericParam(idx) => { | ||
178 | // FIXME: maybe return name in resolution? | ||
179 | let name = resolved_segment.name.clone(); | ||
180 | Ty::Param { idx, name } | ||
181 | } | ||
182 | TypeNs::SelfType(impl_id) => { | ||
183 | let impl_data = db.impl_data(impl_id); | ||
184 | let resolver = impl_id.resolver(db); | ||
185 | Ty::from_hir(db, &resolver, &impl_data.target_type) | ||
186 | } | ||
187 | TypeNs::AdtSelfType(adt) => db.ty(adt.into()), | ||
188 | |||
189 | TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), | ||
190 | TypeNs::BuiltinType(it) => { | ||
191 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
192 | } | ||
193 | TypeNs::TypeAliasId(it) => { | ||
194 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
195 | } | ||
196 | // FIXME: report error | ||
197 | TypeNs::EnumVariantId(_) => return Ty::Unknown, | ||
198 | }; | ||
199 | |||
200 | Ty::from_type_relative_path(db, resolver, ty, remaining_segments) | ||
201 | } | ||
202 | |||
203 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { | ||
204 | // Resolve the path (in type namespace) | ||
205 | if let PathKind::Type(type_ref) = &path.kind { | ||
206 | let ty = Ty::from_hir(db, resolver, &type_ref); | ||
207 | let remaining_segments = &path.segments[..]; | ||
208 | return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); | ||
209 | } | ||
210 | let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) { | ||
211 | Some(it) => it, | ||
212 | None => return Ty::Unknown, | ||
213 | }; | ||
214 | let (resolved_segment, remaining_segments) = match remaining_index { | ||
215 | None => ( | ||
216 | path.segments.last().expect("resolved path has at least one element"), | ||
217 | &[] as &[PathSegment], | ||
218 | ), | ||
219 | Some(i) => (&path.segments[i - 1], &path.segments[i..]), | ||
220 | }; | ||
221 | Ty::from_partly_resolved_hir_path( | ||
222 | db, | ||
223 | resolver, | ||
224 | resolution, | ||
225 | resolved_segment, | ||
226 | remaining_segments, | ||
227 | ) | ||
228 | } | ||
229 | |||
230 | fn select_associated_type( | ||
231 | db: &impl HirDatabase, | ||
232 | resolver: &Resolver, | ||
233 | self_ty: Ty, | ||
234 | segment: &PathSegment, | ||
235 | ) -> Ty { | ||
236 | let param_idx = match self_ty { | ||
237 | Ty::Param { idx, .. } => idx, | ||
238 | _ => return Ty::Unknown, // Error: Ambiguous associated type | ||
239 | }; | ||
240 | let def = match resolver.generic_def() { | ||
241 | Some(def) => def, | ||
242 | None => return Ty::Unknown, // this can't actually happen | ||
243 | }; | ||
244 | let predicates = db.generic_predicates_for_param(def.into(), param_idx); | ||
245 | let traits_from_env = predicates.iter().filter_map(|pred| match pred { | ||
246 | GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), | ||
247 | _ => None, | ||
248 | }); | ||
249 | let traits = traits_from_env.flat_map(|t| all_super_traits(db, t)); | ||
250 | for t in traits { | ||
251 | if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) { | ||
252 | let substs = | ||
253 | Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build(); | ||
254 | // FIXME handle type parameters on the segment | ||
255 | return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); | ||
256 | } | ||
257 | } | ||
258 | Ty::Unknown | ||
259 | } | ||
260 | |||
261 | fn from_hir_path_inner( | ||
262 | db: &impl HirDatabase, | ||
263 | resolver: &Resolver, | ||
264 | segment: &PathSegment, | ||
265 | typable: TyDefId, | ||
266 | ) -> Ty { | ||
267 | let generic_def = match typable { | ||
268 | TyDefId::BuiltinType(_) => None, | ||
269 | TyDefId::AdtId(it) => Some(it.into()), | ||
270 | TyDefId::TypeAliasId(it) => Some(it.into()), | ||
271 | }; | ||
272 | let substs = substs_from_path_segment(db, resolver, segment, generic_def, false); | ||
273 | db.ty(typable).subst(&substs) | ||
274 | } | ||
275 | |||
276 | /// Collect generic arguments from a path into a `Substs`. See also | ||
277 | /// `create_substs_for_ast_path` and `def_to_ty` in rustc. | ||
278 | pub(super) fn substs_from_path( | ||
279 | db: &impl HirDatabase, | ||
280 | resolver: &Resolver, | ||
281 | path: &Path, | ||
282 | // Note that we don't call `db.value_type(resolved)` here, | ||
283 | // `ValueTyDefId` is just a convenient way to pass generics and | ||
284 | // special-case enum variants | ||
285 | resolved: ValueTyDefId, | ||
286 | ) -> Substs { | ||
287 | let last = path.segments.last().expect("path should have at least one segment"); | ||
288 | let (segment, generic_def) = match resolved { | ||
289 | ValueTyDefId::FunctionId(it) => (last, Some(it.into())), | ||
290 | ValueTyDefId::StructId(it) => (last, Some(it.into())), | ||
291 | ValueTyDefId::ConstId(it) => (last, Some(it.into())), | ||
292 | ValueTyDefId::StaticId(_) => (last, None), | ||
293 | ValueTyDefId::EnumVariantId(var) => { | ||
294 | // the generic args for an enum variant may be either specified | ||
295 | // on the segment referring to the enum, or on the segment | ||
296 | // referring to the variant. So `Option::<T>::None` and | ||
297 | // `Option::None::<T>` are both allowed (though the former is | ||
298 | // preferred). See also `def_ids_for_path_segments` in rustc. | ||
299 | let len = path.segments.len(); | ||
300 | let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() { | ||
301 | // Option::<T>::None | ||
302 | &path.segments[len - 2] | ||
303 | } else { | ||
304 | // Option::None::<T> | ||
305 | last | ||
306 | }; | ||
307 | (segment, Some(var.parent.into())) | ||
308 | } | ||
309 | }; | ||
310 | substs_from_path_segment(db, resolver, segment, generic_def, false) | ||
311 | } | ||
312 | } | ||
313 | |||
314 | pub(super) fn substs_from_path_segment( | ||
315 | db: &impl HirDatabase, | ||
316 | resolver: &Resolver, | ||
317 | segment: &PathSegment, | ||
318 | def_generic: Option<GenericDefId>, | ||
319 | add_self_param: bool, | ||
320 | ) -> Substs { | ||
321 | let mut substs = Vec::new(); | ||
322 | let def_generics = def_generic.map(|def| db.generic_params(def.into())); | ||
323 | |||
324 | let (parent_param_count, param_count) = | ||
325 | def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
326 | substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count)); | ||
327 | if add_self_param { | ||
328 | // FIXME this add_self_param argument is kind of a hack: Traits have the | ||
329 | // Self type as an implicit first type parameter, but it can't be | ||
330 | // actually provided in the type arguments | ||
331 | // (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`) | ||
332 | substs.push(Ty::Unknown); | ||
333 | } | ||
334 | if let Some(generic_args) = &segment.args_and_bindings { | ||
335 | // if args are provided, it should be all of them, but we can't rely on that | ||
336 | let self_param_correction = if add_self_param { 1 } else { 0 }; | ||
337 | let param_count = param_count - self_param_correction; | ||
338 | for arg in generic_args.args.iter().take(param_count) { | ||
339 | match arg { | ||
340 | GenericArg::Type(type_ref) => { | ||
341 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
342 | substs.push(ty); | ||
343 | } | ||
344 | } | ||
345 | } | ||
346 | } | ||
347 | // add placeholders for args that were not provided | ||
348 | let supplied_params = substs.len(); | ||
349 | for _ in supplied_params..parent_param_count + param_count { | ||
350 | substs.push(Ty::Unknown); | ||
351 | } | ||
352 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
353 | |||
354 | // handle defaults | ||
355 | if let Some(def_generic) = def_generic { | ||
356 | let default_substs = db.generic_defaults(def_generic.into()); | ||
357 | assert_eq!(substs.len(), default_substs.len()); | ||
358 | |||
359 | for (i, default_ty) in default_substs.iter().enumerate() { | ||
360 | if substs[i] == Ty::Unknown { | ||
361 | substs[i] = default_ty.clone(); | ||
362 | } | ||
363 | } | ||
364 | } | ||
365 | |||
366 | Substs(substs.into()) | ||
367 | } | ||
368 | |||
369 | impl TraitRef { | ||
370 | pub(crate) fn from_path( | ||
371 | db: &impl HirDatabase, | ||
372 | resolver: &Resolver, | ||
373 | path: &Path, | ||
374 | explicit_self_ty: Option<Ty>, | ||
375 | ) -> Option<Self> { | ||
376 | let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? { | ||
377 | TypeNs::TraitId(tr) => tr, | ||
378 | _ => return None, | ||
379 | }; | ||
380 | let segment = path.segments.last().expect("path should have at least one segment"); | ||
381 | Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) | ||
382 | } | ||
383 | |||
384 | pub(super) fn from_resolved_path( | ||
385 | db: &impl HirDatabase, | ||
386 | resolver: &Resolver, | ||
387 | resolved: TraitId, | ||
388 | segment: &PathSegment, | ||
389 | explicit_self_ty: Option<Ty>, | ||
390 | ) -> Self { | ||
391 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | ||
392 | if let Some(self_ty) = explicit_self_ty { | ||
393 | make_mut_slice(&mut substs.0)[0] = self_ty; | ||
394 | } | ||
395 | TraitRef { trait_: resolved, substs } | ||
396 | } | ||
397 | |||
398 | pub(crate) fn from_hir( | ||
399 | db: &impl HirDatabase, | ||
400 | resolver: &Resolver, | ||
401 | type_ref: &TypeRef, | ||
402 | explicit_self_ty: Option<Ty>, | ||
403 | ) -> Option<Self> { | ||
404 | let path = match type_ref { | ||
405 | TypeRef::Path(path) => path, | ||
406 | _ => return None, | ||
407 | }; | ||
408 | TraitRef::from_path(db, resolver, path, explicit_self_ty) | ||
409 | } | ||
410 | |||
411 | fn substs_from_path( | ||
412 | db: &impl HirDatabase, | ||
413 | resolver: &Resolver, | ||
414 | segment: &PathSegment, | ||
415 | resolved: TraitId, | ||
416 | ) -> Substs { | ||
417 | let has_self_param = | ||
418 | segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); | ||
419 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) | ||
420 | } | ||
421 | |||
422 | pub fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef { | ||
423 | let substs = Substs::identity(&db.generic_params(trait_.into())); | ||
424 | TraitRef { trait_, substs } | ||
425 | } | ||
426 | |||
427 | pub(crate) fn from_type_bound( | ||
428 | db: &impl HirDatabase, | ||
429 | resolver: &Resolver, | ||
430 | bound: &TypeBound, | ||
431 | self_ty: Ty, | ||
432 | ) -> Option<TraitRef> { | ||
433 | match bound { | ||
434 | TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), | ||
435 | TypeBound::Error => None, | ||
436 | } | ||
437 | } | ||
438 | } | ||
439 | |||
440 | impl GenericPredicate { | ||
441 | pub(crate) fn from_where_predicate<'a>( | ||
442 | db: &'a impl HirDatabase, | ||
443 | resolver: &'a Resolver, | ||
444 | where_predicate: &'a WherePredicate, | ||
445 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
446 | let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); | ||
447 | GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) | ||
448 | } | ||
449 | |||
450 | pub(crate) fn from_type_bound<'a>( | ||
451 | db: &'a impl HirDatabase, | ||
452 | resolver: &'a Resolver, | ||
453 | bound: &'a TypeBound, | ||
454 | self_ty: Ty, | ||
455 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
456 | let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); | ||
457 | iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) | ||
458 | .chain( | ||
459 | trait_ref.into_iter().flat_map(move |tr| { | ||
460 | assoc_type_bindings_from_type_bound(db, resolver, bound, tr) | ||
461 | }), | ||
462 | ) | ||
463 | } | ||
464 | } | ||
465 | |||
466 | fn assoc_type_bindings_from_type_bound<'a>( | ||
467 | db: &'a impl HirDatabase, | ||
468 | resolver: &'a Resolver, | ||
469 | bound: &'a TypeBound, | ||
470 | trait_ref: TraitRef, | ||
471 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
472 | let last_segment = match bound { | ||
473 | TypeBound::Path(path) => path.segments.last(), | ||
474 | TypeBound::Error => None, | ||
475 | }; | ||
476 | last_segment | ||
477 | .into_iter() | ||
478 | .flat_map(|segment| segment.args_and_bindings.iter()) | ||
479 | .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) | ||
480 | .map(move |(name, type_ref)| { | ||
481 | let associated_ty = | ||
482 | associated_type_by_name_including_super_traits(db, trait_ref.trait_, &name); | ||
483 | let associated_ty = match associated_ty { | ||
484 | None => return GenericPredicate::Error, | ||
485 | Some(t) => t, | ||
486 | }; | ||
487 | let projection_ty = | ||
488 | ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; | ||
489 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
490 | let projection_predicate = ProjectionPredicate { projection_ty, ty }; | ||
491 | GenericPredicate::Projection(projection_predicate) | ||
492 | }) | ||
493 | } | ||
494 | |||
495 | /// Build the signature of a callable item (function, struct or enum variant). | ||
496 | pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { | ||
497 | match def { | ||
498 | CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), | ||
499 | CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), | ||
500 | CallableDef::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e), | ||
501 | } | ||
502 | } | ||
503 | |||
504 | /// Build the type of all specific fields of a struct or enum variant. | ||
505 | pub(crate) fn field_types_query( | ||
506 | db: &impl HirDatabase, | ||
507 | variant_id: VariantId, | ||
508 | ) -> Arc<ArenaMap<LocalStructFieldId, Ty>> { | ||
509 | let var_data = variant_data(db, variant_id); | ||
510 | let resolver = match variant_id { | ||
511 | VariantId::StructId(it) => it.resolver(db), | ||
512 | VariantId::UnionId(it) => it.resolver(db), | ||
513 | VariantId::EnumVariantId(it) => it.parent.resolver(db), | ||
514 | }; | ||
515 | let mut res = ArenaMap::default(); | ||
516 | for (field_id, field_data) in var_data.fields().iter() { | ||
517 | res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) | ||
518 | } | ||
519 | Arc::new(res) | ||
520 | } | ||
521 | |||
522 | /// This query exists only to be used when resolving short-hand associated types | ||
523 | /// like `T::Item`. | ||
524 | /// | ||
525 | /// See the analogous query in rustc and its comment: | ||
526 | /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46 | ||
527 | /// This is a query mostly to handle cycles somewhat gracefully; e.g. the | ||
528 | /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but | ||
529 | /// these are fine: `T: Foo<U::Item>, U: Foo<()>`. | ||
530 | pub(crate) fn generic_predicates_for_param_query( | ||
531 | db: &impl HirDatabase, | ||
532 | def: GenericDefId, | ||
533 | param_idx: u32, | ||
534 | ) -> Arc<[GenericPredicate]> { | ||
535 | let resolver = def.resolver(db); | ||
536 | resolver | ||
537 | .where_predicates_in_scope() | ||
538 | // we have to filter out all other predicates *first*, before attempting to lower them | ||
539 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) | ||
540 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
541 | .collect() | ||
542 | } | ||
543 | |||
544 | impl TraitEnvironment { | ||
545 | pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { | ||
546 | let predicates = resolver | ||
547 | .where_predicates_in_scope() | ||
548 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
549 | .collect::<Vec<_>>(); | ||
550 | |||
551 | Arc::new(TraitEnvironment { predicates }) | ||
552 | } | ||
553 | } | ||
554 | |||
555 | /// Resolve the where clause(s) of an item with generics. | ||
556 | pub(crate) fn generic_predicates_query( | ||
557 | db: &impl HirDatabase, | ||
558 | def: GenericDefId, | ||
559 | ) -> Arc<[GenericPredicate]> { | ||
560 | let resolver = def.resolver(db); | ||
561 | resolver | ||
562 | .where_predicates_in_scope() | ||
563 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
564 | .collect() | ||
565 | } | ||
566 | |||
567 | /// Resolve the default type params from generics | ||
568 | pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs { | ||
569 | let resolver = def.resolver(db); | ||
570 | let generic_params = db.generic_params(def.into()); | ||
571 | |||
572 | let defaults = generic_params | ||
573 | .params_including_parent() | ||
574 | .into_iter() | ||
575 | .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) | ||
576 | .collect(); | ||
577 | |||
578 | Substs(defaults) | ||
579 | } | ||
580 | |||
581 | fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> FnSig { | ||
582 | let data = db.function_data(def); | ||
583 | let resolver = def.resolver(db); | ||
584 | let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>(); | ||
585 | let ret = Ty::from_hir(db, &resolver, &data.ret_type); | ||
586 | FnSig::from_params_and_return(params, ret) | ||
587 | } | ||
588 | |||
589 | /// Build the declared type of a function. This should not need to look at the | ||
590 | /// function body. | ||
591 | fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Ty { | ||
592 | let generics = db.generic_params(def.into()); | ||
593 | let substs = Substs::identity(&generics); | ||
594 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
595 | } | ||
596 | |||
597 | /// Build the declared type of a const. | ||
598 | fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Ty { | ||
599 | let data = db.const_data(def); | ||
600 | let resolver = def.resolver(db); | ||
601 | |||
602 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
603 | } | ||
604 | |||
605 | /// Build the declared type of a static. | ||
606 | fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Ty { | ||
607 | let data = db.static_data(def); | ||
608 | let resolver = def.resolver(db); | ||
609 | |||
610 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
611 | } | ||
612 | |||
613 | /// Build the declared type of a static. | ||
614 | fn type_for_builtin(def: BuiltinType) -> Ty { | ||
615 | Ty::simple(match def { | ||
616 | BuiltinType::Char => TypeCtor::Char, | ||
617 | BuiltinType::Bool => TypeCtor::Bool, | ||
618 | BuiltinType::Str => TypeCtor::Str, | ||
619 | BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()), | ||
620 | BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()), | ||
621 | }) | ||
622 | } | ||
623 | |||
624 | fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> FnSig { | ||
625 | let struct_data = db.struct_data(def.into()); | ||
626 | let fields = struct_data.variant_data.fields(); | ||
627 | let resolver = def.resolver(db); | ||
628 | let params = fields | ||
629 | .iter() | ||
630 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
631 | .collect::<Vec<_>>(); | ||
632 | let ret = type_for_adt(db, def.into()); | ||
633 | FnSig::from_params_and_return(params, ret) | ||
634 | } | ||
635 | |||
636 | /// Build the type of a tuple struct constructor. | ||
637 | fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Ty { | ||
638 | let struct_data = db.struct_data(def.into()); | ||
639 | if struct_data.variant_data.is_unit() { | ||
640 | return type_for_adt(db, def.into()); // Unit struct | ||
641 | } | ||
642 | let generics = db.generic_params(def.into()); | ||
643 | let substs = Substs::identity(&generics); | ||
644 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
645 | } | ||
646 | |||
647 | fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> FnSig { | ||
648 | let enum_data = db.enum_data(def.parent); | ||
649 | let var_data = &enum_data.variants[def.local_id]; | ||
650 | let fields = var_data.variant_data.fields(); | ||
651 | let resolver = def.parent.resolver(db); | ||
652 | let params = fields | ||
653 | .iter() | ||
654 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
655 | .collect::<Vec<_>>(); | ||
656 | let generics = db.generic_params(def.parent.into()); | ||
657 | let substs = Substs::identity(&generics); | ||
658 | let ret = type_for_adt(db, def.parent.into()).subst(&substs); | ||
659 | FnSig::from_params_and_return(params, ret) | ||
660 | } | ||
661 | |||
662 | /// Build the type of a tuple enum variant constructor. | ||
663 | fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Ty { | ||
664 | let enum_data = db.enum_data(def.parent); | ||
665 | let var_data = &enum_data.variants[def.local_id].variant_data; | ||
666 | if var_data.is_unit() { | ||
667 | return type_for_adt(db, def.parent.into()); // Unit variant | ||
668 | } | ||
669 | let generics = db.generic_params(def.parent.into()); | ||
670 | let substs = Substs::identity(&generics); | ||
671 | Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs) | ||
672 | } | ||
673 | |||
674 | fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Ty { | ||
675 | let generics = db.generic_params(adt.into()); | ||
676 | Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) | ||
677 | } | ||
678 | |||
679 | fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Ty { | ||
680 | let generics = db.generic_params(t.into()); | ||
681 | let resolver = t.resolver(db); | ||
682 | let type_ref = &db.type_alias_data(t).type_ref; | ||
683 | let substs = Substs::identity(&generics); | ||
684 | let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error)); | ||
685 | inner.subst(&substs) | ||
686 | } | ||
687 | |||
688 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
689 | pub enum CallableDef { | ||
690 | FunctionId(FunctionId), | ||
691 | StructId(StructId), | ||
692 | EnumVariantId(EnumVariantId), | ||
693 | } | ||
694 | impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId); | ||
695 | |||
696 | impl CallableDef { | ||
697 | pub fn krate(self, db: &impl HirDatabase) -> CrateId { | ||
698 | match self { | ||
699 | CallableDef::FunctionId(f) => f.lookup(db).module(db).krate, | ||
700 | CallableDef::StructId(s) => s.module(db).krate, | ||
701 | CallableDef::EnumVariantId(e) => e.parent.module(db).krate, | ||
702 | } | ||
703 | } | ||
704 | } | ||
705 | |||
706 | impl From<CallableDef> for GenericDefId { | ||
707 | fn from(def: CallableDef) -> GenericDefId { | ||
708 | match def { | ||
709 | CallableDef::FunctionId(f) => f.into(), | ||
710 | CallableDef::StructId(s) => s.into(), | ||
711 | CallableDef::EnumVariantId(e) => e.into(), | ||
712 | } | ||
713 | } | ||
714 | } | ||
715 | |||
716 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
717 | pub enum TyDefId { | ||
718 | BuiltinType(BuiltinType), | ||
719 | AdtId(AdtId), | ||
720 | TypeAliasId(TypeAliasId), | ||
721 | } | ||
722 | impl_froms!(TyDefId: BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId); | ||
723 | |||
724 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
725 | pub enum ValueTyDefId { | ||
726 | FunctionId(FunctionId), | ||
727 | StructId(StructId), | ||
728 | EnumVariantId(EnumVariantId), | ||
729 | ConstId(ConstId), | ||
730 | StaticId(StaticId), | ||
731 | } | ||
732 | impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId); | ||
733 | |||
734 | /// Build the declared type of an item. This depends on the namespace; e.g. for | ||
735 | /// `struct Foo(usize)`, we have two types: The type of the struct itself, and | ||
736 | /// the constructor function `(usize) -> Foo` which lives in the values | ||
737 | /// namespace. | ||
738 | pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Ty { | ||
739 | match def { | ||
740 | TyDefId::BuiltinType(it) => type_for_builtin(it), | ||
741 | TyDefId::AdtId(it) => type_for_adt(db, it), | ||
742 | TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), | ||
743 | } | ||
744 | } | ||
745 | pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty { | ||
746 | match def { | ||
747 | ValueTyDefId::FunctionId(it) => type_for_fn(db, it), | ||
748 | ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), | ||
749 | ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it), | ||
750 | ValueTyDefId::ConstId(it) => type_for_const(db, it), | ||
751 | ValueTyDefId::StaticId(it) => type_for_static(db, it), | ||
752 | } | ||
753 | } | ||
diff --git a/crates/ra_hir_ty/src/marks.rs b/crates/ra_hir_ty/src/marks.rs new file mode 100644 index 000000000..0f754eb9c --- /dev/null +++ b/crates/ra_hir_ty/src/marks.rs | |||
@@ -0,0 +1,9 @@ | |||
1 | //! See test_utils/src/marks.rs | ||
2 | |||
3 | test_utils::marks!( | ||
4 | type_var_cycles_resolve_completely | ||
5 | type_var_cycles_resolve_as_possible | ||
6 | type_var_resolves_to_int_var | ||
7 | match_ergonomics_ref | ||
8 | coerce_merge_fail_fallback | ||
9 | ); | ||
diff --git a/crates/ra_hir_ty/src/method_resolution.rs b/crates/ra_hir_ty/src/method_resolution.rs new file mode 100644 index 000000000..53c541eb8 --- /dev/null +++ b/crates/ra_hir_ty/src/method_resolution.rs | |||
@@ -0,0 +1,363 @@ | |||
1 | //! This module is concerned with finding methods that a given type provides. | ||
2 | //! For details about how this works in rustc, see the method lookup page in the | ||
3 | //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html) | ||
4 | //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs. | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use arrayvec::ArrayVec; | ||
8 | use hir_def::{ | ||
9 | lang_item::LangItemTarget, resolver::HasResolver, resolver::Resolver, type_ref::Mutability, | ||
10 | AssocItemId, AstItemDef, FunctionId, HasModule, ImplId, TraitId, | ||
11 | }; | ||
12 | use hir_expand::name::Name; | ||
13 | use ra_db::CrateId; | ||
14 | use ra_prof::profile; | ||
15 | use rustc_hash::FxHashMap; | ||
16 | |||
17 | use crate::{ | ||
18 | db::HirDatabase, | ||
19 | primitive::{FloatBitness, Uncertain}, | ||
20 | utils::all_super_traits, | ||
21 | Ty, TypeCtor, | ||
22 | }; | ||
23 | |||
24 | use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef}; | ||
25 | |||
26 | /// This is used as a key for indexing impls. | ||
27 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
28 | pub enum TyFingerprint { | ||
29 | Apply(TypeCtor), | ||
30 | } | ||
31 | |||
32 | impl TyFingerprint { | ||
33 | /// Creates a TyFingerprint for looking up an impl. Only certain types can | ||
34 | /// have impls: if we have some `struct S`, we can have an `impl S`, but not | ||
35 | /// `impl &S`. Hence, this will return `None` for reference types and such. | ||
36 | fn for_impl(ty: &Ty) -> Option<TyFingerprint> { | ||
37 | match ty { | ||
38 | Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)), | ||
39 | _ => None, | ||
40 | } | ||
41 | } | ||
42 | } | ||
43 | |||
44 | #[derive(Debug, PartialEq, Eq)] | ||
45 | pub struct CrateImplBlocks { | ||
46 | impls: FxHashMap<TyFingerprint, Vec<ImplId>>, | ||
47 | impls_by_trait: FxHashMap<TraitId, Vec<ImplId>>, | ||
48 | } | ||
49 | |||
50 | impl CrateImplBlocks { | ||
51 | pub(crate) fn impls_in_crate_query( | ||
52 | db: &impl HirDatabase, | ||
53 | krate: CrateId, | ||
54 | ) -> Arc<CrateImplBlocks> { | ||
55 | let _p = profile("impls_in_crate_query"); | ||
56 | let mut res = | ||
57 | CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; | ||
58 | |||
59 | let crate_def_map = db.crate_def_map(krate); | ||
60 | for (_module_id, module_data) in crate_def_map.modules.iter() { | ||
61 | for &impl_id in module_data.impls.iter() { | ||
62 | let impl_data = db.impl_data(impl_id); | ||
63 | let resolver = impl_id.resolver(db); | ||
64 | |||
65 | let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); | ||
66 | |||
67 | match &impl_data.target_trait { | ||
68 | Some(trait_ref) => { | ||
69 | if let Some(tr) = | ||
70 | TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty)) | ||
71 | { | ||
72 | res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); | ||
73 | } | ||
74 | } | ||
75 | None => { | ||
76 | if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { | ||
77 | res.impls.entry(target_ty_fp).or_default().push(impl_id); | ||
78 | } | ||
79 | } | ||
80 | } | ||
81 | } | ||
82 | } | ||
83 | |||
84 | Arc::new(res) | ||
85 | } | ||
86 | pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator<Item = ImplId> + '_ { | ||
87 | let fingerprint = TyFingerprint::for_impl(ty); | ||
88 | fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() | ||
89 | } | ||