aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_ty/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_ty/src')
-rw-r--r--crates/ra_hir_ty/src/autoderef.rs108
-rw-r--r--crates/ra_hir_ty/src/db.rs119
-rw-r--r--crates/ra_hir_ty/src/diagnostics.rs91
-rw-r--r--crates/ra_hir_ty/src/display.rs93
-rw-r--r--crates/ra_hir_ty/src/expr.rs151
-rw-r--r--crates/ra_hir_ty/src/infer.rs723
-rw-r--r--crates/ra_hir_ty/src/infer/coerce.rs344
-rw-r--r--crates/ra_hir_ty/src/infer/expr.rs686
-rw-r--r--crates/ra_hir_ty/src/infer/pat.rs186
-rw-r--r--crates/ra_hir_ty/src/infer/path.rs268
-rw-r--r--crates/ra_hir_ty/src/infer/unify.rs162
-rw-r--r--crates/ra_hir_ty/src/lib.rs1138
-rw-r--r--crates/ra_hir_ty/src/lower.rs759
-rw-r--r--crates/ra_hir_ty/src/marks.rs9
-rw-r--r--crates/ra_hir_ty/src/method_resolution.rs353
-rw-r--r--crates/ra_hir_ty/src/op.rs50
-rw-r--r--crates/ra_hir_ty/src/primitive.rs193
-rw-r--r--crates/ra_hir_ty/src/test_db.rs146
-rw-r--r--crates/ra_hir_ty/src/tests.rs4958
-rw-r--r--crates/ra_hir_ty/src/tests/coercion.rs369
-rw-r--r--crates/ra_hir_ty/src/tests/never_type.rs246
-rw-r--r--crates/ra_hir_ty/src/traits.rs328
-rw-r--r--crates/ra_hir_ty/src/traits/chalk.rs900
-rw-r--r--crates/ra_hir_ty/src/utils.rs84
24 files changed, 12464 insertions, 0 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
6use std::iter::successors;
7
8use hir_def::lang_item::LangItemTarget;
9use hir_expand::name;
10use log::{info, warn};
11use ra_db::CrateId;
12
13use crate::db::HirDatabase;
14
15use super::{
16 traits::{InEnvironment, Solution},
17 Canonical, Substs, Ty, TypeWalk,
18};
19
20const AUTODEREF_RECURSION_LIMIT: usize = 10;
21
22pub 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
34pub(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
46fn 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..9ce154593
--- /dev/null
+++ b/crates/ra_hir_ty/src/db.rs
@@ -0,0 +1,119 @@
1//! FIXME: write short doc here
2
3use std::sync::Arc;
4
5use hir_def::{
6 db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId,
7};
8use ra_arena::map::ArenaMap;
9use ra_db::{salsa, CrateId};
10
11use crate::{
12 method_resolution::CrateImplBlocks,
13 traits::{AssocTyValue, Impl},
14 CallableDef, FnSig, GenericPredicate, ImplTy, InferenceResult, Substs, Ty, TyDefId, TypeCtor,
15 ValueTyDefId,
16};
17
18#[salsa::query_group(HirDatabaseStorage)]
19#[salsa::requires(salsa::Database)]
20pub 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::impl_ty_query)]
31 fn impl_ty(&self, def: ImplId) -> ImplTy;
32
33 #[salsa::invoke(crate::lower::field_types_query)]
34 fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>;
35
36 #[salsa::invoke(crate::callable_item_sig)]
37 fn callable_item_signature(&self, def: CallableDef) -> FnSig;
38
39 #[salsa::invoke(crate::lower::generic_predicates_for_param_query)]
40 fn generic_predicates_for_param(
41 &self,
42 def: GenericDefId,
43 param_idx: u32,
44 ) -> Arc<[GenericPredicate]>;
45
46 #[salsa::invoke(crate::lower::generic_predicates_query)]
47 fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>;
48
49 #[salsa::invoke(crate::lower::generic_defaults_query)]
50 fn generic_defaults(&self, def: GenericDefId) -> Substs;
51
52 #[salsa::invoke(crate::method_resolution::CrateImplBlocks::impls_in_crate_query)]
53 fn impls_in_crate(&self, krate: CrateId) -> Arc<CrateImplBlocks>;
54
55 #[salsa::invoke(crate::traits::impls_for_trait_query)]
56 fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>;
57
58 /// This provides the Chalk trait solver instance. Because Chalk always
59 /// works from a specific crate, this query is keyed on the crate; and
60 /// because Chalk does its own internal caching, the solver is wrapped in a
61 /// Mutex and the query does an untracked read internally, to make sure the
62 /// cached state is thrown away when input facts change.
63 #[salsa::invoke(crate::traits::trait_solver_query)]
64 fn trait_solver(&self, krate: CrateId) -> crate::traits::TraitSolver;
65
66 // Interned IDs for Chalk integration
67 #[salsa::interned]
68 fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
69 #[salsa::interned]
70 fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
71 #[salsa::interned]
72 fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
73
74 #[salsa::invoke(crate::traits::chalk::associated_ty_data_query)]
75 fn associated_ty_data(
76 &self,
77 id: chalk_ir::TypeId,
78 ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>;
79
80 #[salsa::invoke(crate::traits::chalk::trait_datum_query)]
81 fn trait_datum(
82 &self,
83 krate: CrateId,
84 trait_id: chalk_ir::TraitId,
85 ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>;
86
87 #[salsa::invoke(crate::traits::chalk::struct_datum_query)]
88 fn struct_datum(
89 &self,
90 krate: CrateId,
91 struct_id: chalk_ir::StructId,
92 ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>;
93
94 #[salsa::invoke(crate::traits::chalk::impl_datum_query)]
95 fn impl_datum(
96 &self,
97 krate: CrateId,
98 impl_id: chalk_ir::ImplId,
99 ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>;
100
101 #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)]
102 fn associated_ty_value(
103 &self,
104 krate: CrateId,
105 id: chalk_rust_ir::AssociatedTyValueId,
106 ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>;
107
108 #[salsa::invoke(crate::traits::trait_solve_query)]
109 fn trait_solve(
110 &self,
111 krate: CrateId,
112 goal: crate::Canonical<crate::InEnvironment<crate::Obligation>>,
113 ) -> Option<crate::traits::Solution>;
114}
115
116#[test]
117fn hir_database_is_object_safe() {
118 fn _assert_object_safe(_: &dyn HirDatabase) {}
119}
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
3use std::any::Any;
4
5use hir_expand::{db::AstDatabase, name::Name, HirFileId, Source};
6use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
7
8pub use hir_def::diagnostics::UnresolvedModule;
9pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink};
10
11#[derive(Debug)]
12pub struct NoSuchField {
13 pub file: HirFileId,
14 pub field: AstPtr<ast::RecordField>,
15}
16
17impl 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)]
32pub struct MissingFields {
33 pub file: HirFileId,
34 pub field_list: AstPtr<ast::RecordFieldList>,
35 pub missed_fields: Vec<Name>,
36}
37
38impl 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
55impl 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)]
66pub struct MissingOkInTailExpr {
67 pub file: HirFileId,
68 pub expr: AstPtr<ast::Expr>,
69}
70
71impl 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
83impl 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
3use std::fmt;
4
5use crate::db::HirDatabase;
6
7pub 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
15pub 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
37impl<'a, 'b, DB> HirFormatter<'a, 'b, DB>
38where
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
77pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>);
78
79impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T>
80where
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
3use std::sync::Arc;
4
5use hir_def::{
6 path::{known, Path},
7 resolver::HasResolver,
8 AdtId, FunctionId,
9};
10use hir_expand::{diagnostics::DiagnosticSink, name::Name};
11use ra_syntax::ast;
12use ra_syntax::AstPtr;
13use rustc_hash::FxHashSet;
14
15use crate::{
16 db::HirDatabase,
17 diagnostics::{MissingFields, MissingOkInTailExpr},
18 ApplicationTy, InferenceResult, Ty, TypeCtor,
19};
20
21pub 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
32pub struct ExprValidator<'a, 'b: 'a> {
33 func: FunctionId,
34 infer: Arc<InferenceResult>,
35 sink: &'a mut DiagnosticSink<'b>,
36}
37
38impl<'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 && &params[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
16use std::borrow::Cow;
17use std::mem;
18use std::ops::Index;
19use std::sync::Arc;
20
21use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
22use rustc_hash::FxHashMap;
23
24use 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};
33use hir_expand::{diagnostics::DiagnosticSink, name};
34use ra_arena::map::ArenaMap;
35use ra_prof::profile;
36use test_utils::tested_by;
37
38use super::{
39 primitive::{FloatTy, IntTy},
40 traits::{Guidance, Obligation, ProjectionPredicate, Solution},
41 ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor,
42 TypeWalk, Uncertain,
43};
44use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic};
45
46macro_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
55mod unify;
56mod path;
57mod expr;
58mod pat;
59mod coerce;
60
61/// The entry point of type inference.
62pub 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)]
79enum ExprOrPatId {
80 ExprId(ExprId),
81 PatId(PatId),
82}
83
84impl_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)]
89enum BindingMode {
90 Move,
91 Ref(Mutability),
92}
93
94impl 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
104impl 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)]
112pub 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)]
119pub 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
136impl 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
171impl 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
179impl 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)]
189struct 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
208impl<'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)]
584pub struct TypeVarId(pub(super) u32);
585
586impl 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)]
605pub enum TypeVarValue {
606 Known(Ty),
607 Unknown,
608}
609
610impl TypeVarValue {
611 fn known(&self) -> Option<&Ty> {
612 match self {
613 TypeVarValue::Known(ty) => Some(ty),
614 TypeVarValue::Unknown => None,
615 }
616 }
617}
618
619impl 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)]
645pub enum InferTy {
646 TypeVar(TypeVarId),
647 IntVar(TypeVarId),
648 FloatVar(TypeVarId),
649 MaybeNeverTypeVar(TypeVarId),
650}
651
652impl 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)]
675struct 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
682impl 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
695mod 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..719a0f395
--- /dev/null
+++ b/crates/ra_hir_ty/src/infer/coerce.rs
@@ -0,0 +1,344 @@
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
7use hir_def::{lang_item::LangItemTarget, resolver::Resolver, type_ref::Mutability, AdtId};
8use rustc_hash::FxHashMap;
9use test_utils::tested_by;
10
11use crate::{autoderef, db::HirDatabase, ImplTy, Substs, Ty, TypeCtor, TypeWalk};
12
13use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue};
14
15impl<'a, D: HirDatabase> InferenceContext<'a, D> {
16 /// Unify two types, but may coerce the first one to the second one
17 /// using "implicit coercion rules" if needed.
18 pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
19 let from_ty = self.resolve_ty_shallow(from_ty).into_owned();
20 let to_ty = self.resolve_ty_shallow(to_ty);
21 self.coerce_inner(from_ty, &to_ty)
22 }
23
24 /// Merge two types from different branches, with possible implicit coerce.
25 ///
26 /// Note that it is only possible that one type are coerced to another.
27 /// Coercing both types to another least upper bound type is not possible in rustc,
28 /// which will simply result in "incompatible types" error.
29 pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty {
30 if self.coerce(ty1, ty2) {
31 ty2.clone()
32 } else if self.coerce(ty2, ty1) {
33 ty1.clone()
34 } else {
35 tested_by!(coerce_merge_fail_fallback);
36 // For incompatible types, we use the latter one as result
37 // to be better recovery for `if` without `else`.
38 ty2.clone()
39 }
40 }
41
42 pub(super) fn init_coerce_unsized_map(
43 db: &'a D,
44 resolver: &Resolver,
45 ) -> FxHashMap<(TypeCtor, TypeCtor), usize> {
46 let krate = resolver.krate().unwrap();
47 let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) {
48 Some(LangItemTarget::TraitId(trait_)) => {
49 db.impls_for_trait(krate.into(), trait_.into())
50 }
51 _ => return FxHashMap::default(),
52 };
53
54 impls
55 .iter()
56 .filter_map(|&impl_id| {
57 let trait_ref = match db.impl_ty(impl_id) {
58 ImplTy::TraitRef(it) => it,
59 ImplTy::Inherent(_) => return None,
60 };
61
62 // `CoerseUnsized` has one generic parameter for the target type.
63 let cur_from_ty = trait_ref.substs.0.get(0)?;
64 let cur_to_ty = trait_ref.substs.0.get(1)?;
65
66 match (&cur_from_ty, cur_to_ty) {
67 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => {
68 // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type.
69 // This works for smart-pointer-like coercion, which covers all impls from std.
70 st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| {
71 match (ty1, ty2) {
72 (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. })
73 if p1 != p2 =>
74 {
75 Some(((*ctor1, *ctor2), i))
76 }
77 _ => None,
78 }
79 })
80 }
81 _ => None,
82 }
83 })
84 .collect()
85 }
86
87 fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool {
88 match (&from_ty, to_ty) {
89 // Never type will make type variable to fallback to Never Type instead of Unknown.
90 (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => {
91 let var = self.new_maybe_never_type_var();
92 self.var_unification_table.union_value(*tv, TypeVarValue::Known(var));
93 return true;
94 }
95 (ty_app!(TypeCtor::Never), _) => return true,
96
97 // Trivial cases, this should go after `never` check to
98 // avoid infer result type to be never
99 _ => {
100 if self.unify_inner_trivial(&from_ty, &to_ty) {
101 return true;
102 }
103 }
104 }
105
106 // Pointer weakening and function to pointer
107 match (&mut from_ty, to_ty) {
108 // `*mut T`, `&mut T, `&T`` -> `*const T`
109 // `&mut T` -> `&T`
110 // `&mut T` -> `*mut T`
111 (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
112 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared)))
113 | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared)))
114 | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => {
115 *c1 = *c2;
116 }
117
118 // Illegal mutablity conversion
119 (
120 ty_app!(TypeCtor::RawPtr(Mutability::Shared)),
121 ty_app!(TypeCtor::RawPtr(Mutability::Mut)),
122 )
123 | (
124 ty_app!(TypeCtor::Ref(Mutability::Shared)),
125 ty_app!(TypeCtor::Ref(Mutability::Mut)),
126 ) => return false,
127
128 // `{function_type}` -> `fn()`
129 (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => {
130 match from_ty.callable_sig(self.db) {
131 None => return false,
132 Some(sig) => {
133 let num_args = sig.params_and_return.len() as u16 - 1;
134 from_ty =
135 Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return));
136 }
137 }
138 }
139
140 _ => {}
141 }
142
143 if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) {
144 return ret;
145 }
146
147 // Auto Deref if cannot coerce
148 match (&from_ty, to_ty) {
149 // FIXME: DerefMut
150 (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => {
151 self.unify_autoderef_behind_ref(&st1[0], &st2[0])
152 }
153
154 // Otherwise, normal unify
155 _ => self.unify(&from_ty, to_ty),
156 }
157 }
158
159 /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
160 ///
161 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html
162 fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> {
163 let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) {
164 (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2),
165 _ => return None,
166 };
167
168 let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?;
169
170 // Check `Unsize` first
171 match self.check_unsize_and_coerce(
172 st1.0.get(coerce_generic_index)?,
173 st2.0.get(coerce_generic_index)?,
174 0,
175 ) {
176 Some(true) => {}
177 ret => return ret,
178 }
179
180 let ret = st1
181 .iter()
182 .zip(st2.iter())
183 .enumerate()
184 .filter(|&(idx, _)| idx != coerce_generic_index)
185 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
186
187 Some(ret)
188 }
189
190 /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds.
191 ///
192 /// It should not be directly called. It is only used by `try_coerce_unsized`.
193 ///
194 /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html
195 fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> {
196 if depth > 1000 {
197 panic!("Infinite recursion in coercion");
198 }
199
200 match (&from_ty, &to_ty) {
201 // `[T; N]` -> `[T]`
202 (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => {
203 Some(self.unify(&st1[0], &st2[0]))
204 }
205
206 // `T` -> `dyn Trait` when `T: Trait`
207 (_, Ty::Dyn(_)) => {
208 // FIXME: Check predicates
209 Some(true)
210 }
211
212 // `(..., T)` -> `(..., U)` when `T: Unsize<U>`
213 (
214 ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1),
215 ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2),
216 ) => {
217 if len1 != len2 || *len1 == 0 {
218 return None;
219 }
220
221 match self.check_unsize_and_coerce(
222 st1.last().unwrap(),
223 st2.last().unwrap(),
224 depth + 1,
225 ) {
226 Some(true) => {}
227 ret => return ret,
228 }
229
230 let ret = st1[..st1.len() - 1]
231 .iter()
232 .zip(&st2[..st2.len() - 1])
233 .all(|(ty1, ty2)| self.unify(ty1, ty2));
234
235 Some(ret)
236 }
237
238 // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if:
239 // - T: Unsize<U>
240 // - Foo is a struct
241 // - Only the last field of Foo has a type involving T
242 // - T is not part of the type of any other fields
243 // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T>
244 (
245 ty_app!(TypeCtor::Adt(AdtId::StructId(struct1)), st1),
246 ty_app!(TypeCtor::Adt(AdtId::StructId(struct2)), st2),
247 ) if struct1 == struct2 => {
248 let field_tys = self.db.field_types((*struct1).into());
249 let struct_data = self.db.struct_data(*struct1);
250
251 let mut fields = struct_data.variant_data.fields().iter();
252 let (last_field_id, _data) = fields.next_back()?;
253
254 // Get the generic parameter involved in the last field.
255 let unsize_generic_index = {
256 let mut index = None;
257 let mut multiple_param = false;
258 field_tys[last_field_id].walk(&mut |ty| match ty {
259 &Ty::Param { idx, .. } => {
260 if index.is_none() {
261 index = Some(idx);
262 } else if Some(idx) != index {
263 multiple_param = true;
264 }
265 }
266 _ => {}
267 });
268
269 if multiple_param {
270 return None;
271 }
272 index?
273 };
274
275 // Check other fields do not involve it.
276 let mut multiple_used = false;
277 fields.for_each(|(field_id, _data)| {
278 field_tys[field_id].walk(&mut |ty| match ty {
279 &Ty::Param { idx, .. } if idx == unsize_generic_index => {
280 multiple_used = true
281 }
282 _ => {}
283 })
284 });
285 if multiple_used {
286 return None;
287 }
288
289 let unsize_generic_index = unsize_generic_index as usize;
290
291 // Check `Unsize` first
292 match self.check_unsize_and_coerce(
293 st1.get(unsize_generic_index)?,
294 st2.get(unsize_generic_index)?,
295 depth + 1,
296 ) {
297 Some(true) => {}
298 ret => return ret,
299 }
300
301 // Then unify other parameters
302 let ret = st1
303 .iter()
304 .zip(st2.iter())
305 .enumerate()
306 .filter(|&(idx, _)| idx != unsize_generic_index)
307 .all(|(_, (ty1, ty2))| self.unify(ty1, ty2));
308
309 Some(ret)
310 }
311
312 _ => None,
313 }
314 }
315
316 /// Unify `from_ty` to `to_ty` with optional auto Deref
317 ///
318 /// Note that the parameters are already stripped the outer reference.
319 fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
320 let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone());
321 let to_ty = self.resolve_ty_shallow(&to_ty);
322 // FIXME: Auto DerefMut
323 for derefed_ty in autoderef::autoderef(
324 self.db,
325 self.resolver.krate(),
326 InEnvironment {
327 value: canonicalized.value.clone(),
328 environment: self.trait_env.clone(),
329 },
330 ) {
331 let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value);
332 match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) {
333 // Stop when constructor matches.
334 (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => {
335 // It will not recurse to `coerce`.
336 return self.unify_substs(st1, st2, 0);
337 }
338 _ => {}
339 }
340 }
341
342 false
343 }
344}
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
3use std::iter::{repeat, repeat_with};
4use std::sync::Arc;
5
6use 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};
14use hir_expand::name::{self, Name};
15
16use 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
22use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
23
24impl<'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, &param_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, &param_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
3use std::iter::repeat;
4use std::sync::Arc;
5
6use hir_def::{
7 expr::{BindingAnnotation, Pat, PatId, RecordFieldPat},
8 path::Path,
9 type_ref::Mutability,
10};
11use hir_expand::name::Name;
12use test_utils::tested_by;
13
14use super::{BindingMode, InferenceContext};
15use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk};
16
17impl<'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..14be66836
--- /dev/null
+++ b/crates/ra_hir_ty/src/infer/path.rs
@@ -0,0 +1,268 @@
1//! Path expression resolution.
2
3use hir_def::{
4 path::{Path, PathKind, PathSegment},
5 resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs},
6 AssocItemId, ContainerId, Lookup,
7};
8use hir_expand::name::Name;
9
10use crate::{db::HirDatabase, method_resolution, Substs, Ty, TypeWalk, ValueTyDefId};
11
12use super::{ExprOrPatId, InferenceContext, TraitRef};
13
14impl<'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 self_ty = self.db.impl_ty(impl_id).self_type().clone();
248 let self_ty_substs = self_ty.substs()?;
249 let actual_substs = actual_def_ty.substs()?;
250
251 let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()];
252
253 // The following code *link up* the function actual parma type
254 // and impl_block type param index
255 self_ty_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| {
256 if let Ty::Param { idx, .. } = param {
257 if let Some(s) = new_substs.get_mut(*idx as usize) {
258 *s = pty.clone();
259 }
260 }
261 });
262
263 Some(Substs(new_substs.into()))
264 } else {
265 None
266 }
267 }
268}
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
3use super::{InferenceContext, Obligation};
4use crate::{
5 db::HirDatabase, utils::make_mut_slice, Canonical, InEnvironment, InferTy, ProjectionPredicate,
6 ProjectionTy, Substs, TraitRef, Ty, TypeWalk,
7};
8
9impl<'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
18pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase>
19where
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
30pub(super) struct Canonicalized<T> {
31 pub value: Canonical<T>,
32 free_vars: Vec<InferTy>,
33}
34
35impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D>
36where
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
134impl<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
new file mode 100644
index 000000000..b45c8f82f
--- /dev/null
+++ b/crates/ra_hir_ty/src/lib.rs
@@ -0,0 +1,1138 @@
1//! The type system. We currently use this to infer types for completion, hover
2//! information and various assists.
3
4macro_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
23mod autoderef;
24pub mod primitive;
25pub mod traits;
26pub mod method_resolution;
27mod op;
28mod lower;
29mod infer;
30pub mod display;
31pub(crate) mod utils;
32pub mod db;
33pub mod diagnostics;
34pub mod expr;
35
36#[cfg(test)]
37mod tests;
38#[cfg(test)]
39mod test_db;
40mod marks;
41
42use std::ops::Deref;
43use std::sync::Arc;
44use std::{fmt, iter, mem};
45
46use hir_def::{
47 expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId,
48 GenericDefId, HasModule, Lookup, TraitId, TypeAliasId,
49};
50use hir_expand::name::Name;
51use ra_db::{impl_intern_key, salsa, CrateId};
52
53use crate::{
54 db::HirDatabase,
55 primitive::{FloatTy, IntTy, Uncertain},
56 utils::make_mut_slice,
57};
58use display::{HirDisplay, HirFormatter};
59
60pub use autoderef::autoderef;
61pub use infer::{infer_query, InferTy, InferenceResult};
62pub use lower::CallableDef;
63pub use lower::{callable_item_sig, TyDefId, ValueTyDefId};
64pub 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)]
70pub 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)]
150pub struct TypeCtorId(salsa::InternId);
151impl_intern_key!(TypeCtorId);
152
153impl 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)]
233pub 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)]
242pub struct ProjectionTy {
243 pub associated_ty: TypeAliasId,
244 pub parameters: Substs,
245}
246
247impl 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
260impl 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)]
277pub 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)]
330pub struct Substs(Arc<[Ty]>);
331
332impl 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
346impl 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)]
409pub struct SubstsBuilder {
410 vec: Vec<Ty>,
411 param_count: usize,
412}
413
414impl 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
456impl 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)]
467pub struct TraitRef {
468 /// FIXME name?
469 pub trait_: TraitId,
470 pub substs: Substs,
471}
472
473impl TraitRef {
474 pub fn self_ty(&self) -> &Ty {
475 &self.substs[0]
476 }
477}
478
479impl 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#[derive(Clone, PartialEq, Eq, Debug)]
490pub enum ImplTy {
491 Inherent(Ty),
492 TraitRef(TraitRef),
493}
494
495impl ImplTy {
496 pub(crate) fn self_type(&self) -> &Ty {
497 match self {
498 ImplTy::Inherent(it) => it,
499 ImplTy::TraitRef(tr) => &tr.substs[0],
500 }
501 }
502}
503
504/// Like `generics::WherePredicate`, but with resolved types: A condition on the
505/// parameters of a generic item.
506#[derive(Debug, Clone, PartialEq, Eq, Hash)]
507pub enum GenericPredicate {
508 /// The given trait needs to be implemented for its type parameters.
509 Implemented(TraitRef),
510 /// An associated type bindings like in `Iterator<Item = T>`.
511 Projection(ProjectionPredicate),
512 /// We couldn't resolve the trait reference. (If some type parameters can't
513 /// be resolved, they will just be Unknown).
514 Error,
515}
516
517impl GenericPredicate {
518 pub fn is_error(&self) -> bool {
519 match self {
520 GenericPredicate::Error => true,
521 _ => false,
522 }
523 }
524
525 pub fn is_implemented(&self) -> bool {
526 match self {
527 GenericPredicate::Implemented(_) => true,
528 _ => false,
529 }
530 }
531
532 pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> {
533 match self {
534 GenericPredicate::Implemented(tr) => Some(tr.clone()),
535 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
536 GenericPredicate::Error => None,
537 }
538 }
539}
540
541impl TypeWalk for GenericPredicate {
542 fn walk(&self, f: &mut impl FnMut(&Ty)) {
543 match self {
544 GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f),
545 GenericPredicate::Projection(projection_pred) => projection_pred.walk(f),
546 GenericPredicate::Error => {}
547 }
548 }
549
550 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
551 match self {
552 GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders),
553 GenericPredicate::Projection(projection_pred) => {
554 projection_pred.walk_mut_binders(f, binders)
555 }
556 GenericPredicate::Error => {}
557 }
558 }
559}
560
561/// Basically a claim (currently not validated / checked) that the contained
562/// type / trait ref contains no inference variables; any inference variables it
563/// contained have been replaced by bound variables, and `num_vars` tells us how
564/// many there are. This is used to erase irrelevant differences between types
565/// before using them in queries.
566#[derive(Debug, Clone, PartialEq, Eq, Hash)]
567pub struct Canonical<T> {
568 pub value: T,
569 pub num_vars: usize,
570}
571
572/// A function signature as seen by type inference: Several parameter types and
573/// one return type.
574#[derive(Clone, PartialEq, Eq, Debug)]
575pub struct FnSig {
576 params_and_return: Arc<[Ty]>,
577}
578
579impl FnSig {
580 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
581 params.push(ret);
582 FnSig { params_and_return: params.into() }
583 }
584
585 pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig {
586 FnSig { params_and_return: Arc::clone(&substs.0) }
587 }
588
589 pub fn params(&self) -> &[Ty] {
590 &self.params_and_return[0..self.params_and_return.len() - 1]
591 }
592
593 pub fn ret(&self) -> &Ty {
594 &self.params_and_return[self.params_and_return.len() - 1]
595 }
596}
597
598impl TypeWalk for FnSig {
599 fn walk(&self, f: &mut impl FnMut(&Ty)) {
600 for t in self.params_and_return.iter() {
601 t.walk(f);
602 }
603 }
604
605 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
606 for t in make_mut_slice(&mut self.params_and_return) {
607 t.walk_mut_binders(f, binders);
608 }
609 }
610}
611
612impl Ty {
613 pub fn simple(ctor: TypeCtor) -> Ty {
614 Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() })
615 }
616 pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty {
617 Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) })
618 }
619 pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty {
620 Ty::Apply(ApplicationTy { ctor, parameters })
621 }
622 pub fn unit() -> Self {
623 Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty())
624 }
625
626 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
627 match self {
628 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
629 Some((parameters.as_single(), *mutability))
630 }
631 _ => None,
632 }
633 }
634
635 pub fn as_adt(&self) -> Option<(AdtId, &Substs)> {
636 match self {
637 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => {
638 Some((*adt_def, parameters))
639 }
640 _ => None,
641 }
642 }
643
644 pub fn as_tuple(&self) -> Option<&Substs> {
645 match self {
646 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => {
647 Some(parameters)
648 }
649 _ => None,
650 }
651 }
652
653 pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> {
654 match self {
655 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => {
656 Some((*callable_def, parameters))
657 }
658 _ => None,
659 }
660 }
661
662 fn builtin_deref(&self) -> Option<Ty> {
663 match self {
664 Ty::Apply(a_ty) => match a_ty.ctor {
665 TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())),
666 TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())),
667 _ => None,
668 },
669 _ => None,
670 }
671 }
672
673 fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> {
674 match self {
675 Ty::Apply(a_ty) => match a_ty.ctor {
676 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)),
677 TypeCtor::FnDef(def) => {
678 let sig = db.callable_item_signature(def);
679 Some(sig.subst(&a_ty.parameters))
680 }
681 TypeCtor::Closure { .. } => {
682 let sig_param = &a_ty.parameters[0];
683 sig_param.callable_sig(db)
684 }
685 _ => None,
686 },
687 _ => None,
688 }
689 }
690
691 /// If this is a type with type parameters (an ADT or function), replaces
692 /// the `Substs` for these type parameters with the given ones. (So e.g. if
693 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
694 /// `Option<u32>` afterwards.)
695 pub fn apply_substs(self, substs: Substs) -> Ty {
696 match self {
697 Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => {
698 assert_eq!(previous_substs.len(), substs.len());
699 Ty::Apply(ApplicationTy { ctor, parameters: substs })
700 }
701 _ => self,
702 }
703 }
704
705 /// Returns the type parameters of this type if it has some (i.e. is an ADT
706 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
707 pub fn substs(&self) -> Option<Substs> {
708 match self {
709 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
710 _ => None,
711 }
712 }
713
714 /// If this is an `impl Trait` or `dyn Trait`, returns that trait.
715 pub fn inherent_trait(&self) -> Option<TraitId> {
716 match self {
717 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
718 predicates.iter().find_map(|pred| match pred {
719 GenericPredicate::Implemented(tr) => Some(tr.trait_),
720 _ => None,
721 })
722 }
723 _ => None,
724 }
725 }
726}
727
728/// This allows walking structures that contain types to do something with those
729/// types, similar to Chalk's `Fold` trait.
730pub trait TypeWalk {
731 fn walk(&self, f: &mut impl FnMut(&Ty));
732 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
733 self.walk_mut_binders(&mut |ty, _binders| f(ty), 0);
734 }
735 /// Walk the type, counting entered binders.
736 ///
737 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers
738 /// to the innermost binder, 1 to the next, etc.. So when we want to
739 /// substitute a certain bound variable, we can't just walk the whole type
740 /// and blindly replace each instance of a certain index; when we 'enter'
741 /// things that introduce new bound variables, we have to keep track of
742 /// that. Currently, the only thing that introduces bound variables on our
743 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound
744 /// variable for the self type.
745 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize);
746
747 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self
748 where
749 Self: Sized,
750 {
751 self.walk_mut(&mut |ty_mut| {
752 let ty = mem::replace(ty_mut, Ty::Unknown);
753 *ty_mut = f(ty);
754 });
755 self
756 }
757
758 /// Replaces type parameters in this type using the given `Substs`. (So e.g.
759 /// if `self` is `&[T]`, where type parameter T has index 0, and the
760 /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.)
761 fn subst(self, substs: &Substs) -> Self
762 where
763 Self: Sized,
764 {
765 self.fold(&mut |ty| match ty {
766 Ty::Param { idx, name } => {
767 substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name })
768 }
769 ty => ty,
770 })
771 }
772
773 /// Substitutes `Ty::Bound` vars (as opposed to type parameters).
774 fn subst_bound_vars(mut self, substs: &Substs) -> Self
775 where
776 Self: Sized,
777 {
778 self.walk_mut_binders(
779 &mut |ty, binders| match ty {
780 &mut Ty::Bound(idx) => {
781 if idx as usize >= binders && (idx as usize - binders) < substs.len() {
782 *ty = substs.0[idx as usize - binders].clone();
783 }
784 }
785 _ => {}
786 },
787 0,
788 );
789 self
790 }
791
792 /// Shifts up `Ty::Bound` vars by `n`.
793 fn shift_bound_vars(self, n: i32) -> Self
794 where
795 Self: Sized,
796 {
797 self.fold(&mut |ty| match ty {
798 Ty::Bound(idx) => {
799 assert!(idx as i32 >= -n);
800 Ty::Bound((idx as i32 + n) as u32)
801 }
802 ty => ty,
803 })
804 }
805}
806
807impl TypeWalk for Ty {
808 fn walk(&self, f: &mut impl FnMut(&Ty)) {
809 match self {
810 Ty::Apply(a_ty) => {
811 for t in a_ty.parameters.iter() {
812 t.walk(f);
813 }
814 }
815 Ty::Projection(p_ty) => {
816 for t in p_ty.parameters.iter() {
817 t.walk(f);
818 }
819 }
820 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
821 for p in predicates.iter() {
822 p.walk(f);
823 }
824 }
825 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
826 }
827 f(self);
828 }
829
830 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
831 match self {
832 Ty::Apply(a_ty) => {
833 a_ty.parameters.walk_mut_binders(f, binders);
834 }
835 Ty::Projection(p_ty) => {
836 p_ty.parameters.walk_mut_binders(f, binders);
837 }
838 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
839 for p in make_mut_slice(predicates) {
840 p.walk_mut_binders(f, binders + 1);
841 }
842 }
843 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
844 }
845 f(self, binders);
846 }
847}
848
849impl HirDisplay for &Ty {
850 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
851 HirDisplay::hir_fmt(*self, f)
852 }
853}
854
855impl HirDisplay for ApplicationTy {
856 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
857 if f.should_truncate() {
858 return write!(f, "…");
859 }
860
861 match self.ctor {
862 TypeCtor::Bool => write!(f, "bool")?,
863 TypeCtor::Char => write!(f, "char")?,
864 TypeCtor::Int(t) => write!(f, "{}", t)?,
865 TypeCtor::Float(t) => write!(f, "{}", t)?,
866 TypeCtor::Str => write!(f, "str")?,
867 TypeCtor::Slice => {
868 let t = self.parameters.as_single();
869 write!(f, "[{}]", t.display(f.db))?;
870 }
871 TypeCtor::Array => {
872 let t = self.parameters.as_single();
873 write!(f, "[{};_]", t.display(f.db))?;
874 }
875 TypeCtor::RawPtr(m) => {
876 let t = self.parameters.as_single();
877 write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?;
878 }
879 TypeCtor::Ref(m) => {
880 let t = self.parameters.as_single();
881 write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?;
882 }
883 TypeCtor::Never => write!(f, "!")?,
884 TypeCtor::Tuple { .. } => {
885 let ts = &self.parameters;
886 if ts.len() == 1 {
887 write!(f, "({},)", ts[0].display(f.db))?;
888 } else {
889 write!(f, "(")?;
890 f.write_joined(&*ts.0, ", ")?;
891 write!(f, ")")?;
892 }
893 }
894 TypeCtor::FnPtr { .. } => {
895 let sig = FnSig::from_fn_ptr_substs(&self.parameters);
896 write!(f, "fn(")?;
897 f.write_joined(sig.params(), ", ")?;
898 write!(f, ") -> {}", sig.ret().display(f.db))?;
899 }
900 TypeCtor::FnDef(def) => {
901 let sig = f.db.callable_item_signature(def);
902 let name = match def {
903 CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(),
904 CallableDef::StructId(s) => f.db.struct_data(s).name.clone(),
905 CallableDef::EnumVariantId(e) => {
906 let enum_data = f.db.enum_data(e.parent);
907 enum_data.variants[e.local_id].name.clone()
908 }
909 };
910 match def {
911 CallableDef::FunctionId(_) => write!(f, "fn {}", name)?,
912 CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {
913 write!(f, "{}", name)?
914 }
915 }
916 if self.parameters.len() > 0 {
917 write!(f, "<")?;
918 f.write_joined(&*self.parameters.0, ", ")?;
919 write!(f, ">")?;
920 }
921 write!(f, "(")?;
922 f.write_joined(sig.params(), ", ")?;
923 write!(f, ") -> {}", sig.ret().display(f.db))?;
924 }
925 TypeCtor::Adt(def_id) => {
926 let name = match def_id {
927 AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
928 AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
929 AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
930 };
931 write!(f, "{}", name)?;
932 if self.parameters.len() > 0 {
933 write!(f, "<")?;
934 f.write_joined(&*self.parameters.0, ", ")?;
935 write!(f, ">")?;
936 }
937 }
938 TypeCtor::AssociatedType(type_alias) => {
939 let trait_ = match type_alias.lookup(f.db).container {
940 ContainerId::TraitId(it) => it,
941 _ => panic!("not an associated type"),
942 };
943 let trait_name = f.db.trait_data(trait_).name.clone();
944 let name = f.db.type_alias_data(type_alias).name.clone();
945 write!(f, "{}::{}", trait_name, name)?;
946 if self.parameters.len() > 0 {
947 write!(f, "<")?;
948 f.write_joined(&*self.parameters.0, ", ")?;
949 write!(f, ">")?;
950 }
951 }
952 TypeCtor::Closure { .. } => {
953 let sig = self.parameters[0]
954 .callable_sig(f.db)
955 .expect("first closure parameter should contain signature");
956 write!(f, "|")?;
957 f.write_joined(sig.params(), ", ")?;
958 write!(f, "| -> {}", sig.ret().display(f.db))?;
959 }
960 }
961 Ok(())
962 }
963}
964
965impl HirDisplay for ProjectionTy {
966 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
967 if f.should_truncate() {
968 return write!(f, "…");
969 }
970
971 let trait_name = f.db.trait_data(self.trait_(f.db)).name.clone();
972 write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?;
973 if self.parameters.len() > 1 {
974 write!(f, "<")?;
975 f.write_joined(&self.parameters[1..], ", ")?;
976 write!(f, ">")?;
977 }
978 write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?;
979 Ok(())
980 }
981}
982
983impl HirDisplay for Ty {
984 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
985 if f.should_truncate() {
986 return write!(f, "…");
987 }
988
989 match self {
990 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
991 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
992 Ty::Param { name, .. } => write!(f, "{}", name)?,
993 Ty::Bound(idx) => write!(f, "?{}", idx)?,
994 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
995 match self {
996 Ty::Dyn(_) => write!(f, "dyn ")?,
997 Ty::Opaque(_) => write!(f, "impl ")?,
998 _ => unreachable!(),
999 };
1000 // Note: This code is written to produce nice results (i.e.
1001 // corresponding to surface Rust) for types that can occur in
1002 // actual Rust. It will have weird results if the predicates
1003 // aren't as expected (i.e. self types = $0, projection
1004 // predicates for a certain trait come after the Implemented
1005 // predicate for that trait).
1006 let mut first = true;
1007 let mut angle_open = false;
1008 for p in predicates.iter() {
1009 match p {
1010 GenericPredicate::Implemented(trait_ref) => {
1011 if angle_open {
1012 write!(f, ">")?;
1013 }
1014 if !first {
1015 write!(f, " + ")?;
1016 }
1017 // We assume that the self type is $0 (i.e. the
1018 // existential) here, which is the only thing that's
1019 // possible in actual Rust, and hence don't print it
1020 write!(f, "{}", f.db.trait_data(trait_ref.trait_).name.clone())?;
1021 if trait_ref.substs.len() > 1 {
1022 write!(f, "<")?;
1023 f.write_joined(&trait_ref.substs[1..], ", ")?;
1024 // there might be assoc type bindings, so we leave the angle brackets open
1025 angle_open = true;
1026 }
1027 }
1028 GenericPredicate::Projection(projection_pred) => {
1029 // in types in actual Rust, these will always come
1030 // after the corresponding Implemented predicate
1031 if angle_open {
1032 write!(f, ", ")?;
1033 } else {
1034 write!(f, "<")?;
1035 angle_open = true;
1036 }
1037 let name =
1038 f.db.type_alias_data(projection_pred.projection_ty.associated_ty)
1039 .name
1040 .clone();
1041 write!(f, "{} = ", name)?;
1042 projection_pred.ty.hir_fmt(f)?;
1043 }
1044 GenericPredicate::Error => {
1045 if angle_open {
1046 // impl Trait<X, {error}>
1047 write!(f, ", ")?;
1048 } else if !first {
1049 // impl Trait + {error}
1050 write!(f, " + ")?;
1051 }
1052 p.hir_fmt(f)?;
1053 }
1054 }
1055 first = false;
1056 }
1057 if angle_open {
1058 write!(f, ">")?;
1059 }
1060 }
1061 Ty::Unknown => write!(f, "{{unknown}}")?,
1062 Ty::Infer(..) => write!(f, "_")?,
1063 }
1064 Ok(())
1065 }
1066}
1067
1068impl TraitRef {
1069 fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {
1070 if f.should_truncate() {
1071 return write!(f, "…");
1072 }
1073
1074 self.substs[0].hir_fmt(f)?;
1075 if use_as {
1076 write!(f, " as ")?;
1077 } else {
1078 write!(f, ": ")?;
1079 }
1080 write!(f, "{}", f.db.trait_data(self.trait_).name.clone())?;
1081 if self.substs.len() > 1 {
1082 write!(f, "<")?;
1083 f.write_joined(&self.substs[1..], ", ")?;
1084 write!(f, ">")?;
1085 }
1086 Ok(())
1087 }
1088}
1089
1090impl HirDisplay for TraitRef {
1091 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1092 self.hir_fmt_ext(f, false)
1093 }
1094}
1095
1096impl HirDisplay for &GenericPredicate {
1097 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1098 HirDisplay::hir_fmt(*self, f)
1099 }
1100}
1101
1102impl HirDisplay for GenericPredicate {
1103 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1104 if f.should_truncate() {
1105 return write!(f, "…");
1106 }
1107
1108 match self {
1109 GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
1110 GenericPredicate::Projection(projection_pred) => {
1111 write!(f, "<")?;
1112 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
1113 write!(
1114 f,
1115 ">::{} = {}",
1116 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name,
1117 projection_pred.ty.display(f.db)
1118 )?;
1119 }
1120 GenericPredicate::Error => write!(f, "{{error}}")?,
1121 }
1122 Ok(())
1123 }
1124}
1125
1126impl HirDisplay for Obligation {
1127 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1128 match self {
1129 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)),
1130 Obligation::Projection(proj) => write!(
1131 f,
1132 "Normalize({} => {})",
1133 proj.projection_ty.display(f.db),
1134 proj.ty.display(f.db)
1135 ),
1136 }
1137 }
1138}
diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs
new file mode 100644
index 000000000..091c60f4f
--- /dev/null
+++ b/crates/ra_hir_ty/src/lower.rs
@@ -0,0 +1,759 @@
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.
8use std::iter;
9use std::sync::Arc;
10
11use 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, ImplId,
18 LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId,
19};
20use ra_arena::map::ArenaMap;
21use ra_db::CrateId;
22
23use crate::{
24 db::HirDatabase,
25 primitive::{FloatTy, IntTy},
26 utils::{
27 all_super_traits, associated_type_by_name_including_super_traits, make_mut_slice,
28 variant_data,
29 },
30 FnSig, GenericPredicate, ImplTy, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment,
31 TraitRef, Ty, TypeCtor, TypeWalk,
32};
33
34impl 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) => db.impl_ty(impl_id).self_type().clone(),
183 TypeNs::AdtSelfType(adt) => db.ty(adt.into()),
184
185 TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()),
186 TypeNs::BuiltinType(it) => {
187 Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into())
188 }
189 TypeNs::TypeAliasId(it) => {
190 Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into())
191 }
192 // FIXME: report error
193 TypeNs::EnumVariantId(_) => return Ty::Unknown,
194 };
195
196 Ty::from_type_relative_path(db, resolver, ty, remaining_segments)
197 }
198
199 pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty {
200 // Resolve the path (in type namespace)
201 if let PathKind::Type(type_ref) = &path.kind {
202 let ty = Ty::from_hir(db, resolver, &type_ref);
203 let remaining_segments = &path.segments[..];
204 return Ty::from_type_relative_path(db, resolver, ty, remaining_segments);
205 }
206 let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) {
207 Some(it) => it,
208 None => return Ty::Unknown,
209 };
210 let (resolved_segment, remaining_segments) = match remaining_index {
211 None => (
212 path.segments.last().expect("resolved path has at least one element"),
213 &[] as &[PathSegment],
214 ),
215 Some(i) => (&path.segments[i - 1], &path.segments[i..]),
216 };
217 Ty::from_partly_resolved_hir_path(
218 db,
219 resolver,
220 resolution,
221 resolved_segment,
222 remaining_segments,
223 )
224 }
225
226 fn select_associated_type(
227 db: &impl HirDatabase,
228 resolver: &Resolver,
229 self_ty: Ty,
230 segment: &PathSegment,
231 ) -> Ty {
232 let param_idx = match self_ty {
233 Ty::Param { idx, .. } => idx,
234 _ => return Ty::Unknown, // Error: Ambiguous associated type
235 };
236 let def = match resolver.generic_def() {
237 Some(def) => def,
238 None => return Ty::Unknown, // this can't actually happen
239 };
240 let predicates = db.generic_predicates_for_param(def.into(), param_idx);
241 let traits_from_env = predicates.iter().filter_map(|pred| match pred {
242 GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_),
243 _ => None,
244 });
245 let traits = traits_from_env.flat_map(|t| all_super_traits(db, t));
246 for t in traits {
247 if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) {
248 let substs =
249 Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build();
250 // FIXME handle type parameters on the segment
251 return Ty::Projection(ProjectionTy { associated_ty, parameters: substs });
252 }
253 }
254 Ty::Unknown
255 }
256
257 fn from_hir_path_inner(
258 db: &impl HirDatabase,
259 resolver: &Resolver,
260 segment: &PathSegment,
261 typable: TyDefId,
262 ) -> Ty {
263 let generic_def = match typable {
264 TyDefId::BuiltinType(_) => None,
265 TyDefId::AdtId(it) => Some(it.into()),
266 TyDefId::TypeAliasId(it) => Some(it.into()),
267 };
268 let substs = substs_from_path_segment(db, resolver, segment, generic_def, false);
269 db.ty(typable).subst(&substs)
270 }
271
272 /// Collect generic arguments from a path into a `Substs`. See also
273 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
274 pub(super) fn substs_from_path(
275 db: &impl HirDatabase,
276 resolver: &Resolver,
277 path: &Path,
278 // Note that we don't call `db.value_type(resolved)` here,
279 // `ValueTyDefId` is just a convenient way to pass generics and
280 // special-case enum variants
281 resolved: ValueTyDefId,
282 ) -> Substs {
283 let last = path.segments.last().expect("path should have at least one segment");
284 let (segment, generic_def) = match resolved {
285 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
286 ValueTyDefId::StructId(it) => (last, Some(it.into())),
287 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
288 ValueTyDefId::StaticId(_) => (last, None),
289 ValueTyDefId::EnumVariantId(var) => {
290 // the generic args for an enum variant may be either specified
291 // on the segment referring to the enum, or on the segment
292 // referring to the variant. So `Option::<T>::None` and
293 // `Option::None::<T>` are both allowed (though the former is
294 // preferred). See also `def_ids_for_path_segments` in rustc.
295 let len = path.segments.len();
296 let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() {
297 // Option::<T>::None
298 &path.segments[len - 2]
299 } else {
300 // Option::None::<T>
301 last
302 };
303 (segment, Some(var.parent.into()))
304 }
305 };
306 substs_from_path_segment(db, resolver, segment, generic_def, false)
307 }
308}
309
310pub(super) fn substs_from_path_segment(
311 db: &impl HirDatabase,
312 resolver: &Resolver,
313 segment: &PathSegment,
314 def_generic: Option<GenericDefId>,
315 add_self_param: bool,
316) -> Substs {
317 let mut substs = Vec::new();
318 let def_generics = def_generic.map(|def| db.generic_params(def.into()));
319
320 let (parent_param_count, param_count) =
321 def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len()));
322 substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count));
323 if add_self_param {
324 // FIXME this add_self_param argument is kind of a hack: Traits have the
325 // Self type as an implicit first type parameter, but it can't be
326 // actually provided in the type arguments
327 // (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`)
328 substs.push(Ty::Unknown);
329 }
330 if let Some(generic_args) = &segment.args_and_bindings {
331 // if args are provided, it should be all of them, but we can't rely on that
332 let self_param_correction = if add_self_param { 1 } else { 0 };
333 let param_count = param_count - self_param_correction;
334 for arg in generic_args.args.iter().take(param_count) {
335 match arg {
336 GenericArg::Type(type_ref) => {
337 let ty = Ty::from_hir(db, resolver, type_ref);
338 substs.push(ty);
339 }
340 }
341 }
342 }
343 // add placeholders for args that were not provided
344 let supplied_params = substs.len();
345 for _ in supplied_params..parent_param_count + param_count {
346 substs.push(Ty::Unknown);
347 }
348 assert_eq!(substs.len(), parent_param_count + param_count);
349
350 // handle defaults
351 if let Some(def_generic) = def_generic {
352 let default_substs = db.generic_defaults(def_generic.into());
353 assert_eq!(substs.len(), default_substs.len());
354
355 for (i, default_ty) in default_substs.iter().enumerate() {
356 if substs[i] == Ty::Unknown {
357 substs[i] = default_ty.clone();
358 }
359 }
360 }
361
362 Substs(substs.into())
363}
364
365impl TraitRef {
366 fn from_path(
367 db: &impl HirDatabase,
368 resolver: &Resolver,
369 path: &Path,
370 explicit_self_ty: Option<Ty>,
371 ) -> Option<Self> {
372 let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? {
373 TypeNs::TraitId(tr) => tr,
374 _ => return None,
375 };
376 let segment = path.segments.last().expect("path should have at least one segment");
377 Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty))
378 }
379
380 pub(crate) fn from_resolved_path(
381 db: &impl HirDatabase,
382 resolver: &Resolver,
383 resolved: TraitId,
384 segment: &PathSegment,
385 explicit_self_ty: Option<Ty>,
386 ) -> Self {
387 let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved);
388 if let Some(self_ty) = explicit_self_ty {
389 make_mut_slice(&mut substs.0)[0] = self_ty;
390 }
391 TraitRef { trait_: resolved, substs }
392 }
393
394 fn from_hir(
395 db: &impl HirDatabase,
396 resolver: &Resolver,
397 type_ref: &TypeRef,
398 explicit_self_ty: Option<Ty>,
399 ) -> Option<Self> {
400 let path = match type_ref {
401 TypeRef::Path(path) => path,
402 _ => return None,
403 };
404 TraitRef::from_path(db, resolver, path, explicit_self_ty)
405 }
406
407 fn substs_from_path(
408 db: &impl HirDatabase,
409 resolver: &Resolver,
410 segment: &PathSegment,
411 resolved: TraitId,
412 ) -> Substs {
413 let has_self_param =
414 segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false);
415 substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param)
416 }
417
418 pub(crate) fn from_type_bound(
419 db: &impl HirDatabase,
420 resolver: &Resolver,
421 bound: &TypeBound,
422 self_ty: Ty,
423 ) -> Option<TraitRef> {
424 match bound {
425 TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)),
426 TypeBound::Error => None,
427 }
428 }
429}
430
431impl GenericPredicate {
432 pub(crate) fn from_where_predicate<'a>(
433 db: &'a impl HirDatabase,
434 resolver: &'a Resolver,
435 where_predicate: &'a WherePredicate,
436 ) -> impl Iterator<Item = GenericPredicate> + 'a {
437 let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref);
438 GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty)
439 }
440
441 pub(crate) fn from_type_bound<'a>(
442 db: &'a impl HirDatabase,
443 resolver: &'a Resolver,
444 bound: &'a TypeBound,
445 self_ty: Ty,
446 ) -> impl Iterator<Item = GenericPredicate> + 'a {
447 let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty);
448 iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented))
449 .chain(
450 trait_ref.into_iter().flat_map(move |tr| {
451 assoc_type_bindings_from_type_bound(db, resolver, bound, tr)
452 }),
453 )
454 }
455}
456
457fn assoc_type_bindings_from_type_bound<'a>(
458 db: &'a impl HirDatabase,
459 resolver: &'a Resolver,
460 bound: &'a TypeBound,
461 trait_ref: TraitRef,
462) -> impl Iterator<Item = GenericPredicate> + 'a {
463 let last_segment = match bound {
464 TypeBound::Path(path) => path.segments.last(),
465 TypeBound::Error => None,
466 };
467 last_segment
468 .into_iter()
469 .flat_map(|segment| segment.args_and_bindings.iter())
470 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
471 .map(move |(name, type_ref)| {
472 let associated_ty =
473 associated_type_by_name_including_super_traits(db, trait_ref.trait_, &name);
474 let associated_ty = match associated_ty {
475 None => return GenericPredicate::Error,
476 Some(t) => t,
477 };
478 let projection_ty =
479 ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() };
480 let ty = Ty::from_hir(db, resolver, type_ref);
481 let projection_predicate = ProjectionPredicate { projection_ty, ty };
482 GenericPredicate::Projection(projection_predicate)
483 })
484}
485
486/// Build the signature of a callable item (function, struct or enum variant).
487pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig {
488 match def {
489 CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),
490 CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s),
491 CallableDef::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
492 }
493}
494
495/// Build the type of all specific fields of a struct or enum variant.
496pub(crate) fn field_types_query(
497 db: &impl HirDatabase,
498 variant_id: VariantId,
499) -> Arc<ArenaMap<LocalStructFieldId, Ty>> {
500 let var_data = variant_data(db, variant_id);
501 let resolver = match variant_id {
502 VariantId::StructId(it) => it.resolver(db),
503 VariantId::UnionId(it) => it.resolver(db),
504 VariantId::EnumVariantId(it) => it.parent.resolver(db),
505 };
506 let mut res = ArenaMap::default();
507 for (field_id, field_data) in var_data.fields().iter() {
508 res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref))
509 }
510 Arc::new(res)
511}
512
513/// This query exists only to be used when resolving short-hand associated types
514/// like `T::Item`.
515///
516/// See the analogous query in rustc and its comment:
517/// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
518/// This is a query mostly to handle cycles somewhat gracefully; e.g. the
519/// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
520/// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
521pub(crate) fn generic_predicates_for_param_query(
522 db: &impl HirDatabase,
523 def: GenericDefId,
524 param_idx: u32,
525) -> Arc<[GenericPredicate]> {
526 let resolver = def.resolver(db);
527 resolver
528 .where_predicates_in_scope()
529 // we have to filter out all other predicates *first*, before attempting to lower them
530 .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx))
531 .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
532 .collect()
533}
534
535impl TraitEnvironment {
536 pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
537 let predicates = resolver
538 .where_predicates_in_scope()
539 .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
540 .collect::<Vec<_>>();
541
542 Arc::new(TraitEnvironment { predicates })
543 }
544}
545
546/// Resolve the where clause(s) of an item with generics.
547pub(crate) fn generic_predicates_query(
548 db: &impl HirDatabase,
549 def: GenericDefId,
550) -> Arc<[GenericPredicate]> {
551 let resolver = def.resolver(db);
552 resolver
553 .where_predicates_in_scope()
554 .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
555 .collect()
556}
557
558/// Resolve the default type params from generics
559pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs {
560 let resolver = def.resolver(db);
561 let generic_params = db.generic_params(def.into());
562
563 let defaults = generic_params
564 .params_including_parent()
565 .into_iter()
566 .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t)))
567 .collect();
568
569 Substs(defaults)
570}
571
572fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> FnSig {
573 let data = db.function_data(def);
574 let resolver = def.resolver(db);
575 let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>();
576 let ret = Ty::from_hir(db, &resolver, &data.ret_type);
577 FnSig::from_params_and_return(params, ret)
578}
579
580/// Build the declared type of a function. This should not need to look at the
581/// function body.
582fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Ty {
583 let generics = db.generic_params(def.into());
584 let substs = Substs::identity(&generics);
585 Ty::apply(TypeCtor::FnDef(def.into()), substs)
586}
587
588/// Build the declared type of a const.
589fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Ty {
590 let data = db.const_data(def);
591 let resolver = def.resolver(db);
592
593 Ty::from_hir(db, &resolver, &data.type_ref)
594}
595
596/// Build the declared type of a static.
597fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Ty {
598 let data = db.static_data(def);
599 let resolver = def.resolver(db);
600
601 Ty::from_hir(db, &resolver, &data.type_ref)
602}
603
604/// Build the declared type of a static.
605fn type_for_builtin(def: BuiltinType) -> Ty {
606 Ty::simple(match def {
607 BuiltinType::Char => TypeCtor::Char,
608 BuiltinType::Bool => TypeCtor::Bool,
609 BuiltinType::Str => TypeCtor::Str,
610 BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()),
611 BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()),
612 })
613}
614
615fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> FnSig {
616 let struct_data = db.struct_data(def.into());
617 let fields = struct_data.variant_data.fields();
618 let resolver = def.resolver(db);
619 let params = fields
620 .iter()
621 .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref))
622 .collect::<Vec<_>>();
623 let ret = type_for_adt(db, def.into());
624 FnSig::from_params_and_return(params, ret)
625}
626
627/// Build the type of a tuple struct constructor.
628fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Ty {
629 let struct_data = db.struct_data(def.into());
630 if struct_data.variant_data.is_unit() {
631 return type_for_adt(db, def.into()); // Unit struct
632 }
633 let generics = db.generic_params(def.into());
634 let substs = Substs::identity(&generics);
635 Ty::apply(TypeCtor::FnDef(def.into()), substs)
636}
637
638fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> FnSig {
639 let enum_data = db.enum_data(def.parent);
640 let var_data = &enum_data.variants[def.local_id];
641 let fields = var_data.variant_data.fields();
642 let resolver = def.parent.resolver(db);
643 let params = fields
644 .iter()
645 .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref))
646 .collect::<Vec<_>>();
647 let generics = db.generic_params(def.parent.into());
648 let substs = Substs::identity(&generics);
649 let ret = type_for_adt(db, def.parent.into()).subst(&substs);
650 FnSig::from_params_and_return(params, ret)
651}
652
653/// Build the type of a tuple enum variant constructor.
654fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Ty {
655 let enum_data = db.enum_data(def.parent);
656 let var_data = &enum_data.variants[def.local_id].variant_data;
657 if var_data.is_unit() {
658 return type_for_adt(db, def.parent.into()); // Unit variant
659 }
660 let generics = db.generic_params(def.parent.into());
661 let substs = Substs::identity(&generics);
662 Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs)
663}
664
665fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Ty {
666 let generics = db.generic_params(adt.into());
667 Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics))
668}
669
670fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Ty {
671 let generics = db.generic_params(t.into());
672 let resolver = t.resolver(db);
673 let type_ref = &db.type_alias_data(t).type_ref;
674 let substs = Substs::identity(&generics);
675 let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error));
676 inner.subst(&substs)
677}
678
679#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
680pub enum CallableDef {
681 FunctionId(FunctionId),
682 StructId(StructId),
683 EnumVariantId(EnumVariantId),
684}
685impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId);
686
687impl CallableDef {
688 pub fn krate(self, db: &impl HirDatabase) -> CrateId {
689 match self {
690 CallableDef::FunctionId(f) => f.lookup(db).module(db).krate,
691 CallableDef::StructId(s) => s.module(db).krate,
692 CallableDef::EnumVariantId(e) => e.parent.module(db).krate,
693 }
694 }
695}
696
697impl From<CallableDef> for GenericDefId {
698 fn from(def: CallableDef) -> GenericDefId {
699 match def {
700 CallableDef::FunctionId(f) => f.into(),
701 CallableDef::StructId(s) => s.into(),
702 CallableDef::EnumVariantId(e) => e.into(),
703 }
704 }
705}
706
707#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
708pub enum TyDefId {
709 BuiltinType(BuiltinType),
710 AdtId(AdtId),
711 TypeAliasId(TypeAliasId),
712}
713impl_froms!(TyDefId: BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId);
714
715#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
716pub enum ValueTyDefId {
717 FunctionId(FunctionId),
718 StructId(StructId),
719 EnumVariantId(EnumVariantId),
720 ConstId(ConstId),
721 StaticId(StaticId),
722}
723impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId);
724
725/// Build the declared type of an item. This depends on the namespace; e.g. for
726/// `struct Foo(usize)`, we have two types: The type of the struct itself, and
727/// the constructor function `(usize) -> Foo` which lives in the values
728/// namespace.
729pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Ty {
730 match def {
731 TyDefId::BuiltinType(it) => type_for_builtin(it),
732 TyDefId::AdtId(it) => type_for_adt(db, it),
733 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
734 }
735}
736pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty {
737 match def {
738 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
739 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
740 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
741 ValueTyDefId::ConstId(it) => type_for_const(db, it),
742 ValueTyDefId::StaticId(it) => type_for_static(db, it),
743 }
744}
745
746pub(crate) fn impl_ty_query(db: &impl HirDatabase, impl_id: ImplId) -> ImplTy {
747 let impl_data = db.impl_data(impl_id);
748 let resolver = impl_id.resolver(db);
749 let self_ty = Ty::from_hir(db, &resolver, &impl_data.target_type);
750 match impl_data.target_trait.as_ref() {
751 Some(trait_ref) => {
752 match TraitRef::from_hir(db, &resolver, trait_ref, Some(self_ty.clone())) {
753 Some(it) => ImplTy::TraitRef(it),
754 None => ImplTy::Inherent(self_ty),
755 }
756 }
757 None => ImplTy::Inherent(self_ty),
758 }
759}
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
3test_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..ee1936b0e
--- /dev/null
+++ b/crates/ra_hir_ty/src/method_resolution.rs
@@ -0,0 +1,353 @@
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.
5use std::sync::Arc;
6
7use arrayvec::ArrayVec;
8use hir_def::{
9 lang_item::LangItemTarget, resolver::Resolver, type_ref::Mutability, AssocItemId, AstItemDef,
10 FunctionId, HasModule, ImplId, TraitId,
11};
12use hir_expand::name::Name;
13use ra_db::CrateId;
14use ra_prof::profile;
15use rustc_hash::FxHashMap;
16
17use crate::{
18 autoderef,
19 db::HirDatabase,
20 primitive::{FloatBitness, Uncertain},
21 utils::all_super_traits,
22 Canonical, ImplTy, InEnvironment, TraitEnvironment, TraitRef, Ty, TypeCtor,
23};
24
25/// This is used as a key for indexing impls.
26#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
27pub enum TyFingerprint {
28 Apply(TypeCtor),
29}
30
31impl TyFingerprint {
32 /// Creates a TyFingerprint for looking up an impl. Only certain types can
33 /// have impls: if we have some `struct S`, we can have an `impl S`, but not
34 /// `impl &S`. Hence, this will return `None` for reference types and such.
35 fn for_impl(ty: &Ty) -> Option<TyFingerprint> {
36 match ty {
37 Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)),
38 _ => None,
39 }
40 }
41}
42
43#[derive(Debug, PartialEq, Eq)]
44pub struct CrateImplBlocks {
45 impls: FxHashMap<TyFingerprint, Vec<ImplId>>,
46 impls_by_trait: FxHashMap<TraitId, Vec<ImplId>>,
47}
48
49impl CrateImplBlocks {
50 pub(crate) fn impls_in_crate_query(
51 db: &impl HirDatabase,
52 krate: CrateId,
53 ) -> Arc<CrateImplBlocks> {
54 let _p = profile("impls_in_crate_query");
55 let mut res =
56 CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() };
57
58 let crate_def_map = db.crate_def_map(krate);
59 for (_module_id, module_data) in crate_def_map.modules.iter() {
60 for &impl_id in module_data.impls.iter() {
61 match db.impl_ty(impl_id) {
62 ImplTy::TraitRef(tr) => {
63 res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id);
64 }
65 ImplTy::Inherent(self_ty) => {
66 if let Some(self_ty_fp) = TyFingerprint::for_impl(&self_ty) {
67 res.impls.entry(self_ty_fp).or_default().push(impl_id);
68 }
69 }
70 }
71 }
72 }
73
74 Arc::new(res)
75 }
76 pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator<Item = ImplId> + '_ {
77 let fingerprint = TyFingerprint::for_impl(ty);
78 fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied()
79 }
80
81 pub fn lookup_impl_blocks_for_trait(&self, tr: TraitId) -> impl Iterator<Item = ImplId> + '_ {
82 self.impls_by_trait.get(&tr).into_iter().flatten().copied()
83 }
84
85 pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplId> + 'a {
86 self.impls.values().chain(self.impls_by_trait.values()).flatten().copied()
87 }
88}
89
90impl Ty {
91 pub fn def_crates(
92 &self,
93 db: &impl HirDatabase,
94 cur_crate: CrateId,
95 ) -> Option<ArrayVec<[CrateId; 2]>> {
96 // Types like slice can have inherent impls in several crates, (core and alloc).
97 // The corresponding impls are marked with lang items, so we can use them to find the required crates.
98 macro_rules! lang_item_crate {
99 ($($name:expr),+ $(,)?) => {{
100 let mut v = ArrayVec::<[LangItemTarget; 2]>::new();
101 $(
102 v.extend(db.lang_item(cur_crate, $name.into()));
103 )+
104 v
105 }};
106 }
107
108 let lang_item_targets = match self {
109 Ty::Apply(a_ty) => match a_ty.ctor {
110 TypeCtor::Adt(def_id) => {
111 return Some(std::iter::once(def_id.module(db).krate).collect())
112 }
113 TypeCtor::Bool => lang_item_crate!("bool"),
114 TypeCtor::Char => lang_item_crate!("char"),
115 TypeCtor::Float(Uncertain::Known(f)) => match f.bitness {
116 // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)
117 FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"),
118 FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"),
119 },
120 TypeCtor::Int(Uncertain::Known(i)) => lang_item_crate!(i.ty_to_string()),
121 TypeCtor::Str => lang_item_crate!("str_alloc", "str"),
122 TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"),
123 TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"),
124 TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"),
125 _ => return None,
126 },
127 _ => return None,
128 };
129 let res = lang_item_targets
130 .into_iter()
131 .filter_map(|it| match it {
132 LangItemTarget::ImplBlockId(it) => Some(it),
133 _ => None,
134 })
135 .map(|it| it.module(db).krate)
136 .collect();
137 Some(res)
138 }
139}
140/// Look up the method with the given name, returning the actual autoderefed
141/// receiver type (but without autoref applied yet).
142pub(crate) fn lookup_method(
143 ty: &Canonical<Ty>,
144 db: &impl HirDatabase,
145 name: &Name,
146 resolver: &Resolver,
147) -> Option<(Ty, FunctionId)> {
148 iterate_method_candidates(ty, db, resolver, Some(name), LookupMode::MethodCall, |ty, f| match f
149 {
150 AssocItemId::FunctionId(f) => Some((ty.clone(), f)),
151 _ => None,
152 })
153}
154
155/// Whether we're looking up a dotted method call (like `v.len()`) or a path
156/// (like `Vec::new`).
157#[derive(Copy, Clone, Debug, PartialEq, Eq)]
158pub enum LookupMode {
159 /// Looking up a method call like `v.len()`: We only consider candidates
160 /// that have a `self` parameter, and do autoderef.
161 MethodCall,
162 /// Looking up a path like `Vec::new` or `Vec::default`: We consider all
163 /// candidates including associated constants, but don't do autoderef.
164 Path,
165}
166
167// This would be nicer if it just returned an iterator, but that runs into
168// lifetime problems, because we need to borrow temp `CrateImplBlocks`.
169// FIXME add a context type here?
170pub fn iterate_method_candidates<T>(
171 ty: &Canonical<Ty>,
172 db: &impl HirDatabase,
173 resolver: &Resolver,
174 name: Option<&Name>,
175 mode: LookupMode,
176 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
177) -> Option<T> {
178 let krate = resolver.krate()?;
179 match mode {
180 LookupMode::MethodCall => {
181 // For method calls, rust first does any number of autoderef, and then one
182 // autoref (i.e. when the method takes &self or &mut self). We just ignore
183 // the autoref currently -- when we find a method matching the given name,
184 // we assume it fits.
185
186 // Also note that when we've got a receiver like &S, even if the method we
187 // find in the end takes &self, we still do the autoderef step (just as
188 // rustc does an autoderef and then autoref again).
189 let environment = TraitEnvironment::lower(db, resolver);
190 let ty = InEnvironment { value: ty.clone(), environment };
191 for derefed_ty in autoderef::autoderef(db, resolver.krate(), ty) {
192 if let Some(result) =
193 iterate_inherent_methods(&derefed_ty, db, name, mode, krate, &mut callback)
194 {
195 return Some(result);
196 }
197 if let Some(result) = iterate_trait_method_candidates(
198 &derefed_ty,
199 db,
200 resolver,
201 name,
202 mode,
203 &mut callback,
204 ) {
205 return Some(result);
206 }
207 }
208 }
209 LookupMode::Path => {
210 // No autoderef for path lookups
211 if let Some(result) =
212 iterate_inherent_methods(&ty, db, name, mode, krate.into(), &mut callback)
213 {
214 return Some(result);
215 }
216 if let Some(result) =
217 iterate_trait_method_candidates(&ty, db, resolver, name, mode, &mut callback)
218 {
219 return Some(result);
220 }
221 }
222 }
223 None
224}
225
226fn iterate_trait_method_candidates<T>(
227 ty: &Canonical<Ty>,
228 db: &impl HirDatabase,
229 resolver: &Resolver,
230 name: Option<&Name>,
231 mode: LookupMode,
232 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
233) -> Option<T> {
234 let krate = resolver.krate()?;
235 // FIXME: maybe put the trait_env behind a query (need to figure out good input parameters for that)
236 let env = TraitEnvironment::lower(db, resolver);
237 // if ty is `impl Trait` or `dyn Trait`, the trait doesn't need to be in scope
238 let inherent_trait = ty.value.inherent_trait().into_iter();
239 // if we have `T: Trait` in the param env, the trait doesn't need to be in scope
240 let traits_from_env = env
241 .trait_predicates_for_self_ty(&ty.value)
242 .map(|tr| tr.trait_)
243 .flat_map(|t| all_super_traits(db, t));
244 let traits =
245 inherent_trait.chain(traits_from_env).chain(resolver.traits_in_scope(db).into_iter());
246 'traits: for t in traits {
247 let data = db.trait_data(t);
248
249 // we'll be lazy about checking whether the type implements the
250 // trait, but if we find out it doesn't, we'll skip the rest of the
251 // iteration
252 let mut known_implemented = false;
253 for (_name, item) in data.items.iter() {
254 if !is_valid_candidate(db, name, mode, (*item).into()) {
255 continue;
256 }
257 if !known_implemented {
258 let goal = generic_implements_goal(db, env.clone(), t, ty.clone());
259 if db.trait_solve(krate.into(), goal).is_none() {
260 continue 'traits;
261 }
262 }
263 known_implemented = true;
264 if let Some(result) = callback(&ty.value, (*item).into()) {
265 return Some(result);
266 }
267 }
268 }
269 None
270}
271
272fn iterate_inherent_methods<T>(
273 ty: &Canonical<Ty>,
274 db: &impl HirDatabase,
275 name: Option<&Name>,
276 mode: LookupMode,
277 krate: CrateId,
278 mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>,
279) -> Option<T> {
280 for krate in ty.value.def_crates(db, krate)? {
281 let impls = db.impls_in_crate(krate);
282
283 for impl_block in impls.lookup_impl_blocks(&ty.value) {
284 for &item in db.impl_data(impl_block).items.iter() {
285 if !is_valid_candidate(db, name, mode, item) {
286 continue;
287 }
288 if let Some(result) = callback(&ty.value, item.into()) {
289 return Some(result);
290 }
291 }
292 }
293 }
294 None
295}
296
297fn is_valid_candidate(
298 db: &impl HirDatabase,
299 name: Option<&Name>,
300 mode: LookupMode,
301 item: AssocItemId,
302) -> bool {
303 match item {
304 AssocItemId::FunctionId(m) => {
305 let data = db.function_data(m);
306 name.map_or(true, |name| &data.name == name)
307 && (data.has_self_param || mode == LookupMode::Path)
308 }
309 AssocItemId::ConstId(c) => {
310 let data = db.const_data(c);
311 name.map_or(true, |name| data.name.as_ref() == Some(name)) && (mode == LookupMode::Path)
312 }
313 _ => false,
314 }
315}
316
317pub fn implements_trait(
318 ty: &Canonical<Ty>,
319 db: &impl HirDatabase,
320 resolver: &Resolver,
321 krate: CrateId,
322 trait_: TraitId,
323) -> bool {
324 if ty.value.inherent_trait() == Some(trait_) {
325 // FIXME this is a bit of a hack, since Chalk should say the same thing
326 // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet
327 return true;
328 }
329 let env = TraitEnvironment::lower(db, resolver);
330 let goal = generic_implements_goal(db, env, trait_, ty.clone());
331 let solution = db.trait_solve(krate.into(), goal);
332
333 solution.is_some()
334}
335
336/// This creates Substs for a trait with the given Self type and type variables
337/// for all other parameters, to query Chalk with it.
338fn generic_implements_goal(
339 db: &impl HirDatabase,
340 env: Arc<TraitEnvironment>,
341 trait_: TraitId,
342 self_ty: Canonical<Ty>,
343) -> Canonical<InEnvironment<super::Obligation>> {
344 let num_vars = self_ty.num_vars;
345 let substs = super::Substs::build_for_def(db, trait_)
346 .push(self_ty.value)
347 .fill_with_bound_vars(num_vars as u32)
348 .build();
349 let num_vars = substs.len() - 1 + self_ty.num_vars;
350 let trait_ref = TraitRef { trait_, substs };
351 let obligation = super::Obligation::Trait(trait_ref);
352 Canonical { num_vars, value: InEnvironment::new(env, obligation) }
353}
diff --git a/crates/ra_hir_ty/src/op.rs b/crates/ra_hir_ty/src/op.rs
new file mode 100644
index 000000000..09c47a76d
--- /dev/null
+++ b/crates/ra_hir_ty/src/op.rs
@@ -0,0 +1,50 @@
1//! FIXME: write short doc here
2use hir_def::expr::{BinaryOp, CmpOp};
3
4use super::{InferTy, Ty, TypeCtor};
5use crate::ApplicationTy;
6
7pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty {
8 match op {
9 BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => Ty::simple(TypeCtor::Bool),
10 BinaryOp::Assignment { .. } => Ty::unit(),
11 BinaryOp::ArithOp(_) => match rhs_ty {
12 Ty::Apply(ApplicationTy { ctor, .. }) => match ctor {
13 TypeCtor::Int(..) | TypeCtor::Float(..) => rhs_ty,
14 _ => Ty::Unknown,
15 },
16 Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => rhs_ty,
17 _ => Ty::Unknown,
18 },
19 }
20}
21
22pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty {
23 match op {
24 BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool),
25 BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => {
26 match lhs_ty {
27 Ty::Apply(ApplicationTy { ctor, .. }) => match ctor {
28 TypeCtor::Int(..)
29 | TypeCtor::Float(..)
30 | TypeCtor::Str
31 | TypeCtor::Char
32 | TypeCtor::Bool => lhs_ty,
33 _ => Ty::Unknown,
34 },
35 Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty,
36 _ => Ty::Unknown,
37 }
38 }
39 BinaryOp::CmpOp(CmpOp::Ord { .. })
40 | BinaryOp::Assignment { op: Some(_) }
41 | BinaryOp::ArithOp(_) => match lhs_ty {
42 Ty::Apply(ApplicationTy { ctor, .. }) => match ctor {
43 TypeCtor::Int(..) | TypeCtor::Float(..) => lhs_ty,
44 _ => Ty::Unknown,
45 },
46 Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty,
47 _ => Ty::Unknown,
48 },
49 }
50}
diff --git a/crates/ra_hir_ty/src/primitive.rs b/crates/ra_hir_ty/src/primitive.rs
new file mode 100644
index 000000000..02a8179d9
--- /dev/null
+++ b/crates/ra_hir_ty/src/primitive.rs
@@ -0,0 +1,193 @@
1//! Defines primitive types, which have a couple of peculiarities:
2//!
3//! * during type inference, they can be uncertain (ie, `let x = 92;`)
4//! * they don't belong to any particular crate.
5
6use std::fmt;
7
8pub use hir_def::builtin_type::{BuiltinFloat, BuiltinInt, FloatBitness, IntBitness, Signedness};
9
10#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
11pub enum Uncertain<T> {
12 Unknown,
13 Known(T),
14}
15
16impl From<IntTy> for Uncertain<IntTy> {
17 fn from(ty: IntTy) -> Self {
18 Uncertain::Known(ty)
19 }
20}
21
22impl fmt::Display for Uncertain<IntTy> {
23 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24 match *self {
25 Uncertain::Unknown => write!(f, "{{integer}}"),
26 Uncertain::Known(ty) => write!(f, "{}", ty),
27 }
28 }
29}
30
31impl From<FloatTy> for Uncertain<FloatTy> {
32 fn from(ty: FloatTy) -> Self {
33 Uncertain::Known(ty)
34 }
35}
36
37impl fmt::Display for Uncertain<FloatTy> {
38 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 match *self {
40 Uncertain::Unknown => write!(f, "{{float}}"),
41 Uncertain::Known(ty) => write!(f, "{}", ty),
42 }
43 }
44}
45
46#[derive(Copy, Clone, Eq, PartialEq, Hash)]
47pub struct IntTy {
48 pub signedness: Signedness,
49 pub bitness: IntBitness,
50}
51
52impl fmt::Debug for IntTy {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 fmt::Display::fmt(self, f)
55 }
56}
57
58impl fmt::Display for IntTy {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 write!(f, "{}", self.ty_to_string())
61 }
62}
63
64impl IntTy {
65 pub fn isize() -> IntTy {
66 IntTy { signedness: Signedness::Signed, bitness: IntBitness::Xsize }
67 }
68
69 pub fn i8() -> IntTy {
70 IntTy { signedness: Signedness::Signed, bitness: IntBitness::X8 }
71 }
72
73 pub fn i16() -> IntTy {
74 IntTy { signedness: Signedness::Signed, bitness: IntBitness::X16 }
75 }
76
77 pub fn i32() -> IntTy {
78 IntTy { signedness: Signedness::Signed, bitness: IntBitness::X32 }
79 }
80
81 pub fn i64() -> IntTy {
82 IntTy { signedness: Signedness::Signed, bitness: IntBitness::X64 }
83 }
84
85 pub fn i128() -> IntTy {
86 IntTy { signedness: Signedness::Signed, bitness: IntBitness::X128 }
87 }
88
89 pub fn usize() -> IntTy {
90 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize }
91 }
92
93 pub fn u8() -> IntTy {
94 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X8 }
95 }
96
97 pub fn u16() -> IntTy {
98 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X16 }
99 }
100
101 pub fn u32() -> IntTy {
102 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X32 }
103 }
104
105 pub fn u64() -> IntTy {
106 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X64 }
107 }
108
109 pub fn u128() -> IntTy {
110 IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X128 }
111 }
112
113 pub fn ty_to_string(self) -> &'static str {
114 match (self.signedness, self.bitness) {
115 (Signedness::Signed, IntBitness::Xsize) => "isize",
116 (Signedness::Signed, IntBitness::X8) => "i8",
117 (Signedness::Signed, IntBitness::X16) => "i16",
118 (Signedness::Signed, IntBitness::X32) => "i32",
119 (Signedness::Signed, IntBitness::X64) => "i64",
120 (Signedness::Signed, IntBitness::X128) => "i128",
121 (Signedness::Unsigned, IntBitness::Xsize) => "usize",
122 (Signedness::Unsigned, IntBitness::X8) => "u8",
123 (Signedness::Unsigned, IntBitness::X16) => "u16",
124 (Signedness::Unsigned, IntBitness::X32) => "u32",
125 (Signedness::Unsigned, IntBitness::X64) => "u64",
126 (Signedness::Unsigned, IntBitness::X128) => "u128",
127 }
128 }
129}
130
131#[derive(Copy, Clone, PartialEq, Eq, Hash)]
132pub struct FloatTy {
133 pub bitness: FloatBitness,
134}
135
136impl fmt::Debug for FloatTy {
137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 fmt::Display::fmt(self, f)
139 }
140}
141
142impl fmt::Display for FloatTy {
143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144 write!(f, "{}", self.ty_to_string())
145 }
146}
147
148impl FloatTy {
149 pub fn f32() -> FloatTy {
150 FloatTy { bitness: FloatBitness::X32 }
151 }
152
153 pub fn f64() -> FloatTy {
154 FloatTy { bitness: FloatBitness::X64 }
155 }
156
157 pub fn ty_to_string(self) -> &'static str {
158 match self.bitness {
159 FloatBitness::X32 => "f32",
160 FloatBitness::X64 => "f64",
161 }
162 }
163}
164
165impl From<BuiltinInt> for IntTy {
166 fn from(t: BuiltinInt) -> Self {
167 IntTy { signedness: t.signedness, bitness: t.bitness }
168 }
169}
170
171impl From<BuiltinFloat> for FloatTy {
172 fn from(t: BuiltinFloat) -> Self {
173 FloatTy { bitness: t.bitness }
174 }
175}
176
177impl From<Option<BuiltinInt>> for Uncertain<IntTy> {
178 fn from(t: Option<BuiltinInt>) -> Self {
179 match t {
180 None => Uncertain::Unknown,
181 Some(t) => Uncertain::Known(t.into()),
182 }
183 }
184}
185
186impl From<Option<BuiltinFloat>> for Uncertain<FloatTy> {
187 fn from(t: Option<BuiltinFloat>) -> Self {
188 match t {
189 None => Uncertain::Unknown,
190 Some(t) => Uncertain::Known(t.into()),
191 }
192 }
193}
diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs
new file mode 100644
index 000000000..1dc9793f9
--- /dev/null
+++ b/crates/ra_hir_ty/src/test_db.rs
@@ -0,0 +1,146 @@
1//! Database used for testing `hir`.
2
3use std::{
4 panic,
5 sync::{Arc, Mutex},
6};
7
8use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId};
9use hir_expand::diagnostics::DiagnosticSink;
10use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase};
11
12use crate::{db::HirDatabase, expr::ExprValidator};
13
14#[salsa::database(
15 ra_db::SourceDatabaseExtStorage,
16 ra_db::SourceDatabaseStorage,
17 hir_expand::db::AstDatabaseStorage,
18 hir_def::db::InternDatabaseStorage,
19 hir_def::db::DefDatabaseStorage,
20 crate::db::HirDatabaseStorage
21)]
22#[derive(Debug, Default)]
23pub struct TestDB {
24 events: Mutex<Option<Vec<salsa::Event<TestDB>>>>,
25 runtime: salsa::Runtime<TestDB>,
26}
27
28impl salsa::Database for TestDB {
29 fn salsa_runtime(&self) -> &salsa::Runtime<TestDB> {
30 &self.runtime
31 }
32
33 fn salsa_runtime_mut(&mut self) -> &mut salsa::Runtime<Self> {
34 &mut self.runtime
35 }
36
37 fn salsa_event(&self, event: impl Fn() -> salsa::Event<TestDB>) {
38 let mut events = self.events.lock().unwrap();
39 if let Some(events) = &mut *events {
40 events.push(event());
41 }
42 }
43}
44
45impl salsa::ParallelDatabase for TestDB {
46 fn snapshot(&self) -> salsa::Snapshot<TestDB> {
47 salsa::Snapshot::new(TestDB {
48 events: Default::default(),
49 runtime: self.runtime.snapshot(self),
50 })
51 }
52}
53
54impl panic::RefUnwindSafe for TestDB {}
55
56impl FileLoader for TestDB {
57 fn file_text(&self, file_id: FileId) -> Arc<String> {
58 FileLoaderDelegate(self).file_text(file_id)
59 }
60 fn resolve_relative_path(
61 &self,
62 anchor: FileId,
63 relative_path: &RelativePath,
64 ) -> Option<FileId> {
65 FileLoaderDelegate(self).resolve_relative_path(anchor, relative_path)
66 }
67 fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> {
68 FileLoaderDelegate(self).relevant_crates(file_id)
69 }
70}
71
72impl TestDB {
73 pub fn module_for_file(&self, file_id: FileId) -> ModuleId {
74 for &krate in self.relevant_crates(file_id).iter() {
75 let crate_def_map = self.crate_def_map(krate);
76 for (local_id, data) in crate_def_map.modules.iter() {
77 if data.definition == Some(file_id) {
78 return ModuleId { krate, local_id };
79 }
80 }
81 }
82 panic!("Can't find module for file")
83 }
84
85 // FIXME: don't duplicate this
86 pub fn diagnostics(&self) -> String {
87 let mut buf = String::new();
88 let crate_graph = self.crate_graph();
89 for krate in crate_graph.iter().next() {
90 let crate_def_map = self.crate_def_map(krate);
91
92 let mut fns = Vec::new();
93 for (module_id, _) in crate_def_map.modules.iter() {
94 for decl in crate_def_map[module_id].scope.declarations() {
95 match decl {
96 ModuleDefId::FunctionId(f) => fns.push(f),
97 _ => (),
98 }
99 }
100
101 for &impl_id in crate_def_map[module_id].impls.iter() {
102 let impl_data = self.impl_data(impl_id);
103 for item in impl_data.items.iter() {
104 if let AssocItemId::FunctionId(f) = item {
105 fns.push(*f)
106 }
107 }
108 }
109 }
110
111 for f in fns {
112 let infer = self.infer(f.into());
113 let mut sink = DiagnosticSink::new(|d| {
114 buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message());
115 });
116 infer.add_diagnostics(self, f, &mut sink);
117 let mut validator = ExprValidator::new(f, infer, &mut sink);
118 validator.validate_body(self);
119 }
120 }
121 buf
122 }
123}
124
125impl TestDB {
126 pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event<TestDB>> {
127 *self.events.lock().unwrap() = Some(Vec::new());
128 f();
129 self.events.lock().unwrap().take().unwrap()
130 }
131
132 pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
133 let events = self.log(f);
134 events
135 .into_iter()
136 .filter_map(|e| match e.kind {
137 // This pretty horrible, but `Debug` is the only way to inspect
138 // QueryDescriptor at the moment.
139 salsa::EventKind::WillExecute { database_key } => {
140 Some(format!("{:?}", database_key))
141 }
142 _ => None,
143 })
144 .collect()
145 }
146}
diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs
new file mode 100644
index 000000000..c8461b447
--- /dev/null
+++ b/crates/ra_hir_ty/src/tests.rs
@@ -0,0 +1,4958 @@
1mod never_type;
2mod coercion;
3
4use std::fmt::Write;
5use std::sync::Arc;
6
7use hir_def::{
8 body::BodySourceMap, db::DefDatabase, nameres::CrateDefMap, AssocItemId, DefWithBodyId,
9 LocalModuleId, Lookup, ModuleDefId,
10};
11use hir_expand::Source;
12use insta::assert_snapshot;
13use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase};
14use ra_syntax::{
15 algo,
16 ast::{self, AstNode},
17};
18use test_utils::covers;
19
20use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult};
21
22// These tests compare the inference results for all expressions in a file
23// against snapshots of the expected results using insta. Use cargo-insta to
24// update the snapshots.
25
26#[test]
27fn cfg_impl_block() {
28 let (db, pos) = TestDB::with_position(
29 r#"
30//- /main.rs crate:main deps:foo cfg:test
31use foo::S as T;
32struct S;
33
34#[cfg(test)]
35impl S {
36 fn foo1(&self) -> i32 { 0 }
37}
38
39#[cfg(not(test))]
40impl S {
41 fn foo2(&self) -> i32 { 0 }
42}
43
44fn test() {
45 let t = (S.foo1(), S.foo2(), T.foo3(), T.foo4());
46 t<|>;
47}
48
49//- /foo.rs crate:foo
50struct S;
51
52#[cfg(not(test))]
53impl S {
54 fn foo3(&self) -> i32 { 0 }
55}
56
57#[cfg(test)]
58impl S {
59 fn foo4(&self) -> i32 { 0 }
60}
61"#,
62 );
63 assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos));
64}
65
66#[test]
67fn infer_await() {
68 let (db, pos) = TestDB::with_position(
69 r#"
70//- /main.rs crate:main deps:std
71
72struct IntFuture;
73
74impl Future for IntFuture {
75 type Output = u64;
76}
77
78fn test() {
79 let r = IntFuture;
80 let v = r.await;
81 v<|>;
82}
83
84//- /std.rs crate:std
85#[prelude_import] use future::*;
86mod future {
87 trait Future {
88 type Output;
89 }
90}
91
92"#,
93 );
94 assert_eq!("u64", type_at_pos(&db, pos));
95}
96
97#[test]
98fn infer_box() {
99 let (db, pos) = TestDB::with_position(
100 r#"
101//- /main.rs crate:main deps:std
102
103fn test() {
104 let x = box 1;
105 let t = (x, box x, box &1, box [1]);
106 t<|>;
107}
108
109//- /std.rs crate:std
110#[prelude_import] use prelude::*;
111mod prelude {}
112
113mod boxed {
114 pub struct Box<T: ?Sized> {
115 inner: *mut T,
116 }
117}
118
119"#,
120 );
121 assert_eq!("(Box<i32>, Box<Box<i32>>, Box<&i32>, Box<[i32;_]>)", type_at_pos(&db, pos));
122}
123
124#[test]
125fn infer_adt_self() {
126 let (db, pos) = TestDB::with_position(
127 r#"
128//- /main.rs
129enum Nat { Succ(Self), Demo(Nat), Zero }
130
131fn test() {
132 let foo: Nat = Nat::Zero;
133 if let Nat::Succ(x) = foo {
134 x<|>
135 }
136}
137
138"#,
139 );
140 assert_eq!("Nat", type_at_pos(&db, pos));
141}
142
143#[test]
144fn infer_try() {
145 let (db, pos) = TestDB::with_position(
146 r#"
147//- /main.rs crate:main deps:std
148
149fn test() {
150 let r: Result<i32, u64> = Result::Ok(1);
151 let v = r?;
152 v<|>;
153}
154
155//- /std.rs crate:std
156
157#[prelude_import] use ops::*;
158mod ops {
159 trait Try {
160 type Ok;
161 type Error;
162 }
163}
164
165#[prelude_import] use result::*;
166mod result {
167 enum Result<O, E> {
168 Ok(O),
169 Err(E)
170 }
171
172 impl<O, E> crate::ops::Try for Result<O, E> {
173 type Ok = O;
174 type Error = E;
175 }
176}
177
178"#,
179 );
180 assert_eq!("i32", type_at_pos(&db, pos));
181}
182
183#[test]
184fn infer_for_loop() {
185 let (db, pos) = TestDB::with_position(
186 r#"
187//- /main.rs crate:main deps:std
188
189use std::collections::Vec;
190
191fn test() {
192 let v = Vec::new();
193 v.push("foo");
194 for x in v {
195 x<|>;
196 }
197}
198
199//- /std.rs crate:std
200
201#[prelude_import] use iter::*;
202mod iter {
203 trait IntoIterator {
204 type Item;
205 }
206}
207
208mod collections {
209 struct Vec<T> {}
210 impl<T> Vec<T> {
211 fn new() -> Self { Vec {} }
212 fn push(&mut self, t: T) { }
213 }
214
215 impl<T> crate::iter::IntoIterator for Vec<T> {
216 type Item=T;
217 }
218}
219"#,
220 );
221 assert_eq!("&str", type_at_pos(&db, pos));
222}
223
224#[test]
225fn infer_while_let() {
226 let (db, pos) = TestDB::with_position(
227 r#"
228//- /main.rs
229enum Option<T> { Some(T), None }
230
231fn test() {
232 let foo: Option<f32> = None;
233 while let Option::Some(x) = foo {
234 <|>x
235 }
236}
237
238"#,
239 );
240 assert_eq!("f32", type_at_pos(&db, pos));
241}
242
243#[test]
244fn infer_basics() {
245 assert_snapshot!(
246 infer(r#"
247fn test(a: u32, b: isize, c: !, d: &str) {
248 a;
249 b;
250 c;
251 d;
252 1usize;
253 1isize;
254 "test";
255 1.0f32;
256}"#),
257 @r###"
258 [9; 10) 'a': u32
259 [17; 18) 'b': isize
260 [27; 28) 'c': !
261 [33; 34) 'd': &str
262 [42; 121) '{ ...f32; }': !
263 [48; 49) 'a': u32
264 [55; 56) 'b': isize
265 [62; 63) 'c': !
266 [69; 70) 'd': &str
267 [76; 82) '1usize': usize
268 [88; 94) '1isize': isize
269 [100; 106) '"test"': &str
270 [112; 118) '1.0f32': f32
271 "###
272 );
273}
274
275#[test]
276fn infer_let() {
277 assert_snapshot!(
278 infer(r#"
279fn test() {
280 let a = 1isize;
281 let b: usize = 1;
282 let c = b;
283 let d: u32;
284 let e;
285 let f: i32 = e;
286}
287"#),
288 @r###"
289 [11; 118) '{ ...= e; }': ()
290 [21; 22) 'a': isize
291 [25; 31) '1isize': isize
292 [41; 42) 'b': usize
293 [52; 53) '1': usize
294 [63; 64) 'c': usize
295 [67; 68) 'b': usize
296 [78; 79) 'd': u32
297 [94; 95) 'e': i32
298 [105; 106) 'f': i32
299 [114; 115) 'e': i32
300 "###
301 );
302}
303
304#[test]
305fn infer_paths() {
306 assert_snapshot!(
307 infer(r#"
308fn a() -> u32 { 1 }
309
310mod b {
311 fn c() -> u32 { 1 }
312}
313
314fn test() {
315 a();
316 b::c();
317}
318"#),
319 @r###"
320 [15; 20) '{ 1 }': u32
321 [17; 18) '1': u32
322 [48; 53) '{ 1 }': u32
323 [50; 51) '1': u32
324 [67; 91) '{ ...c(); }': ()
325 [73; 74) 'a': fn a() -> u32
326 [73; 76) 'a()': u32
327 [82; 86) 'b::c': fn c() -> u32
328 [82; 88) 'b::c()': u32
329 "###
330 );
331}
332
333#[test]
334fn infer_path_type() {
335 assert_snapshot!(
336 infer(r#"
337struct S;
338
339impl S {
340 fn foo() -> i32 { 1 }
341}
342
343fn test() {
344 S::foo();
345 <S>::foo();
346}
347"#),
348 @r###"
349 [41; 46) '{ 1 }': i32
350 [43; 44) '1': i32
351 [60; 93) '{ ...o(); }': ()
352 [66; 72) 'S::foo': fn foo() -> i32
353 [66; 74) 'S::foo()': i32
354 [80; 88) '<S>::foo': fn foo() -> i32
355 [80; 90) '<S>::foo()': i32
356 "###
357 );
358}
359
360#[test]
361fn infer_slice_method() {
362 assert_snapshot!(
363 infer(r#"
364#[lang = "slice"]
365impl<T> [T] {
366 fn foo(&self) -> T {
367 loop {}
368 }
369}
370
371#[lang = "slice_alloc"]
372impl<T> [T] {}
373
374fn test() {
375 <[_]>::foo(b"foo");
376}
377"#),
378 @r###"
379 [45; 49) 'self': &[T]
380 [56; 79) '{ ... }': T
381 [66; 73) 'loop {}': !
382 [71; 73) '{}': ()
383 [133; 160) '{ ...o"); }': ()
384 [139; 149) '<[_]>::foo': fn foo<u8>(&[T]) -> T
385 [139; 157) '<[_]>:..."foo")': u8
386 [150; 156) 'b"foo"': &[u8]
387 "###
388 );
389}
390
391#[test]
392fn infer_struct() {
393 assert_snapshot!(
394 infer(r#"
395struct A {
396 b: B,
397 c: C,
398}
399struct B;
400struct C(usize);
401
402fn test() {
403 let c = C(1);
404 B;
405 let a: A = A { b: B, c: C(1) };
406 a.b;
407 a.c;
408}
409"#),
410 @r###"
411 [72; 154) '{ ...a.c; }': ()
412 [82; 83) 'c': C
413 [86; 87) 'C': C(usize) -> C
414 [86; 90) 'C(1)': C
415 [88; 89) '1': usize
416 [96; 97) 'B': B
417 [107; 108) 'a': A
418 [114; 133) 'A { b:...C(1) }': A
419 [121; 122) 'B': B
420 [127; 128) 'C': C(usize) -> C
421 [127; 131) 'C(1)': C
422 [129; 130) '1': usize
423 [139; 140) 'a': A
424 [139; 142) 'a.b': B
425 [148; 149) 'a': A
426 [148; 151) 'a.c': C
427 "###
428 );
429}
430
431#[test]
432fn infer_enum() {
433 assert_snapshot!(
434 infer(r#"
435enum E {
436 V1 { field: u32 },
437 V2
438}
439fn test() {
440 E::V1 { field: 1 };
441 E::V2;
442}"#),
443 @r###"
444 [48; 82) '{ E:...:V2; }': ()
445 [52; 70) 'E::V1 ...d: 1 }': E
446 [67; 68) '1': u32
447 [74; 79) 'E::V2': E
448 "###
449 );
450}
451
452#[test]
453fn infer_refs() {
454 assert_snapshot!(
455 infer(r#"
456fn test(a: &u32, b: &mut u32, c: *const u32, d: *mut u32) {
457 a;
458 *a;
459 &a;
460 &mut a;
461 b;
462 *b;
463 &b;
464 c;
465 *c;
466 d;
467 *d;
468}
469"#),
470 @r###"
471 [9; 10) 'a': &u32
472 [18; 19) 'b': &mut u32
473 [31; 32) 'c': *const u32
474 [46; 47) 'd': *mut u32
475 [59; 150) '{ ... *d; }': ()
476 [65; 66) 'a': &u32
477 [72; 74) '*a': u32
478 [73; 74) 'a': &u32
479 [80; 82) '&a': &&u32
480 [81; 82) 'a': &u32
481 [88; 94) '&mut a': &mut &u32
482 [93; 94) 'a': &u32
483 [100; 101) 'b': &mut u32
484 [107; 109) '*b': u32
485 [108; 109) 'b': &mut u32
486 [115; 117) '&b': &&mut u32
487 [116; 117) 'b': &mut u32
488 [123; 124) 'c': *const u32
489 [130; 132) '*c': u32
490 [131; 132) 'c': *const u32
491 [138; 139) 'd': *mut u32
492 [145; 147) '*d': u32
493 [146; 147) 'd': *mut u32
494 "###
495 );
496}
497
498#[test]
499fn infer_literals() {
500 assert_snapshot!(
501 infer(r##"
502fn test() {
503 5i32;
504 5f32;
505 5f64;
506 "hello";
507 b"bytes";
508 'c';
509 b'b';
510 3.14;
511 5000;
512 false;
513 true;
514 r#"
515 //! doc
516 // non-doc
517 mod foo {}
518 "#;
519 br#"yolo"#;
520}
521"##),
522 @r###"
523 [11; 221) '{ ...o"#; }': ()
524 [17; 21) '5i32': i32
525 [27; 31) '5f32': f32
526 [37; 41) '5f64': f64
527 [47; 54) '"hello"': &str
528 [60; 68) 'b"bytes"': &[u8]
529 [74; 77) ''c'': char
530 [83; 87) 'b'b'': u8
531 [93; 97) '3.14': f64
532 [103; 107) '5000': i32
533 [113; 118) 'false': bool
534 [124; 128) 'true': bool
535 [134; 202) 'r#" ... "#': &str
536 [208; 218) 'br#"yolo"#': &[u8]
537 "###
538 );
539}
540
541#[test]
542fn infer_unary_op() {
543 assert_snapshot!(
544 infer(r#"
545enum SomeType {}
546
547fn test(x: SomeType) {
548 let b = false;
549 let c = !b;
550 let a = 100;
551 let d: i128 = -a;
552 let e = -100;
553 let f = !!!true;
554 let g = !42;
555 let h = !10u32;
556 let j = !a;
557 -3.14;
558 !3;
559 -x;
560 !x;
561 -"hello";
562 !"hello";
563}
564"#),
565 @r###"
566 [27; 28) 'x': SomeType
567 [40; 272) '{ ...lo"; }': ()
568 [50; 51) 'b': bool
569 [54; 59) 'false': bool
570 [69; 70) 'c': bool
571 [73; 75) '!b': bool
572 [74; 75) 'b': bool
573 [85; 86) 'a': i128
574 [89; 92) '100': i128
575 [102; 103) 'd': i128
576 [112; 114) '-a': i128
577 [113; 114) 'a': i128
578 [124; 125) 'e': i32
579 [128; 132) '-100': i32
580 [129; 132) '100': i32
581 [142; 143) 'f': bool
582 [146; 153) '!!!true': bool
583 [147; 153) '!!true': bool
584 [148; 153) '!true': bool
585 [149; 153) 'true': bool
586 [163; 164) 'g': i32
587 [167; 170) '!42': i32
588 [168; 170) '42': i32
589 [180; 181) 'h': u32
590 [184; 190) '!10u32': u32
591 [185; 190) '10u32': u32
592 [200; 201) 'j': i128
593 [204; 206) '!a': i128
594 [205; 206) 'a': i128
595 [212; 217) '-3.14': f64
596 [213; 217) '3.14': f64
597 [223; 225) '!3': i32
598 [224; 225) '3': i32
599 [231; 233) '-x': {unknown}
600 [232; 233) 'x': SomeType
601 [239; 241) '!x': {unknown}
602 [240; 241) 'x': SomeType
603 [247; 255) '-"hello"': {unknown}
604 [248; 255) '"hello"': &str
605 [261; 269) '!"hello"': {unknown}
606 [262; 269) '"hello"': &str
607 "###
608 );
609}
610
611#[test]
612fn infer_backwards() {
613 assert_snapshot!(
614 infer(r#"
615fn takes_u32(x: u32) {}
616
617struct S { i32_field: i32 }
618
619fn test() -> &mut &f64 {
620 let a = unknown_function();
621 takes_u32(a);
622 let b = unknown_function();
623 S { i32_field: b };
624 let c = unknown_function();
625 &mut &c
626}
627"#),
628 @r###"
629 [14; 15) 'x': u32
630 [22; 24) '{}': ()
631 [78; 231) '{ ...t &c }': &mut &f64
632 [88; 89) 'a': u32
633 [92; 108) 'unknow...nction': {unknown}
634 [92; 110) 'unknow...tion()': u32
635 [116; 125) 'takes_u32': fn takes_u32(u32) -> ()
636 [116; 128) 'takes_u32(a)': ()
637 [126; 127) 'a': u32
638 [138; 139) 'b': i32
639 [142; 158) 'unknow...nction': {unknown}
640 [142; 160) 'unknow...tion()': i32
641 [166; 184) 'S { i3...d: b }': S
642 [181; 182) 'b': i32
643 [194; 195) 'c': f64
644 [198; 214) 'unknow...nction': {unknown}
645 [198; 216) 'unknow...tion()': f64
646 [222; 229) '&mut &c': &mut &f64
647 [227; 229) '&c': &f64
648 [228; 229) 'c': f64
649 "###
650 );
651}
652
653#[test]
654fn infer_self() {
655 assert_snapshot!(
656 infer(r#"
657struct S;
658
659impl S {
660 fn test(&self) {
661 self;
662 }
663 fn test2(self: &Self) {
664 self;
665 }
666 fn test3() -> Self {
667 S {}
668 }
669 fn test4() -> Self {
670 Self {}
671 }
672}
673"#),
674 @r###"
675 [34; 38) 'self': &S
676 [40; 61) '{ ... }': ()
677 [50; 54) 'self': &S
678 [75; 79) 'self': &S
679 [88; 109) '{ ... }': ()
680 [98; 102) 'self': &S
681 [133; 153) '{ ... }': S
682 [143; 147) 'S {}': S
683 [177; 200) '{ ... }': S
684 [187; 194) 'Self {}': S
685 "###
686 );
687}
688
689#[test]
690fn infer_binary_op() {
691 assert_snapshot!(
692 infer(r#"
693fn f(x: bool) -> i32 {
694 0i32
695}
696
697fn test() -> bool {
698 let x = a && b;
699 let y = true || false;
700 let z = x == y;
701 let t = x != y;
702 let minus_forty: isize = -40isize;
703 let h = minus_forty <= CONST_2;
704 let c = f(z || y) + 5;
705 let d = b;
706 let g = minus_forty ^= i;
707 let ten: usize = 10;
708 let ten_is_eleven = ten == some_num;
709
710 ten < 3
711}
712"#),
713 @r###"
714 [6; 7) 'x': bool
715 [22; 34) '{ 0i32 }': i32
716 [28; 32) '0i32': i32
717 [54; 370) '{ ... < 3 }': bool
718 [64; 65) 'x': bool
719 [68; 69) 'a': bool
720 [68; 74) 'a && b': bool
721 [73; 74) 'b': bool
722 [84; 85) 'y': bool
723 [88; 92) 'true': bool
724 [88; 101) 'true || false': bool
725 [96; 101) 'false': bool
726 [111; 112) 'z': bool
727 [115; 116) 'x': bool
728 [115; 121) 'x == y': bool
729 [120; 121) 'y': bool
730 [131; 132) 't': bool
731 [135; 136) 'x': bool
732 [135; 141) 'x != y': bool
733 [140; 141) 'y': bool
734 [151; 162) 'minus_forty': isize
735 [172; 180) '-40isize': isize
736 [173; 180) '40isize': isize
737 [190; 191) 'h': bool
738 [194; 205) 'minus_forty': isize
739 [194; 216) 'minus_...ONST_2': bool
740 [209; 216) 'CONST_2': isize
741 [226; 227) 'c': i32
742 [230; 231) 'f': fn f(bool) -> i32
743 [230; 239) 'f(z || y)': i32
744 [230; 243) 'f(z || y) + 5': i32
745 [232; 233) 'z': bool
746 [232; 238) 'z || y': bool
747 [237; 238) 'y': bool
748 [242; 243) '5': i32
749 [253; 254) 'd': {unknown}
750 [257; 258) 'b': {unknown}
751 [268; 269) 'g': ()
752 [272; 283) 'minus_forty': isize
753 [272; 288) 'minus_...y ^= i': ()
754 [287; 288) 'i': isize
755 [298; 301) 'ten': usize
756 [311; 313) '10': usize
757 [323; 336) 'ten_is_eleven': bool
758 [339; 342) 'ten': usize
759 [339; 354) 'ten == some_num': bool
760 [346; 354) 'some_num': usize
761 [361; 364) 'ten': usize
762 [361; 368) 'ten < 3': bool
763 [367; 368) '3': usize
764 "###
765 );
766}
767
768#[test]
769fn infer_field_autoderef() {
770 assert_snapshot!(
771 infer(r#"
772struct A {
773 b: B,
774}
775struct B;
776
777fn test1(a: A) {
778 let a1 = a;
779 a1.b;
780 let a2 = &a;
781 a2.b;
782 let a3 = &mut a;
783 a3.b;
784 let a4 = &&&&&&&a;
785 a4.b;
786 let a5 = &mut &&mut &&mut a;
787 a5.b;
788}
789
790fn test2(a1: *const A, a2: *mut A) {
791 a1.b;
792 a2.b;
793}
794"#),
795 @r###"
796 [44; 45) 'a': A
797 [50; 213) '{ ...5.b; }': ()
798 [60; 62) 'a1': A
799 [65; 66) 'a': A
800 [72; 74) 'a1': A
801 [72; 76) 'a1.b': B
802 [86; 88) 'a2': &A
803 [91; 93) '&a': &A
804 [92; 93) 'a': A
805 [99; 101) 'a2': &A
806 [99; 103) 'a2.b': B
807 [113; 115) 'a3': &mut A
808 [118; 124) '&mut a': &mut A
809 [123; 124) 'a': A
810 [130; 132) 'a3': &mut A
811 [130; 134) 'a3.b': B
812 [144; 146) 'a4': &&&&&&&A
813 [149; 157) '&&&&&&&a': &&&&&&&A
814 [150; 157) '&&&&&&a': &&&&&&A
815 [151; 157) '&&&&&a': &&&&&A
816 [152; 157) '&&&&a': &&&&A
817 [153; 157) '&&&a': &&&A
818 [154; 157) '&&a': &&A
819 [155; 157) '&a': &A
820 [156; 157) 'a': A
821 [163; 165) 'a4': &&&&&&&A
822 [163; 167) 'a4.b': B
823 [177; 179) 'a5': &mut &&mut &&mut A
824 [182; 200) '&mut &...&mut a': &mut &&mut &&mut A
825 [187; 200) '&&mut &&mut a': &&mut &&mut A
826 [188; 200) '&mut &&mut a': &mut &&mut A
827 [193; 200) '&&mut a': &&mut A
828 [194; 200) '&mut a': &mut A
829 [199; 200) 'a': A
830 [206; 208) 'a5': &mut &&mut &&mut A
831 [206; 210) 'a5.b': B
832 [224; 226) 'a1': *const A
833 [238; 240) 'a2': *mut A
834 [250; 273) '{ ...2.b; }': ()
835 [256; 258) 'a1': *const A
836 [256; 260) 'a1.b': B
837 [266; 268) 'a2': *mut A
838 [266; 270) 'a2.b': B
839 "###
840 );
841}
842
843#[test]
844fn infer_argument_autoderef() {
845 assert_snapshot!(
846 infer(r#"
847#[lang = "deref"]
848pub trait Deref {
849 type Target;
850 fn deref(&self) -> &Self::Target;
851}
852
853struct A<T>(T);
854
855impl<T> A<T> {
856 fn foo(&self) -> &T {
857 &self.0
858 }
859}
860
861struct B<T>(T);
862
863impl<T> Deref for B<T> {
864 type Target = T;
865 fn deref(&self) -> &Self::Target {
866 &self.0
867 }
868}
869
870fn test() {
871 let t = A::foo(&&B(B(A(42))));
872}
873"#),
874 @r###"
875 [68; 72) 'self': &Self
876 [139; 143) 'self': &A<T>
877 [151; 174) '{ ... }': &T
878 [161; 168) '&self.0': &T
879 [162; 166) 'self': &A<T>
880 [162; 168) 'self.0': T
881 [255; 259) 'self': &B<T>
882 [278; 301) '{ ... }': &T
883 [288; 295) '&self.0': &T
884 [289; 293) 'self': &B<T>
885 [289; 295) 'self.0': T
886 [315; 353) '{ ...))); }': ()
887 [325; 326) 't': &i32
888 [329; 335) 'A::foo': fn foo<i32>(&A<T>) -> &T
889 [329; 350) 'A::foo...42))))': &i32
890 [336; 349) '&&B(B(A(42)))': &&B<B<A<i32>>>
891 [337; 349) '&B(B(A(42)))': &B<B<A<i32>>>
892 [338; 339) 'B': B<B<A<i32>>>(T) -> B<T>
893 [338; 349) 'B(B(A(42)))': B<B<A<i32>>>
894 [340; 341) 'B': B<A<i32>>(T) -> B<T>
895 [340; 348) 'B(A(42))': B<A<i32>>
896 [342; 343) 'A': A<i32>(T) -> A<T>
897 [342; 347) 'A(42)': A<i32>
898 [344; 346) '42': i32
899 "###
900 );
901}
902
903#[test]
904fn infer_method_argument_autoderef() {
905 assert_snapshot!(
906 infer(r#"
907#[lang = "deref"]
908pub trait Deref {
909 type Target;
910 fn deref(&self) -> &Self::Target;
911}
912
913struct A<T>(*mut T);
914
915impl<T> A<T> {
916 fn foo(&self, x: &A<T>) -> &T {
917 &*x.0
918 }
919}
920
921struct B<T>(T);
922
923impl<T> Deref for B<T> {
924 type Target = T;
925 fn deref(&self) -> &Self::Target {
926 &self.0
927 }
928}
929
930fn test(a: A<i32>) {
931 let t = A(0 as *mut _).foo(&&B(B(a)));
932}
933"#),
934 @r###"
935 [68; 72) 'self': &Self
936 [144; 148) 'self': &A<T>
937 [150; 151) 'x': &A<T>
938 [166; 187) '{ ... }': &T
939 [176; 181) '&*x.0': &T
940 [177; 181) '*x.0': T
941 [178; 179) 'x': &A<T>
942 [178; 181) 'x.0': *mut T
943 [268; 272) 'self': &B<T>
944 [291; 314) '{ ... }': &T
945 [301; 308) '&self.0': &T
946 [302; 306) 'self': &B<T>
947 [302; 308) 'self.0': T
948 [326; 327) 'a': A<i32>
949 [337; 383) '{ ...))); }': ()
950 [347; 348) 't': &i32
951 [351; 352) 'A': A<i32>(*mut T) -> A<T>
952 [351; 365) 'A(0 as *mut _)': A<i32>
953 [351; 380) 'A(0 as...B(a)))': &i32
954 [353; 354) '0': i32
955 [353; 364) '0 as *mut _': *mut i32
956 [370; 379) '&&B(B(a))': &&B<B<A<i32>>>
957 [371; 379) '&B(B(a))': &B<B<A<i32>>>
958 [372; 373) 'B': B<B<A<i32>>>(T) -> B<T>
959 [372; 379) 'B(B(a))': B<B<A<i32>>>
960 [374; 375) 'B': B<A<i32>>(T) -> B<T>
961 [374; 378) 'B(a)': B<A<i32>>
962 [376; 377) 'a': A<i32>
963 "###
964 );
965}
966
967#[test]
968fn bug_484() {
969 assert_snapshot!(
970 infer(r#"
971fn test() {
972 let x = if true {};
973}
974"#),
975 @r###"
976 [11; 37) '{ l... {}; }': ()
977 [20; 21) 'x': ()
978 [24; 34) 'if true {}': ()
979 [27; 31) 'true': bool
980 [32; 34) '{}': ()
981 "###
982 );
983}
984
985#[test]
986fn infer_in_elseif() {
987 assert_snapshot!(
988 infer(r#"
989struct Foo { field: i32 }
990fn main(foo: Foo) {
991 if true {
992
993 } else if false {
994 foo.field
995 }
996}
997"#),
998 @r###"
999 [35; 38) 'foo': Foo
1000 [45; 109) '{ ... } }': ()
1001 [51; 107) 'if tru... }': ()
1002 [54; 58) 'true': bool
1003 [59; 67) '{ }': ()
1004 [73; 107) 'if fal... }': ()
1005 [76; 81) 'false': bool
1006 [82; 107) '{ ... }': i32
1007 [92; 95) 'foo': Foo
1008 [92; 101) 'foo.field': i32
1009 "###
1010 )
1011}
1012
1013#[test]
1014fn infer_if_match_with_return() {
1015 assert_snapshot!(
1016 infer(r#"
1017fn foo() {
1018 let _x1 = if true {
1019 1
1020 } else {
1021 return;
1022 };
1023 let _x2 = if true {
1024 2
1025 } else {
1026 return
1027 };
1028 let _x3 = match true {
1029 true => 3,
1030 _ => {
1031 return;
1032 }
1033 };
1034 let _x4 = match true {
1035 true => 4,
1036 _ => return
1037 };
1038}"#),
1039 @r###"
1040 [10; 323) '{ ... }; }': ()
1041 [20; 23) '_x1': i32
1042 [26; 80) 'if tru... }': i32
1043 [29; 33) 'true': bool
1044 [34; 51) '{ ... }': i32
1045 [44; 45) '1': i32
1046 [57; 80) '{ ... }': !
1047 [67; 73) 'return': !
1048 [90; 93) '_x2': i32
1049 [96; 149) 'if tru... }': i32
1050 [99; 103) 'true': bool
1051 [104; 121) '{ ... }': i32
1052 [114; 115) '2': i32
1053 [127; 149) '{ ... }': !
1054 [137; 143) 'return': !
1055 [159; 162) '_x3': i32
1056 [165; 247) 'match ... }': i32
1057 [171; 175) 'true': bool
1058 [186; 190) 'true': bool
1059 [194; 195) '3': i32
1060 [205; 206) '_': bool
1061 [210; 241) '{ ... }': !
1062 [224; 230) 'return': !
1063 [257; 260) '_x4': i32
1064 [263; 320) 'match ... }': i32
1065 [269; 273) 'true': bool
1066 [284; 288) 'true': bool
1067 [292; 293) '4': i32
1068 [303; 304) '_': bool
1069 [308; 314) 'return': !
1070 "###
1071 )
1072}
1073
1074#[test]
1075fn infer_inherent_method() {
1076 assert_snapshot!(
1077 infer(r#"
1078struct A;
1079
1080impl A {
1081 fn foo(self, x: u32) -> i32 {}
1082}
1083
1084mod b {
1085 impl super::A {
1086 fn bar(&self, x: u64) -> i64 {}
1087 }
1088}
1089
1090fn test(a: A) {
1091 a.foo(1);
1092 (&a).bar(1);
1093 a.bar(1);
1094}
1095"#),
1096 @r###"
1097 [32; 36) 'self': A
1098 [38; 39) 'x': u32
1099 [53; 55) '{}': ()
1100 [103; 107) 'self': &A
1101 [109; 110) 'x': u64
1102 [124; 126) '{}': ()
1103 [144; 145) 'a': A
1104 [150; 198) '{ ...(1); }': ()
1105 [156; 157) 'a': A
1106 [156; 164) 'a.foo(1)': i32
1107 [162; 163) '1': u32
1108 [170; 181) '(&a).bar(1)': i64
1109 [171; 173) '&a': &A
1110 [172; 173) 'a': A
1111 [179; 180) '1': u64
1112 [187; 188) 'a': A
1113 [187; 195) 'a.bar(1)': i64
1114 [193; 194) '1': u64
1115 "###
1116 );
1117}
1118
1119#[test]
1120fn infer_inherent_method_str() {
1121 assert_snapshot!(
1122 infer(r#"
1123#[lang = "str"]
1124impl str {
1125 fn foo(&self) -> i32 {}
1126}
1127
1128fn test() {
1129 "foo".foo();
1130}
1131"#),
1132 @r###"
1133 [40; 44) 'self': &str
1134 [53; 55) '{}': ()
1135 [69; 89) '{ ...o(); }': ()
1136 [75; 80) '"foo"': &str
1137 [75; 86) '"foo".foo()': i32
1138 "###
1139 );
1140}
1141
1142#[test]
1143fn infer_tuple() {
1144 assert_snapshot!(
1145 infer(r#"
1146fn test(x: &str, y: isize) {
1147 let a: (u32, &str) = (1, "a");
1148 let b = (a, x);
1149 let c = (y, x);
1150 let d = (c, x);
1151 let e = (1, "e");
1152 let f = (e, "d");
1153}
1154"#),
1155 @r###"
1156 [9; 10) 'x': &str
1157 [18; 19) 'y': isize
1158 [28; 170) '{ ...d"); }': ()
1159 [38; 39) 'a': (u32, &str)
1160 [55; 63) '(1, "a")': (u32, &str)
1161 [56; 57) '1': u32
1162 [59; 62) '"a"': &str
1163 [73; 74) 'b': ((u32, &str), &str)
1164 [77; 83) '(a, x)': ((u32, &str), &str)
1165 [78; 79) 'a': (u32, &str)
1166 [81; 82) 'x': &str
1167 [93; 94) 'c': (isize, &str)
1168 [97; 103) '(y, x)': (isize, &str)
1169 [98; 99) 'y': isize
1170 [101; 102) 'x': &str
1171 [113; 114) 'd': ((isize, &str), &str)
1172 [117; 123) '(c, x)': ((isize, &str), &str)
1173 [118; 119) 'c': (isize, &str)
1174 [121; 122) 'x': &str
1175 [133; 134) 'e': (i32, &str)
1176 [137; 145) '(1, "e")': (i32, &str)
1177 [138; 139) '1': i32
1178 [141; 144) '"e"': &str
1179 [155; 156) 'f': ((i32, &str), &str)
1180 [159; 167) '(e, "d")': ((i32, &str), &str)
1181 [160; 161) 'e': (i32, &str)
1182 [163; 166) '"d"': &str
1183 "###
1184 );
1185}
1186
1187#[test]
1188fn infer_array() {
1189 assert_snapshot!(
1190 infer(r#"
1191fn test(x: &str, y: isize) {
1192 let a = [x];
1193 let b = [a, a];
1194 let c = [b, b];
1195
1196 let d = [y, 1, 2, 3];
1197 let d = [1, y, 2, 3];
1198 let e = [y];
1199 let f = [d, d];
1200 let g = [e, e];
1201
1202 let h = [1, 2];
1203 let i = ["a", "b"];
1204
1205 let b = [a, ["b"]];
1206 let x: [u8; 0] = [];
1207}
1208"#),
1209 @r###"
1210 [9; 10) 'x': &str
1211 [18; 19) 'y': isize
1212 [28; 293) '{ ... []; }': ()
1213 [38; 39) 'a': [&str;_]
1214 [42; 45) '[x]': [&str;_]
1215 [43; 44) 'x': &str
1216 [55; 56) 'b': [[&str;_];_]
1217 [59; 65) '[a, a]': [[&str;_];_]
1218 [60; 61) 'a': [&str;_]
1219 [63; 64) 'a': [&str;_]
1220 [75; 76) 'c': [[[&str;_];_];_]
1221 [79; 85) '[b, b]': [[[&str;_];_];_]
1222 [80; 81) 'b': [[&str;_];_]
1223 [83; 84) 'b': [[&str;_];_]
1224 [96; 97) 'd': [isize;_]
1225 [100; 112) '[y, 1, 2, 3]': [isize;_]
1226 [101; 102) 'y': isize
1227 [104; 105) '1': isize
1228 [107; 108) '2': isize
1229 [110; 111) '3': isize
1230 [122; 123) 'd': [isize;_]
1231 [126; 138) '[1, y, 2, 3]': [isize;_]
1232 [127; 128) '1': isize
1233 [130; 131) 'y': isize
1234 [133; 134) '2': isize
1235 [136; 137) '3': isize
1236 [148; 149) 'e': [isize;_]
1237 [152; 155) '[y]': [isize;_]
1238 [153; 154) 'y': isize
1239 [165; 166) 'f': [[isize;_];_]
1240 [169; 175) '[d, d]': [[isize;_];_]
1241 [170; 171) 'd': [isize;_]
1242 [173; 174) 'd': [isize;_]
1243 [185; 186) 'g': [[isize;_];_]
1244 [189; 195) '[e, e]': [[isize;_];_]
1245 [190; 191) 'e': [isize;_]
1246 [193; 194) 'e': [isize;_]
1247 [206; 207) 'h': [i32;_]
1248 [210; 216) '[1, 2]': [i32;_]
1249 [211; 212) '1': i32
1250 [214; 215) '2': i32
1251 [226; 227) 'i': [&str;_]
1252 [230; 240) '["a", "b"]': [&str;_]
1253 [231; 234) '"a"': &str
1254 [236; 239) '"b"': &str
1255 [251; 252) 'b': [[&str;_];_]
1256 [255; 265) '[a, ["b"]]': [[&str;_];_]
1257 [256; 257) 'a': [&str;_]
1258 [259; 264) '["b"]': [&str;_]
1259 [260; 263) '"b"': &str
1260 [275; 276) 'x': [u8;_]
1261 [288; 290) '[]': [u8;_]
1262 "###
1263 );
1264}
1265
1266#[test]
1267fn infer_pattern() {
1268 assert_snapshot!(
1269 infer(r#"
1270fn test(x: &i32) {
1271 let y = x;
1272 let &z = x;
1273 let a = z;
1274 let (c, d) = (1, "hello");
1275
1276 for (e, f) in some_iter {
1277 let g = e;
1278 }
1279
1280 if let [val] = opt {
1281 let h = val;
1282 }
1283
1284 let lambda = |a: u64, b, c: i32| { a + b; c };
1285
1286 let ref ref_to_x = x;
1287 let mut mut_x = x;
1288 let ref mut mut_ref_to_x = x;
1289 let k = mut_ref_to_x;
1290}
1291"#),
1292 @r###"
1293 [9; 10) 'x': &i32
1294 [18; 369) '{ ...o_x; }': ()
1295 [28; 29) 'y': &i32
1296 [32; 33) 'x': &i32
1297 [43; 45) '&z': &i32
1298 [44; 45) 'z': i32
1299 [48; 49) 'x': &i32
1300 [59; 60) 'a': i32
1301 [63; 64) 'z': i32
1302 [74; 80) '(c, d)': (i32, &str)
1303 [75; 76) 'c': i32
1304 [78; 79) 'd': &str
1305 [83; 95) '(1, "hello")': (i32, &str)
1306 [84; 85) '1': i32
1307 [87; 94) '"hello"': &str
1308 [102; 152) 'for (e... }': ()
1309 [106; 112) '(e, f)': ({unknown}, {unknown})
1310 [107; 108) 'e': {unknown}
1311 [110; 111) 'f': {unknown}
1312 [116; 125) 'some_iter': {unknown}
1313 [126; 152) '{ ... }': ()
1314 [140; 141) 'g': {unknown}
1315 [144; 145) 'e': {unknown}
1316 [158; 205) 'if let... }': ()
1317 [165; 170) '[val]': {unknown}
1318 [173; 176) 'opt': {unknown}
1319 [177; 205) '{ ... }': ()
1320 [191; 192) 'h': {unknown}
1321 [195; 198) 'val': {unknown}
1322 [215; 221) 'lambda': |u64, u64, i32| -> i32
1323 [224; 256) '|a: u6...b; c }': |u64, u64, i32| -> i32
1324 [225; 226) 'a': u64
1325 [233; 234) 'b': u64
1326 [236; 237) 'c': i32
1327 [244; 256) '{ a + b; c }': i32
1328 [246; 247) 'a': u64
1329 [246; 251) 'a + b': u64
1330 [250; 251) 'b': u64
1331 [253; 254) 'c': i32
1332 [267; 279) 'ref ref_to_x': &&i32
1333 [282; 283) 'x': &i32
1334 [293; 302) 'mut mut_x': &i32
1335 [305; 306) 'x': &i32
1336 [316; 336) 'ref mu...f_to_x': &mut &i32
1337 [339; 340) 'x': &i32
1338 [350; 351) 'k': &mut &i32
1339 [354; 366) 'mut_ref_to_x': &mut &i32
1340 "###
1341 );
1342}
1343
1344#[test]
1345fn infer_pattern_match_ergonomics() {
1346 assert_snapshot!(
1347 infer(r#"
1348struct A<T>(T);
1349
1350fn test() {
1351 let A(n) = &A(1);
1352 let A(n) = &mut A(1);
1353}
1354"#),
1355 @r###"
1356 [28; 79) '{ ...(1); }': ()
1357 [38; 42) 'A(n)': A<i32>
1358 [40; 41) 'n': &i32
1359 [45; 50) '&A(1)': &A<i32>
1360 [46; 47) 'A': A<i32>(T) -> A<T>
1361 [46; 50) 'A(1)': A<i32>
1362 [48; 49) '1': i32
1363 [60; 64) 'A(n)': A<i32>
1364 [62; 63) 'n': &mut i32
1365 [67; 76) '&mut A(1)': &mut A<i32>
1366 [72; 73) 'A': A<i32>(T) -> A<T>
1367 [72; 76) 'A(1)': A<i32>
1368 [74; 75) '1': i32
1369 "###
1370 );
1371}
1372
1373#[test]
1374fn infer_pattern_match_ergonomics_ref() {
1375 covers!(match_ergonomics_ref);
1376 assert_snapshot!(
1377 infer(r#"
1378fn test() {
1379 let v = &(1, &2);
1380 let (_, &w) = v;
1381}
1382"#),
1383 @r###"
1384 [11; 57) '{ ...= v; }': ()
1385 [21; 22) 'v': &(i32, &i32)
1386 [25; 33) '&(1, &2)': &(i32, &i32)
1387 [26; 33) '(1, &2)': (i32, &i32)
1388 [27; 28) '1': i32
1389 [30; 32) '&2': &i32
1390 [31; 32) '2': i32
1391 [43; 50) '(_, &w)': (i32, &i32)
1392 [44; 45) '_': i32
1393 [47; 49) '&w': &i32
1394 [48; 49) 'w': i32
1395 [53; 54) 'v': &(i32, &i32)
1396 "###
1397 );
1398}
1399
1400#[test]
1401fn infer_adt_pattern() {
1402 assert_snapshot!(
1403 infer(r#"
1404enum E {
1405 A { x: usize },
1406 B
1407}
1408
1409struct S(u32, E);
1410
1411fn test() {
1412 let e = E::A { x: 3 };
1413
1414 let S(y, z) = foo;
1415 let E::A { x: new_var } = e;
1416
1417 match e {
1418 E::A { x } => x,
1419 E::B if foo => 1,
1420 E::B => 10,
1421 };
1422
1423 let ref d @ E::A { .. } = e;
1424 d;
1425}
1426"#),
1427 @r###"
1428 [68; 289) '{ ... d; }': ()
1429 [78; 79) 'e': E
1430 [82; 95) 'E::A { x: 3 }': E
1431 [92; 93) '3': usize
1432 [106; 113) 'S(y, z)': S
1433 [108; 109) 'y': u32
1434 [111; 112) 'z': E
1435 [116; 119) 'foo': S
1436 [129; 148) 'E::A {..._var }': E
1437 [139; 146) 'new_var': usize
1438 [151; 152) 'e': E
1439 [159; 245) 'match ... }': usize
1440 [165; 166) 'e': E
1441 [177; 187) 'E::A { x }': E
1442 [184; 185) 'x': usize
1443 [191; 192) 'x': usize
1444 [202; 206) 'E::B': E
1445 [210; 213) 'foo': bool
1446 [217; 218) '1': usize
1447 [228; 232) 'E::B': E
1448 [236; 238) '10': usize
1449 [256; 275) 'ref d ...{ .. }': &E
1450 [264; 275) 'E::A { .. }': E
1451 [278; 279) 'e': E
1452 [285; 286) 'd': &E
1453 "###
1454 );
1455}
1456
1457#[test]
1458fn infer_struct_generics() {
1459 assert_snapshot!(
1460 infer(r#"
1461struct A<T> {
1462 x: T,
1463}
1464
1465fn test(a1: A<u32>, i: i32) {
1466 a1.x;
1467 let a2 = A { x: i };
1468 a2.x;
1469 let a3 = A::<i128> { x: 1 };
1470 a3.x;
1471}
1472"#),
1473 @r###"
1474 [36; 38) 'a1': A<u32>
1475 [48; 49) 'i': i32
1476 [56; 147) '{ ...3.x; }': ()
1477 [62; 64) 'a1': A<u32>
1478 [62; 66) 'a1.x': u32
1479 [76; 78) 'a2': A<i32>
1480 [81; 91) 'A { x: i }': A<i32>
1481 [88; 89) 'i': i32
1482 [97; 99) 'a2': A<i32>
1483 [97; 101) 'a2.x': i32
1484 [111; 113) 'a3': A<i128>
1485 [116; 134) 'A::<i1...x: 1 }': A<i128>
1486 [131; 132) '1': i128
1487 [140; 142) 'a3': A<i128>
1488 [140; 144) 'a3.x': i128
1489 "###
1490 );
1491}
1492
1493#[test]
1494fn infer_tuple_struct_generics() {
1495 assert_snapshot!(
1496 infer(r#"
1497struct A<T>(T);
1498enum Option<T> { Some(T), None }
1499use Option::*;
1500
1501fn test() {
1502 A(42);
1503 A(42u128);
1504 Some("x");
1505 Option::Some("x");
1506 None;
1507 let x: Option<i64> = None;
1508}
1509"#),
1510 @r###"
1511 [76; 184) '{ ...one; }': ()
1512 [82; 83) 'A': A<i32>(T) -> A<T>
1513 [82; 87) 'A(42)': A<i32>
1514 [84; 86) '42': i32
1515 [93; 94) 'A': A<u128>(T) -> A<T>
1516 [93; 102) 'A(42u128)': A<u128>
1517 [95; 101) '42u128': u128
1518 [108; 112) 'Some': Some<&str>(T) -> Option<T>
1519 [108; 117) 'Some("x")': Option<&str>
1520 [113; 116) '"x"': &str
1521 [123; 135) 'Option::Some': Some<&str>(T) -> Option<T>
1522 [123; 140) 'Option...e("x")': Option<&str>
1523 [136; 139) '"x"': &str
1524 [146; 150) 'None': Option<{unknown}>
1525 [160; 161) 'x': Option<i64>
1526 [177; 181) 'None': Option<i64>
1527 "###
1528 );
1529}
1530
1531#[test]
1532fn infer_generics_in_patterns() {
1533 assert_snapshot!(
1534 infer(r#"
1535struct A<T> {
1536 x: T,
1537}
1538
1539enum Option<T> {
1540 Some(T),
1541 None,
1542}
1543
1544fn test(a1: A<u32>, o: Option<u64>) {
1545 let A { x: x2 } = a1;
1546 let A::<i64> { x: x3 } = A { x: 1 };
1547 match o {
1548 Option::Some(t) => t,
1549 _ => 1,
1550 };
1551}
1552"#),
1553 @r###"
1554 [79; 81) 'a1': A<u32>
1555 [91; 92) 'o': Option<u64>
1556 [107; 244) '{ ... }; }': ()
1557 [117; 128) 'A { x: x2 }': A<u32>
1558 [124; 126) 'x2': u32
1559 [131; 133) 'a1': A<u32>
1560 [143; 161) 'A::<i6...: x3 }': A<i64>
1561 [157; 159) 'x3': i64
1562 [164; 174) 'A { x: 1 }': A<i64>
1563 [171; 172) '1': i64
1564 [180; 241) 'match ... }': u64
1565 [186; 187) 'o': Option<u64>
1566 [198; 213) 'Option::Some(t)': Option<u64>
1567 [211; 212) 't': u64
1568 [217; 218) 't': u64
1569 [228; 229) '_': Option<u64>
1570 [233; 234) '1': u64
1571 "###
1572 );
1573}
1574
1575#[test]
1576fn infer_function_generics() {
1577 assert_snapshot!(
1578 infer(r#"
1579fn id<T>(t: T) -> T { t }
1580
1581fn test() {
1582 id(1u32);
1583 id::<i128>(1);
1584 let x: u64 = id(1);
1585}
1586"#),
1587 @r###"
1588 [10; 11) 't': T
1589 [21; 26) '{ t }': T
1590 [23; 24) 't': T
1591 [38; 98) '{ ...(1); }': ()
1592 [44; 46) 'id': fn id<u32>(T) -> T
1593 [44; 52) 'id(1u32)': u32
1594 [47; 51) '1u32': u32
1595 [58; 68) 'id::<i128>': fn id<i128>(T) -> T
1596 [58; 71) 'id::<i128>(1)': i128
1597 [69; 70) '1': i128
1598 [81; 82) 'x': u64
1599 [90; 92) 'id': fn id<u64>(T) -> T
1600 [90; 95) 'id(1)': u64
1601 [93; 94) '1': u64
1602 "###
1603 );
1604}
1605
1606#[test]
1607fn infer_impl_generics() {
1608 assert_snapshot!(
1609 infer(r#"
1610struct A<T1, T2> {
1611 x: T1,
1612 y: T2,
1613}
1614impl<Y, X> A<X, Y> {
1615 fn x(self) -> X {
1616 self.x
1617 }
1618 fn y(self) -> Y {
1619 self.y
1620 }
1621 fn z<T>(self, t: T) -> (X, Y, T) {
1622 (self.x, self.y, t)
1623 }
1624}
1625
1626fn test() -> i128 {
1627 let a = A { x: 1u64, y: 1i64 };
1628 a.x();
1629 a.y();
1630 a.z(1i128);
1631 a.z::<u128>(1);
1632}
1633"#),
1634 @r###"
1635 [74; 78) 'self': A<X, Y>
1636 [85; 107) '{ ... }': X
1637 [95; 99) 'self': A<X, Y>
1638 [95; 101) 'self.x': X
1639 [117; 121) 'self': A<X, Y>
1640 [128; 150) '{ ... }': Y
1641 [138; 142) 'self': A<X, Y>
1642 [138; 144) 'self.y': Y
1643 [163; 167) 'self': A<X, Y>
1644 [169; 170) 't': T
1645 [188; 223) '{ ... }': (X, Y, T)
1646 [198; 217) '(self.....y, t)': (X, Y, T)
1647 [199; 203) 'self': A<X, Y>
1648 [199; 205) 'self.x': X
1649 [207; 211) 'self': A<X, Y>
1650 [207; 213) 'self.y': Y
1651 [215; 216) 't': T
1652 [245; 342) '{ ...(1); }': ()
1653 [255; 256) 'a': A<u64, i64>
1654 [259; 281) 'A { x:...1i64 }': A<u64, i64>
1655 [266; 270) '1u64': u64
1656 [275; 279) '1i64': i64
1657 [287; 288) 'a': A<u64, i64>
1658 [287; 292) 'a.x()': u64
1659 [298; 299) 'a': A<u64, i64>
1660 [298; 303) 'a.y()': i64
1661 [309; 310) 'a': A<u64, i64>
1662 [309; 319) 'a.z(1i128)': (u64, i64, i128)
1663 [313; 318) '1i128': i128
1664 [325; 326) 'a': A<u64, i64>
1665 [325; 339) 'a.z::<u128>(1)': (u64, i64, u128)
1666 [337; 338) '1': u128
1667 "###
1668 );
1669}
1670
1671#[test]
1672fn infer_impl_generics_with_autoderef() {
1673 assert_snapshot!(
1674 infer(r#"
1675enum Option<T> {
1676 Some(T),
1677 None,
1678}
1679impl<T> Option<T> {
1680 fn as_ref(&self) -> Option<&T> {}
1681}
1682fn test(o: Option<u32>) {
1683 (&o).as_ref();
1684 o.as_ref();
1685}
1686"#),
1687 @r###"
1688 [78; 82) 'self': &Option<T>
1689 [98; 100) '{}': ()
1690 [111; 112) 'o': Option<u32>
1691 [127; 165) '{ ...f(); }': ()
1692 [133; 146) '(&o).as_ref()': Option<&u32>
1693 [134; 136) '&o': &Option<u32>
1694 [135; 136) 'o': Option<u32>
1695 [152; 153) 'o': Option<u32>
1696 [152; 162) 'o.as_ref()': Option<&u32>
1697 "###
1698 );
1699}
1700
1701#[test]
1702fn infer_generic_chain() {
1703 assert_snapshot!(
1704 infer(r#"
1705struct A<T> {
1706 x: T,
1707}
1708impl<T2> A<T2> {
1709 fn x(self) -> T2 {
1710 self.x
1711 }
1712}
1713fn id<T>(t: T) -> T { t }
1714
1715fn test() -> i128 {
1716 let x = 1;
1717 let y = id(x);
1718 let a = A { x: id(y) };
1719 let z = id(a.x);
1720 let b = A { x: z };
1721 b.x()
1722}
1723"#),
1724 @r###"
1725 [53; 57) 'self': A<T2>
1726 [65; 87) '{ ... }': T2
1727 [75; 79) 'self': A<T2>
1728 [75; 81) 'self.x': T2
1729 [99; 100) 't': T
1730 [110; 115) '{ t }': T
1731 [112; 113) 't': T
1732 [135; 261) '{ ....x() }': i128
1733 [146; 147) 'x': i128
1734 [150; 151) '1': i128
1735 [162; 163) 'y': i128
1736 [166; 168) 'id': fn id<i128>(T) -> T
1737 [166; 171) 'id(x)': i128
1738 [169; 170) 'x': i128
1739 [182; 183) 'a': A<i128>
1740 [186; 200) 'A { x: id(y) }': A<i128>
1741 [193; 195) 'id': fn id<i128>(T) -> T
1742 [193; 198) 'id(y)': i128
1743 [196; 197) 'y': i128
1744 [211; 212) 'z': i128
1745 [215; 217) 'id': fn id<i128>(T) -> T
1746 [215; 222) 'id(a.x)': i128
1747 [218; 219) 'a': A<i128>
1748 [218; 221) 'a.x': i128
1749 [233; 234) 'b': A<i128>
1750 [237; 247) 'A { x: z }': A<i128>
1751 [244; 245) 'z': i128
1752 [254; 255) 'b': A<i128>
1753 [254; 259) 'b.x()': i128
1754 "###
1755 );
1756}
1757
1758#[test]
1759fn infer_associated_const() {
1760 assert_snapshot!(
1761 infer(r#"
1762struct Struct;
1763
1764impl Struct {
1765 const FOO: u32 = 1;
1766}
1767
1768enum Enum {}
1769
1770impl Enum {
1771 const BAR: u32 = 2;
1772}
1773
1774trait Trait {
1775 const ID: u32;
1776}
1777
1778struct TraitTest;
1779
1780impl Trait for TraitTest {
1781 const ID: u32 = 5;
1782}
1783
1784fn test() {
1785 let x = Struct::FOO;
1786 let y = Enum::BAR;
1787 let z = TraitTest::ID;
1788}
1789"#),
1790 @r###"
1791 [52; 53) '1': u32
1792 [105; 106) '2': u32
1793 [213; 214) '5': u32
1794 [229; 307) '{ ...:ID; }': ()
1795 [239; 240) 'x': u32
1796 [243; 254) 'Struct::FOO': u32
1797 [264; 265) 'y': u32
1798 [268; 277) 'Enum::BAR': u32
1799 [287; 288) 'z': u32
1800 [291; 304) 'TraitTest::ID': u32
1801 "###
1802 );
1803}
1804
1805#[test]
1806fn infer_associated_method_struct() {
1807 assert_snapshot!(
1808 infer(r#"
1809struct A { x: u32 }
1810
1811impl A {
1812 fn new() -> A {
1813 A { x: 0 }
1814 }
1815}
1816fn test() {
1817 let a = A::new();
1818 a.x;
1819}
1820"#),
1821 @r###"
1822 [49; 75) '{ ... }': A
1823 [59; 69) 'A { x: 0 }': A
1824 [66; 67) '0': u32
1825 [88; 122) '{ ...a.x; }': ()
1826 [98; 99) 'a': A
1827 [102; 108) 'A::new': fn new() -> A
1828 [102; 110) 'A::new()': A
1829 [116; 117) 'a': A
1830 [116; 119) 'a.x': u32
1831 "###
1832 );
1833}
1834
1835#[test]
1836fn infer_associated_method_enum() {
1837 assert_snapshot!(
1838 infer(r#"
1839enum A { B, C }
1840
1841impl A {
1842 pub fn b() -> A {
1843 A::B
1844 }
1845 pub fn c() -> A {
1846 A::C
1847 }
1848}
1849fn test() {
1850 let a = A::b();
1851 a;
1852 let c = A::c();
1853 c;
1854}
1855"#),
1856 @r###"
1857 [47; 67) '{ ... }': A
1858 [57; 61) 'A::B': A
1859 [88; 108) '{ ... }': A
1860 [98; 102) 'A::C': A
1861 [121; 178) '{ ... c; }': ()
1862 [131; 132) 'a': A
1863 [135; 139) 'A::b': fn b() -> A
1864 [135; 141) 'A::b()': A
1865 [147; 148) 'a': A
1866 [158; 159) 'c': A
1867 [162; 166) 'A::c': fn c() -> A
1868 [162; 168) 'A::c()': A
1869 [174; 175) 'c': A
1870 "###
1871 );
1872}
1873
1874#[test]
1875fn infer_associated_method_with_modules() {
1876 assert_snapshot!(
1877 infer(r#"
1878mod a {
1879 struct A;
1880 impl A { pub fn thing() -> A { A {} }}
1881}
1882
1883mod b {
1884 struct B;
1885 impl B { pub fn thing() -> u32 { 99 }}
1886
1887 mod c {
1888 struct C;
1889 impl C { pub fn thing() -> C { C {} }}
1890 }
1891}
1892use b::c;
1893
1894fn test() {
1895 let x = a::A::thing();
1896 let y = b::B::thing();
1897 let z = c::C::thing();
1898}
1899"#),
1900 @r###"
1901 [56; 64) '{ A {} }': A
1902 [58; 62) 'A {}': A
1903 [126; 132) '{ 99 }': u32
1904 [128; 130) '99': u32
1905 [202; 210) '{ C {} }': C
1906 [204; 208) 'C {}': C
1907 [241; 325) '{ ...g(); }': ()
1908 [251; 252) 'x': A
1909 [255; 266) 'a::A::thing': fn thing() -> A
1910 [255; 268) 'a::A::thing()': A
1911 [278; 279) 'y': u32
1912 [282; 293) 'b::B::thing': fn thing() -> u32
1913 [282; 295) 'b::B::thing()': u32
1914 [305; 306) 'z': C
1915 [309; 320) 'c::C::thing': fn thing() -> C
1916 [309; 322) 'c::C::thing()': C
1917 "###
1918 );
1919}
1920
1921#[test]
1922fn infer_associated_method_generics() {
1923 assert_snapshot!(
1924 infer(r#"
1925struct Gen<T> {
1926 val: T
1927}
1928
1929impl<T> Gen<T> {
1930 pub fn make(val: T) -> Gen<T> {
1931 Gen { val }
1932 }
1933}
1934
1935fn test() {
1936 let a = Gen::make(0u32);
1937}
1938"#),
1939 @r###"
1940 [64; 67) 'val': T
1941 [82; 109) '{ ... }': Gen<T>
1942 [92; 103) 'Gen { val }': Gen<T>
1943 [98; 101) 'val': T
1944 [123; 155) '{ ...32); }': ()
1945 [133; 134) 'a': Gen<u32>
1946 [137; 146) 'Gen::make': fn make<u32>(T) -> Gen<T>
1947 [137; 152) 'Gen::make(0u32)': Gen<u32>
1948 [147; 151) '0u32': u32
1949 "###
1950 );
1951}
1952
1953#[test]
1954fn infer_associated_method_generics_with_default_param() {
1955 assert_snapshot!(
1956 infer(r#"
1957struct Gen<T=u32> {
1958 val: T
1959}
1960
1961impl<T> Gen<T> {
1962 pub fn make() -> Gen<T> {
1963 loop { }
1964 }
1965}
1966
1967fn test() {
1968 let a = Gen::make();
1969}
1970"#),
1971 @r###"
1972 [80; 104) '{ ... }': Gen<T>
1973 [90; 98) 'loop { }': !
1974 [95; 98) '{ }': ()
1975 [118; 146) '{ ...e(); }': ()
1976 [128; 129) 'a': Gen<u32>
1977 [132; 141) 'Gen::make': fn make<u32>() -> Gen<T>
1978 [132; 143) 'Gen::make()': Gen<u32>
1979 "###
1980 );
1981}
1982
1983#[test]
1984fn infer_associated_method_generics_with_default_tuple_param() {
1985 let t = type_at(
1986 r#"
1987//- /main.rs
1988struct Gen<T=()> {
1989 val: T
1990}
1991
1992impl<T> Gen<T> {
1993 pub fn make() -> Gen<T> {
1994 loop { }
1995 }
1996}
1997
1998fn test() {
1999 let a = Gen::make();
2000 a.val<|>;
2001}
2002"#,
2003 );
2004 assert_eq!(t, "()");
2005}
2006
2007#[test]
2008fn infer_associated_method_generics_without_args() {
2009 assert_snapshot!(
2010 infer(r#"
2011struct Gen<T> {
2012 val: T
2013}
2014
2015impl<T> Gen<T> {
2016 pub fn make() -> Gen<T> {
2017 loop { }
2018 }
2019}
2020
2021fn test() {
2022 let a = Gen::<u32>::make();
2023}
2024"#),
2025 @r###"
2026 [76; 100) '{ ... }': Gen<T>
2027 [86; 94) 'loop { }': !
2028 [91; 94) '{ }': ()
2029 [114; 149) '{ ...e(); }': ()
2030 [124; 125) 'a': Gen<u32>
2031 [128; 144) 'Gen::<...::make': fn make<u32>() -> Gen<T>
2032 [128; 146) 'Gen::<...make()': Gen<u32>
2033 "###
2034 );
2035}
2036
2037#[test]
2038fn infer_associated_method_generics_2_type_params_without_args() {
2039 assert_snapshot!(
2040 infer(r#"
2041struct Gen<T, U> {
2042 val: T,
2043 val2: U,
2044}
2045
2046impl<T> Gen<u32, T> {
2047 pub fn make() -> Gen<u32,T> {
2048 loop { }
2049 }
2050}
2051
2052fn test() {
2053 let a = Gen::<u32, u64>::make();
2054}
2055"#),
2056 @r###"
2057 [102; 126) '{ ... }': Gen<u32, T>
2058 [112; 120) 'loop { }': !
2059 [117; 120) '{ }': ()
2060 [140; 180) '{ ...e(); }': ()
2061 [150; 151) 'a': Gen<u32, u64>
2062 [154; 175) 'Gen::<...::make': fn make<u64>() -> Gen<u32, T>
2063 [154; 177) 'Gen::<...make()': Gen<u32, u64>
2064 "###
2065 );
2066}
2067
2068#[test]
2069fn infer_type_alias() {
2070 assert_snapshot!(
2071 infer(r#"
2072struct A<X, Y> { x: X, y: Y }
2073type Foo = A<u32, i128>;
2074type Bar<T> = A<T, u128>;
2075type Baz<U, V> = A<V, U>;
2076fn test(x: Foo, y: Bar<&str>, z: Baz<i8, u8>) {
2077 x.x;
2078 x.y;
2079 y.x;
2080 y.y;
2081 z.x;
2082 z.y;
2083}
2084"#),
2085 @r###"
2086 [116; 117) 'x': A<u32, i128>
2087 [124; 125) 'y': A<&str, u128>
2088 [138; 139) 'z': A<u8, i8>
2089 [154; 211) '{ ...z.y; }': ()
2090 [160; 161) 'x': A<u32, i128>
2091 [160; 163) 'x.x': u32
2092 [169; 170) 'x': A<u32, i128>
2093 [169; 172) 'x.y': i128
2094 [178; 179) 'y': A<&str, u128>
2095 [178; 181) 'y.x': &str
2096 [187; 188) 'y': A<&str, u128>
2097 [187; 190) 'y.y': u128
2098 [196; 197) 'z': A<u8, i8>
2099 [196; 199) 'z.x': u8
2100 [205; 206) 'z': A<u8, i8>
2101 [205; 208) 'z.y': i8
2102 "###
2103 )
2104}
2105
2106#[test]
2107#[should_panic] // we currently can't handle this
2108fn recursive_type_alias() {
2109 assert_snapshot!(
2110 infer(r#"
2111struct A<X> {}
2112type Foo = Foo;
2113type Bar = A<Bar>;
2114fn test(x: Foo) {}
2115"#),
2116 @""
2117 )
2118}
2119
2120#[test]
2121fn no_panic_on_field_of_enum() {
2122 assert_snapshot!(
2123 infer(r#"
2124enum X {}
2125
2126fn test(x: X) {
2127 x.some_field;
2128}
2129"#),
2130 @r###"
2131 [20; 21) 'x': X
2132 [26; 47) '{ ...eld; }': ()
2133 [32; 33) 'x': X
2134 [32; 44) 'x.some_field': {unknown}
2135 "###
2136 );
2137}
2138
2139#[test]
2140fn bug_585() {
2141 assert_snapshot!(
2142 infer(r#"
2143fn test() {
2144 X {};
2145 match x {
2146 A::B {} => (),
2147 A::Y() => (),
2148 }
2149}
2150"#),
2151 @r###"
2152 [11; 89) '{ ... } }': ()
2153 [17; 21) 'X {}': {unknown}
2154 [27; 87) 'match ... }': ()
2155 [33; 34) 'x': {unknown}
2156 [45; 52) 'A::B {}': {unknown}
2157 [56; 58) '()': ()
2158 [68; 74) 'A::Y()': {unknown}
2159 [78; 80) '()': ()
2160 "###
2161 );
2162}
2163
2164#[test]
2165fn bug_651() {
2166 assert_snapshot!(
2167 infer(r#"
2168fn quux() {
2169 let y = 92;
2170 1 + y;
2171}
2172"#),
2173 @r###"
2174 [11; 41) '{ ...+ y; }': ()
2175 [21; 22) 'y': i32
2176 [25; 27) '92': i32
2177 [33; 34) '1': i32
2178 [33; 38) '1 + y': i32
2179 [37; 38) 'y': i32
2180 "###
2181 );
2182}
2183
2184#[test]
2185fn recursive_vars() {
2186 covers!(type_var_cycles_resolve_completely);
2187 covers!(type_var_cycles_resolve_as_possible);
2188 assert_snapshot!(
2189 infer(r#"
2190fn test() {
2191 let y = unknown;
2192 [y, &y];
2193}
2194"#),
2195 @r###"
2196 [11; 48) '{ ...&y]; }': ()
2197 [21; 22) 'y': &{unknown}
2198 [25; 32) 'unknown': &{unknown}
2199 [38; 45) '[y, &y]': [&&{unknown};_]
2200 [39; 40) 'y': &{unknown}
2201 [42; 44) '&y': &&{unknown}
2202 [43; 44) 'y': &{unknown}
2203 "###
2204 );
2205}
2206
2207#[test]
2208fn recursive_vars_2() {
2209 covers!(type_var_cycles_resolve_completely);
2210 covers!(type_var_cycles_resolve_as_possible);
2211 assert_snapshot!(
2212 infer(r#"
2213fn test() {
2214 let x = unknown;
2215 let y = unknown;
2216 [(x, y), (&y, &x)];
2217}
2218"#),
2219 @r###"
2220 [11; 80) '{ ...x)]; }': ()
2221 [21; 22) 'x': &&{unknown}
2222 [25; 32) 'unknown': &&{unknown}
2223 [42; 43) 'y': &&{unknown}
2224 [46; 53) 'unknown': &&{unknown}
2225 [59; 77) '[(x, y..., &x)]': [(&&&{unknown}, &&&{unknown});_]
2226 [60; 66) '(x, y)': (&&&{unknown}, &&&{unknown})
2227 [61; 62) 'x': &&{unknown}
2228 [64; 65) 'y': &&{unknown}
2229 [68; 76) '(&y, &x)': (&&&{unknown}, &&&{unknown})
2230 [69; 71) '&y': &&&{unknown}
2231 [70; 71) 'y': &&{unknown}
2232 [73; 75) '&x': &&&{unknown}
2233 [74; 75) 'x': &&{unknown}
2234 "###
2235 );
2236}
2237
2238#[test]
2239fn infer_type_param() {
2240 assert_snapshot!(
2241 infer(r#"
2242fn id<T>(x: T) -> T {
2243 x
2244}
2245
2246fn clone<T>(x: &T) -> T {
2247 *x
2248}
2249
2250fn test() {
2251 let y = 10u32;
2252 id(y);
2253 let x: bool = clone(z);
2254 id::<i128>(1);
2255}
2256"#),
2257 @r###"
2258 [10; 11) 'x': T
2259 [21; 30) '{ x }': T
2260 [27; 28) 'x': T
2261 [44; 45) 'x': &T
2262 [56; 66) '{ *x }': T
2263 [62; 64) '*x': T
2264 [63; 64) 'x': &T
2265 [78; 158) '{ ...(1); }': ()
2266 [88; 89) 'y': u32
2267 [92; 97) '10u32': u32
2268 [103; 105) 'id': fn id<u32>(T) -> T
2269 [103; 108) 'id(y)': u32
2270 [106; 107) 'y': u32
2271 [118; 119) 'x': bool
2272 [128; 133) 'clone': fn clone<bool>(&T) -> T
2273 [128; 136) 'clone(z)': bool
2274 [134; 135) 'z': &bool
2275 [142; 152) 'id::<i128>': fn id<i128>(T) -> T
2276 [142; 155) 'id::<i128>(1)': i128
2277 [153; 154) '1': i128
2278 "###
2279 );
2280}
2281
2282#[test]
2283fn infer_std_crash_1() {
2284 // caused stack overflow, taken from std
2285 assert_snapshot!(
2286 infer(r#"
2287enum Maybe<T> {
2288 Real(T),
2289 Fake,
2290}
2291
2292fn write() {
2293 match something_unknown {
2294 Maybe::Real(ref mut something) => (),
2295 }
2296}
2297"#),
2298 @r###"
2299 [54; 139) '{ ... } }': ()
2300 [60; 137) 'match ... }': ()
2301 [66; 83) 'someth...nknown': Maybe<{unknown}>
2302 [94; 124) 'Maybe:...thing)': Maybe<{unknown}>
2303 [106; 123) 'ref mu...ething': &mut {unknown}
2304 [128; 130) '()': ()
2305 "###
2306 );
2307}
2308
2309#[test]
2310fn infer_std_crash_2() {
2311 covers!(type_var_resolves_to_int_var);
2312 // caused "equating two type variables, ...", taken from std
2313 assert_snapshot!(
2314 infer(r#"
2315fn test_line_buffer() {
2316 &[0, b'\n', 1, b'\n'];
2317}
2318"#),
2319 @r###"
2320 [23; 53) '{ ...n']; }': ()
2321 [29; 50) '&[0, b...b'\n']': &[u8;_]
2322 [30; 50) '[0, b'...b'\n']': [u8;_]
2323 [31; 32) '0': u8
2324 [34; 39) 'b'\n'': u8
2325 [41; 42) '1': u8
2326 [44; 49) 'b'\n'': u8
2327 "###
2328 );
2329}
2330
2331#[test]
2332fn infer_std_crash_3() {
2333 // taken from rustc
2334 assert_snapshot!(
2335 infer(r#"
2336pub fn compute() {
2337 match nope!() {
2338 SizeSkeleton::Pointer { non_zero: true, tail } => {}
2339 }
2340}
2341"#),
2342 @r###"
2343 [18; 108) '{ ... } }': ()
2344 [24; 106) 'match ... }': ()
2345 [30; 37) 'nope!()': {unknown}
2346 [48; 94) 'SizeSk...tail }': {unknown}
2347 [82; 86) 'true': {unknown}
2348 [88; 92) 'tail': {unknown}
2349 [98; 100) '{}': ()
2350 "###
2351 );
2352}
2353
2354#[test]
2355fn infer_std_crash_4() {
2356 // taken from rustc
2357 assert_snapshot!(
2358 infer(r#"
2359pub fn primitive_type() {
2360 match *self {
2361 BorrowedRef { type_: Primitive(p), ..} => {},
2362 }
2363}
2364"#),
2365 @r###"
2366 [25; 106) '{ ... } }': ()
2367 [31; 104) 'match ... }': ()
2368 [37; 42) '*self': {unknown}
2369 [38; 42) 'self': {unknown}
2370 [53; 91) 'Borrow...), ..}': {unknown}
2371 [74; 86) 'Primitive(p)': {unknown}
2372 [84; 85) 'p': {unknown}
2373 [95; 97) '{}': ()
2374 "###
2375 );
2376}
2377
2378#[test]
2379fn infer_std_crash_5() {
2380 // taken from rustc
2381 assert_snapshot!(
2382 infer(r#"
2383fn extra_compiler_flags() {
2384 for content in doesnt_matter {
2385 let name = if doesnt_matter {
2386 first
2387 } else {
2388 &content
2389 };
2390
2391 let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) {
2392 name
2393 } else {
2394 content
2395 };
2396 }
2397}
2398"#),
2399 @r###"
2400 [27; 323) '{ ... } }': ()
2401 [33; 321) 'for co... }': ()
2402 [37; 44) 'content': &{unknown}
2403 [48; 61) 'doesnt_matter': {unknown}
2404 [62; 321) '{ ... }': ()
2405 [76; 80) 'name': &&{unknown}
2406 [83; 167) 'if doe... }': &&{unknown}
2407 [86; 99) 'doesnt_matter': bool
2408 [100; 129) '{ ... }': &&{unknown}
2409 [114; 119) 'first': &&{unknown}
2410 [135; 167) '{ ... }': &&{unknown}
2411 [149; 157) '&content': &&{unknown}
2412 [150; 157) 'content': &{unknown}
2413 [182; 189) 'content': &{unknown}
2414 [192; 314) 'if ICE... }': &{unknown}
2415 [195; 232) 'ICE_RE..._VALUE': {unknown}
2416 [195; 248) 'ICE_RE...&name)': bool
2417 [242; 247) '&name': &&&{unknown}
2418 [243; 247) 'name': &&{unknown}
2419 [249; 277) '{ ... }': &&{unknown}
2420 [263; 267) 'name': &&{unknown}
2421 [283; 314) '{ ... }': &{unknown}
2422 [297; 304) 'content': &{unknown}
2423 "###
2424 );
2425}
2426
2427#[test]
2428fn infer_nested_generics_crash() {
2429 // another crash found typechecking rustc
2430 assert_snapshot!(
2431 infer(r#"
2432struct Canonical<V> {
2433 value: V,
2434}
2435struct QueryResponse<V> {
2436 value: V,
2437}
2438fn test<R>(query_response: Canonical<QueryResponse<R>>) {
2439 &query_response.value;
2440}
2441"#),
2442 @r###"
2443 [92; 106) 'query_response': Canonical<QueryResponse<R>>
2444 [137; 167) '{ ...lue; }': ()
2445 [143; 164) '&query....value': &QueryResponse<R>
2446 [144; 158) 'query_response': Canonical<QueryResponse<R>>
2447 [144; 164) 'query_....value': QueryResponse<R>
2448 "###
2449 );
2450}
2451
2452#[test]
2453fn bug_1030() {
2454 assert_snapshot!(infer(r#"
2455struct HashSet<T, H>;
2456struct FxHasher;
2457type FxHashSet<T> = HashSet<T, FxHasher>;
2458
2459impl<T, H> HashSet<T, H> {
2460 fn default() -> HashSet<T, H> {}
2461}
2462
2463pub fn main_loop() {
2464 FxHashSet::default();
2465}
2466"#),
2467 @r###"
2468 [144; 146) '{}': ()
2469 [169; 198) '{ ...t(); }': ()
2470 [175; 193) 'FxHash...efault': fn default<{unknown}, FxHasher>() -> HashSet<T, H>
2471 [175; 195) 'FxHash...ault()': HashSet<{unknown}, FxHasher>
2472 "###
2473 );
2474}
2475
2476#[test]
2477fn cross_crate_associated_method_call() {
2478 let (db, pos) = TestDB::with_position(
2479 r#"
2480//- /main.rs crate:main deps:other_crate
2481fn test() {
2482 let x = other_crate::foo::S::thing();
2483 x<|>;
2484}
2485
2486//- /lib.rs crate:other_crate
2487mod foo {
2488 struct S;
2489 impl S {
2490 fn thing() -> i128 {}
2491 }
2492}
2493"#,
2494 );
2495 assert_eq!("i128", type_at_pos(&db, pos));
2496}
2497
2498#[test]
2499fn infer_const() {
2500 assert_snapshot!(
2501 infer(r#"
2502struct Foo;
2503impl Foo { const ASSOC_CONST: u32 = 0; }
2504const GLOBAL_CONST: u32 = 101;
2505fn test() {
2506 const LOCAL_CONST: u32 = 99;
2507 let x = LOCAL_CONST;
2508 let z = GLOBAL_CONST;
2509 let id = Foo::ASSOC_CONST;
2510}
2511"#),
2512 @r###"
2513 [49; 50) '0': u32
2514 [80; 83) '101': u32
2515 [95; 213) '{ ...NST; }': ()
2516 [138; 139) 'x': {unknown}
2517 [142; 153) 'LOCAL_CONST': {unknown}
2518 [163; 164) 'z': u32
2519 [167; 179) 'GLOBAL_CONST': u32
2520 [189; 191) 'id': u32
2521 [194; 210) 'Foo::A..._CONST': u32
2522 "###
2523 );
2524}
2525
2526#[test]
2527fn infer_static() {
2528 assert_snapshot!(
2529 infer(r#"
2530static GLOBAL_STATIC: u32 = 101;
2531static mut GLOBAL_STATIC_MUT: u32 = 101;
2532fn test() {
2533 static LOCAL_STATIC: u32 = 99;
2534 static mut LOCAL_STATIC_MUT: u32 = 99;
2535 let x = LOCAL_STATIC;
2536 let y = LOCAL_STATIC_MUT;
2537 let z = GLOBAL_STATIC;
2538 let w = GLOBAL_STATIC_MUT;
2539}
2540"#),
2541 @r###"
2542 [29; 32) '101': u32
2543 [70; 73) '101': u32
2544 [85; 280) '{ ...MUT; }': ()
2545 [173; 174) 'x': {unknown}
2546 [177; 189) 'LOCAL_STATIC': {unknown}
2547 [199; 200) 'y': {unknown}
2548 [203; 219) 'LOCAL_...IC_MUT': {unknown}
2549 [229; 230) 'z': u32
2550 [233; 246) 'GLOBAL_STATIC': u32
2551 [256; 257) 'w': u32
2552 [260; 277) 'GLOBAL...IC_MUT': u32
2553 "###
2554 );
2555}
2556
2557#[test]
2558fn infer_trait_method_simple() {
2559 // the trait implementation is intentionally incomplete -- it shouldn't matter
2560 assert_snapshot!(
2561 infer(r#"
2562trait Trait1 {
2563 fn method(&self) -> u32;
2564}
2565struct S1;
2566impl Trait1 for S1 {}
2567trait Trait2 {
2568 fn method(&self) -> i128;
2569}
2570struct S2;
2571impl Trait2 for S2 {}
2572fn test() {
2573 S1.method(); // -> u32
2574 S2.method(); // -> i128
2575}
2576"#),
2577 @r###"
2578 [31; 35) 'self': &Self
2579 [110; 114) 'self': &Self
2580 [170; 228) '{ ...i128 }': ()
2581 [176; 178) 'S1': S1
2582 [176; 187) 'S1.method()': u32
2583 [203; 205) 'S2': S2
2584 [203; 214) 'S2.method()': i128
2585 "###
2586 );
2587}
2588
2589#[test]
2590fn infer_trait_method_scoped() {
2591 // the trait implementation is intentionally incomplete -- it shouldn't matter
2592 assert_snapshot!(
2593 infer(r#"
2594struct S;
2595mod foo {
2596 pub trait Trait1 {
2597 fn method(&self) -> u32;
2598 }
2599 impl Trait1 for super::S {}
2600}
2601mod bar {
2602 pub trait Trait2 {
2603 fn method(&self) -> i128;
2604 }
2605 impl Trait2 for super::S {}
2606}
2607
2608mod foo_test {
2609 use super::S;
2610 use super::foo::Trait1;
2611 fn test() {
2612 S.method(); // -> u32
2613 }
2614}
2615
2616mod bar_test {
2617 use super::S;
2618 use super::bar::Trait2;
2619 fn test() {
2620 S.method(); // -> i128
2621 }
2622}
2623"#),
2624 @r###"
2625 [63; 67) 'self': &Self
2626 [169; 173) 'self': &Self
2627 [300; 337) '{ ... }': ()
2628 [310; 311) 'S': S
2629 [310; 320) 'S.method()': u32
2630 [416; 454) '{ ... }': ()
2631 [426; 427) 'S': S
2632 [426; 436) 'S.method()': i128
2633 "###
2634 );
2635}
2636
2637#[test]
2638fn infer_trait_method_generic_1() {
2639 // the trait implementation is intentionally incomplete -- it shouldn't matter
2640 assert_snapshot!(
2641 infer(r#"
2642trait Trait<T> {
2643 fn method(&self) -> T;
2644}
2645struct S;
2646impl Trait<u32> for S {}
2647fn test() {
2648 S.method();
2649}
2650"#),
2651 @r###"
2652 [33; 37) 'self': &Self
2653 [92; 111) '{ ...d(); }': ()
2654 [98; 99) 'S': S
2655 [98; 108) 'S.method()': u32
2656 "###
2657 );
2658}
2659
2660#[test]
2661fn infer_trait_method_generic_more_params() {
2662 // the trait implementation is intentionally incomplete -- it shouldn't matter
2663 assert_snapshot!(
2664 infer(r#"
2665trait Trait<T1, T2, T3> {
2666 fn method1(&self) -> (T1, T2, T3);
2667 fn method2(&self) -> (T3, T2, T1);
2668}
2669struct S1;
2670impl Trait<u8, u16, u32> for S1 {}
2671struct S2;
2672impl<T> Trait<i8, i16, T> for S2 {}
2673fn test() {
2674 S1.method1(); // u8, u16, u32
2675 S1.method2(); // u32, u16, u8
2676 S2.method1(); // i8, i16, {unknown}
2677 S2.method2(); // {unknown}, i16, i8
2678}
2679"#),
2680 @r###"
2681 [43; 47) 'self': &Self
2682 [82; 86) 'self': &Self
2683 [210; 361) '{ ..., i8 }': ()
2684 [216; 218) 'S1': S1
2685 [216; 228) 'S1.method1()': (u8, u16, u32)
2686 [250; 252) 'S1': S1
2687 [250; 262) 'S1.method2()': (u32, u16, u8)
2688 [284; 286) 'S2': S2
2689 [284; 296) 'S2.method1()': (i8, i16, {unknown})
2690 [324; 326) 'S2': S2
2691 [324; 336) 'S2.method2()': ({unknown}, i16, i8)
2692 "###
2693 );
2694}
2695
2696#[test]
2697fn infer_trait_method_generic_2() {
2698 // the trait implementation is intentionally incomplete -- it shouldn't matter
2699 assert_snapshot!(
2700 infer(r#"
2701trait Trait<T> {
2702 fn method(&self) -> T;
2703}
2704struct S<T>(T);
2705impl<U> Trait<U> for S<U> {}
2706fn test() {
2707 S(1u32).method();
2708}
2709"#),
2710 @r###"
2711 [33; 37) 'self': &Self
2712 [102; 127) '{ ...d(); }': ()
2713 [108; 109) 'S': S<u32>(T) -> S<T>
2714 [108; 115) 'S(1u32)': S<u32>
2715 [108; 124) 'S(1u32...thod()': u32
2716 [110; 114) '1u32': u32
2717 "###
2718 );
2719}
2720
2721#[test]
2722fn infer_trait_assoc_method() {
2723 assert_snapshot!(
2724 infer(r#"
2725trait Default {
2726 fn default() -> Self;
2727}
2728struct S;
2729impl Default for S {}
2730fn test() {
2731 let s1: S = Default::default();
2732 let s2 = S::default();
2733 let s3 = <S as Default>::default();
2734}
2735"#),
2736 @r###"
2737 [87; 193) '{ ...t(); }': ()
2738 [97; 99) 's1': S
2739 [105; 121) 'Defaul...efault': fn default<S>() -> Self
2740 [105; 123) 'Defaul...ault()': S
2741 [133; 135) 's2': S
2742 [138; 148) 'S::default': fn default<S>() -> Self
2743 [138; 150) 'S::default()': S
2744 [160; 162) 's3': S
2745 [165; 188) '<S as ...efault': fn default<S>() -> Self
2746 [165; 190) '<S as ...ault()': S
2747 "###
2748 );
2749}
2750
2751#[test]
2752fn infer_trait_assoc_method_generics_1() {
2753 assert_snapshot!(
2754 infer(r#"
2755trait Trait<T> {
2756 fn make() -> T;
2757}
2758struct S;
2759impl Trait<u32> for S {}
2760struct G<T>;
2761impl<T> Trait<T> for G<T> {}
2762fn test() {
2763 let a = S::make();
2764 let b = G::<u64>::make();
2765 let c: f64 = G::make();
2766}
2767"#),
2768 @r###"
2769 [127; 211) '{ ...e(); }': ()
2770 [137; 138) 'a': u32
2771 [141; 148) 'S::make': fn make<S, u32>() -> T
2772 [141; 150) 'S::make()': u32
2773 [160; 161) 'b': u64
2774 [164; 178) 'G::<u64>::make': fn make<G<u64>, u64>() -> T
2775 [164; 180) 'G::<u6...make()': u64
2776 [190; 191) 'c': f64
2777 [199; 206) 'G::make': fn make<G<f64>, f64>() -> T
2778 [199; 208) 'G::make()': f64
2779 "###
2780 );
2781}
2782
2783#[test]
2784fn infer_trait_assoc_method_generics_2() {
2785 assert_snapshot!(
2786 infer(r#"
2787trait Trait<T> {
2788 fn make<U>() -> (T, U);
2789}
2790struct S;
2791impl Trait<u32> for S {}
2792struct G<T>;
2793impl<T> Trait<T> for G<T> {}
2794fn test() {
2795 let a = S::make::<i64>();
2796 let b: (_, i64) = S::make();
2797 let c = G::<u32>::make::<i64>();
2798 let d: (u32, _) = G::make::<i64>();
2799 let e: (u32, i64) = G::make();
2800}
2801"#),
2802 @r###"
2803 [135; 313) '{ ...e(); }': ()
2804 [145; 146) 'a': (u32, i64)
2805 [149; 163) 'S::make::<i64>': fn make<S, u32, i64>() -> (T, U)
2806 [149; 165) 'S::mak...i64>()': (u32, i64)
2807 [175; 176) 'b': (u32, i64)
2808 [189; 196) 'S::make': fn make<S, u32, i64>() -> (T, U)
2809 [189; 198) 'S::make()': (u32, i64)
2810 [208; 209) 'c': (u32, i64)
2811 [212; 233) 'G::<u3...:<i64>': fn make<G<u32>, u32, i64>() -> (T, U)
2812 [212; 235) 'G::<u3...i64>()': (u32, i64)
2813 [245; 246) 'd': (u32, i64)
2814 [259; 273) 'G::make::<i64>': fn make<G<u32>, u32, i64>() -> (T, U)
2815 [259; 275) 'G::mak...i64>()': (u32, i64)
2816 [285; 286) 'e': (u32, i64)
2817 [301; 308) 'G::make': fn make<G<u32>, u32, i64>() -> (T, U)
2818 [301; 310) 'G::make()': (u32, i64)
2819 "###
2820 );
2821}
2822
2823#[test]
2824fn infer_trait_assoc_method_generics_3() {
2825 assert_snapshot!(
2826 infer(r#"
2827trait Trait<T> {
2828 fn make() -> (Self, T);
2829}
2830struct S<T>;
2831impl Trait<i64> for S<i32> {}
2832fn test() {
2833 let a = S::make();
2834}
2835"#),
2836 @r###"
2837 [101; 127) '{ ...e(); }': ()
2838 [111; 112) 'a': (S<i32>, i64)
2839 [115; 122) 'S::make': fn make<S<i32>, i64>() -> (Self, T)
2840 [115; 124) 'S::make()': (S<i32>, i64)
2841 "###
2842 );
2843}
2844
2845#[test]
2846fn infer_trait_assoc_method_generics_4() {
2847 assert_snapshot!(
2848 infer(r#"
2849trait Trait<T> {
2850 fn make() -> (Self, T);
2851}
2852struct S<T>;
2853impl Trait<i64> for S<u64> {}
2854impl Trait<i32> for S<u32> {}
2855fn test() {
2856 let a: (S<u64>, _) = S::make();
2857 let b: (_, i32) = S::make();
2858}
2859"#),
2860 @r###"
2861 [131; 203) '{ ...e(); }': ()
2862 [141; 142) 'a': (S<u64>, i64)
2863 [158; 165) 'S::make': fn make<S<u64>, i64>() -> (Self, T)
2864 [158; 167) 'S::make()': (S<u64>, i64)
2865 [177; 178) 'b': (S<u32>, i32)
2866 [191; 198) 'S::make': fn make<S<u32>, i32>() -> (Self, T)
2867 [191; 200) 'S::make()': (S<u32>, i32)
2868 "###
2869 );
2870}
2871
2872#[test]
2873fn infer_trait_assoc_method_generics_5() {
2874 assert_snapshot!(
2875 infer(r#"
2876trait Trait<T> {
2877 fn make<U>() -> (Self, T, U);
2878}
2879struct S<T>;
2880impl Trait<i64> for S<u64> {}
2881fn test() {
2882 let a = <S as Trait<i64>>::make::<u8>();
2883 let b: (S<u64>, _, _) = Trait::<i64>::make::<u8>();
2884}
2885"#),
2886 @r###"
2887 [107; 211) '{ ...>(); }': ()
2888 [117; 118) 'a': (S<u64>, i64, u8)
2889 [121; 150) '<S as ...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U)
2890 [121; 152) '<S as ...<u8>()': (S<u64>, i64, u8)
2891 [162; 163) 'b': (S<u64>, i64, u8)
2892 [182; 206) 'Trait:...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U)
2893 [182; 208) 'Trait:...<u8>()': (S<u64>, i64, u8)
2894 "###
2895 );
2896}
2897
2898#[test]
2899fn infer_from_bound_1() {
2900 assert_snapshot!(
2901 infer(r#"
2902trait Trait<T> {}
2903struct S<T>(T);
2904impl<U> Trait<U> for S<U> {}
2905fn foo<T: Trait<u32>>(t: T) {}
2906fn test() {
2907 let s = S(unknown);
2908 foo(s);
2909}
2910"#),
2911 @r###"
2912 [86; 87) 't': T
2913 [92; 94) '{}': ()
2914 [105; 144) '{ ...(s); }': ()
2915 [115; 116) 's': S<u32>
2916 [119; 120) 'S': S<u32>(T) -> S<T>
2917 [119; 129) 'S(unknown)': S<u32>
2918 [121; 128) 'unknown': u32
2919 [135; 138) 'foo': fn foo<S<u32>>(T) -> ()
2920 [135; 141) 'foo(s)': ()
2921 [139; 140) 's': S<u32>
2922 "###
2923 );
2924}
2925
2926#[test]
2927fn infer_from_bound_2() {
2928 assert_snapshot!(
2929 infer(r#"
2930trait Trait<T> {}
2931struct S<T>(T);
2932impl<U> Trait<U> for S<U> {}
2933fn foo<U, T: Trait<U>>(t: T) -> U {}
2934fn test() {
2935 let s = S(unknown);
2936 let x: u32 = foo(s);
2937}
2938"#),
2939 @r###"
2940 [87; 88) 't': T
2941 [98; 100) '{}': ()
2942 [111; 163) '{ ...(s); }': ()
2943 [121; 122) 's': S<u32>
2944 [125; 126) 'S': S<u32>(T) -> S<T>
2945 [125; 135) 'S(unknown)': S<u32>
2946 [127; 134) 'unknown': u32
2947 [145; 146) 'x': u32
2948 [154; 157) 'foo': fn foo<u32, S<u32>>(T) -> U
2949 [154; 160) 'foo(s)': u32
2950 [158; 159) 's': S<u32>
2951 "###
2952 );
2953}
2954
2955#[test]
2956fn infer_call_trait_method_on_generic_param_1() {
2957 assert_snapshot!(
2958 infer(r#"
2959trait Trait {
2960 fn method(&self) -> u32;
2961}
2962fn test<T: Trait>(t: T) {
2963 t.method();
2964}
2965"#),
2966 @r###"
2967 [30; 34) 'self': &Self
2968 [64; 65) 't': T
2969 [70; 89) '{ ...d(); }': ()
2970 [76; 77) 't': T
2971 [76; 86) 't.method()': u32
2972 "###
2973 );
2974}
2975
2976#[test]
2977fn infer_call_trait_method_on_generic_param_2() {
2978 assert_snapshot!(
2979 infer(r#"
2980trait Trait<T> {
2981 fn method(&self) -> T;
2982}
2983fn test<U, T: Trait<U>>(t: T) {
2984 t.method();
2985}
2986"#),
2987 @r###"
2988 [33; 37) 'self': &Self
2989 [71; 72) 't': T
2990 [77; 96) '{ ...d(); }': ()
2991 [83; 84) 't': T
2992 [83; 93) 't.method()': [missing name]
2993 "###
2994 );
2995}
2996
2997#[test]
2998fn infer_with_multiple_trait_impls() {
2999 assert_snapshot!(
3000 infer(r#"
3001trait Into<T> {
3002 fn into(self) -> T;
3003}
3004struct S;
3005impl Into<u32> for S {}
3006impl Into<u64> for S {}
3007fn test() {
3008 let x: u32 = S.into();
3009 let y: u64 = S.into();
3010 let z = Into::<u64>::into(S);
3011}
3012"#),
3013 @r###"
3014 [29; 33) 'self': Self
3015 [111; 202) '{ ...(S); }': ()
3016 [121; 122) 'x': u32
3017 [130; 131) 'S': S
3018 [130; 138) 'S.into()': u32
3019 [148; 149) 'y': u64
3020 [157; 158) 'S': S
3021 [157; 165) 'S.into()': u64
3022 [175; 176) 'z': u64
3023 [179; 196) 'Into::...::into': fn into<S, u64>(Self) -> T
3024 [179; 199) 'Into::...nto(S)': u64
3025 [197; 198) 'S': S
3026 "###
3027 );
3028}
3029
3030#[test]
3031fn infer_project_associated_type() {
3032 // y, z, a don't yet work because of https://github.com/rust-lang/chalk/issues/234
3033 assert_snapshot!(
3034 infer(r#"
3035trait Iterable {
3036 type Item;
3037}
3038struct S;
3039impl Iterable for S { type Item = u32; }
3040fn test<T: Iterable>() {
3041 let x: <S as Iterable>::Item = 1;
3042 let y: <T as Iterable>::Item = no_matter;
3043 let z: T::Item = no_matter;
3044 let a: <T>::Item = no_matter;
3045}
3046"#),
3047 @r###"
3048 [108; 261) '{ ...ter; }': ()
3049 [118; 119) 'x': u32
3050 [145; 146) '1': u32
3051 [156; 157) 'y': {unknown}
3052 [183; 192) 'no_matter': {unknown}
3053 [202; 203) 'z': {unknown}
3054 [215; 224) 'no_matter': {unknown}
3055 [234; 235) 'a': {unknown}
3056 [249; 258) 'no_matter': {unknown}
3057 "###
3058 );
3059}
3060
3061#[test]
3062fn infer_return_associated_type() {
3063 assert_snapshot!(
3064 infer(r#"
3065trait Iterable {
3066 type Item;
3067}
3068struct S;
3069impl Iterable for S { type Item = u32; }
3070fn foo1<T: Iterable>(t: T) -> T::Item {}
3071fn foo2<T: Iterable>(t: T) -> <T as Iterable>::Item {}
3072fn foo3<T: Iterable>(t: T) -> <T>::Item {}
3073fn test() {
3074 let x = foo1(S);
3075 let y = foo2(S);
3076 let z = foo3(S);
3077}
3078"#),
3079 @r###"
3080 [106; 107) 't': T
3081 [123; 125) '{}': ()
3082 [147; 148) 't': T
3083 [178; 180) '{}': ()
3084 [202; 203) 't': T
3085 [221; 223) '{}': ()
3086 [234; 300) '{ ...(S); }': ()
3087 [244; 245) 'x': u32
3088 [248; 252) 'foo1': fn foo1<S>(T) -> <T as Iterable>::Item
3089 [248; 255) 'foo1(S)': u32
3090 [253; 254) 'S': S
3091 [265; 266) 'y': u32
3092 [269; 273) 'foo2': fn foo2<S>(T) -> <T as Iterable>::Item
3093 [269; 276) 'foo2(S)': u32
3094 [274; 275) 'S': S
3095 [286; 287) 'z': u32
3096 [290; 294) 'foo3': fn foo3<S>(T) -> <T as Iterable>::Item
3097 [290; 297) 'foo3(S)': u32
3098 [295; 296) 'S': S
3099 "###
3100 );
3101}
3102
3103#[test]
3104fn infer_associated_type_bound() {
3105 assert_snapshot!(
3106 infer(r#"
3107trait Iterable {
3108 type Item;
3109}
3110fn test<T: Iterable<Item=u32>>() {
3111 let y: T::Item = unknown;
3112}
3113"#),
3114 @r###"
3115 [67; 100) '{ ...own; }': ()
3116 [77; 78) 'y': {unknown}
3117 [90; 97) 'unknown': {unknown}
3118 "###
3119 );
3120}
3121
3122#[test]
3123fn infer_const_body() {
3124 assert_snapshot!(
3125 infer(r#"
3126const A: u32 = 1 + 1;
3127static B: u64 = { let x = 1; x };
3128"#),
3129 @r###"
3130 [16; 17) '1': u32
3131 [16; 21) '1 + 1': u32
3132 [20; 21) '1': u32
3133 [39; 55) '{ let ...1; x }': u64
3134 [45; 46) 'x': u64
3135 [49; 50) '1': u64
3136 [52; 53) 'x': u64
3137 "###
3138 );
3139}
3140
3141#[test]
3142fn tuple_struct_fields() {
3143 assert_snapshot!(
3144 infer(r#"
3145struct S(i32, u64);
3146fn test() -> u64 {
3147 let a = S(4, 6);
3148 let b = a.0;
3149 a.1
3150}
3151"#),
3152 @r###"
3153 [38; 87) '{ ... a.1 }': u64
3154 [48; 49) 'a': S
3155 [52; 53) 'S': S(i32, u64) -> S
3156 [52; 59) 'S(4, 6)': S
3157 [54; 55) '4': i32
3158 [57; 58) '6': u64
3159 [69; 70) 'b': i32
3160 [73; 74) 'a': S
3161 [73; 76) 'a.0': i32
3162 [82; 83) 'a': S
3163 [82; 85) 'a.1': u64
3164 "###
3165 );
3166}
3167
3168#[test]
3169fn tuple_struct_with_fn() {
3170 assert_snapshot!(
3171 infer(r#"
3172struct S(fn(u32) -> u64);
3173fn test() -> u64 {
3174 let a = S(|i| 2*i);
3175 let b = a.0(4);
3176 a.0(2)
3177}
3178"#),
3179 @r###"
3180 [44; 102) '{ ...0(2) }': u64
3181 [54; 55) 'a': S
3182 [58; 59) 'S': S(fn(u32) -> u64) -> S
3183 [58; 68) 'S(|i| 2*i)': S
3184 [60; 67) '|i| 2*i': |i32| -> i32
3185 [61; 62) 'i': i32
3186 [64; 65) '2': i32
3187 [64; 67) '2*i': i32
3188 [66; 67) 'i': i32
3189 [78; 79) 'b': u64
3190 [82; 83) 'a': S
3191 [82; 85) 'a.0': fn(u32) -> u64
3192 [82; 88) 'a.0(4)': u64
3193 [86; 87) '4': u32
3194 [94; 95) 'a': S
3195 [94; 97) 'a.0': fn(u32) -> u64
3196 [94; 100) 'a.0(2)': u64
3197 [98; 99) '2': u32
3198 "###
3199 );
3200}
3201
3202#[test]
3203fn indexing_arrays() {
3204 assert_snapshot!(
3205 infer("fn main() { &mut [9][2]; }"),
3206 @r###"
3207 [10; 26) '{ &mut...[2]; }': ()
3208 [12; 23) '&mut [9][2]': &mut {unknown}
3209 [17; 20) '[9]': [i32;_]
3210 [17; 23) '[9][2]': {unknown}
3211 [18; 19) '9': i32
3212 [21; 22) '2': i32
3213 "###
3214 )
3215}
3216
3217#[test]
3218fn infer_macros_expanded() {
3219 assert_snapshot!(
3220 infer(r#"
3221struct Foo(Vec<i32>);
3222
3223macro_rules! foo {
3224 ($($item:expr),*) => {
3225 {
3226 Foo(vec![$($item,)*])
3227 }
3228 };
3229}
3230
3231fn main() {
3232 let x = foo!(1,2);
3233}
3234"#),
3235 @r###"
3236 ![0; 17) '{Foo(v...,2,])}': Foo
3237 ![1; 4) 'Foo': Foo({unknown}) -> Foo
3238 ![1; 16) 'Foo(vec![1,2,])': Foo
3239 ![5; 15) 'vec![1,2,]': {unknown}
3240 [156; 182) '{ ...,2); }': ()
3241 [166; 167) 'x': Foo
3242 "###
3243 );
3244}
3245
3246#[test]
3247fn infer_legacy_textual_scoped_macros_expanded() {
3248 assert_snapshot!(
3249 infer(r#"
3250struct Foo(Vec<i32>);
3251
3252#[macro_use]
3253mod m {
3254 macro_rules! foo {
3255 ($($item:expr),*) => {
3256 {
3257 Foo(vec![$($item,)*])
3258 }
3259 };
3260 }
3261}
3262
3263fn main() {
3264 let x = foo!(1,2);
3265 let y = crate::foo!(1,2);
3266}
3267"#),
3268 @r###"
3269 ![0; 17) '{Foo(v...,2,])}': Foo
3270 ![1; 4) 'Foo': Foo({unknown}) -> Foo
3271 ![1; 16) 'Foo(vec![1,2,])': Foo
3272 ![5; 15) 'vec![1,2,]': {unknown}
3273 [195; 251) '{ ...,2); }': ()
3274 [205; 206) 'x': Foo
3275 [228; 229) 'y': {unknown}
3276 [232; 248) 'crate:...!(1,2)': {unknown}
3277 "###
3278 );
3279}
3280
3281#[test]
3282fn infer_path_qualified_macros_expanded() {
3283 assert_snapshot!(
3284 infer(r#"
3285#[macro_export]
3286macro_rules! foo {
3287 () => { 42i32 }
3288}
3289
3290mod m {
3291 pub use super::foo as bar;
3292}
3293
3294fn main() {
3295 let x = crate::foo!();
3296 let y = m::bar!();
3297}
3298"#),
3299 @r###"
3300 ![0; 5) '42i32': i32
3301 ![0; 5) '42i32': i32
3302 [111; 164) '{ ...!(); }': ()
3303 [121; 122) 'x': i32
3304 [148; 149) 'y': i32
3305 "###
3306 );
3307}
3308
3309#[test]
3310fn infer_type_value_macro_having_same_name() {
3311 assert_snapshot!(
3312 infer(r#"
3313#[macro_export]
3314macro_rules! foo {
3315 () => {
3316 mod foo {
3317 pub use super::foo;
3318 }
3319 };
3320 ($x:tt) => {
3321 $x
3322 };
3323}
3324
3325foo!();
3326
3327fn foo() {
3328 let foo = foo::foo!(42i32);
3329}
3330"#),
3331 @r###"
3332 ![0; 5) '42i32': i32
3333 [171; 206) '{ ...32); }': ()
3334 [181; 184) 'foo': i32
3335 "###
3336 );
3337}
3338
3339#[test]
3340fn processes_impls_generated_by_macros() {
3341 let t = type_at(
3342 r#"
3343//- /main.rs
3344macro_rules! m {
3345 ($ident:ident) => (impl Trait for $ident {})
3346}
3347trait Trait { fn foo(self) -> u128 {} }
3348struct S;
3349m!(S);
3350fn test() { S.foo()<|>; }
3351"#,
3352 );
3353 assert_eq!(t, "u128");
3354}
3355
3356#[test]
3357fn infer_macro_with_dollar_crate_is_correct_in_expr() {
3358 let (db, pos) = TestDB::with_position(
3359 r#"
3360//- /main.rs crate:main deps:foo
3361fn test() {
3362 let x = (foo::foo!(1), foo::foo!(2));
3363 x<|>;
3364}
3365
3366//- /lib.rs crate:foo
3367#[macro_export]
3368macro_rules! foo {
3369 (1) => { $crate::bar!() };
3370 (2) => { 1 + $crate::baz() };
3371}
3372
3373#[macro_export]
3374macro_rules! bar {
3375 () => { 42 }
3376}
3377
3378pub fn baz() -> usize { 31usize }
3379"#,
3380 );
3381 assert_eq!("(i32, usize)", type_at_pos(&db, pos));
3382}
3383
3384#[ignore]
3385#[test]
3386fn method_resolution_trait_before_autoref() {
3387 let t = type_at(
3388 r#"
3389//- /main.rs
3390trait Trait { fn foo(self) -> u128; }
3391struct S;
3392impl S { fn foo(&self) -> i8 { 0 } }
3393impl Trait for S { fn foo(self) -> u128 { 0 } }
3394fn test() { S.foo()<|>; }
3395"#,
3396 );
3397 assert_eq!(t, "u128");
3398}
3399
3400#[ignore]
3401#[test]
3402fn method_resolution_by_value_before_autoref() {
3403 let t = type_at(
3404 r#"
3405//- /main.rs
3406trait Clone { fn clone(&self) -> Self; }
3407struct S;
3408impl Clone for S {}
3409impl Clone for &S {}
3410fn test() { (S.clone(), (&S).clone(), (&&S).clone())<|>; }
3411"#,
3412 );
3413 assert_eq!(t, "(S, S, &S)");
3414}
3415
3416#[test]
3417fn method_resolution_trait_before_autoderef() {
3418 let t = type_at(
3419 r#"
3420//- /main.rs
3421trait Trait { fn foo(self) -> u128; }
3422struct S;
3423impl S { fn foo(self) -> i8 { 0 } }
3424impl Trait for &S { fn foo(self) -> u128 { 0 } }
3425fn test() { (&S).foo()<|>; }
3426"#,
3427 );
3428 assert_eq!(t, "u128");
3429}
3430
3431#[test]
3432fn method_resolution_impl_before_trait() {
3433 let t = type_at(
3434 r#"
3435//- /main.rs
3436trait Trait { fn foo(self) -> u128; }
3437struct S;
3438impl S { fn foo(self) -> i8 { 0 } }
3439impl Trait for S { fn foo(self) -> u128 { 0 } }
3440fn test() { S.foo()<|>; }
3441"#,
3442 );
3443 assert_eq!(t, "i8");
3444}
3445
3446#[test]
3447fn method_resolution_trait_autoderef() {
3448 let t = type_at(
3449 r#"
3450//- /main.rs
3451trait Trait { fn foo(self) -> u128; }
3452struct S;
3453impl Trait for S { fn foo(self) -> u128 { 0 } }
3454fn test() { (&S).foo()<|>; }
3455"#,
3456 );
3457 assert_eq!(t, "u128");
3458}
3459
3460#[test]
3461fn method_resolution_trait_from_prelude() {
3462 let (db, pos) = TestDB::with_position(
3463 r#"
3464//- /main.rs crate:main deps:other_crate
3465struct S;
3466impl Clone for S {}
3467
3468fn test() {
3469 S.clone()<|>;
3470}
3471
3472//- /lib.rs crate:other_crate
3473#[prelude_import] use foo::*;
3474
3475mod foo {
3476 trait Clone {
3477 fn clone(&self) -> Self;
3478 }
3479}
3480"#,
3481 );
3482 assert_eq!("S", type_at_pos(&db, pos));
3483}
3484
3485#[test]
3486fn method_resolution_where_clause_for_unknown_trait() {
3487 // The blanket impl shouldn't apply because we can't even resolve UnknownTrait
3488 let t = type_at(
3489 r#"
3490//- /main.rs
3491trait Trait { fn foo(self) -> u128; }
3492struct S;
3493impl<T> Trait for T where T: UnknownTrait {}
3494fn test() { (&S).foo()<|>; }
3495"#,
3496 );
3497 assert_eq!(t, "{unknown}");
3498}
3499
3500#[test]
3501fn method_resolution_where_clause_not_met() {
3502 // The blanket impl shouldn't apply because we can't prove S: Clone
3503 let t = type_at(
3504 r#"
3505//- /main.rs
3506trait Clone {}
3507trait Trait { fn foo(self) -> u128; }
3508struct S;
3509impl<T> Trait for T where T: Clone {}
3510fn test() { (&S).foo()<|>; }
3511"#,
3512 );
3513 // This is also to make sure that we don't resolve to the foo method just
3514 // because that's the only method named foo we can find, which would make
3515 // the below tests not work
3516 assert_eq!(t, "{unknown}");
3517}
3518
3519#[test]
3520fn method_resolution_where_clause_inline_not_met() {
3521 // The blanket impl shouldn't apply because we can't prove S: Clone
3522 let t = type_at(
3523 r#"
3524//- /main.rs
3525trait Clone {}
3526trait Trait { fn foo(self) -> u128; }
3527struct S;
3528impl<T: Clone> Trait for T {}
3529fn test() { (&S).foo()<|>; }
3530"#,
3531 );
3532 assert_eq!(t, "{unknown}");
3533}
3534
3535#[test]
3536fn method_resolution_where_clause_1() {
3537 let t = type_at(
3538 r#"
3539//- /main.rs
3540trait Clone {}
3541trait Trait { fn foo(self) -> u128; }
3542struct S;
3543impl Clone for S {}
3544impl<T> Trait for T where T: Clone {}
3545fn test() { S.foo()<|>; }
3546"#,
3547 );
3548 assert_eq!(t, "u128");
3549}
3550
3551#[test]
3552fn method_resolution_where_clause_2() {
3553 let t = type_at(
3554 r#"
3555//- /main.rs
3556trait Into<T> { fn into(self) -> T; }
3557trait From<T> { fn from(other: T) -> Self; }
3558struct S1;
3559struct S2;
3560impl From<S2> for S1 {}
3561impl<T, U> Into<U> for T where U: From<T> {}
3562fn test() { S2.into()<|>; }
3563"#,
3564 );
3565 assert_eq!(t, "{unknown}");
3566}
3567
3568#[test]
3569fn method_resolution_where_clause_inline() {
3570 let t = type_at(
3571 r#"
3572//- /main.rs
3573trait Into<T> { fn into(self) -> T; }
3574trait From<T> { fn from(other: T) -> Self; }
3575struct S1;
3576struct S2;
3577impl From<S2> for S1 {}
3578impl<T, U: From<T>> Into<U> for T {}
3579fn test() { S2.into()<|>; }
3580"#,
3581 );
3582 assert_eq!(t, "{unknown}");
3583}
3584
3585#[test]
3586fn method_resolution_encountering_fn_type() {
3587 type_at(
3588 r#"
3589//- /main.rs
3590fn foo() {}
3591trait FnOnce { fn call(self); }
3592fn test() { foo.call()<|>; }
3593"#,
3594 );
3595}
3596
3597#[test]
3598fn method_resolution_slow() {
3599 // this can get quite slow if we set the solver size limit too high
3600 let t = type_at(
3601 r#"
3602//- /main.rs
3603trait SendX {}
3604
3605struct S1; impl SendX for S1 {}
3606struct S2; impl SendX for S2 {}
3607struct U1;
3608
3609trait Trait { fn method(self); }
3610
3611struct X1<A, B> {}
3612impl<A, B> SendX for X1<A, B> where A: SendX, B: SendX {}
3613
3614struct S<B, C> {}
3615
3616trait FnX {}
3617
3618impl<B, C> Trait for S<B, C> where C: FnX, B: SendX {}
3619
3620fn test() { (S {}).method()<|>; }
3621"#,
3622 );
3623 assert_eq!(t, "()");
3624}
3625
3626#[test]
3627fn shadowing_primitive() {
3628 let t = type_at(
3629 r#"
3630//- /main.rs
3631struct i32;
3632struct Foo;
3633
3634impl i32 { fn foo(&self) -> Foo { Foo } }
3635
3636fn main() {
3637 let x: i32 = i32;
3638 x.foo()<|>;
3639}"#,
3640 );
3641 assert_eq!(t, "Foo");
3642}
3643
3644#[test]
3645fn deref_trait() {
3646 let t = type_at(
3647 r#"
3648//- /main.rs
3649#[lang = "deref"]
3650trait Deref {
3651 type Target;
3652 fn deref(&self) -> &Self::Target;
3653}
3654
3655struct Arc<T>;
3656impl<T> Deref for Arc<T> {
3657 type Target = T;
3658}
3659
3660struct S;
3661impl S {
3662 fn foo(&self) -> u128 {}
3663}
3664
3665fn test(s: Arc<S>) {
3666 (*s, s.foo())<|>;
3667}
3668"#,
3669 );
3670 assert_eq!(t, "(S, u128)");
3671}
3672
3673#[test]
3674fn deref_trait_with_inference_var() {
3675 let t = type_at(
3676 r#"
3677//- /main.rs
3678#[lang = "deref"]
3679trait Deref {
3680 type Target;
3681 fn deref(&self) -> &Self::Target;
3682}
3683
3684struct Arc<T>;
3685fn new_arc<T>() -> Arc<T> {}
3686impl<T> Deref for Arc<T> {
3687 type Target = T;
3688}
3689
3690struct S;
3691fn foo(a: Arc<S>) {}
3692
3693fn test() {
3694 let a = new_arc();
3695 let b = (*a)<|>;
3696 foo(a);
3697}
3698"#,
3699 );
3700 assert_eq!(t, "S");
3701}
3702
3703#[test]
3704fn deref_trait_infinite_recursion() {
3705 let t = type_at(
3706 r#"
3707//- /main.rs
3708#[lang = "deref"]
3709trait Deref {
3710 type Target;
3711 fn deref(&self) -> &Self::Target;
3712}
3713
3714struct S;
3715
3716impl Deref for S {
3717 type Target = S;
3718}
3719
3720fn test(s: S) {
3721 s.foo()<|>;
3722}
3723"#,
3724 );
3725 assert_eq!(t, "{unknown}");
3726}
3727
3728#[test]
3729fn deref_trait_with_question_mark_size() {
3730 let t = type_at(
3731 r#"
3732//- /main.rs
3733#[lang = "deref"]
3734trait Deref {
3735 type Target;
3736 fn deref(&self) -> &Self::Target;
3737}
3738
3739struct Arc<T>;
3740impl<T> Deref for Arc<T> {
3741 type Target = T;
3742}
3743
3744struct S;
3745impl S {
3746 fn foo(&self) -> u128 {}
3747}
3748
3749fn test(s: Arc<S>) {
3750 (*s, s.foo())<|>;
3751}
3752"#,
3753 );
3754 assert_eq!(t, "(S, u128)");
3755}
3756
3757#[test]
3758fn obligation_from_function_clause() {
3759 let t = type_at(
3760 r#"
3761//- /main.rs
3762struct S;
3763
3764trait Trait<T> {}
3765impl Trait<u32> for S {}
3766
3767fn foo<T: Trait<U>, U>(t: T) -> U {}
3768
3769fn test(s: S) {
3770 foo(s)<|>;
3771}
3772"#,
3773 );
3774 assert_eq!(t, "u32");
3775}
3776
3777#[test]
3778fn obligation_from_method_clause() {
3779 let t = type_at(
3780 r#"
3781//- /main.rs
3782struct S;
3783
3784trait Trait<T> {}
3785impl Trait<isize> for S {}
3786
3787struct O;
3788impl O {
3789 fn foo<T: Trait<U>, U>(&self, t: T) -> U {}
3790}
3791
3792fn test() {
3793 O.foo(S)<|>;
3794}
3795"#,
3796 );
3797 assert_eq!(t, "isize");
3798}
3799
3800#[test]
3801fn obligation_from_self_method_clause() {
3802 let t = type_at(
3803 r#"
3804//- /main.rs
3805struct S;
3806
3807trait Trait<T> {}
3808impl Trait<i64> for S {}
3809
3810impl S {
3811 fn foo<U>(&self) -> U where Self: Trait<U> {}
3812}
3813
3814fn test() {
3815 S.foo()<|>;
3816}
3817"#,
3818 );
3819 assert_eq!(t, "i64");
3820}
3821
3822#[test]
3823fn obligation_from_impl_clause() {
3824 let t = type_at(
3825 r#"
3826//- /main.rs
3827struct S;
3828
3829trait Trait<T> {}
3830impl Trait<&str> for S {}
3831
3832struct O<T>;
3833impl<U, T: Trait<U>> O<T> {
3834 fn foo(&self) -> U {}
3835}
3836
3837fn test(o: O<S>) {
3838 o.foo()<|>;
3839}
3840"#,
3841 );
3842 assert_eq!(t, "&str");
3843}
3844
3845#[test]
3846fn generic_param_env_1() {
3847 let t = type_at(
3848 r#"
3849//- /main.rs
3850trait Clone {}
3851trait Trait { fn foo(self) -> u128; }
3852struct S;
3853impl Clone for S {}
3854impl<T> Trait for T where T: Clone {}
3855fn test<T: Clone>(t: T) { t.foo()<|>; }
3856"#,
3857 );
3858 assert_eq!(t, "u128");
3859}
3860
3861#[test]
3862fn generic_param_env_1_not_met() {
3863 let t = type_at(
3864 r#"
3865//- /main.rs
3866trait Clone {}
3867trait Trait { fn foo(self) -> u128; }
3868struct S;
3869impl Clone for S {}
3870impl<T> Trait for T where T: Clone {}
3871fn test<T>(t: T) { t.foo()<|>; }
3872"#,
3873 );
3874 assert_eq!(t, "{unknown}");
3875}
3876
3877#[test]
3878fn generic_param_env_2() {
3879 let t = type_at(
3880 r#"
3881//- /main.rs
3882trait Trait { fn foo(self) -> u128; }
3883struct S;
3884impl Trait for S {}
3885fn test<T: Trait>(t: T) { t.foo()<|>; }
3886"#,
3887 );
3888 assert_eq!(t, "u128");
3889}
3890
3891#[test]
3892fn generic_param_env_2_not_met() {
3893 let t = type_at(
3894 r#"
3895//- /main.rs
3896trait Trait { fn foo(self) -> u128; }
3897struct S;
3898impl Trait for S {}
3899fn test<T>(t: T) { t.foo()<|>; }
3900"#,
3901 );
3902 assert_eq!(t, "{unknown}");
3903}
3904
3905#[test]
3906fn generic_param_env_deref() {
3907 let t = type_at(
3908 r#"
3909//- /main.rs
3910#[lang = "deref"]
3911trait Deref {
3912 type Target;
3913}
3914trait Trait {}
3915impl<T> Deref for T where T: Trait {
3916 type Target = i128;
3917}
3918fn test<T: Trait>(t: T) { (*t)<|>; }
3919"#,
3920 );
3921 assert_eq!(t, "i128");
3922}
3923
3924#[test]
3925fn associated_type_placeholder() {
3926 let t = type_at(
3927 r#"
3928//- /main.rs
3929pub trait ApplyL {
3930 type Out;
3931}
3932
3933pub struct RefMutL<T>;
3934
3935impl<T> ApplyL for RefMutL<T> {
3936 type Out = <T as ApplyL>::Out;
3937}
3938
3939fn test<T: ApplyL>() {
3940 let y: <RefMutL<T> as ApplyL>::Out = no_matter;
3941 y<|>;
3942}
3943"#,
3944 );
3945 // inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out<T>` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types].
3946 // FIXME: fix type parameter names going missing when going through Chalk
3947 assert_eq!(t, "ApplyL::Out<[missing name]>");
3948}
3949
3950#[test]
3951fn associated_type_placeholder_2() {
3952 let t = type_at(
3953 r#"
3954//- /main.rs
3955pub trait ApplyL {
3956 type Out;
3957}
3958fn foo<T: ApplyL>(t: T) -> <T as ApplyL>::Out;
3959
3960fn test<T: ApplyL>(t: T) {
3961 let y = foo(t);
3962 y<|>;
3963}
3964"#,
3965 );
3966 // FIXME here Chalk doesn't normalize the type to a placeholder. I think we
3967 // need to add a rule like Normalize(<T as ApplyL>::Out -> ApplyL::Out<T>)
3968 // to the trait env ourselves here; probably Chalk can't do this by itself.
3969 // assert_eq!(t, "ApplyL::Out<[missing name]>");
3970 assert_eq!(t, "{unknown}");
3971}
3972
3973#[test]
3974fn impl_trait() {
3975 assert_snapshot!(
3976 infer(r#"
3977trait Trait<T> {
3978 fn foo(&self) -> T;
3979 fn foo2(&self) -> i64;
3980}
3981fn bar() -> impl Trait<u64> {}
3982
3983fn test(x: impl Trait<u64>, y: &impl Trait<u64>) {
3984 x;
3985 y;
3986 let z = bar();
3987 x.foo();
3988 y.foo();
3989 z.foo();
3990 x.foo2();
3991 y.foo2();
3992 z.foo2();
3993}
3994"#),
3995 @r###"
3996 [30; 34) 'self': &Self
3997 [55; 59) 'self': &Self
3998 [99; 101) '{}': ()
3999 [111; 112) 'x': impl Trait<u64>
4000 [131; 132) 'y': &impl Trait<u64>
4001 [152; 269) '{ ...2(); }': ()
4002 [158; 159) 'x': impl Trait<u64>
4003 [165; 166) 'y': &impl Trait<u64>
4004 [176; 177) 'z': impl Trait<u64>
4005 [180; 183) 'bar': fn bar() -> impl Trait<u64>
4006 [180; 185) 'bar()': impl Trait<u64>
4007 [191; 192) 'x': impl Trait<u64>
4008 [191; 198) 'x.foo()': u64
4009 [204; 205) 'y': &impl Trait<u64>
4010 [204; 211) 'y.foo()': u64
4011 [217; 218) 'z': impl Trait<u64>
4012 [217; 224) 'z.foo()': u64
4013 [230; 231) 'x': impl Trait<u64>
4014 [230; 238) 'x.foo2()': i64
4015 [244; 245) 'y': &impl Trait<u64>
4016 [244; 252) 'y.foo2()': i64
4017 [258; 259) 'z': impl Trait<u64>
4018 [258; 266) 'z.foo2()': i64
4019 "###
4020 );
4021}
4022
4023#[test]
4024fn dyn_trait() {
4025 assert_snapshot!(
4026 infer(r#"
4027trait Trait<T> {
4028 fn foo(&self) -> T;
4029 fn foo2(&self) -> i64;
4030}
4031fn bar() -> dyn Trait<u64> {}
4032
4033fn test(x: dyn Trait<u64>, y: &dyn Trait<u64>) {
4034 x;
4035 y;
4036 let z = bar();
4037 x.foo();
4038 y.foo();
4039 z.foo();
4040 x.foo2();
4041 y.foo2();
4042 z.foo2();
4043}
4044"#),
4045 @r###"
4046 [30; 34) 'self': &Self
4047 [55; 59) 'self': &Self
4048 [98; 100) '{}': ()
4049 [110; 111) 'x': dyn Trait<u64>
4050 [129; 130) 'y': &dyn Trait<u64>
4051 [149; 266) '{ ...2(); }': ()
4052 [155; 156) 'x': dyn Trait<u64>
4053 [162; 163) 'y': &dyn Trait<u64>
4054 [173; 174) 'z': dyn Trait<u64>
4055 [177; 180) 'bar': fn bar() -> dyn Trait<u64>
4056 [177; 182) 'bar()': dyn Trait<u64>
4057 [188; 189) 'x': dyn Trait<u64>
4058 [188; 195) 'x.foo()': u64
4059 [201; 202) 'y': &dyn Trait<u64>
4060 [201; 208) 'y.foo()': u64
4061 [214; 215) 'z': dyn Trait<u64>
4062 [214; 221) 'z.foo()': u64
4063 [227; 228) 'x': dyn Trait<u64>
4064 [227; 235) 'x.foo2()': i64
4065 [241; 242) 'y': &dyn Trait<u64>
4066 [241; 249) 'y.foo2()': i64
4067 [255; 256) 'z': dyn Trait<u64>
4068 [255; 263) 'z.foo2()': i64
4069 "###
4070 );
4071}
4072
4073#[test]
4074fn dyn_trait_bare() {
4075 assert_snapshot!(
4076 infer(r#"
4077trait Trait {
4078 fn foo(&self) -> u64;
4079}
4080fn bar() -> Trait {}
4081
4082fn test(x: Trait, y: &Trait) -> u64 {
4083 x;
4084 y;
4085 let z = bar();
4086 x.foo();
4087 y.foo();
4088 z.foo();
4089}
4090"#),
4091 @r###"
4092 [27; 31) 'self': &Self
4093 [61; 63) '{}': ()
4094 [73; 74) 'x': dyn Trait
4095 [83; 84) 'y': &dyn Trait
4096 [101; 176) '{ ...o(); }': ()
4097 [107; 108) 'x': dyn Trait
4098 [114; 115) 'y': &dyn Trait
4099 [125; 126) 'z': dyn Trait
4100 [129; 132) 'bar': fn bar() -> dyn Trait
4101 [129; 134) 'bar()': dyn Trait
4102 [140; 141) 'x': dyn Trait
4103 [140; 147) 'x.foo()': u64
4104 [153; 154) 'y': &dyn Trait
4105 [153; 160) 'y.foo()': u64
4106 [166; 167) 'z': dyn Trait
4107 [166; 173) 'z.foo()': u64
4108 "###
4109 );
4110}
4111
4112#[test]
4113fn weird_bounds() {
4114 assert_snapshot!(
4115 infer(r#"
4116trait Trait {}
4117fn test() {
4118 let a: impl Trait + 'lifetime = foo;
4119 let b: impl 'lifetime = foo;
4120 let b: impl (Trait) = foo;
4121 let b: impl ('lifetime) = foo;
4122 let d: impl ?Sized = foo;
4123 let e: impl Trait + ?Sized = foo;
4124}
4125"#),
4126 @r###"
4127 [26; 237) '{ ...foo; }': ()
4128 [36; 37) 'a': impl Trait + {error}
4129 [64; 67) 'foo': impl Trait + {error}
4130 [77; 78) 'b': impl {error}
4131 [97; 100) 'foo': impl {error}
4132 [110; 111) 'b': impl Trait
4133 [128; 131) 'foo': impl Trait
4134 [141; 142) 'b': impl {error}
4135 [163; 166) 'foo': impl {error}
4136 [176; 177) 'd': impl {error}
4137 [193; 196) 'foo': impl {error}
4138 [206; 207) 'e': impl Trait + {error}
4139 [231; 234) 'foo': impl Trait + {error}
4140 "###
4141 );
4142}
4143
4144#[test]
4145fn assoc_type_bindings() {
4146 assert_snapshot!(
4147 infer(r#"
4148trait Trait {
4149 type Type;
4150}
4151
4152fn get<T: Trait>(t: T) -> <T as Trait>::Type {}
4153fn get2<U, T: Trait<Type = U>>(t: T) -> U {}
4154fn set<T: Trait<Type = u64>>(t: T) -> T {t}
4155
4156struct S<T>;
4157impl<T> Trait for S<T> { type Type = T; }
4158
4159fn test<T: Trait<Type = u32>>(x: T, y: impl Trait<Type = i64>) {
4160 get(x);
4161 get2(x);
4162 get(y);
4163 get2(y);
4164 get(set(S));
4165 get2(set(S));
4166 get2(S::<str>);
4167}
4168"#),
4169 @r###"
4170 [50; 51) 't': T
4171 [78; 80) '{}': ()
4172 [112; 113) 't': T
4173 [123; 125) '{}': ()
4174 [155; 156) 't': T
4175 [166; 169) '{t}': T
4176 [167; 168) 't': T
4177 [257; 258) 'x': T
4178 [263; 264) 'y': impl Trait<Type = i64>
4179 [290; 398) '{ ...r>); }': ()
4180 [296; 299) 'get': fn get<T>(T) -> <T as Trait>::Type
4181 [296; 302) 'get(x)': {unknown}
4182 [300; 301) 'x': T
4183 [308; 312) 'get2': fn get2<{unknown}, T>(T) -> U
4184 [308; 315) 'get2(x)': {unknown}
4185 [313; 314) 'x': T
4186 [321; 324) 'get': fn get<impl Trait<Type = i64>>(T) -> <T as Trait>::Type
4187 [321; 327) 'get(y)': {unknown}
4188 [325; 326) 'y': impl Trait<Type = i64>
4189 [333; 337) 'get2': fn get2<{unknown}, impl Trait<Type = i64>>(T) -> U
4190 [333; 340) 'get2(y)': {unknown}
4191 [338; 339) 'y': impl Trait<Type = i64>
4192 [346; 349) 'get': fn get<S<u64>>(T) -> <T as Trait>::Type
4193 [346; 357) 'get(set(S))': u64
4194 [350; 353) 'set': fn set<S<u64>>(T) -> T
4195 [350; 356) 'set(S)': S<u64>
4196 [354; 355) 'S': S<u64>
4197 [363; 367) 'get2': fn get2<u64, S<u64>>(T) -> U
4198 [363; 375) 'get2(set(S))': u64
4199 [368; 371) 'set': fn set<S<u64>>(T) -> T
4200 [368; 374) 'set(S)': S<u64>
4201 [372; 373) 'S': S<u64>
4202 [381; 385) 'get2': fn get2<str, S<str>>(T) -> U
4203 [381; 395) 'get2(S::<str>)': str
4204 [386; 394) 'S::<str>': S<str>
4205 "###
4206 );
4207}
4208
4209#[test]
4210fn impl_trait_assoc_binding_projection_bug() {
4211 let (db, pos) = TestDB::with_position(
4212 r#"
4213//- /main.rs crate:main deps:std
4214pub trait Language {
4215 type Kind;
4216}
4217pub enum RustLanguage {}
4218impl Language for RustLanguage {
4219 type Kind = SyntaxKind;
4220}
4221struct SyntaxNode<L> {}
4222fn foo() -> impl Iterator<Item = SyntaxNode<RustLanguage>> {}
4223
4224trait Clone {
4225 fn clone(&self) -> Self;
4226}
4227
4228fn api_walkthrough() {
4229 for node in foo() {
4230 node.clone()<|>;
4231 }
4232}
4233
4234//- /std.rs crate:std
4235#[prelude_import] use iter::*;
4236mod iter {
4237 trait IntoIterator {
4238 type Item;
4239 }
4240 trait Iterator {
4241 type Item;
4242 }
4243 impl<T: Iterator> IntoIterator for T {
4244 type Item = <T as Iterator>::Item;
4245 }
4246}
4247"#,
4248 );
4249 assert_eq!("{unknown}", type_at_pos(&db, pos));
4250}
4251
4252#[test]
4253fn projection_eq_within_chalk() {
4254 // std::env::set_var("CHALK_DEBUG", "1");
4255 assert_snapshot!(
4256 infer(r#"
4257trait Trait1 {
4258 type Type;
4259}
4260trait Trait2<T> {
4261 fn foo(self) -> T;
4262}
4263impl<T, U> Trait2<T> for U where U: Trait1<Type = T> {}
4264
4265fn test<T: Trait1<Type = u32>>(x: T) {
4266 x.foo();
4267}
4268"#),
4269 @r###"
4270 [62; 66) 'self': Self
4271 [164; 165) 'x': T
4272 [170; 186) '{ ...o(); }': ()
4273 [176; 177) 'x': T
4274 [176; 183) 'x.foo()': {unknown}
4275 "###
4276 );
4277}
4278
4279#[test]
4280fn where_clause_trait_in_scope_for_method_resolution() {
4281 let t = type_at(
4282 r#"
4283//- /main.rs
4284mod foo {
4285 trait Trait {
4286 fn foo(&self) -> u32 {}
4287 }
4288}
4289
4290fn test<T: foo::Trait>(x: T) {
4291 x.foo()<|>;
4292}
4293"#,
4294 );
4295 assert_eq!(t, "u32");
4296}
4297
4298#[test]
4299fn super_trait_method_resolution() {
4300 assert_snapshot!(
4301 infer(r#"
4302mod foo {
4303 trait SuperTrait {
4304 fn foo(&self) -> u32 {}
4305 }
4306}
4307trait Trait1: foo::SuperTrait {}
4308trait Trait2 where Self: foo::SuperTrait {}
4309
4310fn test<T: Trait1, U: Trait2>(x: T, y: U) {
4311 x.foo();
4312 y.foo();
4313}
4314"#),
4315 @r###"
4316 [50; 54) 'self': &Self
4317 [63; 65) '{}': ()
4318 [182; 183) 'x': T
4319 [188; 189) 'y': U
4320 [194; 223) '{ ...o(); }': ()
4321 [200; 201) 'x': T
4322 [200; 207) 'x.foo()': u32
4323 [213; 214) 'y': U
4324 [213; 220) 'y.foo()': u32
4325 "###
4326 );
4327}
4328
4329#[test]
4330fn super_trait_cycle() {
4331 // This just needs to not crash
4332 assert_snapshot!(
4333 infer(r#"
4334trait A: B {}
4335trait B: A {}
4336
4337fn test<T: A>(x: T) {
4338 x.foo();
4339}
4340"#),
4341 @r###"
4342 [44; 45) 'x': T
4343 [50; 66) '{ ...o(); }': ()
4344 [56; 57) 'x': T
4345 [56; 63) 'x.foo()': {unknown}
4346 "###
4347 );
4348}
4349
4350#[test]
4351fn super_trait_assoc_type_bounds() {
4352 assert_snapshot!(
4353 infer(r#"
4354trait SuperTrait { type Type; }
4355trait Trait where Self: SuperTrait {}
4356
4357fn get2<U, T: Trait<Type = U>>(t: T) -> U {}
4358fn set<T: Trait<Type = u64>>(t: T) -> T {t}
4359
4360struct S<T>;
4361impl<T> SuperTrait for S<T> { type Type = T; }
4362impl<T> Trait for S<T> {}
4363
4364fn test() {
4365 get2(set(S));
4366}
4367"#),
4368 @r###"
4369 [103; 104) 't': T
4370 [114; 116) '{}': ()
4371 [146; 147) 't': T
4372 [157; 160) '{t}': T
4373 [158; 159) 't': T
4374 [259; 280) '{ ...S)); }': ()
4375 [265; 269) 'get2': fn get2<u64, S<u64>>(T) -> U
4376 [265; 277) 'get2(set(S))': u64
4377 [270; 273) 'set': fn set<S<u64>>(T) -> T
4378 [270; 276) 'set(S)': S<u64>
4379 [274; 275) 'S': S<u64>
4380 "###
4381 );
4382}
4383
4384#[test]
4385fn fn_trait() {
4386 assert_snapshot!(
4387 infer(r#"
4388trait FnOnce<Args> {
4389 type Output;
4390
4391 fn call_once(self, args: Args) -> <Self as FnOnce<Args>>::Output;
4392}
4393
4394fn test<F: FnOnce(u32, u64) -> u128>(f: F) {
4395 f.call_once((1, 2));
4396}
4397"#),
4398 @r###"
4399 [57; 61) 'self': Self
4400 [63; 67) 'args': Args
4401 [150; 151) 'f': F
4402 [156; 184) '{ ...2)); }': ()
4403 [162; 163) 'f': F
4404 [162; 181) 'f.call...1, 2))': {unknown}
4405 [174; 180) '(1, 2)': (u32, u64)
4406 [175; 176) '1': u32
4407 [178; 179) '2': u64
4408 "###
4409 );
4410}
4411
4412#[test]
4413fn closure_1() {
4414 assert_snapshot!(
4415 infer(r#"
4416#[lang = "fn_once"]
4417trait FnOnce<Args> {
4418 type Output;
4419}
4420
4421enum Option<T> { Some(T), None }
4422impl<T> Option<T> {
4423 fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {}
4424}
4425
4426fn test() {
4427 let x = Option::Some(1u32);
4428 x.map(|v| v + 1);
4429 x.map(|_v| 1u64);
4430 let y: Option<i64> = x.map(|_v| 1);
4431}
4432"#),
4433 @r###"
4434 [148; 152) 'self': Option<T>
4435 [154; 155) 'f': F
4436 [173; 175) '{}': ()
4437 [189; 308) '{ ... 1); }': ()
4438 [199; 200) 'x': Option<u32>
4439 [203; 215) 'Option::Some': Some<u32>(T) -> Option<T>
4440 [203; 221) 'Option...(1u32)': Option<u32>
4441 [216; 220) '1u32': u32
4442 [227; 228) 'x': Option<u32>
4443 [227; 243) 'x.map(...v + 1)': Option<u32>
4444 [233; 242) '|v| v + 1': |u32| -> u32
4445 [234; 235) 'v': u32
4446 [237; 238) 'v': u32
4447 [237; 242) 'v + 1': u32
4448 [241; 242) '1': u32
4449 [249; 250) 'x': Option<u32>
4450 [249; 265) 'x.map(... 1u64)': Option<u64>
4451 [255; 264) '|_v| 1u64': |u32| -> u64
4452 [256; 258) '_v': u32
4453 [260; 264) '1u64': u64
4454 [275; 276) 'y': Option<i64>
4455 [292; 293) 'x': Option<u32>
4456 [292; 305) 'x.map(|_v| 1)': Option<i64>
4457 [298; 304) '|_v| 1': |u32| -> i64
4458 [299; 301) '_v': u32
4459 [303; 304) '1': i64
4460 "###
4461 );
4462}
4463
4464#[test]
4465fn closure_2() {
4466 assert_snapshot!(
4467 infer(r#"
4468trait FnOnce<Args> {
4469 type Output;
4470}
4471
4472fn test<F: FnOnce(u32) -> u64>(f: F) {
4473 f(1);
4474 let g = |v| v + 1;
4475 g(1u64);
4476 let h = |v| 1u128 + v;
4477}
4478"#),
4479 @r###"
4480 [73; 74) 'f': F
4481 [79; 155) '{ ...+ v; }': ()
4482 [85; 86) 'f': F
4483 [85; 89) 'f(1)': {unknown}
4484 [87; 88) '1': i32
4485 [99; 100) 'g': |u64| -> i32
4486 [103; 112) '|v| v + 1': |u64| -> i32
4487 [104; 105) 'v': u64
4488 [107; 108) 'v': u64
4489 [107; 112) 'v + 1': i32
4490 [111; 112) '1': i32
4491 [118; 119) 'g': |u64| -> i32
4492 [118; 125) 'g(1u64)': i32
4493 [120; 124) '1u64': u64
4494 [135; 136) 'h': |u128| -> u128
4495 [139; 152) '|v| 1u128 + v': |u128| -> u128
4496 [140; 141) 'v': u128
4497 [143; 148) '1u128': u128
4498 [143; 152) '1u128 + v': u128
4499 [151; 152) 'v': u128
4500 "###
4501 );
4502}
4503
4504#[test]
4505fn closure_as_argument_inference_order() {
4506 assert_snapshot!(
4507 infer(r#"
4508#[lang = "fn_once"]
4509trait FnOnce<Args> {
4510 type Output;
4511}
4512
4513fn foo1<T, U, F: FnOnce(T) -> U>(x: T, f: F) -> U {}
4514fn foo2<T, U, F: FnOnce(T) -> U>(f: F, x: T) -> U {}
4515
4516struct S;
4517impl S {
4518 fn method(self) -> u64;
4519
4520 fn foo1<T, U, F: FnOnce(T) -> U>(self, x: T, f: F) -> U {}
4521 fn foo2<T, U, F: FnOnce(T) -> U>(self, f: F, x: T) -> U {}
4522}
4523
4524fn test() {
4525 let x1 = foo1(S, |s| s.method());
4526 let x2 = foo2(|s| s.method(), S);
4527 let x3 = S.foo1(S, |s| s.method());
4528 let x4 = S.foo2(|s| s.method(), S);
4529}
4530"#),
4531 @r###"
4532 [95; 96) 'x': T
4533 [101; 102) 'f': F
4534 [112; 114) '{}': ()
4535 [148; 149) 'f': F
4536 [154; 155) 'x': T
4537 [165; 167) '{}': ()
4538 [202; 206) 'self': S
4539 [254; 258) 'self': S
4540 [260; 261) 'x': T
4541 [266; 267) 'f': F
4542 [277; 279) '{}': ()
4543 [317; 321) 'self': S
4544 [323; 324) 'f': F
4545 [329; 330) 'x': T
4546 [340; 342) '{}': ()
4547 [356; 515) '{ ... S); }': ()
4548 [366; 368) 'x1': u64
4549 [371; 375) 'foo1': fn foo1<S, u64, |S| -> u64>(T, F) -> U
4550 [371; 394) 'foo1(S...hod())': u64
4551 [376; 377) 'S': S
4552 [379; 393) '|s| s.method()': |S| -> u64
4553 [380; 381) 's': S
4554 [383; 384) 's': S
4555 [383; 393) 's.method()': u64
4556 [404; 406) 'x2': u64
4557 [409; 413) 'foo2': fn foo2<S, u64, |S| -> u64>(F, T) -> U
4558 [409; 432) 'foo2(|...(), S)': u64
4559 [414; 428) '|s| s.method()': |S| -> u64
4560 [415; 416) 's': S
4561 [418; 419) 's': S
4562 [418; 428) 's.method()': u64
4563 [430; 431) 'S': S
4564 [442; 444) 'x3': u64
4565 [447; 448) 'S': S
4566 [447; 472) 'S.foo1...hod())': u64
4567 [454; 455) 'S': S
4568 [457; 471) '|s| s.method()': |S| -> u64
4569 [458; 459) 's': S
4570 [461; 462) 's': S
4571 [461; 471) 's.method()': u64
4572 [482; 484) 'x4': u64
4573 [487; 488) 'S': S
4574 [487; 512) 'S.foo2...(), S)': u64
4575 [494; 508) '|s| s.method()': |S| -> u64
4576 [495; 496) 's': S
4577 [498; 499) 's': S
4578 [498; 508) 's.method()': u64
4579 [510; 511) 'S': S
4580 "###
4581 );
4582}
4583
4584#[test]
4585fn unselected_projection_in_trait_env_1() {
4586 let t = type_at(
4587 r#"
4588//- /main.rs
4589trait Trait {
4590 type Item;
4591}
4592
4593trait Trait2 {
4594 fn foo(&self) -> u32;
4595}
4596
4597fn test<T: Trait>() where T::Item: Trait2 {
4598 let x: T::Item = no_matter;
4599 x.foo()<|>;
4600}
4601"#,
4602 );
4603 assert_eq!(t, "u32");
4604}
4605
4606#[test]
4607fn unselected_projection_in_trait_env_2() {
4608 let t = type_at(
4609 r#"
4610//- /main.rs
4611trait Trait<T> {
4612 type Item;
4613}
4614
4615trait Trait2 {
4616 fn foo(&self) -> u32;
4617}
4618
4619fn test<T, U>() where T::Item: Trait2, T: Trait<U::Item>, U: Trait<()> {
4620 let x: T::Item = no_matter;
4621 x.foo()<|>;
4622}
4623"#,
4624 );
4625 assert_eq!(t, "u32");
4626}
4627
4628#[test]
4629// FIXME this is currently a Salsa panic; it would be nicer if it just returned
4630// in Unknown, and we should be able to do that once Salsa allows us to handle
4631// the cycle. But at least it doesn't overflow for now.
4632#[should_panic]
4633fn unselected_projection_in_trait_env_cycle_1() {
4634 let t = type_at(
4635 r#"
4636//- /main.rs
4637trait Trait {
4638 type Item;
4639}
4640
4641trait Trait2<T> {}
4642
4643fn test<T: Trait>() where T: Trait2<T::Item> {
4644 let x: T::Item = no_matter<|>;
4645}
4646"#,
4647 );
4648 // this is a legitimate cycle
4649 assert_eq!(t, "{unknown}");
4650}
4651
4652#[test]
4653// FIXME this is currently a Salsa panic; it would be nicer if it just returned
4654// in Unknown, and we should be able to do that once Salsa allows us to handle
4655// the cycle. But at least it doesn't overflow for now.
4656#[should_panic]
4657fn unselected_projection_in_trait_env_cycle_2() {
4658 let t = type_at(
4659 r#"
4660//- /main.rs
4661trait Trait<T> {
4662 type Item;
4663}
4664
4665fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> {
4666 let x: T::Item = no_matter<|>;
4667}
4668"#,
4669 );
4670 // this is a legitimate cycle
4671 assert_eq!(t, "{unknown}");
4672}
4673
4674fn type_at_pos(db: &TestDB, pos: FilePosition) -> String {
4675 let file = db.parse(pos.file_id).ok().unwrap();
4676 let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap();
4677
4678 let module = db.module_for_file(pos.file_id);
4679 let crate_def_map = db.crate_def_map(module.krate);
4680 for decl in crate_def_map[module.local_id].scope.declarations() {
4681 if let ModuleDefId::FunctionId(func) = decl {
4682 let (_body, source_map) = db.body_with_source_map(func.into());
4683 if let Some(expr_id) = source_map.node_expr(Source::new(pos.file_id.into(), &expr)) {
4684 let infer = db.infer(func.into());
4685 let ty = &infer[expr_id];
4686 return ty.display(db).to_string();
4687 }
4688 }
4689 }
4690 panic!("Can't find expression")
4691}
4692
4693fn type_at(content: &str) -> String {
4694 let (db, file_pos) = TestDB::with_position(content);
4695 type_at_pos(&db, file_pos)
4696}
4697
4698fn infer(content: &str) -> String {
4699 let (db, file_id) = TestDB::with_single_file(content);
4700
4701 let mut acc = String::new();
4702
4703 let mut infer_def = |inference_result: Arc<InferenceResult>,
4704 body_source_map: Arc<BodySourceMap>| {
4705 let mut types = Vec::new();
4706
4707 for (pat, ty) in inference_result.type_of_pat.iter() {
4708 let syntax_ptr = match body_source_map.pat_syntax(pat) {
4709 Some(sp) => {
4710 sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()))
4711 }
4712 None => continue,
4713 };
4714 types.push((syntax_ptr, ty));
4715 }
4716
4717 for (expr, ty) in inference_result.type_of_expr.iter() {
4718 let syntax_ptr = match body_source_map.expr_syntax(expr) {
4719 Some(sp) => {
4720 sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()))
4721 }
4722 None => continue,
4723 };
4724 types.push((syntax_ptr, ty));
4725 }
4726
4727 // sort ranges for consistency
4728 types.sort_by_key(|(src_ptr, _)| {
4729 (src_ptr.value.range().start(), src_ptr.value.range().end())
4730 });
4731 for (src_ptr, ty) in &types {
4732 let node = src_ptr.value.to_node(&src_ptr.file_syntax(&db));
4733
4734 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) {
4735 (self_param.self_kw_token().text_range(), "self".to_string())
4736 } else {
4737 (src_ptr.value.range(), node.text().to_string().replace("\n", " "))
4738 };
4739 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
4740 write!(
4741 acc,
4742 "{}{} '{}': {}\n",
4743 macro_prefix,
4744 range,
4745 ellipsize(text, 15),
4746 ty.display(&db)
4747 )
4748 .unwrap();
4749 }
4750 };
4751
4752 let module = db.module_for_file(file_id);
4753 let crate_def_map = db.crate_def_map(module.krate);
4754
4755 let mut defs: Vec<DefWithBodyId> = Vec::new();
4756 visit_module(&db, &crate_def_map, module.local_id, &mut |it| defs.push(it));
4757 defs.sort_by_key(|def| match def {
4758 DefWithBodyId::FunctionId(it) => {
4759 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4760 }
4761 DefWithBodyId::ConstId(it) => {
4762 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4763 }
4764 DefWithBodyId::StaticId(it) => {
4765 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4766 }
4767 });
4768 for def in defs {
4769 let (_body, source_map) = db.body_with_source_map(def);
4770 let infer = db.infer(def);
4771 infer_def(infer, source_map);
4772 }
4773
4774 acc.truncate(acc.trim_end().len());
4775 acc
4776}
4777
4778fn visit_module(
4779 db: &TestDB,
4780 crate_def_map: &CrateDefMap,
4781 module_id: LocalModuleId,
4782 cb: &mut dyn FnMut(DefWithBodyId),
4783) {
4784 for decl in crate_def_map[module_id].scope.declarations() {
4785 match decl {
4786 ModuleDefId::FunctionId(it) => cb(it.into()),
4787 ModuleDefId::ConstId(it) => cb(it.into()),
4788 ModuleDefId::StaticId(it) => cb(it.into()),
4789 ModuleDefId::TraitId(it) => {
4790 let trait_data = db.trait_data(it);
4791 for &(_, item) in trait_data.items.iter() {
4792 match item {
4793 AssocItemId::FunctionId(it) => cb(it.into()),
4794 AssocItemId::ConstId(it) => cb(it.into()),
4795 AssocItemId::TypeAliasId(_) => (),
4796 }
4797 }
4798 }
4799 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
4800 _ => (),
4801 }
4802 }
4803 for &impl_id in crate_def_map[module_id].impls.iter() {
4804 let impl_data = db.impl_data(impl_id);
4805 for &item in impl_data.items.iter() {
4806 match item {
4807 AssocItemId::FunctionId(it) => cb(it.into()),
4808 AssocItemId::ConstId(it) => cb(it.into()),
4809 AssocItemId::TypeAliasId(_) => (),
4810 }
4811 }
4812 }
4813}
4814
4815fn ellipsize(mut text: String, max_len: usize) -> String {
4816 if text.len() <= max_len {
4817 return text;
4818 }
4819 let ellipsis = "...";
4820 let e_len = ellipsis.len();
4821 let mut prefix_len = (max_len - e_len) / 2;
4822 while !text.is_char_boundary(prefix_len) {
4823 prefix_len += 1;
4824 }
4825 let mut suffix_len = max_len - e_len - prefix_len;
4826 while !text.is_char_boundary(text.len() - suffix_len) {
4827 suffix_len += 1;
4828 }
4829 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
4830 text
4831}
4832
4833#[test]
4834fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
4835 let (mut db, pos) = TestDB::with_position(
4836 "
4837 //- /lib.rs
4838 fn foo() -> i32 {
4839 <|>1 + 1
4840 }
4841 ",
4842 );
4843 {
4844 let events = db.log_executed(|| {
4845 let module = db.module_for_file(pos.file_id);
4846 let crate_def_map = db.crate_def_map(module.krate);
4847 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
4848 db.infer(def);
4849 });
4850 });
4851 assert!(format!("{:?}", events).contains("infer"))
4852 }
4853
4854 let new_text = "
4855 fn foo() -> i32 {
4856 1
4857 +
4858 1
4859 }
4860 "
4861 .to_string();
4862
4863 db.query_mut(ra_db::FileTextQuery).set(pos.file_id, Arc::new(new_text));
4864
4865 {
4866 let events = db.log_executed(|| {
4867 let module = db.module_for_file(pos.file_id);
4868 let crate_def_map = db.crate_def_map(module.krate);
4869 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
4870 db.infer(def);
4871 });
4872 });
4873 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
4874 }
4875}
4876
4877#[test]
4878fn no_such_field_diagnostics() {
4879 let diagnostics = TestDB::with_files(
4880 r"
4881 //- /lib.rs
4882 struct S { foo: i32, bar: () }
4883 impl S {
4884 fn new() -> S {
4885 S {
4886 foo: 92,
4887 baz: 62,
4888 }
4889 }
4890 }
4891 ",
4892 )
4893 .diagnostics();
4894
4895 assert_snapshot!(diagnostics, @r###"
4896 "baz: 62": no such field
4897 "{\n foo: 92,\n baz: 62,\n }": Missing structure fields:
4898 - bar
4899 "###
4900 );
4901}
4902
4903#[test]
4904fn infer_builtin_macros_line() {
4905 assert_snapshot!(
4906 infer(r#"
4907#[rustc_builtin_macro]
4908macro_rules! line {() => {}}
4909
4910fn main() {
4911 let x = line!();
4912}
4913"#),
4914 @r###"
4915 ![0; 1) '6': i32
4916 [64; 88) '{ ...!(); }': ()
4917 [74; 75) 'x': i32
4918 "###
4919 );
4920}
4921
4922#[test]
4923fn infer_builtin_macros_file() {
4924 assert_snapshot!(
4925 infer(r#"
4926#[rustc_builtin_macro]
4927macro_rules! file {() => {}}
4928
4929fn main() {
4930 let x = file!();
4931}
4932"#),
4933 @r###"
4934 ![0; 2) '""': &str
4935 [64; 88) '{ ...!(); }': ()
4936 [74; 75) 'x': &str
4937 "###
4938 );
4939}
4940
4941#[test]
4942fn infer_builtin_macros_column() {
4943 assert_snapshot!(
4944 infer(r#"
4945#[rustc_builtin_macro]
4946macro_rules! column {() => {}}
4947
4948fn main() {
4949 let x = column!();
4950}
4951"#),
4952 @r###"
4953 ![0; 2) '13': i32
4954 [66; 92) '{ ...!(); }': ()
4955 [76; 77) 'x': i32
4956 "###
4957 );
4958}
diff --git a/crates/ra_hir_ty/src/tests/coercion.rs b/crates/ra_hir_ty/src/tests/coercion.rs
new file mode 100644
index 000000000..1530fcc63
--- /dev/null
+++ b/crates/ra_hir_ty/src/tests/coercion.rs
@@ -0,0 +1,369 @@
1use insta::assert_snapshot;
2use test_utils::covers;
3
4// Infer with some common definitions and impls.
5fn infer(source: &str) -> String {
6 let defs = r#"
7 #[lang = "sized"]
8 pub trait Sized {}
9 #[lang = "unsize"]
10 pub trait Unsize<T: ?Sized> {}
11 #[lang = "coerce_unsized"]
12 pub trait CoerceUnsized<T> {}
13
14 impl<'a, 'b: 'a, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {}
15 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {}
16 "#;
17
18 // Append to the end to keep positions unchanged.
19 super::infer(&format!("{}{}", source, defs))
20}
21
22#[test]
23fn infer_block_expr_type_mismatch() {
24 assert_snapshot!(
25 infer(r#"
26fn test() {
27 let a: i32 = { 1i64 };
28}
29"#),
30 @r###"
31 [11; 41) '{ ...4 }; }': ()
32 [21; 22) 'a': i32
33 [30; 38) '{ 1i64 }': i64
34 [32; 36) '1i64': i64
35 "###);
36}
37
38#[test]
39fn coerce_places() {
40 assert_snapshot!(
41 infer(r#"
42struct S<T> { a: T }
43
44fn f<T>(_: &[T]) -> T { loop {} }
45fn g<T>(_: S<&[T]>) -> T { loop {} }
46
47fn gen<T>() -> *mut [T; 2] { loop {} }
48fn test1<U>() -> *mut [U] {
49 gen()
50}
51
52fn test2() {
53 let arr: &[u8; 1] = &[1];
54
55 let a: &[_] = arr;
56 let b = f(arr);
57 let c: &[_] = { arr };
58 let d = g(S { a: arr });
59 let e: [&[_]; 1] = [arr];
60 let f: [&[_]; 2] = [arr; 2];
61 let g: (&[_], &[_]) = (arr, arr);
62}
63"#),
64 @r###"
65 [31; 32) '_': &[T]
66 [45; 56) '{ loop {} }': T
67 [47; 54) 'loop {}': !
68 [52; 54) '{}': ()
69 [65; 66) '_': S<&[T]>
70 [82; 93) '{ loop {} }': T
71 [84; 91) 'loop {}': !
72 [89; 91) '{}': ()
73 [122; 133) '{ loop {} }': *mut [T;_]
74 [124; 131) 'loop {}': !
75 [129; 131) '{}': ()
76 [160; 173) '{ gen() }': *mut [U]
77 [166; 169) 'gen': fn gen<U>() -> *mut [T;_]
78 [166; 171) 'gen()': *mut [U;_]
79 [186; 420) '{ ...rr); }': ()
80 [196; 199) 'arr': &[u8;_]
81 [212; 216) '&[1]': &[u8;_]
82 [213; 216) '[1]': [u8;_]
83 [214; 215) '1': u8
84 [227; 228) 'a': &[u8]
85 [237; 240) 'arr': &[u8;_]
86 [250; 251) 'b': u8
87 [254; 255) 'f': fn f<u8>(&[T]) -> T
88 [254; 260) 'f(arr)': u8
89 [256; 259) 'arr': &[u8;_]
90 [270; 271) 'c': &[u8]
91 [280; 287) '{ arr }': &[u8]
92 [282; 285) 'arr': &[u8;_]
93 [297; 298) 'd': u8
94 [301; 302) 'g': fn g<u8>(S<&[T]>) -> T
95 [301; 316) 'g(S { a: arr })': u8
96 [303; 315) 'S { a: arr }': S<&[u8]>
97 [310; 313) 'arr': &[u8;_]
98 [326; 327) 'e': [&[u8];_]
99 [341; 346) '[arr]': [&[u8];_]
100 [342; 345) 'arr': &[u8;_]
101 [356; 357) 'f': [&[u8];_]
102 [371; 379) '[arr; 2]': [&[u8];_]
103 [372; 375) 'arr': &[u8;_]
104 [377; 378) '2': usize
105 [389; 390) 'g': (&[u8], &[u8])
106 [407; 417) '(arr, arr)': (&[u8], &[u8])
107 [408; 411) 'arr': &[u8;_]
108 [413; 416) 'arr': &[u8;_]
109 "###
110 );
111}
112
113#[test]
114fn infer_let_stmt_coerce() {
115 assert_snapshot!(
116 infer(r#"
117fn test() {
118 let x: &[i32] = &[1];
119}
120"#),
121 @r###"
122 [11; 40) '{ ...[1]; }': ()
123 [21; 22) 'x': &[i32]
124 [33; 37) '&[1]': &[i32;_]
125 [34; 37) '[1]': [i32;_]
126 [35; 36) '1': i32
127 "###);
128}
129
130#[test]
131fn infer_custom_coerce_unsized() {
132 assert_snapshot!(
133 infer(r#"
134struct A<T: ?Sized>(*const T);
135struct B<T: ?Sized>(*const T);
136struct C<T: ?Sized> { inner: *const T }
137
138impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<B<U>> for B<T> {}
139impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<C<U>> for C<T> {}
140
141fn foo1<T>(x: A<[T]>) -> A<[T]> { x }
142fn foo2<T>(x: B<[T]>) -> B<[T]> { x }
143fn foo3<T>(x: C<[T]>) -> C<[T]> { x }
144
145fn test(a: A<[u8; 2]>, b: B<[u8; 2]>, c: C<[u8; 2]>) {
146 let d = foo1(a);
147 let e = foo2(b);
148 let f = foo3(c);
149}
150"#),
151 @r###"
152 [258; 259) 'x': A<[T]>
153 [279; 284) '{ x }': A<[T]>
154 [281; 282) 'x': A<[T]>
155 [296; 297) 'x': B<[T]>
156 [317; 322) '{ x }': B<[T]>
157 [319; 320) 'x': B<[T]>
158 [334; 335) 'x': C<[T]>
159 [355; 360) '{ x }': C<[T]>
160 [357; 358) 'x': C<[T]>
161 [370; 371) 'a': A<[u8;_]>
162 [385; 386) 'b': B<[u8;_]>
163 [400; 401) 'c': C<[u8;_]>
164 [415; 481) '{ ...(c); }': ()
165 [425; 426) 'd': A<[{unknown}]>
166 [429; 433) 'foo1': fn foo1<{unknown}>(A<[T]>) -> A<[T]>
167 [429; 436) 'foo1(a)': A<[{unknown}]>
168 [434; 435) 'a': A<[u8;_]>
169 [446; 447) 'e': B<[u8]>
170 [450; 454) 'foo2': fn foo2<u8>(B<[T]>) -> B<[T]>
171 [450; 457) 'foo2(b)': B<[u8]>
172 [455; 456) 'b': B<[u8;_]>
173 [467; 468) 'f': C<[u8]>
174 [471; 475) 'foo3': fn foo3<u8>(C<[T]>) -> C<[T]>
175 [471; 478) 'foo3(c)': C<[u8]>
176 [476; 477) 'c': C<[u8;_]>
177 "###
178 );
179}
180
181#[test]
182fn infer_if_coerce() {
183 assert_snapshot!(
184 infer(r#"
185fn foo<T>(x: &[T]) -> &[T] { loop {} }
186fn test() {
187 let x = if true {
188 foo(&[1])
189 } else {
190 &[1]
191 };
192}
193"#),
194 @r###"
195 [11; 12) 'x': &[T]
196 [28; 39) '{ loop {} }': &[T]
197 [30; 37) 'loop {}': !
198 [35; 37) '{}': ()
199 [50; 126) '{ ... }; }': ()
200 [60; 61) 'x': &[i32]
201 [64; 123) 'if tru... }': &[i32]
202 [67; 71) 'true': bool
203 [72; 97) '{ ... }': &[i32]
204 [82; 85) 'foo': fn foo<i32>(&[T]) -> &[T]
205 [82; 91) 'foo(&[1])': &[i32]
206 [86; 90) '&[1]': &[i32;_]
207 [87; 90) '[1]': [i32;_]
208 [88; 89) '1': i32
209 [103; 123) '{ ... }': &[i32;_]
210 [113; 117) '&[1]': &[i32;_]
211 [114; 117) '[1]': [i32;_]
212 [115; 116) '1': i32
213 "###
214 );
215}
216
217#[test]
218fn infer_if_else_coerce() {
219 assert_snapshot!(
220 infer(r#"
221fn foo<T>(x: &[T]) -> &[T] { loop {} }
222fn test() {
223 let x = if true {
224 &[1]
225 } else {
226 foo(&[1])
227 };
228}
229"#),
230 @r###"
231 [11; 12) 'x': &[T]
232 [28; 39) '{ loop {} }': &[T]
233 [30; 37) 'loop {}': !
234 [35; 37) '{}': ()
235 [50; 126) '{ ... }; }': ()
236 [60; 61) 'x': &[i32]
237 [64; 123) 'if tru... }': &[i32]
238 [67; 71) 'true': bool
239 [72; 92) '{ ... }': &[i32;_]
240 [82; 86) '&[1]': &[i32;_]
241 [83; 86) '[1]': [i32;_]
242 [84; 85) '1': i32
243 [98; 123) '{ ... }': &[i32]
244 [108; 111) 'foo': fn foo<i32>(&[T]) -> &[T]
245 [108; 117) 'foo(&[1])': &[i32]
246 [112; 116) '&[1]': &[i32;_]
247 [113; 116) '[1]': [i32;_]
248 [114; 115) '1': i32
249 "###
250 );
251}
252
253#[test]
254fn infer_match_first_coerce() {
255 assert_snapshot!(
256 infer(r#"
257fn foo<T>(x: &[T]) -> &[T] { loop {} }
258fn test(i: i32) {
259 let x = match i {
260 2 => foo(&[2]),
261 1 => &[1],
262 _ => &[3],
263 };
264}
265"#),
266 @r###"
267 [11; 12) 'x': &[T]
268 [28; 39) '{ loop {} }': &[T]
269 [30; 37) 'loop {}': !
270 [35; 37) '{}': ()
271 [48; 49) 'i': i32
272 [56; 150) '{ ... }; }': ()
273 [66; 67) 'x': &[i32]
274 [70; 147) 'match ... }': &[i32]
275 [76; 77) 'i': i32
276 [88; 89) '2': i32
277 [93; 96) 'foo': fn foo<i32>(&[T]) -> &[T]
278 [93; 102) 'foo(&[2])': &[i32]
279 [97; 101) '&[2]': &[i32;_]
280 [98; 101) '[2]': [i32;_]
281 [99; 100) '2': i32
282 [112; 113) '1': i32
283 [117; 121) '&[1]': &[i32;_]
284 [118; 121) '[1]': [i32;_]
285 [119; 120) '1': i32
286 [131; 132) '_': i32
287 [136; 140) '&[3]': &[i32;_]
288 [137; 140) '[3]': [i32;_]
289 [138; 139) '3': i32
290 "###
291 );
292}
293
294#[test]
295fn infer_match_second_coerce() {
296 assert_snapshot!(
297 infer(r#"
298fn foo<T>(x: &[T]) -> &[T] { loop {} }
299fn test(i: i32) {
300 let x = match i {
301 1 => &[1],
302 2 => foo(&[2]),
303 _ => &[3],
304 };
305}
306"#),
307 @r###"
308 [11; 12) 'x': &[T]
309 [28; 39) '{ loop {} }': &[T]
310 [30; 37) 'loop {}': !
311 [35; 37) '{}': ()
312 [48; 49) 'i': i32
313 [56; 150) '{ ... }; }': ()
314 [66; 67) 'x': &[i32]
315 [70; 147) 'match ... }': &[i32]
316 [76; 77) 'i': i32
317 [88; 89) '1': i32
318 [93; 97) '&[1]': &[i32;_]
319 [94; 97) '[1]': [i32;_]
320 [95; 96) '1': i32
321 [107; 108) '2': i32
322 [112; 115) 'foo': fn foo<i32>(&[T]) -> &[T]
323 [112; 121) 'foo(&[2])': &[i32]
324 [116; 120) '&[2]': &[i32;_]
325 [117; 120) '[2]': [i32;_]
326 [118; 119) '2': i32
327 [131; 132) '_': i32
328 [136; 140) '&[3]': &[i32;_]
329 [137; 140) '[3]': [i32;_]
330 [138; 139) '3': i32
331 "###
332 );
333}
334
335#[test]
336fn coerce_merge_one_by_one1() {
337 covers!(coerce_merge_fail_fallback);
338
339 assert_snapshot!(
340 infer(r#"
341fn test() {
342 let t = &mut 1;
343 let x = match 1 {
344 1 => t as *mut i32,
345 2 => t as &i32,
346 _ => t as *const i32,
347 };
348}
349"#),
350 @r###"
351 [11; 145) '{ ... }; }': ()
352 [21; 22) 't': &mut i32
353 [25; 31) '&mut 1': &mut i32
354 [30; 31) '1': i32
355 [41; 42) 'x': *const i32
356 [45; 142) 'match ... }': *const i32
357 [51; 52) '1': i32
358 [63; 64) '1': i32
359 [68; 69) 't': &mut i32
360 [68; 81) 't as *mut i32': *mut i32
361 [91; 92) '2': i32
362 [96; 97) 't': &mut i32
363 [96; 105) 't as &i32': &i32
364 [115; 116) '_': i32
365 [120; 121) 't': &mut i32
366 [120; 135) 't as *const i32': *const i32
367 "###
368 );
369}
diff --git a/crates/ra_hir_ty/src/tests/never_type.rs b/crates/ra_hir_ty/src/tests/never_type.rs
new file mode 100644
index 000000000..c202f545a
--- /dev/null
+++ b/crates/ra_hir_ty/src/tests/never_type.rs
@@ -0,0 +1,246 @@
1use super::type_at;
2
3#[test]
4fn infer_never1() {
5 let t = type_at(
6 r#"
7//- /main.rs
8fn test() {
9 let t = return;
10 t<|>;
11}
12"#,
13 );
14 assert_eq!(t, "!");
15}
16
17#[test]
18fn infer_never2() {
19 let t = type_at(
20 r#"
21//- /main.rs
22fn gen<T>() -> T { loop {} }
23
24fn test() {
25 let a = gen();
26 if false { a } else { loop {} };
27 a<|>;
28}
29"#,
30 );
31 assert_eq!(t, "!");
32}
33
34#[test]
35fn infer_never3() {
36 let t = type_at(
37 r#"
38//- /main.rs
39fn gen<T>() -> T { loop {} }
40
41fn test() {
42 let a = gen();
43 if false { loop {} } else { a };
44 a<|>;
45}
46"#,
47 );
48 assert_eq!(t, "!");
49}
50
51#[test]
52fn never_type_in_generic_args() {
53 let t = type_at(
54 r#"
55//- /main.rs
56enum Option<T> { None, Some(T) }
57
58fn test() {
59 let a = if true { Option::None } else { Option::Some(return) };
60 a<|>;
61}
62"#,
63 );
64 assert_eq!(t, "Option<!>");
65}
66
67#[test]
68fn never_type_can_be_reinferred1() {
69 let t = type_at(
70 r#"
71//- /main.rs
72fn gen<T>() -> T { loop {} }
73
74fn test() {
75 let a = gen();
76 if false { loop {} } else { a };
77 a<|>;
78 if false { a };
79}
80"#,
81 );
82 assert_eq!(t, "()");
83}
84
85#[test]
86fn never_type_can_be_reinferred2() {
87 let t = type_at(
88 r#"
89//- /main.rs
90enum Option<T> { None, Some(T) }
91
92fn test() {
93 let a = if true { Option::None } else { Option::Some(return) };
94 a<|>;
95 match 42 {
96 42 => a,
97 _ => Option::Some(42),
98 };
99}
100"#,
101 );
102 assert_eq!(t, "Option<i32>");
103}
104#[test]
105fn never_type_can_be_reinferred3() {
106 let t = type_at(
107 r#"
108//- /main.rs
109enum Option<T> { None, Some(T) }
110
111fn test() {
112 let a = if true { Option::None } else { Option::Some(return) };
113 a<|>;
114 match 42 {
115 42 => a,
116 _ => Option::Some("str"),
117 };
118}
119"#,
120 );
121 assert_eq!(t, "Option<&str>");
122}
123
124#[test]
125fn match_no_arm() {
126 let t = type_at(
127 r#"
128//- /main.rs
129enum Void {}
130
131fn test(a: Void) {
132 let t = match a {};
133 t<|>;
134}
135"#,
136 );
137 assert_eq!(t, "!");
138}
139
140#[test]
141fn if_never() {
142 let t = type_at(
143 r#"
144//- /main.rs
145fn test() {
146 let i = if true {
147 loop {}
148 } else {
149 3.0
150 };
151 i<|>;
152}
153"#,
154 );
155 assert_eq!(t, "f64");
156}
157
158#[test]
159fn if_else_never() {
160 let t = type_at(
161 r#"
162//- /main.rs
163fn test(input: bool) {
164 let i = if input {
165 2.0
166 } else {
167 return
168 };
169 i<|>;
170}
171"#,
172 );
173 assert_eq!(t, "f64");
174}
175
176#[test]
177fn match_first_arm_never() {
178 let t = type_at(
179 r#"
180//- /main.rs
181fn test(a: i32) {
182 let i = match a {
183 1 => return,
184 2 => 2.0,
185 3 => loop {},
186 _ => 3.0,
187 };
188 i<|>;
189}
190"#,
191 );
192 assert_eq!(t, "f64");
193}
194
195#[test]
196fn match_second_arm_never() {
197 let t = type_at(
198 r#"
199//- /main.rs
200fn test(a: i32) {
201 let i = match a {
202 1 => 3.0,
203 2 => loop {},
204 3 => 3.0,
205 _ => return,
206 };
207 i<|>;
208}
209"#,
210 );
211 assert_eq!(t, "f64");
212}
213
214#[test]
215fn match_all_arms_never() {
216 let t = type_at(
217 r#"
218//- /main.rs
219fn test(a: i32) {
220 let i = match a {
221 2 => return,
222 _ => loop {},
223 };
224 i<|>;
225}
226"#,
227 );
228 assert_eq!(t, "!");
229}
230
231#[test]
232fn match_no_never_arms() {
233 let t = type_at(
234 r#"
235//- /main.rs
236fn test(a: i32) {
237 let i = match a {
238 2 => 2.0,
239 _ => 3.0,
240 };
241 i<|>;
242}
243"#,
244 );
245 assert_eq!(t, "f64");
246}
diff --git a/crates/ra_hir_ty/src/traits.rs b/crates/ra_hir_ty/src/traits.rs
new file mode 100644
index 000000000..76189a60b
--- /dev/null
+++ b/crates/ra_hir_ty/src/traits.rs
@@ -0,0 +1,328 @@
1//! Trait solving using Chalk.
2use std::sync::{Arc, Mutex};
3
4use chalk_ir::{cast::Cast, family::ChalkIr};
5use hir_def::{expr::ExprId, DefWithBodyId, ImplId, TraitId, TypeAliasId};
6use log::debug;
7use ra_db::{impl_intern_key, salsa, CrateId};
8use ra_prof::profile;
9use rustc_hash::FxHashSet;
10
11use crate::db::HirDatabase;
12
13use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk};
14
15use self::chalk::{from_chalk, ToChalk};
16
17pub(crate) mod chalk;
18
19#[derive(Debug, Clone)]
20pub struct TraitSolver {
21 krate: CrateId,
22 inner: Arc<Mutex<chalk_solve::Solver<ChalkIr>>>,
23}
24
25/// We need eq for salsa
26impl PartialEq for TraitSolver {
27 fn eq(&self, other: &TraitSolver) -> bool {
28 Arc::ptr_eq(&self.inner, &other.inner)
29 }
30}
31
32impl Eq for TraitSolver {}
33
34impl TraitSolver {
35 fn solve(
36 &self,
37 db: &impl HirDatabase,
38 goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<ChalkIr>>>,
39 ) -> Option<chalk_solve::Solution<ChalkIr>> {
40 let context = ChalkContext { db, krate: self.krate };
41 debug!("solve goal: {:?}", goal);
42 let mut solver = match self.inner.lock() {
43 Ok(it) => it,
44 // Our cancellation works via unwinding, but, as chalk is not
45 // panic-safe, we need to make sure to propagate the cancellation.
46 // Ideally, we should also make chalk panic-safe.
47 Err(_) => ra_db::Canceled::throw(),
48 };
49 let solution = solver.solve(&context, goal);
50 debug!("solve({:?}) => {:?}", goal, solution);
51 solution
52 }
53}
54
55/// This controls the maximum size of types Chalk considers. If we set this too
56/// high, we can run into slow edge cases; if we set it too low, Chalk won't
57/// find some solutions.
58const CHALK_SOLVER_MAX_SIZE: usize = 4;
59
60#[derive(Debug, Copy, Clone)]
61struct ChalkContext<'a, DB> {
62 db: &'a DB,
63 krate: CrateId,
64}
65
66pub(crate) fn trait_solver_query(
67 db: &(impl HirDatabase + salsa::Database),
68 krate: CrateId,
69) -> TraitSolver {
70 db.salsa_runtime().report_untracked_read();
71 // krate parameter is just so we cache a unique solver per crate
72 let solver_choice = chalk_solve::SolverChoice::SLG { max_size: CHALK_SOLVER_MAX_SIZE };
73 debug!("Creating new solver for crate {:?}", krate);
74 TraitSolver { krate, inner: Arc::new(Mutex::new(solver_choice.into_solver())) }
75}
76
77/// Collects impls for the given trait in the whole dependency tree of `krate`.
78pub(crate) fn impls_for_trait_query(
79 db: &impl HirDatabase,
80 krate: CrateId,
81 trait_: TraitId,
82) -> Arc<[ImplId]> {
83 let mut impls = FxHashSet::default();
84 // We call the query recursively here. On the one hand, this means we can
85 // reuse results from queries for different crates; on the other hand, this
86 // will only ever get called for a few crates near the root of the tree (the
87 // ones the user is editing), so this may actually be a waste of memory. I'm
88 // doing it like this mainly for simplicity for now.
89 for dep in db.crate_graph().dependencies(krate) {
90 impls.extend(db.impls_for_trait(dep.crate_id, trait_).iter());
91 }
92 let crate_impl_blocks = db.impls_in_crate(krate);
93 impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_));
94 impls.into_iter().collect()
95}
96
97/// A set of clauses that we assume to be true. E.g. if we are inside this function:
98/// ```rust
99/// fn foo<T: Default>(t: T) {}
100/// ```
101/// we assume that `T: Default`.
102#[derive(Clone, Debug, PartialEq, Eq, Hash)]
103pub struct TraitEnvironment {
104 pub predicates: Vec<GenericPredicate>,
105}
106
107impl TraitEnvironment {
108 /// Returns trait refs with the given self type which are supposed to hold
109 /// in this trait env. E.g. if we are in `foo<T: SomeTrait>()`, this will
110 /// find that `T: SomeTrait` if we call it for `T`.
111 pub(crate) fn trait_predicates_for_self_ty<'a>(
112 &'a self,
113 ty: &'a Ty,
114 ) -> impl Iterator<Item = &'a TraitRef> + 'a {
115 self.predicates.iter().filter_map(move |pred| match pred {
116 GenericPredicate::Implemented(tr) if tr.self_ty() == ty => Some(tr),
117 _ => None,
118 })
119 }
120}
121
122/// Something (usually a goal), along with an environment.
123#[derive(Clone, Debug, PartialEq, Eq, Hash)]
124pub struct InEnvironment<T> {
125 pub environment: Arc<TraitEnvironment>,
126 pub value: T,
127}
128
129impl<T> InEnvironment<T> {
130 pub fn new(environment: Arc<TraitEnvironment>, value: T) -> InEnvironment<T> {
131 InEnvironment { environment, value }
132 }
133}
134
135/// Something that needs to be proven (by Chalk) during type checking, e.g. that
136/// a certain type implements a certain trait. Proving the Obligation might
137/// result in additional information about inference variables.
138#[derive(Clone, Debug, PartialEq, Eq, Hash)]
139pub enum Obligation {
140 /// Prove that a certain type implements a trait (the type is the `Self` type
141 /// parameter to the `TraitRef`).
142 Trait(TraitRef),
143 Projection(ProjectionPredicate),
144}
145
146impl Obligation {
147 pub fn from_predicate(predicate: GenericPredicate) -> Option<Obligation> {
148 match predicate {
149 GenericPredicate::Implemented(trait_ref) => Some(Obligation::Trait(trait_ref)),
150 GenericPredicate::Projection(projection_pred) => {
151 Some(Obligation::Projection(projection_pred))
152 }
153 GenericPredicate::Error => None,
154 }
155 }
156}
157
158#[derive(Clone, Debug, PartialEq, Eq, Hash)]
159pub struct ProjectionPredicate {
160 pub projection_ty: ProjectionTy,
161 pub ty: Ty,
162}
163
164impl TypeWalk for ProjectionPredicate {
165 fn walk(&self, f: &mut impl FnMut(&Ty)) {
166 self.projection_ty.walk(f);
167 self.ty.walk(f);
168 }
169
170 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
171 self.projection_ty.walk_mut_binders(f, binders);
172 self.ty.walk_mut_binders(f, binders);
173 }
174}
175
176/// Solve a trait goal using Chalk.
177pub(crate) fn trait_solve_query(
178 db: &impl HirDatabase,
179 krate: CrateId,
180 goal: Canonical<InEnvironment<Obligation>>,
181) -> Option<Solution> {
182 let _p = profile("trait_solve_query");
183 debug!("trait_solve_query({})", goal.value.value.display(db));
184
185 if let Obligation::Projection(pred) = &goal.value.value {
186 if let Ty::Bound(_) = &pred.projection_ty.parameters[0] {
187 // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible
188 return Some(Solution::Ambig(Guidance::Unknown));
189 }
190 }
191
192 let canonical = goal.to_chalk(db).cast();
193
194 // We currently don't deal with universes (I think / hope they're not yet
195 // relevant for our use cases?)
196 let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 };
197 let solution = db.trait_solver(krate).solve(db, &u_canonical);
198 solution.map(|solution| solution_from_chalk(db, solution))
199}
200
201fn solution_from_chalk(
202 db: &impl HirDatabase,
203 solution: chalk_solve::Solution<ChalkIr>,
204) -> Solution {
205 let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<ChalkIr>>| {
206 let value = subst
207 .value
208 .parameters
209 .into_iter()
210 .map(|p| {
211 let ty = match p {
212 chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty),
213 chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(),
214 };
215 ty
216 })
217 .collect();
218 let result = Canonical { value, num_vars: subst.binders.len() };
219 SolutionVariables(result)
220 };
221 match solution {
222 chalk_solve::Solution::Unique(constr_subst) => {
223 let subst = chalk_ir::Canonical {
224 value: constr_subst.value.subst,
225 binders: constr_subst.binders,
226 };
227 Solution::Unique(convert_subst(subst))
228 }
229 chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst)) => {
230 Solution::Ambig(Guidance::Definite(convert_subst(subst)))
231 }
232 chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst)) => {
233 Solution::Ambig(Guidance::Suggested(convert_subst(subst)))
234 }
235 chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown) => {
236 Solution::Ambig(Guidance::Unknown)
237 }
238 }
239}
240
241#[derive(Clone, Debug, PartialEq, Eq)]
242pub struct SolutionVariables(pub Canonical<Vec<Ty>>);
243
244#[derive(Clone, Debug, PartialEq, Eq)]
245/// A (possible) solution for a proposed goal.
246pub enum Solution {
247 /// The goal indeed holds, and there is a unique value for all existential
248 /// variables.
249 Unique(SolutionVariables),
250
251 /// The goal may be provable in multiple ways, but regardless we may have some guidance
252 /// for type inference. In this case, we don't return any lifetime
253 /// constraints, since we have not "committed" to any particular solution
254 /// yet.
255 Ambig(Guidance),
256}
257
258#[derive(Clone, Debug, PartialEq, Eq)]
259/// When a goal holds ambiguously (e.g., because there are multiple possible
260/// solutions), we issue a set of *guidance* back to type inference.
261pub enum Guidance {
262 /// The existential variables *must* have the given values if the goal is
263 /// ever to hold, but that alone isn't enough to guarantee the goal will
264 /// actually hold.
265 Definite(SolutionVariables),
266
267 /// There are multiple plausible values for the existentials, but the ones
268 /// here are suggested as the preferred choice heuristically. These should
269 /// be used for inference fallback only.
270 Suggested(SolutionVariables),
271
272 /// There's no useful information to feed back to type inference
273 Unknown,
274}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
277pub enum FnTrait {
278 FnOnce,
279 FnMut,
280 Fn,
281}
282
283impl FnTrait {
284 fn lang_item_name(self) -> &'static str {
285 match self {
286 FnTrait::FnOnce => "fn_once",
287 FnTrait::FnMut => "fn_mut",
288 FnTrait::Fn => "fn",
289 }
290 }
291}
292
293#[derive(Debug, Clone, PartialEq, Eq, Hash)]
294pub struct ClosureFnTraitImplData {
295 def: DefWithBodyId,
296 expr: ExprId,
297 fn_trait: FnTrait,
298}
299
300/// An impl. Usually this comes from an impl block, but some built-in types get
301/// synthetic impls.
302#[derive(Debug, Clone, PartialEq, Eq, Hash)]
303pub enum Impl {
304 /// A normal impl from an impl block.
305 ImplBlock(ImplId),
306 /// Closure types implement the Fn traits synthetically.
307 ClosureFnTraitImpl(ClosureFnTraitImplData),
308}
309/// This exists just for Chalk, because our ImplIds are only unique per module.
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub struct GlobalImplId(salsa::InternId);
312impl_intern_key!(GlobalImplId);
313
314/// An associated type value. Usually this comes from a `type` declaration
315/// inside an impl block, but for built-in impls we have to synthesize it.
316/// (We only need this because Chalk wants a unique ID for each of these.)
317#[derive(Debug, Clone, PartialEq, Eq, Hash)]
318pub enum AssocTyValue {
319 /// A normal assoc type value from an impl block.
320 TypeAlias(TypeAliasId),
321 /// The output type of the Fn trait implementation.
322 ClosureFnTraitImplOutput(ClosureFnTraitImplData),
323}
324/// This exists just for Chalk, because it needs a unique ID for each associated
325/// type value in an impl (even synthetic ones).
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
327pub struct AssocTyValueId(salsa::InternId);
328impl_intern_key!(AssocTyValueId);
diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs
new file mode 100644
index 000000000..35de37e6b
--- /dev/null
+++ b/crates/ra_hir_ty/src/traits/chalk.rs
@@ -0,0 +1,900 @@
1//! Conversion code from/to Chalk.
2use std::sync::Arc;
3
4use log::debug;
5
6use chalk_ir::{
7 cast::Cast, family::ChalkIr, Identifier, Parameter, PlaceholderIndex, TypeId, TypeKindId,
8 TypeName, UniverseIndex,
9};
10use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum};
11use ra_db::CrateId;
12
13use hir_def::{
14 expr::Expr, lang_item::LangItemTarget, AssocItemId, AstItemDef, ContainerId, GenericDefId,
15 ImplId, Lookup, TraitId, TypeAliasId,
16};
17use hir_expand::name;
18
19use ra_db::salsa::{InternId, InternKey};
20
21use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation};
22use crate::{
23 db::HirDatabase, display::HirDisplay, ApplicationTy, GenericPredicate, ImplTy, ProjectionTy,
24 Substs, TraitRef, Ty, TypeCtor, TypeWalk,
25};
26
27/// This represents a trait whose name we could not resolve.
28const UNKNOWN_TRAIT: chalk_ir::TraitId =
29 chalk_ir::TraitId(chalk_ir::RawId { index: u32::max_value() });
30
31pub(super) trait ToChalk {
32 type Chalk;
33 fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk;
34 fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self;
35}
36
37pub(super) fn from_chalk<T, ChalkT>(db: &impl HirDatabase, chalk: ChalkT) -> T
38where
39 T: ToChalk<Chalk = ChalkT>,
40{
41 T::from_chalk(db, chalk)
42}
43
44impl ToChalk for Ty {
45 type Chalk = chalk_ir::Ty<ChalkIr>;
46 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty<ChalkIr> {
47 match self {
48 Ty::Apply(apply_ty) => {
49 let name = match apply_ty.ctor {
50 TypeCtor::AssociatedType(type_alias) => {
51 let type_id = type_alias.to_chalk(db);
52 TypeName::AssociatedType(type_id)
53 }
54 _ => {
55 // other TypeCtors get interned and turned into a chalk StructId
56 let struct_id = apply_ty.ctor.to_chalk(db);
57 TypeName::TypeKindId(struct_id.into())
58 }
59 };
60 let parameters = apply_ty.parameters.to_chalk(db);
61 chalk_ir::ApplicationTy { name, parameters }.cast().intern()
62 }
63 Ty::Projection(proj_ty) => {
64 let associated_ty_id = proj_ty.associated_ty.to_chalk(db);
65 let parameters = proj_ty.parameters.to_chalk(db);
66 chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern()
67 }
68 Ty::Param { idx, .. } => {
69 PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::<ChalkIr>()
70 }
71 Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(),
72 Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
73 Ty::Dyn(predicates) => {
74 let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect();
75 chalk_ir::TyData::Dyn(make_binders(where_clauses, 1)).intern()
76 }
77 Ty::Opaque(predicates) => {
78 let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect();
79 chalk_ir::TyData::Opaque(make_binders(where_clauses, 1)).intern()
80 }
81 Ty::Unknown => {
82 let parameters = Vec::new();
83 let name = TypeName::Error;
84 chalk_ir::ApplicationTy { name, parameters }.cast().intern()
85 }
86 }
87 }
88 fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty<ChalkIr>) -> Self {
89 match chalk.data().clone() {
90 chalk_ir::TyData::Apply(apply_ty) => {
91 // FIXME this is kind of hacky due to the fact that
92 // TypeName::Placeholder is a Ty::Param on our side
93 match apply_ty.name {
94 TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => {
95 let ctor = from_chalk(db, struct_id);
96 let parameters = from_chalk(db, apply_ty.parameters);
97 Ty::Apply(ApplicationTy { ctor, parameters })
98 }
99 TypeName::AssociatedType(type_id) => {
100 let ctor = TypeCtor::AssociatedType(from_chalk(db, type_id));
101 let parameters = from_chalk(db, apply_ty.parameters);
102 Ty::Apply(ApplicationTy { ctor, parameters })
103 }
104 TypeName::Error => Ty::Unknown,
105 // FIXME handle TypeKindId::Trait/Type here
106 TypeName::TypeKindId(_) => unimplemented!(),
107 TypeName::Placeholder(idx) => {
108 assert_eq!(idx.ui, UniverseIndex::ROOT);
109 Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() }
110 }
111 }
112 }
113 chalk_ir::TyData::Projection(proj) => {
114 let associated_ty = from_chalk(db, proj.associated_ty_id);
115 let parameters = from_chalk(db, proj.parameters);
116 Ty::Projection(ProjectionTy { associated_ty, parameters })
117 }
118 chalk_ir::TyData::ForAll(_) => unimplemented!(),
119 chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32),
120 chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown,
121 chalk_ir::TyData::Dyn(where_clauses) => {
122 assert_eq!(where_clauses.binders.len(), 1);
123 let predicates =
124 where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect();
125 Ty::Dyn(predicates)
126 }
127 chalk_ir::TyData::Opaque(where_clauses) => {
128 assert_eq!(where_clauses.binders.len(), 1);
129 let predicates =
130 where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect();
131 Ty::Opaque(predicates)
132 }
133 }
134 }
135}
136
137impl ToChalk for Substs {
138 type Chalk = Vec<chalk_ir::Parameter<ChalkIr>>;
139
140 fn to_chalk(self, db: &impl HirDatabase) -> Vec<Parameter<ChalkIr>> {
141 self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect()
142 }
143
144 fn from_chalk(db: &impl HirDatabase, parameters: Vec<chalk_ir::Parameter<ChalkIr>>) -> Substs {
145 let tys = parameters
146 .into_iter()
147 .map(|p| match p {
148 chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty),
149 chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(),
150 })
151 .collect();
152 Substs(tys)
153 }
154}
155
156impl ToChalk for TraitRef {
157 type Chalk = chalk_ir::TraitRef<ChalkIr>;
158
159 fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef<ChalkIr> {
160 let trait_id = self.trait_.to_chalk(db);
161 let parameters = self.substs.to_chalk(db);
162 chalk_ir::TraitRef { trait_id, parameters }
163 }
164
165 fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef<ChalkIr>) -> Self {
166 let trait_ = from_chalk(db, trait_ref.trait_id);
167 let substs = from_chalk(db, trait_ref.parameters);
168 TraitRef { trait_, substs }
169 }
170}
171
172impl ToChalk for TraitId {
173 type Chalk = chalk_ir::TraitId;
174
175 fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TraitId {
176 chalk_ir::TraitId(id_to_chalk(self))
177 }
178
179 fn from_chalk(_db: &impl HirDatabase, trait_id: chalk_ir::TraitId) -> TraitId {
180 id_from_chalk(trait_id.0)
181 }
182}
183
184impl ToChalk for TypeCtor {
185 type Chalk = chalk_ir::StructId;
186
187 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId {
188 db.intern_type_ctor(self).into()
189 }
190
191 fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor {
192 db.lookup_intern_type_ctor(struct_id.into())
193 }
194}
195
196impl ToChalk for Impl {
197 type Chalk = chalk_ir::ImplId;
198
199 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId {
200 db.intern_chalk_impl(self).into()
201 }
202
203 fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> Impl {
204 db.lookup_intern_chalk_impl(impl_id.into())
205 }
206}
207
208impl ToChalk for TypeAliasId {
209 type Chalk = chalk_ir::TypeId;
210
211 fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TypeId {
212 chalk_ir::TypeId(id_to_chalk(self))
213 }
214
215 fn from_chalk(_db: &impl HirDatabase, type_alias_id: chalk_ir::TypeId) -> TypeAliasId {
216 id_from_chalk(type_alias_id.0)
217 }
218}
219
220impl ToChalk for AssocTyValue {
221 type Chalk = chalk_rust_ir::AssociatedTyValueId;
222
223 fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId {
224 db.intern_assoc_ty_value(self).into()
225 }
226
227 fn from_chalk(
228 db: &impl HirDatabase,
229 assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId,
230 ) -> AssocTyValue {
231 db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into())
232 }
233}
234
235impl ToChalk for GenericPredicate {
236 type Chalk = chalk_ir::QuantifiedWhereClause<ChalkIr>;
237
238 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause<ChalkIr> {
239 match self {
240 GenericPredicate::Implemented(trait_ref) => {
241 make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0)
242 }
243 GenericPredicate::Projection(projection_pred) => make_binders(
244 chalk_ir::WhereClause::ProjectionEq(chalk_ir::ProjectionEq {
245 projection: projection_pred.projection_ty.to_chalk(db),
246 ty: projection_pred.ty.to_chalk(db),
247 }),
248 0,
249 ),
250 GenericPredicate::Error => {
251 let impossible_trait_ref = chalk_ir::TraitRef {
252 trait_id: UNKNOWN_TRAIT,
253 parameters: vec![Ty::Unknown.to_chalk(db).cast()],
254 };
255 make_binders(chalk_ir::WhereClause::Implemented(impossible_trait_ref), 0)
256 }
257 }
258 }
259
260 fn from_chalk(
261 db: &impl HirDatabase,
262 where_clause: chalk_ir::QuantifiedWhereClause<ChalkIr>,
263 ) -> GenericPredicate {
264 match where_clause.value {
265 chalk_ir::WhereClause::Implemented(tr) => {
266 if tr.trait_id == UNKNOWN_TRAIT {
267 // FIXME we need an Error enum on the Chalk side to avoid this
268 return GenericPredicate::Error;
269 }
270 GenericPredicate::Implemented(from_chalk(db, tr))
271 }
272 chalk_ir::WhereClause::ProjectionEq(projection_eq) => {
273 let projection_ty = from_chalk(db, projection_eq.projection);
274 let ty = from_chalk(db, projection_eq.ty);
275 GenericPredicate::Projection(super::ProjectionPredicate { projection_ty, ty })
276 }
277 }
278 }
279}
280
281impl ToChalk for ProjectionTy {
282 type Chalk = chalk_ir::ProjectionTy<ChalkIr>;
283
284 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ProjectionTy<ChalkIr> {
285 chalk_ir::ProjectionTy {
286 associated_ty_id: self.associated_ty.to_chalk(db),
287 parameters: self.parameters.to_chalk(db),
288 }
289 }
290
291 fn from_chalk(
292 db: &impl HirDatabase,
293 projection_ty: chalk_ir::ProjectionTy<ChalkIr>,
294 ) -> ProjectionTy {
295 ProjectionTy {
296 associated_ty: from_chalk(db, projection_ty.associated_ty_id),
297 parameters: from_chalk(db, projection_ty.parameters),
298 }
299 }
300}
301
302impl ToChalk for super::ProjectionPredicate {
303 type Chalk = chalk_ir::Normalize<ChalkIr>;
304
305 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize<ChalkIr> {
306 chalk_ir::Normalize {
307 projection: self.projection_ty.to_chalk(db),
308 ty: self.ty.to_chalk(db),
309 }
310 }
311
312 fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize<ChalkIr>) -> Self {
313 unimplemented!()
314 }
315}
316
317impl ToChalk for Obligation {
318 type Chalk = chalk_ir::DomainGoal<ChalkIr>;
319
320 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal<ChalkIr> {
321 match self {
322 Obligation::Trait(tr) => tr.to_chalk(db).cast(),
323 Obligation::Projection(pr) => pr.to_chalk(db).cast(),
324 }
325 }
326
327 fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal<ChalkIr>) -> Self {
328 unimplemented!()
329 }
330}
331
332impl<T> ToChalk for Canonical<T>
333where
334 T: ToChalk,
335{
336 type Chalk = chalk_ir::Canonical<T::Chalk>;
337
338 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
339 let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT);
340 let value = self.value.to_chalk(db);
341 let canonical = chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] };
342 canonical
343 }
344
345 fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {
346 Canonical { num_vars: canonical.binders.len(), value: from_chalk(db, canonical.value) }
347 }
348}
349
350impl ToChalk for Arc<super::TraitEnvironment> {
351 type Chalk = chalk_ir::Environment<ChalkIr>;
352
353 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment<ChalkIr> {
354 let mut clauses = Vec::new();
355 for pred in &self.predicates {
356 if pred.is_error() {
357 // for env, we just ignore errors
358 continue;
359 }
360 let program_clause: chalk_ir::ProgramClause<ChalkIr> = pred.clone().to_chalk(db).cast();
361 clauses.push(program_clause.into_from_env_clause());
362 }
363 chalk_ir::Environment::new().add_clauses(clauses)
364 }
365
366 fn from_chalk(
367 _db: &impl HirDatabase,
368 _env: chalk_ir::Environment<ChalkIr>,
369 ) -> Arc<super::TraitEnvironment> {
370 unimplemented!()
371 }
372}
373
374impl<T: ToChalk> ToChalk for super::InEnvironment<T>
375where
376 T::Chalk: chalk_ir::family::HasTypeFamily<TypeFamily = ChalkIr>,
377{
378 type Chalk = chalk_ir::InEnvironment<T::Chalk>;
379
380 fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
381 chalk_ir::InEnvironment {
382 environment: self.environment.to_chalk(db),
383 goal: self.value.to_chalk(db),
384 }
385 }
386
387 fn from_chalk(
388 db: &impl HirDatabase,
389 in_env: chalk_ir::InEnvironment<T::Chalk>,
390 ) -> super::InEnvironment<T> {
391 super::InEnvironment {
392 environment: from_chalk(db, in_env.environment),
393 value: from_chalk(db, in_env.goal),
394 }
395 }
396}
397
398fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T> {
399 chalk_ir::Binders {
400 value,
401 binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(),
402 }
403}
404
405fn convert_where_clauses(
406 db: &impl HirDatabase,
407 def: GenericDefId,
408 substs: &Substs,
409) -> Vec<chalk_ir::QuantifiedWhereClause<ChalkIr>> {
410 let generic_predicates = db.generic_predicates(def);
411 let mut result = Vec::with_capacity(generic_predicates.len());
412 for pred in generic_predicates.iter() {
413 if pred.is_error() {
414 // HACK: Return just the single predicate (which is always false
415 // anyway), otherwise Chalk can easily get into slow situations
416 return vec![pred.clone().subst(substs).to_chalk(db)];
417 }
418 result.push(pred.clone().subst(substs).to_chalk(db));
419 }
420 result
421}
422
423impl<'a, DB> chalk_solve::RustIrDatabase<ChalkIr> for ChalkContext<'a, DB>
424where
425 DB: HirDatabase,
426{
427 fn associated_ty_data(&self, id: TypeId) -> Arc<AssociatedTyDatum<ChalkIr>> {
428 self.db.associated_ty_data(id)
429 }
430 fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc<TraitDatum<ChalkIr>> {
431 self.db.trait_datum(self.krate, trait_id)
432 }
433 fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc<StructDatum<ChalkIr>> {
434 self.db.struct_datum(self.krate, struct_id)
435 }
436 fn impl_datum(&self, impl_id: chalk_ir::ImplId) -> Arc<ImplDatum<ChalkIr>> {
437 self.db.impl_datum(self.krate, impl_id)
438 }
439 fn impls_for_trait(
440 &self,
441 trait_id: chalk_ir::TraitId,
442 parameters: &[Parameter<ChalkIr>],
443 ) -> Vec<chalk_ir::ImplId> {
444 debug!("impls_for_trait {:?}", trait_id);
445 if trait_id == UNKNOWN_TRAIT {
446 return Vec::new();
447 }
448 let trait_: TraitId = from_chalk(self.db, trait_id);
449 let mut result: Vec<_> = self
450 .db
451 .impls_for_trait(self.krate, trait_.into())
452 .iter()
453 .copied()
454 .map(|it| Impl::ImplBlock(it.into()))
455 .map(|impl_| impl_.to_chalk(self.db))
456 .collect();
457
458 let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref().clone());
459 if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { def, expr }, .. }) = ty {
460 for &fn_trait in
461 [super::FnTrait::FnOnce, super::FnTrait::FnMut, super::FnTrait::Fn].iter()
462 {
463 if let Some(actual_trait) = get_fn_trait(self.db, self.krate, fn_trait) {
464 if trait_ == actual_trait {
465 let impl_ = super::ClosureFnTraitImplData { def, expr, fn_trait };
466 result.push(Impl::ClosureFnTraitImpl(impl_).to_chalk(self.db));
467 }
468 }
469 }
470 }
471
472 debug!("impls_for_trait returned {} impls", result.len());
473 result
474 }
475 fn impl_provided_for(
476 &self,
477 auto_trait_id: chalk_ir::TraitId,
478 struct_id: chalk_ir::StructId,
479 ) -> bool {
480 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id);
481 false // FIXME
482 }
483 fn type_name(&self, _id: TypeKindId) -> Identifier {
484 unimplemented!()
485 }
486 fn associated_ty_value(
487 &self,
488 id: chalk_rust_ir::AssociatedTyValueId,
489 ) -> Arc<AssociatedTyValue<ChalkIr>> {
490 self.db.associated_ty_value(self.krate.into(), id)
491 }
492 fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<ChalkIr>> {
493 vec![]
494 }
495 fn local_impls_to_coherence_check(
496 &self,
497 _trait_id: chalk_ir::TraitId,
498 ) -> Vec<chalk_ir::ImplId> {
499 // We don't do coherence checking (yet)
500 unimplemented!()
501 }
502}
503
504pub(crate) fn associated_ty_data_query(
505 db: &impl HirDatabase,
506 id: TypeId,
507) -> Arc<AssociatedTyDatum<ChalkIr>> {
508 debug!("associated_ty_data {:?}", id);
509 let type_alias: TypeAliasId = from_chalk(db, id);
510 let trait_ = match type_alias.lookup(db).container {
511 ContainerId::TraitId(t) => t,
512 _ => panic!("associated type not in trait"),
513 };
514 let generic_params = db.generic_params(type_alias.into());
515 let bound_data = chalk_rust_ir::AssociatedTyDatumBound {
516 // FIXME add bounds and where clauses
517 bounds: vec![],
518 where_clauses: vec![],
519 };
520 let datum = AssociatedTyDatum {
521 trait_id: trait_.to_chalk(db),
522 id,
523 name: lalrpop_intern::intern(&db.type_alias_data(type_alias).name.to_string()),
524 binders: make_binders(bound_data, generic_params.count_params_including_parent()),
525 };
526 Arc::new(datum)
527}
528
529pub(crate) fn trait_datum_query(
530 db: &impl HirDatabase,
531 krate: CrateId,
532 trait_id: chalk_ir::TraitId,
533) -> Arc<TraitDatum<ChalkIr>> {
534 debug!("trait_datum {:?}", trait_id);
535 if trait_id == UNKNOWN_TRAIT {
536 let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() };
537
538 let flags = chalk_rust_ir::TraitFlags {
539 auto: false,
540 marker: false,
541 upstream: true,
542 fundamental: false,
543 non_enumerable: true,
544 coinductive: false,
545 };
546 return Arc::new(TraitDatum {
547 id: trait_id,
548 binders: make_binders(trait_datum_bound, 1),
549 flags,
550 associated_ty_ids: vec![],
551 });
552 }
553 let trait_: TraitId = from_chalk(db, trait_id);
554 let trait_data = db.trait_data(trait_);
555 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
556 let generic_params = db.generic_params(trait_.into());
557 let bound_vars = Substs::bound_vars(&generic_params);
558 let flags = chalk_rust_ir::TraitFlags {
559 auto: trait_data.auto,
560 upstream: trait_.module(db).krate != krate,
561 non_enumerable: true,
562 coinductive: false, // only relevant for Chalk testing
563 // FIXME set these flags correctly
564 marker: false,
565 fundamental: false,
566 };
567 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
568 let associated_ty_ids =
569 trait_data.associated_types().map(|type_alias| type_alias.to_chalk(db)).collect();
570 let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses };
571 let trait_datum = TraitDatum {
572 id: trait_id,
573 binders: make_binders(trait_datum_bound, bound_vars.len()),
574 flags,
575 associated_ty_ids,
576 };
577 Arc::new(trait_datum)
578}
579
580pub(crate) fn struct_datum_query(
581 db: &impl HirDatabase,
582 krate: CrateId,
583 struct_id: chalk_ir::StructId,
584) -> Arc<StructDatum<ChalkIr>> {
585 debug!("struct_datum {:?}", struct_id);
586 let type_ctor: TypeCtor = from_chalk(db, struct_id);
587 debug!("struct {:?} = {:?}", struct_id, type_ctor);
588 let num_params = type_ctor.num_ty_params(db);
589 let upstream = type_ctor.krate(db) != Some(krate);
590 let where_clauses = type_ctor
591 .as_generic_def()
592 .map(|generic_def| {
593 let generic_params = db.generic_params(generic_def.into());
594 let bound_vars = Substs::bound_vars(&generic_params);
595 convert_where_clauses(db, generic_def, &bound_vars)
596 })
597 .unwrap_or_else(Vec::new);
598 let flags = chalk_rust_ir::StructFlags {
599 upstream,
600 // FIXME set fundamental flag correctly
601 fundamental: false,
602 };
603 let struct_datum_bound = chalk_rust_ir::StructDatumBound {
604 fields: Vec::new(), // FIXME add fields (only relevant for auto traits)
605 where_clauses,
606 };
607 let struct_datum =
608 StructDatum { id: struct_id, binders: make_binders(struct_datum_bound, num_params), flags };
609 Arc::new(struct_datum)
610}
611
612pub(crate) fn impl_datum_query(
613 db: &impl HirDatabase,
614 krate: CrateId,
615 impl_id: chalk_ir::ImplId,
616) -> Arc<ImplDatum<ChalkIr>> {
617 let _p = ra_prof::profile("impl_datum");
618 debug!("impl_datum {:?}", impl_id);
619 let impl_: Impl = from_chalk(db, impl_id);
620 match impl_ {
621 Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block),
622 Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data),
623 }
624 .unwrap_or_else(invalid_impl_datum)
625}
626
627fn impl_block_datum(
628 db: &impl HirDatabase,
629 krate: CrateId,
630 chalk_id: chalk_ir::ImplId,
631 impl_id: ImplId,
632) -> Option<Arc<ImplDatum<ChalkIr>>> {
633 let trait_ref = match db.impl_ty(impl_id) {
634 ImplTy::TraitRef(it) => it,
635 ImplTy::Inherent(_) => return None,
636 };
637 let impl_data = db.impl_data(impl_id);
638
639 let generic_params = db.generic_params(impl_id.into());
640 let bound_vars = Substs::bound_vars(&generic_params);
641 let trait_ref = trait_ref.subst(&bound_vars);
642 let trait_ = trait_ref.trait_;
643 let impl_type = if impl_id.module(db).krate == krate {
644 chalk_rust_ir::ImplType::Local
645 } else {
646 chalk_rust_ir::ImplType::External
647 };
648 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
649 let negative = impl_data.is_negative;
650 debug!(
651 "impl {:?}: {}{} where {:?}",
652 chalk_id,
653 if negative { "!" } else { "" },
654 trait_ref.display(db),
655 where_clauses
656 );
657 let trait_ref = trait_ref.to_chalk(db);
658
659 let polarity = if negative {
660 chalk_rust_ir::Polarity::Negative
661 } else {
662 chalk_rust_ir::Polarity::Positive
663 };
664
665 let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses };
666 let trait_data = db.trait_data(trait_);
667 let associated_ty_value_ids = impl_data
668 .items
669 .iter()
670 .filter_map(|item| match item {
671 AssocItemId::TypeAliasId(type_alias) => Some(*type_alias),
672 _ => None,
673 })
674 .filter(|&type_alias| {
675 // don't include associated types that don't exist in the trait
676 let name = &db.type_alias_data(type_alias).name;
677 trait_data.associated_type_by_name(name).is_some()
678 })
679 .map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db))
680 .collect();
681 debug!("impl_datum: {:?}", impl_datum_bound);
682 let impl_datum = ImplDatum {
683 binders: make_binders(impl_datum_bound, bound_vars.len()),
684 impl_type,
685 polarity,
686 associated_ty_value_ids,
687 };
688 Some(Arc::new(impl_datum))
689}
690
691fn invalid_impl_datum() -> Arc<ImplDatum<ChalkIr>> {
692 let trait_ref = chalk_ir::TraitRef {
693 trait_id: UNKNOWN_TRAIT,
694 parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()],
695 };
696 let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() };
697 let impl_datum = ImplDatum {
698 binders: make_binders(impl_datum_bound, 1),
699 impl_type: chalk_rust_ir::ImplType::External,
700 polarity: chalk_rust_ir::Polarity::Positive,
701 associated_ty_value_ids: Vec::new(),
702 };
703 Arc::new(impl_datum)
704}
705
706fn closure_fn_trait_impl_datum(
707 db: &impl HirDatabase,
708 krate: CrateId,
709 data: super::ClosureFnTraitImplData,
710) -> Option<Arc<ImplDatum<ChalkIr>>> {
711 // for some closure |X, Y| -> Z:
712 // impl<T, U, V> Fn<(T, U)> for closure<fn(T, U) -> V> { Output = V }
713
714 let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait
715
716 // validate FnOnce trait, since we need it in the assoc ty value definition
717 // and don't want to return a valid value only to find out later that FnOnce
718 // is broken
719 let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?;
720 let _output = db.trait_data(fn_once_trait).associated_type_by_name(&name::OUTPUT_TYPE)?;
721
722 let num_args: u16 = match &db.body(data.def.into())[data.expr] {
723 Expr::Lambda { args, .. } => args.len() as u16,
724 _ => {
725 log::warn!("closure for closure type {:?} not found", data);
726 0
727 }
728 };
729
730 let arg_ty = Ty::apply(
731 TypeCtor::Tuple { cardinality: num_args },
732 Substs::builder(num_args as usize).fill_with_bound_vars(0).build(),
733 );
734 let sig_ty = Ty::apply(
735 TypeCtor::FnPtr { num_args },
736 Substs::builder(num_args as usize + 1).fill_with_bound_vars(0).build(),
737 );
738
739 let self_ty = Ty::apply_one(TypeCtor::Closure { def: data.def, expr: data.expr }, sig_ty);
740
741 let trait_ref = TraitRef {
742 trait_: trait_.into(),
743 substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(),
744 };
745
746 let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()).to_chalk(db);
747
748 let impl_type = chalk_rust_ir::ImplType::External;
749
750 let impl_datum_bound = chalk_rust_ir::ImplDatumBound {
751 trait_ref: trait_ref.to_chalk(db),
752 where_clauses: Vec::new(),
753 };
754 let impl_datum = ImplDatum {
755 binders: make_binders(impl_datum_bound, num_args as usize + 1),
756 impl_type,
757 polarity: chalk_rust_ir::Polarity::Positive,
758 associated_ty_value_ids: vec![output_ty_id],
759 };
760 Some(Arc::new(impl_datum))
761}
762
763pub(crate) fn associated_ty_value_query(
764 db: &impl HirDatabase,
765 krate: CrateId,
766 id: chalk_rust_ir::AssociatedTyValueId,
767) -> Arc<chalk_rust_ir::AssociatedTyValue<ChalkIr>> {
768 let data: AssocTyValue = from_chalk(db, id);
769 match data {
770 AssocTyValue::TypeAlias(type_alias) => {
771 type_alias_associated_ty_value(db, krate, type_alias)
772 }
773 AssocTyValue::ClosureFnTraitImplOutput(data) => {
774 closure_fn_trait_output_assoc_ty_value(db, krate, data)
775 }
776 }
777}
778
779fn type_alias_associated_ty_value(
780 db: &impl HirDatabase,
781 _krate: CrateId,
782 type_alias: TypeAliasId,
783) -> Arc<AssociatedTyValue<ChalkIr>> {
784 let type_alias_data = db.type_alias_data(type_alias);
785 let impl_id = match type_alias.lookup(db).container {
786 ContainerId::ImplId(it) => it,
787 _ => panic!("assoc ty value should be in impl"),
788 };
789
790 let trait_ref = match db.impl_ty(impl_id) {
791 ImplTy::TraitRef(it) => it,
792 // we don't return any assoc ty values if the impl'd trait can't be resolved
793 ImplTy::Inherent(_) => panic!("assoc ty value should not exist"),
794 };
795
796 let assoc_ty = db
797 .trait_data(trait_ref.trait_)
798 .associated_type_by_name(&type_alias_data.name)
799 .expect("assoc ty value should not exist"); // validated when building the impl data as well
800 let generic_params = db.generic_params(impl_id.into());
801 let bound_vars = Substs::bound_vars(&generic_params);
802 let ty = db.ty(type_alias.into()).subst(&bound_vars);
803 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) };
804 let value = chalk_rust_ir::AssociatedTyValue {
805 impl_id: Impl::ImplBlock(impl_id.into()).to_chalk(db),
806 associated_ty_id: assoc_ty.to_chalk(db),
807 value: make_binders(value_bound, bound_vars.len()),
808 };
809 Arc::new(value)
810}
811
812fn closure_fn_trait_output_assoc_ty_value(
813 db: &impl HirDatabase,
814 krate: CrateId,
815 data: super::ClosureFnTraitImplData,
816) -> Arc<AssociatedTyValue<ChalkIr>> {
817 let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db);
818
819 let num_args: u16 = match &db.body(data.def.into())[data.expr] {
820 Expr::Lambda { args, .. } => args.len() as u16,
821 _ => {
822 log::warn!("closure for closure type {:?} not found", data);
823 0
824 }
825 };
826
827 let output_ty = Ty::Bound(num_args.into());
828
829 let fn_once_trait =
830 get_fn_trait(db, krate, super::FnTrait::FnOnce).expect("assoc ty value should not exist");
831
832 let output_ty_id = db
833 .trait_data(fn_once_trait)
834 .associated_type_by_name(&name::OUTPUT_TYPE)
835 .expect("assoc ty value should not exist");
836
837 let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) };
838
839 let value = chalk_rust_ir::AssociatedTyValue {
840 associated_ty_id: output_ty_id.to_chalk(db),
841 impl_id,
842 value: make_binders(value_bound, num_args as usize + 1),
843 };
844 Arc::new(value)
845}
846
847fn get_fn_trait(
848 db: &impl HirDatabase,
849 krate: CrateId,
850 fn_trait: super::FnTrait,
851) -> Option<TraitId> {
852 let target = db.lang_item(krate, fn_trait.lang_item_name().into())?;
853 match target {
854 LangItemTarget::TraitId(t) => Some(t),
855 _ => None,
856 }
857}
858
859fn id_from_chalk<T: InternKey>(chalk_id: chalk_ir::RawId) -> T {
860 T::from_intern_id(InternId::from(chalk_id.index))
861}
862fn id_to_chalk<T: InternKey>(salsa_id: T) -> chalk_ir::RawId {
863 chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() }
864}
865
866impl From<chalk_ir::StructId> for crate::TypeCtorId {
867 fn from(struct_id: chalk_ir::StructId) -> Self {
868 id_from_chalk(struct_id.0)
869 }
870}
871
872impl From<crate::TypeCtorId> for chalk_ir::StructId {
873 fn from(type_ctor_id: crate::TypeCtorId) -> Self {
874 chalk_ir::StructId(id_to_chalk(type_ctor_id))
875 }
876}
877
878impl From<chalk_ir::ImplId> for crate::traits::GlobalImplId {
879 fn from(impl_id: chalk_ir::ImplId) -> Self {
880 id_from_chalk(impl_id.0)
881 }
882}
883
884impl From<crate::traits::GlobalImplId> for chalk_ir::ImplId {
885 fn from(impl_id: crate::traits::GlobalImplId) -> Self {
886 chalk_ir::ImplId(id_to_chalk(impl_id))
887 }
888}
889
890impl From<chalk_rust_ir::AssociatedTyValueId> for crate::traits::AssocTyValueId {
891 fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self {
892 id_from_chalk(id.0)
893 }
894}
895
896impl From<crate::traits::AssocTyValueId> for chalk_rust_ir::AssociatedTyValueId {
897 fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self {
898 chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id))
899 }
900}
diff --git a/crates/ra_hir_ty/src/utils.rs b/crates/ra_hir_ty/src/utils.rs
new file mode 100644
index 000000000..e4ba890ef
--- /dev/null
+++ b/crates/ra_hir_ty/src/utils.rs
@@ -0,0 +1,84 @@
1//! Helper functions for working with def, which don't need to be a separate
2//! query, but can't be computed directly from `*Data` (ie, which need a `db`).
3use std::sync::Arc;
4
5use hir_def::{
6 adt::VariantData,
7 db::DefDatabase,
8 resolver::{HasResolver, TypeNs},
9 type_ref::TypeRef,
10 TraitId, TypeAliasId, VariantId,
11};
12use hir_expand::name::{self, Name};
13
14// FIXME: this is wrong, b/c it can't express `trait T: PartialEq<()>`.
15// We should return a `TraitREf` here.
16fn direct_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> {
17 let resolver = trait_.resolver(db);
18 // returning the iterator directly doesn't easily work because of
19 // lifetime problems, but since there usually shouldn't be more than a
20 // few direct traits this should be fine (we could even use some kind of
21 // SmallVec if performance is a concern)
22 db.generic_params(trait_.into())
23 .where_predicates
24 .iter()
25 .filter_map(|pred| match &pred.type_ref {
26 TypeRef::Path(p) if p.as_ident() == Some(&name::SELF_TYPE) => pred.bound.as_path(),
27 _ => None,
28 })
29 .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) {
30 Some(TypeNs::TraitId(t)) => Some(t),
31 _ => None,
32 })
33 .collect()
34}
35
36/// Returns an iterator over the whole super trait hierarchy (including the
37/// trait itself).
38pub(super) fn all_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> {
39 // we need to take care a bit here to avoid infinite loops in case of cycles
40 // (i.e. if we have `trait A: B; trait B: A;`)
41 let mut result = vec![trait_];
42 let mut i = 0;
43 while i < result.len() {
44 let t = result[i];
45 // yeah this is quadratic, but trait hierarchies should be flat
46 // enough that this doesn't matter
47 for tt in direct_super_traits(db, t) {
48 if !result.contains(&tt) {
49 result.push(tt);
50 }
51 }
52 i += 1;
53 }
54 result
55}
56
57pub(super) fn associated_type_by_name_including_super_traits(
58 db: &impl DefDatabase,
59 trait_: TraitId,
60 name: &Name,
61) -> Option<TypeAliasId> {
62 all_super_traits(db, trait_)
63 .into_iter()
64 .find_map(|t| db.trait_data(t).associated_type_by_name(name))
65}
66
67pub(super) fn variant_data(db: &impl DefDatabase, var: VariantId) -> Arc<VariantData> {
68 match var {
69 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
70 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
71 VariantId::EnumVariantId(it) => {
72 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
73 }
74 }
75}
76
77/// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices).
78/// The underlying values are cloned if there are other strong references.
79pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
80 if Arc::get_mut(a).is_none() {
81 *a = a.iter().cloned().collect();
82 }
83 Arc::get_mut(a).unwrap()
84}