diff options
author | Aleksey Kladov <[email protected]> | 2019-11-27 14:46:02 +0000 |
---|---|---|
committer | Aleksey Kladov <[email protected]> | 2019-11-27 18:16:00 +0000 |
commit | a87579500a2c35597071efd0ad6983927f0c1815 (patch) | |
tree | 9805b3dcbf8d767b2fc0623f42794068f3660d44 /crates/ra_hir | |
parent | 368653081558ab389c6543d6b5027859e26beb3b (diff) |
Move Ty
Diffstat (limited to 'crates/ra_hir')
28 files changed, 46 insertions, 12229 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 52ad4e5d1..87c78d98e 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -6,8 +6,10 @@ use std::sync::Arc; | |||
6 | 6 | ||
7 | use hir_def::{ | 7 | use hir_def::{ |
8 | adt::VariantData, | 8 | adt::VariantData, |
9 | body::{Body, BodySourceMap}, | ||
9 | builtin_type::BuiltinType, | 10 | builtin_type::BuiltinType, |
10 | docs::Documentation, | 11 | docs::Documentation, |
12 | expr::{BindingAnnotation, Pat, PatId}, | ||
11 | per_ns::PerNs, | 13 | per_ns::PerNs, |
12 | resolver::HasResolver, | 14 | resolver::HasResolver, |
13 | type_ref::{Mutability, TypeRef}, | 15 | type_ref::{Mutability, TypeRef}, |
@@ -20,12 +22,12 @@ use hir_expand::{ | |||
20 | name::{self, AsName}, | 22 | name::{self, AsName}, |
21 | AstId, MacroDefId, | 23 | AstId, MacroDefId, |
22 | }; | 24 | }; |
25 | use hir_ty::expr::ExprValidator; | ||
23 | use ra_db::{CrateId, Edition, FileId, FilePosition}; | 26 | use ra_db::{CrateId, Edition, FileId, FilePosition}; |
24 | use ra_syntax::{ast, AstNode, SyntaxNode}; | 27 | use ra_syntax::{ast, AstNode, SyntaxNode}; |
25 | 28 | ||
26 | use crate::{ | 29 | use crate::{ |
27 | db::{DefDatabase, HirDatabase}, | 30 | db::{DefDatabase, HirDatabase}, |
28 | expr::{BindingAnnotation, Body, BodySourceMap, ExprValidator, Pat, PatId}, | ||
29 | ty::display::HirFormatter, | 31 | ty::display::HirFormatter, |
30 | ty::{ | 32 | ty::{ |
31 | self, InEnvironment, InferenceResult, TraitEnvironment, TraitRef, Ty, TyDefId, TypeCtor, | 33 | self, InEnvironment, InferenceResult, TraitEnvironment, TraitRef, Ty, TyDefId, TypeCtor, |
@@ -353,8 +355,8 @@ impl Struct { | |||
353 | .map(|(id, _)| StructField { parent: self.into(), id }) | 355 | .map(|(id, _)| StructField { parent: self.into(), id }) |
354 | } | 356 | } |
355 | 357 | ||
356 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 358 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
357 | db.ty(self.id.into()) | 359 | Type::from_def(db, self.id.module(db).krate, self.id) |
358 | } | 360 | } |
359 | 361 | ||
360 | pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty { | 362 | pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty { |
@@ -380,8 +382,8 @@ impl Union { | |||
380 | Module { id: self.id.module(db) } | 382 | Module { id: self.id.module(db) } |
381 | } | 383 | } |
382 | 384 | ||
383 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 385 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
384 | db.ty(self.id.into()) | 386 | Type::from_def(db, self.id.module(db).krate, self.id) |
385 | } | 387 | } |
386 | 388 | ||
387 | pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { | 389 | pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { |
@@ -441,8 +443,8 @@ impl Enum { | |||
441 | .map(|(id, _)| EnumVariant { parent: self, id }) | 443 | .map(|(id, _)| EnumVariant { parent: self, id }) |
442 | } | 444 | } |
443 | 445 | ||
444 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 446 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
445 | db.ty(self.id.into()) | 447 | Type::from_def(db, self.id.module(db).krate, self.id) |
446 | } | 448 | } |
447 | } | 449 | } |
448 | 450 | ||
@@ -640,7 +642,7 @@ impl Function { | |||
640 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { | 642 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { |
641 | let infer = self.infer(db); | 643 | let infer = self.infer(db); |
642 | infer.add_diagnostics(db, self.id, sink); | 644 | infer.add_diagnostics(db, self.id, sink); |
643 | let mut validator = ExprValidator::new(self, infer, sink); | 645 | let mut validator = ExprValidator::new(self.id, infer, sink); |
644 | validator.validate_body(db); | 646 | validator.validate_body(db); |
645 | } | 647 | } |
646 | } | 648 | } |
@@ -946,13 +948,12 @@ impl ImplBlock { | |||
946 | db.impl_data(self.id).target_type.clone() | 948 | db.impl_data(self.id).target_type.clone() |
947 | } | 949 | } |
948 | 950 | ||
949 | pub fn target_ty(&self, db: &impl HirDatabase) -> Ty { | 951 | pub fn target_ty(&self, db: &impl HirDatabase) -> Type { |
950 | Ty::from_hir(db, &self.id.resolver(db), &self.target_type(db)) | 952 | let impl_data = db.impl_data(self.id); |
951 | } | 953 | let resolver = self.id.resolver(db); |
952 | 954 | let environment = TraitEnvironment::lower(db, &resolver); | |
953 | pub fn target_trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { | 955 | let ty = Ty::from_hir(db, &resolver, &impl_data.target_type); |
954 | let target_ty = self.target_ty(db); | 956 | Type { krate: self.id.module(db).krate, ty: InEnvironment { value: ty, environment } } |
955 | TraitRef::from_hir(db, &self.id.resolver(db), &self.target_trait(db)?, Some(target_ty)) | ||
956 | } | 957 | } |
957 | 958 | ||
958 | pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { | 959 | pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { |
@@ -1130,6 +1131,22 @@ impl Type { | |||
1130 | Some(adt.into()) | 1131 | Some(adt.into()) |
1131 | } | 1132 | } |
1132 | 1133 | ||
1134 | // FIXME: provide required accessors such that it becomes implementable from outside. | ||
1135 | pub fn is_equal_for_find_impls(&self, other: &Type) -> bool { | ||
1136 | match (&self.ty.value, &other.ty.value) { | ||
1137 | (Ty::Apply(a_original_ty), Ty::Apply(ty::ApplicationTy { ctor, parameters })) => { | ||
1138 | match ctor { | ||
1139 | TypeCtor::Ref(..) => match parameters.as_single() { | ||
1140 | Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor, | ||
1141 | _ => false, | ||
1142 | }, | ||
1143 | _ => a_original_ty.ctor == *ctor, | ||
1144 | } | ||
1145 | } | ||
1146 | _ => false, | ||
1147 | } | ||
1148 | } | ||
1149 | |||
1133 | fn derived(&self, ty: Ty) -> Type { | 1150 | fn derived(&self, ty: Ty) -> Type { |
1134 | Type { | 1151 | Type { |
1135 | krate: self.krate, | 1152 | krate: self.krate, |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index e192c8f47..bfae3660b 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -1,18 +1,5 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_def::{DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId}; | ||
6 | use ra_arena::map::ArenaMap; | ||
7 | use ra_db::{salsa, CrateId}; | ||
8 | |||
9 | use crate::ty::{ | ||
10 | method_resolution::CrateImplBlocks, | ||
11 | traits::{AssocTyValue, Impl}, | ||
12 | CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor, | ||
13 | ValueTyDefId, | ||
14 | }; | ||
15 | |||
16 | pub use hir_def::db::{ | 3 | pub use hir_def::db::{ |
17 | BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery, | 4 | BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery, |
18 | DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery, | 5 | DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery, |
@@ -24,104 +11,12 @@ pub use hir_expand::db::{ | |||
24 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, | 11 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, |
25 | ParseMacroQuery, | 12 | ParseMacroQuery, |
26 | }; | 13 | }; |
27 | 14 | pub use hir_ty::db::{ | |
28 | #[salsa::query_group(HirDatabaseStorage)] | 15 | AssociatedTyDataQuery, CallableItemSignatureQuery, FieldTypesQuery, GenericDefaultsQuery, |
29 | #[salsa::requires(salsa::Database)] | 16 | GenericPredicatesQuery, HirDatabase, HirDatabaseStorage, ImplDatumQuery, ImplsForTraitQuery, |
30 | pub trait HirDatabase: DefDatabase { | 17 | ImplsInCrateQuery, InferQuery, StructDatumQuery, TraitDatumQuery, TraitSolveQuery, TyQuery, |
31 | #[salsa::invoke(crate::ty::infer_query)] | 18 | ValueTyQuery, |
32 | fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>; | 19 | }; |
33 | |||
34 | #[salsa::invoke(crate::ty::ty_query)] | ||
35 | fn ty(&self, def: TyDefId) -> Ty; | ||
36 | |||
37 | #[salsa::invoke(crate::ty::value_ty_query)] | ||
38 | fn value_ty(&self, def: ValueTyDefId) -> Ty; | ||
39 | |||
40 | #[salsa::invoke(crate::ty::field_types_query)] | ||
41 | fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>; | ||
42 | |||
43 | #[salsa::invoke(crate::ty::callable_item_sig)] | ||
44 | fn callable_item_signature(&self, def: CallableDef) -> FnSig; | ||
45 | |||
46 | #[salsa::invoke(crate::ty::generic_predicates_for_param_query)] | ||
47 | fn generic_predicates_for_param( | ||
48 | &self, | ||
49 | def: GenericDefId, | ||
50 | param_idx: u32, | ||
51 | ) -> Arc<[GenericPredicate]>; | ||
52 | |||
53 | #[salsa::invoke(crate::ty::generic_predicates_query)] | ||
54 | fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>; | ||
55 | |||
56 | #[salsa::invoke(crate::ty::generic_defaults_query)] | ||
57 | fn generic_defaults(&self, def: GenericDefId) -> Substs; | ||
58 | |||
59 | #[salsa::invoke(crate::ty::method_resolution::CrateImplBlocks::impls_in_crate_query)] | ||
60 | fn impls_in_crate(&self, krate: CrateId) -> Arc<CrateImplBlocks>; | ||
61 | |||
62 | #[salsa::invoke(crate::ty::traits::impls_for_trait_query)] | ||
63 | fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>; | ||
64 | |||
65 | /// This provides the Chalk trait solver instance. Because Chalk always | ||
66 | /// works from a specific crate, this query is keyed on the crate; and | ||
67 | /// because Chalk does its own internal caching, the solver is wrapped in a | ||
68 | /// Mutex and the query does an untracked read internally, to make sure the | ||
69 | /// cached state is thrown away when input facts change. | ||
70 | #[salsa::invoke(crate::ty::traits::trait_solver_query)] | ||
71 | fn trait_solver(&self, krate: CrateId) -> crate::ty::traits::TraitSolver; | ||
72 | |||
73 | // Interned IDs for Chalk integration | ||
74 | #[salsa::interned] | ||
75 | fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::ty::TypeCtorId; | ||
76 | #[salsa::interned] | ||
77 | fn intern_chalk_impl(&self, impl_: Impl) -> crate::ty::traits::GlobalImplId; | ||
78 | #[salsa::interned] | ||
79 | fn intern_assoc_ty_value( | ||
80 | &self, | ||
81 | assoc_ty_value: AssocTyValue, | ||
82 | ) -> crate::ty::traits::AssocTyValueId; | ||
83 | |||
84 | #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)] | ||
85 | fn associated_ty_data( | ||
86 | &self, | ||
87 | id: chalk_ir::TypeId, | ||
88 | ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>; | ||
89 | |||
90 | #[salsa::invoke(crate::ty::traits::chalk::trait_datum_query)] | ||
91 | fn trait_datum( | ||
92 | &self, | ||
93 | krate: CrateId, | ||
94 | trait_id: chalk_ir::TraitId, | ||
95 | ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>; | ||
96 | |||
97 | #[salsa::invoke(crate::ty::traits::chalk::struct_datum_query)] | ||
98 | fn struct_datum( | ||
99 | &self, | ||
100 | krate: CrateId, | ||
101 | struct_id: chalk_ir::StructId, | ||
102 | ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>; | ||
103 | |||
104 | #[salsa::invoke(crate::ty::traits::chalk::impl_datum_query)] | ||
105 | fn impl_datum( | ||
106 | &self, | ||
107 | krate: CrateId, | ||
108 | impl_id: chalk_ir::ImplId, | ||
109 | ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>; | ||
110 | |||
111 | #[salsa::invoke(crate::ty::traits::chalk::associated_ty_value_query)] | ||
112 | fn associated_ty_value( | ||
113 | &self, | ||
114 | krate: CrateId, | ||
115 | id: chalk_rust_ir::AssociatedTyValueId, | ||
116 | ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>; | ||
117 | |||
118 | #[salsa::invoke(crate::ty::traits::trait_solve_query)] | ||
119 | fn trait_solve( | ||
120 | &self, | ||
121 | krate: CrateId, | ||
122 | goal: crate::ty::Canonical<crate::ty::InEnvironment<crate::ty::Obligation>>, | ||
123 | ) -> Option<crate::ty::traits::Solution>; | ||
124 | } | ||
125 | 20 | ||
126 | #[test] | 21 | #[test] |
127 | fn hir_database_is_object_safe() { | 22 | fn hir_database_is_object_safe() { |
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs index 6db499e06..a9040ea3d 100644 --- a/crates/ra_hir/src/diagnostics.rs +++ b/crates/ra_hir/src/diagnostics.rs | |||
@@ -1,93 +1,4 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | |||
3 | use std::any::Any; | ||
4 | |||
5 | use hir_expand::HirFileId; | ||
6 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; | ||
7 | |||
8 | use crate::{db::AstDatabase, Name, Source}; | ||
9 | |||
10 | pub use hir_def::diagnostics::UnresolvedModule; | 2 | pub use hir_def::diagnostics::UnresolvedModule; |
11 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; | 3 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; |
12 | 4 | pub use hir_ty::diagnostics::{MissingFields, MissingOkInTailExpr, NoSuchField}; | |
13 | #[derive(Debug)] | ||
14 | pub struct NoSuchField { | ||
15 | pub file: HirFileId, | ||
16 | pub field: AstPtr<ast::RecordField>, | ||
17 | } | ||
18 | |||
19 | impl Diagnostic for NoSuchField { | ||
20 | fn message(&self) -> String { | ||
21 | "no such field".to_string() | ||
22 | } | ||
23 | |||
24 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
25 | Source { file_id: self.file, value: self.field.into() } | ||
26 | } | ||
27 | |||
28 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
29 | self | ||
30 | } | ||
31 | } | ||
32 | |||
33 | #[derive(Debug)] | ||
34 | pub struct MissingFields { | ||
35 | pub file: HirFileId, | ||
36 | pub field_list: AstPtr<ast::RecordFieldList>, | ||
37 | pub missed_fields: Vec<Name>, | ||
38 | } | ||
39 | |||
40 | impl Diagnostic for MissingFields { | ||
41 | fn message(&self) -> String { | ||
42 | use std::fmt::Write; | ||
43 | let mut message = String::from("Missing structure fields:\n"); | ||
44 | for field in &self.missed_fields { | ||
45 | write!(message, "- {}\n", field).unwrap(); | ||
46 | } | ||
47 | message | ||
48 | } | ||
49 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
50 | Source { file_id: self.file, value: self.field_list.into() } | ||
51 | } | ||
52 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
53 | self | ||
54 | } | ||
55 | } | ||
56 | |||
57 | impl AstDiagnostic for MissingFields { | ||
58 | type AST = ast::RecordFieldList; | ||
59 | |||
60 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
61 | let root = db.parse_or_expand(self.source().file_id).unwrap(); | ||
62 | let node = self.source().value.to_node(&root); | ||
63 | ast::RecordFieldList::cast(node).unwrap() | ||
64 | } | ||
65 | } | ||
66 | |||
67 | #[derive(Debug)] | ||
68 | pub struct MissingOkInTailExpr { | ||
69 | pub file: HirFileId, | ||
70 | pub expr: AstPtr<ast::Expr>, | ||
71 | } | ||
72 | |||
73 | impl Diagnostic for MissingOkInTailExpr { | ||
74 | fn message(&self) -> String { | ||
75 | "wrap return expression in Ok".to_string() | ||
76 | } | ||
77 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
78 | Source { file_id: self.file, value: self.expr.into() } | ||
79 | } | ||
80 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
81 | self | ||
82 | } | ||
83 | } | ||
84 | |||
85 | impl AstDiagnostic for MissingOkInTailExpr { | ||
86 | type AST = ast::Expr; | ||
87 | |||
88 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
89 | let root = db.parse_or_expand(self.file).unwrap(); | ||
90 | let node = self.source().value.to_node(&root); | ||
91 | ast::Expr::cast(node).unwrap() | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs deleted file mode 100644 index 5c82c23d6..000000000 --- a/crates/ra_hir/src/expr.rs +++ /dev/null | |||
@@ -1,146 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_def::{path::known, resolver::HasResolver, AdtId}; | ||
6 | use hir_expand::diagnostics::DiagnosticSink; | ||
7 | use ra_syntax::ast; | ||
8 | use ra_syntax::AstPtr; | ||
9 | use rustc_hash::FxHashSet; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | diagnostics::{MissingFields, MissingOkInTailExpr}, | ||
14 | ty::{ApplicationTy, InferenceResult, Ty, TypeCtor}, | ||
15 | Function, Name, Path, Struct, | ||
16 | }; | ||
17 | |||
18 | pub use hir_def::{ | ||
19 | body::{ | ||
20 | scope::{ExprScopes, ScopeEntry, ScopeId}, | ||
21 | Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource, | ||
22 | }, | ||
23 | expr::{ | ||
24 | ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp, | ||
25 | MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp, | ||
26 | }, | ||
27 | }; | ||
28 | |||
29 | pub(crate) struct ExprValidator<'a, 'b: 'a> { | ||
30 | func: Function, | ||
31 | infer: Arc<InferenceResult>, | ||
32 | sink: &'a mut DiagnosticSink<'b>, | ||
33 | } | ||
34 | |||
35 | impl<'a, 'b> ExprValidator<'a, 'b> { | ||
36 | pub(crate) fn new( | ||
37 | func: Function, | ||
38 | infer: Arc<InferenceResult>, | ||
39 | sink: &'a mut DiagnosticSink<'b>, | ||
40 | ) -> ExprValidator<'a, 'b> { | ||
41 | ExprValidator { func, infer, sink } | ||
42 | } | ||
43 | |||
44 | pub(crate) fn validate_body(&mut self, db: &impl HirDatabase) { | ||
45 | let body = self.func.body(db); | ||
46 | |||
47 | for e in body.exprs.iter() { | ||
48 | if let (id, Expr::RecordLit { path, fields, spread }) = e { | ||
49 | self.validate_record_literal(id, path, fields, *spread, db); | ||
50 | } | ||
51 | } | ||
52 | |||
53 | let body_expr = &body[body.body_expr]; | ||
54 | if let Expr::Block { statements: _, tail: Some(t) } = body_expr { | ||
55 | self.validate_results_in_tail_expr(body.body_expr, *t, db); | ||
56 | } | ||
57 | } | ||
58 | |||
59 | fn validate_record_literal( | ||
60 | &mut self, | ||
61 | id: ExprId, | ||
62 | _path: &Option<Path>, | ||
63 | fields: &[RecordLitField], | ||
64 | spread: Option<ExprId>, | ||
65 | db: &impl HirDatabase, | ||
66 | ) { | ||
67 | if spread.is_some() { | ||
68 | return; | ||
69 | } | ||
70 | |||
71 | let struct_def = match self.infer[id].as_adt() { | ||
72 | Some((AdtId::StructId(s), _)) => Struct::from(s), | ||
73 | _ => return, | ||
74 | }; | ||
75 | |||
76 | let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); | ||
77 | let missed_fields: Vec<Name> = struct_def | ||
78 | .fields(db) | ||
79 | .iter() | ||
80 | .filter_map(|f| { | ||
81 | let name = f.name(db); | ||
82 | if lit_fields.contains(&name) { | ||
83 | None | ||
84 | } else { | ||
85 | Some(name) | ||
86 | } | ||
87 | }) | ||
88 | .collect(); | ||
89 | if missed_fields.is_empty() { | ||
90 | return; | ||
91 | } | ||
92 | let source_map = self.func.body_source_map(db); | ||
93 | |||
94 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
95 | if let Some(expr) = source_ptr.value.a() { | ||
96 | let root = source_ptr.file_syntax(db); | ||
97 | if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) { | ||
98 | if let Some(field_list) = record_lit.record_field_list() { | ||
99 | self.sink.push(MissingFields { | ||
100 | file: source_ptr.file_id, | ||
101 | field_list: AstPtr::new(&field_list), | ||
102 | missed_fields, | ||
103 | }) | ||
104 | } | ||
105 | } | ||
106 | } | ||
107 | } | ||
108 | } | ||
109 | |||
110 | fn validate_results_in_tail_expr( | ||
111 | &mut self, | ||
112 | body_id: ExprId, | ||
113 | id: ExprId, | ||
114 | db: &impl HirDatabase, | ||
115 | ) { | ||
116 | // the mismatch will be on the whole block currently | ||
117 | let mismatch = match self.infer.type_mismatch_for_expr(body_id) { | ||
118 | Some(m) => m, | ||
119 | None => return, | ||
120 | }; | ||
121 | |||
122 | let std_result_path = known::std_result_result(); | ||
123 | |||
124 | let resolver = self.func.id.resolver(db); | ||
125 | let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { | ||
126 | Some(it) => it, | ||
127 | _ => return, | ||
128 | }; | ||
129 | |||
130 | let std_result_ctor = TypeCtor::Adt(AdtId::EnumId(std_result_enum)); | ||
131 | let params = match &mismatch.expected { | ||
132 | Ty::Apply(ApplicationTy { ctor, parameters }) if ctor == &std_result_ctor => parameters, | ||
133 | _ => return, | ||
134 | }; | ||
135 | |||
136 | if params.len() == 2 && ¶ms[0] == &mismatch.actual { | ||
137 | let source_map = self.func.body_source_map(db); | ||
138 | |||
139 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
140 | if let Some(expr) = source_ptr.value.a() { | ||
141 | self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr }); | ||
142 | } | ||
143 | } | ||
144 | } | ||
145 | } | ||
146 | } | ||
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index b88e4c745..3c12c61f0 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -32,20 +32,13 @@ pub mod db; | |||
32 | pub mod source_binder; | 32 | pub mod source_binder; |
33 | 33 | ||
34 | mod ty; | 34 | mod ty; |
35 | mod expr; | ||
36 | pub mod diagnostics; | 35 | pub mod diagnostics; |
37 | mod util; | ||
38 | 36 | ||
39 | mod from_id; | 37 | mod from_id; |
40 | mod code_model; | 38 | mod code_model; |
41 | 39 | ||
42 | pub mod from_source; | 40 | pub mod from_source; |
43 | 41 | ||
44 | #[cfg(test)] | ||
45 | mod test_db; | ||
46 | #[cfg(test)] | ||
47 | mod marks; | ||
48 | |||
49 | pub use crate::{ | 42 | pub use crate::{ |
50 | code_model::{ | 43 | code_model::{ |
51 | src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency, | 44 | src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency, |
@@ -53,7 +46,6 @@ pub use crate::{ | |||
53 | HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef, | 46 | HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef, |
54 | Static, Struct, StructField, Trait, Type, TypeAlias, Union, VariantDef, | 47 | Static, Struct, StructField, Trait, Type, TypeAlias, Union, VariantDef, |
55 | }, | 48 | }, |
56 | expr::ExprScopes, | ||
57 | from_source::FromSource, | 49 | from_source::FromSource, |
58 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, | 50 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, |
59 | ty::{ | 51 | ty::{ |
@@ -64,6 +56,7 @@ pub use crate::{ | |||
64 | }; | 56 | }; |
65 | 57 | ||
66 | pub use hir_def::{ | 58 | pub use hir_def::{ |
59 | body::scope::ExprScopes, | ||
67 | builtin_type::BuiltinType, | 60 | builtin_type::BuiltinType, |
68 | docs::Documentation, | 61 | docs::Documentation, |
69 | path::{Path, PathKind}, | 62 | path::{Path, PathKind}, |
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs deleted file mode 100644 index 0f754eb9c..000000000 --- a/crates/ra_hir/src/marks.rs +++ /dev/null | |||
@@ -1,9 +0,0 @@ | |||
1 | //! See test_utils/src/marks.rs | ||
2 | |||
3 | test_utils::marks!( | ||
4 | type_var_cycles_resolve_completely | ||
5 | type_var_cycles_resolve_as_possible | ||
6 | type_var_resolves_to_int_var | ||
7 | match_ergonomics_ref | ||
8 | coerce_merge_fail_fallback | ||
9 | ); | ||
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 05f5bca57..76c493f1a 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs | |||
@@ -8,6 +8,10 @@ | |||
8 | use std::sync::Arc; | 8 | use std::sync::Arc; |
9 | 9 | ||
10 | use hir_def::{ | 10 | use hir_def::{ |
11 | body::{ | ||
12 | scope::{ExprScopes, ScopeId}, | ||
13 | BodySourceMap, | ||
14 | }, | ||
11 | expr::{ExprId, PatId}, | 15 | expr::{ExprId, PatId}, |
12 | path::known, | 16 | path::known, |
13 | resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs}, | 17 | resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs}, |
@@ -25,7 +29,6 @@ use ra_syntax::{ | |||
25 | 29 | ||
26 | use crate::{ | 30 | use crate::{ |
27 | db::HirDatabase, | 31 | db::HirDatabase, |
28 | expr::{BodySourceMap, ExprScopes, ScopeId}, | ||
29 | ty::{ | 32 | ty::{ |
30 | method_resolution::{self, implements_trait}, | 33 | method_resolution::{self, implements_trait}, |
31 | InEnvironment, TraitEnvironment, Ty, | 34 | InEnvironment, TraitEnvironment, Ty, |
@@ -91,7 +94,7 @@ pub struct SourceAnalyzer { | |||
91 | body_owner: Option<DefWithBody>, | 94 | body_owner: Option<DefWithBody>, |
92 | body_source_map: Option<Arc<BodySourceMap>>, | 95 | body_source_map: Option<Arc<BodySourceMap>>, |
93 | infer: Option<Arc<crate::ty::InferenceResult>>, | 96 | infer: Option<Arc<crate::ty::InferenceResult>>, |
94 | scopes: Option<Arc<crate::expr::ExprScopes>>, | 97 | scopes: Option<Arc<ExprScopes>>, |
95 | } | 98 | } |
96 | 99 | ||
97 | #[derive(Debug, Clone, PartialEq, Eq)] | 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
@@ -455,21 +458,6 @@ impl SourceAnalyzer { | |||
455 | macro_file_kind: to_macro_file_kind(macro_call.value), | 458 | macro_file_kind: to_macro_file_kind(macro_call.value), |
456 | }) | 459 | }) |
457 | } | 460 | } |
458 | |||
459 | #[cfg(test)] | ||
460 | pub(crate) fn body_source_map(&self) -> Arc<BodySourceMap> { | ||
461 | self.body_source_map.clone().unwrap() | ||
462 | } | ||
463 | |||
464 | #[cfg(test)] | ||
465 | pub(crate) fn inference_result(&self) -> Arc<crate::ty::InferenceResult> { | ||
466 | self.infer.clone().unwrap() | ||
467 | } | ||
468 | |||
469 | #[cfg(test)] | ||
470 | pub(crate) fn analyzed_declaration(&self) -> Option<DefWithBody> { | ||
471 | self.body_owner | ||
472 | } | ||
473 | } | 461 | } |
474 | 462 | ||
475 | fn scope_for( | 463 | fn scope_for( |
diff --git a/crates/ra_hir/src/test_db.rs b/crates/ra_hir/src/test_db.rs deleted file mode 100644 index a2071f71c..000000000 --- a/crates/ra_hir/src/test_db.rs +++ /dev/null | |||
@@ -1,123 +0,0 @@ | |||
1 | //! Database used for testing `hir`. | ||
2 | |||
3 | use std::{panic, sync::Arc}; | ||
4 | |||
5 | use hir_def::{db::DefDatabase, ModuleId}; | ||
6 | use hir_expand::diagnostics::DiagnosticSink; | ||
7 | use parking_lot::Mutex; | ||
8 | use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; | ||
9 | |||
10 | use crate::{db, debug::HirDebugHelper}; | ||
11 | |||
12 | #[salsa::database( | ||
13 | ra_db::SourceDatabaseExtStorage, | ||
14 | ra_db::SourceDatabaseStorage, | ||
15 | db::InternDatabaseStorage, | ||
16 | db::AstDatabaseStorage, | ||
17 | db::DefDatabaseStorage, | ||
18 | db::HirDatabaseStorage | ||
19 | )] | ||
20 | #[derive(Debug, Default)] | ||
21 | pub struct TestDB { | ||
22 | events: Mutex<Option<Vec<salsa::Event<TestDB>>>>, | ||
23 | runtime: salsa::Runtime<TestDB>, | ||
24 | } | ||
25 | |||
26 | impl salsa::Database for TestDB { | ||
27 | fn salsa_runtime(&self) -> &salsa::Runtime<TestDB> { | ||
28 | &self.runtime | ||
29 | } | ||
30 | |||
31 | fn salsa_runtime_mut(&mut self) -> &mut salsa::Runtime<Self> { | ||
32 | &mut self.runtime | ||
33 | } | ||
34 | |||
35 | fn salsa_event(&self, event: impl Fn() -> salsa::Event<TestDB>) { | ||
36 | let mut events = self.events.lock(); | ||
37 | if let Some(events) = &mut *events { | ||
38 | events.push(event()); | ||
39 | } | ||
40 | } | ||
41 | } | ||
42 | |||
43 | impl salsa::ParallelDatabase for TestDB { | ||
44 | fn snapshot(&self) -> salsa::Snapshot<TestDB> { | ||
45 | salsa::Snapshot::new(TestDB { | ||
46 | events: Default::default(), | ||
47 | runtime: self.runtime.snapshot(self), | ||
48 | }) | ||
49 | } | ||
50 | } | ||
51 | |||
52 | impl panic::RefUnwindSafe for TestDB {} | ||
53 | |||
54 | impl FileLoader for TestDB { | ||
55 | fn file_text(&self, file_id: FileId) -> Arc<String> { | ||
56 | FileLoaderDelegate(self).file_text(file_id) | ||
57 | } | ||
58 | fn resolve_relative_path( | ||
59 | &self, | ||
60 | anchor: FileId, | ||
61 | relative_path: &RelativePath, | ||
62 | ) -> Option<FileId> { | ||
63 | FileLoaderDelegate(self).resolve_relative_path(anchor, relative_path) | ||
64 | } | ||
65 | fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> { | ||
66 | FileLoaderDelegate(self).relevant_crates(file_id) | ||
67 | } | ||
68 | } | ||
69 | |||
70 | // FIXME: improve `WithFixture` to bring useful hir debugging back | ||
71 | impl HirDebugHelper for TestDB { | ||
72 | fn crate_name(&self, _krate: CrateId) -> Option<String> { | ||
73 | None | ||
74 | } | ||
75 | |||
76 | fn file_path(&self, _file_id: FileId) -> Option<String> { | ||
77 | None | ||
78 | } | ||
79 | } | ||
80 | |||
81 | impl TestDB { | ||
82 | pub fn diagnostics(&self) -> String { | ||
83 | let mut buf = String::new(); | ||
84 | let crate_graph = self.crate_graph(); | ||
85 | for krate in crate_graph.iter().next() { | ||
86 | let crate_def_map = self.crate_def_map(krate); | ||
87 | for (module_id, _) in crate_def_map.modules.iter() { | ||
88 | let module_id = ModuleId { krate, module_id }; | ||
89 | let module = crate::Module::from(module_id); | ||
90 | module.diagnostics( | ||
91 | self, | ||
92 | &mut DiagnosticSink::new(|d| { | ||
93 | buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message()); | ||
94 | }), | ||
95 | ) | ||
96 | } | ||
97 | } | ||
98 | buf | ||
99 | } | ||
100 | } | ||
101 | |||
102 | impl TestDB { | ||
103 | pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event<TestDB>> { | ||
104 | *self.events.lock() = Some(Vec::new()); | ||
105 | f(); | ||
106 | self.events.lock().take().unwrap() | ||
107 | } | ||
108 | |||
109 | pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> { | ||
110 | let events = self.log(f); | ||
111 | events | ||
112 | .into_iter() | ||
113 | .filter_map(|e| match e.kind { | ||
114 | // This pretty horrible, but `Debug` is the only way to inspect | ||
115 | // QueryDescriptor at the moment. | ||
116 | salsa::EventKind::WillExecute { database_key } => { | ||
117 | Some(format!("{:?}", database_key)) | ||
118 | } | ||
119 | _ => None, | ||
120 | }) | ||
121 | .collect() | ||
122 | } | ||
123 | } | ||
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index e4ba8afa6..4ed69c00d 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -1,1113 +1,4 @@ | |||
1 | //! The type system. We currently use this to infer types for completion, hover | 1 | //! The type system. We currently use this to infer types for completion, hover |
2 | //! information and various assists. | 2 | //! information and various assists. |
3 | 3 | ||
4 | mod autoderef; | 4 | pub use hir_ty::*; |
5 | pub(crate) mod primitive; | ||
6 | pub(crate) mod traits; | ||
7 | pub(crate) mod method_resolution; | ||
8 | mod op; | ||
9 | mod lower; | ||
10 | mod infer; | ||
11 | pub(crate) mod display; | ||
12 | pub(crate) mod utils; | ||
13 | |||
14 | #[cfg(test)] | ||
15 | mod tests; | ||
16 | |||
17 | use std::ops::Deref; | ||
18 | use std::sync::Arc; | ||
19 | use std::{fmt, iter, mem}; | ||
20 | |||
21 | use hir_def::{ | ||
22 | expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId, | ||
23 | GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, | ||
24 | }; | ||
25 | use hir_expand::name::Name; | ||
26 | use ra_db::{impl_intern_key, salsa, CrateId}; | ||
27 | |||
28 | use crate::{ | ||
29 | db::HirDatabase, | ||
30 | ty::primitive::{FloatTy, IntTy, Uncertain}, | ||
31 | util::make_mut_slice, | ||
32 | }; | ||
33 | use display::{HirDisplay, HirFormatter}; | ||
34 | |||
35 | pub(crate) use autoderef::autoderef; | ||
36 | pub(crate) use infer::{infer_query, InferTy, InferenceResult}; | ||
37 | pub use lower::CallableDef; | ||
38 | pub(crate) use lower::{ | ||
39 | callable_item_sig, field_types_query, generic_defaults_query, | ||
40 | generic_predicates_for_param_query, generic_predicates_query, ty_query, value_ty_query, | ||
41 | TyDefId, ValueTyDefId, | ||
42 | }; | ||
43 | pub(crate) use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; | ||
44 | |||
45 | /// A type constructor or type name: this might be something like the primitive | ||
46 | /// type `bool`, a struct like `Vec`, or things like function pointers or | ||
47 | /// tuples. | ||
48 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] | ||
49 | pub enum TypeCtor { | ||
50 | /// The primitive boolean type. Written as `bool`. | ||
51 | Bool, | ||
52 | |||
53 | /// The primitive character type; holds a Unicode scalar value | ||
54 | /// (a non-surrogate code point). Written as `char`. | ||
55 | Char, | ||
56 | |||
57 | /// A primitive integer type. For example, `i32`. | ||
58 | Int(Uncertain<IntTy>), | ||
59 | |||
60 | /// A primitive floating-point type. For example, `f64`. | ||
61 | Float(Uncertain<FloatTy>), | ||
62 | |||
63 | /// Structures, enumerations and unions. | ||
64 | Adt(AdtId), | ||
65 | |||
66 | /// The pointee of a string slice. Written as `str`. | ||
67 | Str, | ||
68 | |||
69 | /// The pointee of an array slice. Written as `[T]`. | ||
70 | Slice, | ||
71 | |||
72 | /// An array with the given length. Written as `[T; n]`. | ||
73 | Array, | ||
74 | |||
75 | /// A raw pointer. Written as `*mut T` or `*const T` | ||
76 | RawPtr(Mutability), | ||
77 | |||
78 | /// A reference; a pointer with an associated lifetime. Written as | ||
79 | /// `&'a mut T` or `&'a T`. | ||
80 | Ref(Mutability), | ||
81 | |||
82 | /// The anonymous type of a function declaration/definition. Each | ||
83 | /// function has a unique type, which is output (for a function | ||
84 | /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. | ||
85 | /// | ||
86 | /// This includes tuple struct / enum variant constructors as well. | ||
87 | /// | ||
88 | /// For example the type of `bar` here: | ||
89 | /// | ||
90 | /// ``` | ||
91 | /// fn foo() -> i32 { 1 } | ||
92 | /// let bar = foo; // bar: fn() -> i32 {foo} | ||
93 | /// ``` | ||
94 | FnDef(CallableDef), | ||
95 | |||
96 | /// A pointer to a function. Written as `fn() -> i32`. | ||
97 | /// | ||
98 | /// For example the type of `bar` here: | ||
99 | /// | ||
100 | /// ``` | ||
101 | /// fn foo() -> i32 { 1 } | ||
102 | /// let bar: fn() -> i32 = foo; | ||
103 | /// ``` | ||
104 | FnPtr { num_args: u16 }, | ||
105 | |||
106 | /// The never type `!`. | ||
107 | Never, | ||
108 | |||
109 | /// A tuple type. For example, `(i32, bool)`. | ||
110 | Tuple { cardinality: u16 }, | ||
111 | |||
112 | /// Represents an associated item like `Iterator::Item`. This is used | ||
113 | /// when we have tried to normalize a projection like `T::Item` but | ||
114 | /// couldn't find a better representation. In that case, we generate | ||
115 | /// an **application type** like `(Iterator::Item)<T>`. | ||
116 | AssociatedType(TypeAliasId), | ||
117 | |||
118 | /// The type of a specific closure. | ||
119 | /// | ||
120 | /// The closure signature is stored in a `FnPtr` type in the first type | ||
121 | /// parameter. | ||
122 | Closure { def: DefWithBodyId, expr: ExprId }, | ||
123 | } | ||
124 | |||
125 | /// This exists just for Chalk, because Chalk just has a single `StructId` where | ||
126 | /// we have different kinds of ADTs, primitive types and special type | ||
127 | /// constructors like tuples and function pointers. | ||
128 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
129 | pub struct TypeCtorId(salsa::InternId); | ||
130 | impl_intern_key!(TypeCtorId); | ||
131 | |||
132 | impl TypeCtor { | ||
133 | pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { | ||
134 | match self { | ||
135 | TypeCtor::Bool | ||
136 | | TypeCtor::Char | ||
137 | | TypeCtor::Int(_) | ||
138 | | TypeCtor::Float(_) | ||
139 | | TypeCtor::Str | ||
140 | | TypeCtor::Never => 0, | ||
141 | TypeCtor::Slice | ||
142 | | TypeCtor::Array | ||
143 | | TypeCtor::RawPtr(_) | ||
144 | | TypeCtor::Ref(_) | ||
145 | | TypeCtor::Closure { .. } // 1 param representing the signature of the closure | ||
146 | => 1, | ||
147 | TypeCtor::Adt(adt) => { | ||
148 | let generic_params = db.generic_params(AdtId::from(adt).into()); | ||
149 | generic_params.count_params_including_parent() | ||
150 | } | ||
151 | TypeCtor::FnDef(callable) => { | ||
152 | let generic_params = db.generic_params(callable.into()); | ||
153 | generic_params.count_params_including_parent() | ||
154 | } | ||
155 | TypeCtor::AssociatedType(type_alias) => { | ||
156 | let generic_params = db.generic_params(type_alias.into()); | ||
157 | generic_params.count_params_including_parent() | ||
158 | } | ||
159 | TypeCtor::FnPtr { num_args } => num_args as usize + 1, | ||
160 | TypeCtor::Tuple { cardinality } => cardinality as usize, | ||
161 | } | ||
162 | } | ||
163 | |||
164 | pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> { | ||
165 | match self { | ||
166 | TypeCtor::Bool | ||
167 | | TypeCtor::Char | ||
168 | | TypeCtor::Int(_) | ||
169 | | TypeCtor::Float(_) | ||
170 | | TypeCtor::Str | ||
171 | | TypeCtor::Never | ||
172 | | TypeCtor::Slice | ||
173 | | TypeCtor::Array | ||
174 | | TypeCtor::RawPtr(_) | ||
175 | | TypeCtor::Ref(_) | ||
176 | | TypeCtor::FnPtr { .. } | ||
177 | | TypeCtor::Tuple { .. } => None, | ||
178 | // Closure's krate is irrelevant for coherence I would think? | ||
179 | TypeCtor::Closure { .. } => None, | ||
180 | TypeCtor::Adt(adt) => Some(adt.module(db).krate), | ||
181 | TypeCtor::FnDef(callable) => Some(callable.krate(db)), | ||
182 | TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate), | ||
183 | } | ||
184 | } | ||
185 | |||
186 | pub fn as_generic_def(self) -> Option<GenericDefId> { | ||
187 | match self { | ||
188 | TypeCtor::Bool | ||
189 | | TypeCtor::Char | ||
190 | | TypeCtor::Int(_) | ||
191 | | TypeCtor::Float(_) | ||
192 | | TypeCtor::Str | ||
193 | | TypeCtor::Never | ||
194 | | TypeCtor::Slice | ||
195 | | TypeCtor::Array | ||
196 | | TypeCtor::RawPtr(_) | ||
197 | | TypeCtor::Ref(_) | ||
198 | | TypeCtor::FnPtr { .. } | ||
199 | | TypeCtor::Tuple { .. } | ||
200 | | TypeCtor::Closure { .. } => None, | ||
201 | TypeCtor::Adt(adt) => Some(adt.into()), | ||
202 | TypeCtor::FnDef(callable) => Some(callable.into()), | ||
203 | TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()), | ||
204 | } | ||
205 | } | ||
206 | } | ||
207 | |||
208 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
209 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
210 | /// several other things. | ||
211 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
212 | pub struct ApplicationTy { | ||
213 | pub ctor: TypeCtor, | ||
214 | pub parameters: Substs, | ||
215 | } | ||
216 | |||
217 | /// A "projection" type corresponds to an (unnormalized) | ||
218 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
219 | /// trait and all its parameters are fully known. | ||
220 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
221 | pub struct ProjectionTy { | ||
222 | pub associated_ty: TypeAliasId, | ||
223 | pub parameters: Substs, | ||
224 | } | ||
225 | |||
226 | impl ProjectionTy { | ||
227 | pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { | ||
228 | TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() } | ||
229 | } | ||
230 | |||
231 | fn trait_(&self, db: &impl HirDatabase) -> TraitId { | ||
232 | match self.associated_ty.lookup(db).container { | ||
233 | ContainerId::TraitId(it) => it, | ||
234 | _ => panic!("projection ty without parent trait"), | ||
235 | } | ||
236 | } | ||
237 | } | ||
238 | |||
239 | impl TypeWalk for ProjectionTy { | ||
240 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
241 | self.parameters.walk(f); | ||
242 | } | ||
243 | |||
244 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
245 | self.parameters.walk_mut_binders(f, binders); | ||
246 | } | ||
247 | } | ||
248 | |||
249 | /// A type. | ||
250 | /// | ||
251 | /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents | ||
252 | /// the same thing (but in a different way). | ||
253 | /// | ||
254 | /// This should be cheap to clone. | ||
255 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
256 | pub enum Ty { | ||
257 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
258 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
259 | /// several other things. | ||
260 | Apply(ApplicationTy), | ||
261 | |||
262 | /// A "projection" type corresponds to an (unnormalized) | ||
263 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
264 | /// trait and all its parameters are fully known. | ||
265 | Projection(ProjectionTy), | ||
266 | |||
267 | /// A type parameter; for example, `T` in `fn f<T>(x: T) {} | ||
268 | Param { | ||
269 | /// The index of the parameter (starting with parameters from the | ||
270 | /// surrounding impl, then the current function). | ||
271 | idx: u32, | ||
272 | /// The name of the parameter, for displaying. | ||
273 | // FIXME get rid of this | ||
274 | name: Name, | ||
275 | }, | ||
276 | |||
277 | /// A bound type variable. Used during trait resolution to represent Chalk | ||
278 | /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. | ||
279 | Bound(u32), | ||
280 | |||
281 | /// A type variable used during type checking. Not to be confused with a | ||
282 | /// type parameter. | ||
283 | Infer(InferTy), | ||
284 | |||
285 | /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). | ||
286 | /// | ||
287 | /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)` | ||
288 | /// represents the `Self` type inside the bounds. This is currently | ||
289 | /// implicit; Chalk has the `Binders` struct to make it explicit, but it | ||
290 | /// didn't seem worth the overhead yet. | ||
291 | Dyn(Arc<[GenericPredicate]>), | ||
292 | |||
293 | /// An opaque type (`impl Trait`). | ||
294 | /// | ||
295 | /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for | ||
296 | /// more. | ||
297 | Opaque(Arc<[GenericPredicate]>), | ||
298 | |||
299 | /// A placeholder for a type which could not be computed; this is propagated | ||
300 | /// to avoid useless error messages. Doubles as a placeholder where type | ||
301 | /// variables are inserted before type checking, since we want to try to | ||
302 | /// infer a better type here anyway -- for the IDE use case, we want to try | ||
303 | /// to infer as much as possible even in the presence of type errors. | ||
304 | Unknown, | ||
305 | } | ||
306 | |||
307 | /// A list of substitutions for generic parameters. | ||
308 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
309 | pub struct Substs(Arc<[Ty]>); | ||
310 | |||
311 | impl TypeWalk for Substs { | ||
312 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
313 | for t in self.0.iter() { | ||
314 | t.walk(f); | ||
315 | } | ||
316 | } | ||
317 | |||
318 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
319 | for t in make_mut_slice(&mut self.0) { | ||
320 | t.walk_mut_binders(f, binders); | ||
321 | } | ||
322 | } | ||
323 | } | ||
324 | |||
325 | impl Substs { | ||
326 | pub fn empty() -> Substs { | ||
327 | Substs(Arc::new([])) | ||
328 | } | ||
329 | |||
330 | pub fn single(ty: Ty) -> Substs { | ||
331 | Substs(Arc::new([ty])) | ||
332 | } | ||
333 | |||
334 | pub fn prefix(&self, n: usize) -> Substs { | ||
335 | Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) | ||
336 | } | ||
337 | |||
338 | pub fn as_single(&self) -> &Ty { | ||
339 | if self.0.len() != 1 { | ||
340 | panic!("expected substs of len 1, got {:?}", self); | ||
341 | } | ||
342 | &self.0[0] | ||
343 | } | ||
344 | |||
345 | /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). | ||
346 | pub fn identity(generic_params: &GenericParams) -> Substs { | ||
347 | Substs( | ||
348 | generic_params | ||
349 | .params_including_parent() | ||
350 | .into_iter() | ||
351 | .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) | ||
352 | .collect(), | ||
353 | ) | ||
354 | } | ||
355 | |||
356 | /// Return Substs that replace each parameter by a bound variable. | ||
357 | pub fn bound_vars(generic_params: &GenericParams) -> Substs { | ||
358 | Substs( | ||
359 | generic_params | ||
360 | .params_including_parent() | ||
361 | .into_iter() | ||
362 | .map(|p| Ty::Bound(p.idx)) | ||
363 | .collect(), | ||
364 | ) | ||
365 | } | ||
366 | |||
367 | pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder { | ||
368 | let def = def.into(); | ||
369 | let params = db.generic_params(def); | ||
370 | let param_count = params.count_params_including_parent(); | ||
371 | Substs::builder(param_count) | ||
372 | } | ||
373 | |||
374 | pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder { | ||
375 | Substs::builder(generic_params.count_params_including_parent()) | ||
376 | } | ||
377 | |||
378 | pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { | ||
379 | Substs::builder(type_ctor.num_ty_params(db)) | ||
380 | } | ||
381 | |||
382 | fn builder(param_count: usize) -> SubstsBuilder { | ||
383 | SubstsBuilder { vec: Vec::with_capacity(param_count), param_count } | ||
384 | } | ||
385 | } | ||
386 | |||
387 | #[derive(Debug, Clone)] | ||
388 | pub struct SubstsBuilder { | ||
389 | vec: Vec<Ty>, | ||
390 | param_count: usize, | ||
391 | } | ||
392 | |||
393 | impl SubstsBuilder { | ||
394 | pub fn build(self) -> Substs { | ||
395 | assert_eq!(self.vec.len(), self.param_count); | ||
396 | Substs(self.vec.into()) | ||
397 | } | ||
398 | |||
399 | pub fn push(mut self, ty: Ty) -> Self { | ||
400 | self.vec.push(ty); | ||
401 | self | ||
402 | } | ||
403 | |||
404 | fn remaining(&self) -> usize { | ||
405 | self.param_count - self.vec.len() | ||
406 | } | ||
407 | |||
408 | pub fn fill_with_bound_vars(self, starting_from: u32) -> Self { | ||
409 | self.fill((starting_from..).map(Ty::Bound)) | ||
410 | } | ||
411 | |||
412 | pub fn fill_with_params(self) -> Self { | ||
413 | let start = self.vec.len() as u32; | ||
414 | self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() })) | ||
415 | } | ||
416 | |||
417 | pub fn fill_with_unknown(self) -> Self { | ||
418 | self.fill(iter::repeat(Ty::Unknown)) | ||
419 | } | ||
420 | |||
421 | pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { | ||
422 | self.vec.extend(filler.take(self.remaining())); | ||
423 | assert_eq!(self.remaining(), 0); | ||
424 | self | ||
425 | } | ||
426 | |||
427 | pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { | ||
428 | assert!(self.vec.is_empty()); | ||
429 | assert!(parent_substs.len() <= self.param_count); | ||
430 | self.vec.extend(parent_substs.iter().cloned()); | ||
431 | self | ||
432 | } | ||
433 | } | ||
434 | |||
435 | impl Deref for Substs { | ||
436 | type Target = [Ty]; | ||
437 | |||
438 | fn deref(&self) -> &[Ty] { | ||
439 | &self.0 | ||
440 | } | ||
441 | } | ||
442 | |||
443 | /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. | ||
444 | /// Name to be bikeshedded: TraitBound? TraitImplements? | ||
445 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
446 | pub struct TraitRef { | ||
447 | /// FIXME name? | ||
448 | pub trait_: TraitId, | ||
449 | pub substs: Substs, | ||
450 | } | ||
451 | |||
452 | impl TraitRef { | ||
453 | pub fn self_ty(&self) -> &Ty { | ||
454 | &self.substs[0] | ||
455 | } | ||
456 | } | ||
457 | |||
458 | impl TypeWalk for TraitRef { | ||
459 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
460 | self.substs.walk(f); | ||
461 | } | ||
462 | |||
463 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
464 | self.substs.walk_mut_binders(f, binders); | ||
465 | } | ||
466 | } | ||
467 | |||
468 | /// Like `generics::WherePredicate`, but with resolved types: A condition on the | ||
469 | /// parameters of a generic item. | ||
470 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
471 | pub enum GenericPredicate { | ||
472 | /// The given trait needs to be implemented for its type parameters. | ||
473 | Implemented(TraitRef), | ||
474 | /// An associated type bindings like in `Iterator<Item = T>`. | ||
475 | Projection(ProjectionPredicate), | ||
476 | /// We couldn't resolve the trait reference. (If some type parameters can't | ||
477 | /// be resolved, they will just be Unknown). | ||
478 | Error, | ||
479 | } | ||
480 | |||
481 | impl GenericPredicate { | ||
482 | pub fn is_error(&self) -> bool { | ||
483 | match self { | ||
484 | GenericPredicate::Error => true, | ||
485 | _ => false, | ||
486 | } | ||
487 | } | ||
488 | |||
489 | pub fn is_implemented(&self) -> bool { | ||
490 | match self { | ||
491 | GenericPredicate::Implemented(_) => true, | ||
492 | _ => false, | ||
493 | } | ||
494 | } | ||
495 | |||
496 | pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { | ||
497 | match self { | ||
498 | GenericPredicate::Implemented(tr) => Some(tr.clone()), | ||
499 | GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), | ||
500 | GenericPredicate::Error => None, | ||
501 | } | ||
502 | } | ||
503 | } | ||
504 | |||
505 | impl TypeWalk for GenericPredicate { | ||
506 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
507 | match self { | ||
508 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f), | ||
509 | GenericPredicate::Projection(projection_pred) => projection_pred.walk(f), | ||
510 | GenericPredicate::Error => {} | ||
511 | } | ||
512 | } | ||
513 | |||
514 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
515 | match self { | ||
516 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), | ||
517 | GenericPredicate::Projection(projection_pred) => { | ||
518 | projection_pred.walk_mut_binders(f, binders) | ||
519 | } | ||
520 | GenericPredicate::Error => {} | ||
521 | } | ||
522 | } | ||
523 | } | ||
524 | |||
525 | /// Basically a claim (currently not validated / checked) that the contained | ||
526 | /// type / trait ref contains no inference variables; any inference variables it | ||
527 | /// contained have been replaced by bound variables, and `num_vars` tells us how | ||
528 | /// many there are. This is used to erase irrelevant differences between types | ||
529 | /// before using them in queries. | ||
530 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
531 | pub struct Canonical<T> { | ||
532 | pub value: T, | ||
533 | pub num_vars: usize, | ||
534 | } | ||
535 | |||
536 | /// A function signature as seen by type inference: Several parameter types and | ||
537 | /// one return type. | ||
538 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
539 | pub struct FnSig { | ||
540 | params_and_return: Arc<[Ty]>, | ||
541 | } | ||
542 | |||
543 | impl FnSig { | ||
544 | pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig { | ||
545 | params.push(ret); | ||
546 | FnSig { params_and_return: params.into() } | ||
547 | } | ||
548 | |||
549 | pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig { | ||
550 | FnSig { params_and_return: Arc::clone(&substs.0) } | ||
551 | } | ||
552 | |||
553 | pub fn params(&self) -> &[Ty] { | ||
554 | &self.params_and_return[0..self.params_and_return.len() - 1] | ||
555 | } | ||
556 | |||
557 | pub fn ret(&self) -> &Ty { | ||
558 | &self.params_and_return[self.params_and_return.len() - 1] | ||
559 | } | ||
560 | } | ||
561 | |||
562 | impl TypeWalk for FnSig { | ||
563 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
564 | for t in self.params_and_return.iter() { | ||
565 | t.walk(f); | ||
566 | } | ||
567 | } | ||
568 | |||
569 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
570 | for t in make_mut_slice(&mut self.params_and_return) { | ||
571 | t.walk_mut_binders(f, binders); | ||
572 | } | ||
573 | } | ||
574 | } | ||
575 | |||
576 | impl Ty { | ||
577 | pub fn simple(ctor: TypeCtor) -> Ty { | ||
578 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() }) | ||
579 | } | ||
580 | pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty { | ||
581 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) }) | ||
582 | } | ||
583 | pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty { | ||
584 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
585 | } | ||
586 | pub fn unit() -> Self { | ||
587 | Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) | ||
588 | } | ||
589 | |||
590 | pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { | ||
591 | match self { | ||
592 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => { | ||
593 | Some((parameters.as_single(), *mutability)) | ||
594 | } | ||
595 | _ => None, | ||
596 | } | ||
597 | } | ||
598 | |||
599 | pub fn as_adt(&self) -> Option<(AdtId, &Substs)> { | ||
600 | match self { | ||
601 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => { | ||
602 | Some((*adt_def, parameters)) | ||
603 | } | ||
604 | _ => None, | ||
605 | } | ||
606 | } | ||
607 | |||
608 | pub fn as_tuple(&self) -> Option<&Substs> { | ||
609 | match self { | ||
610 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { | ||
611 | Some(parameters) | ||
612 | } | ||
613 | _ => None, | ||
614 | } | ||
615 | } | ||
616 | |||
617 | pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> { | ||
618 | match self { | ||
619 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => { | ||
620 | Some((*callable_def, parameters)) | ||
621 | } | ||
622 | _ => None, | ||
623 | } | ||
624 | } | ||
625 | |||
626 | fn builtin_deref(&self) -> Option<Ty> { | ||
627 | match self { | ||
628 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
629 | TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
630 | TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
631 | _ => None, | ||
632 | }, | ||
633 | _ => None, | ||
634 | } | ||
635 | } | ||
636 | |||
637 | fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> { | ||
638 | match self { | ||
639 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
640 | TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), | ||
641 | TypeCtor::FnDef(def) => { | ||
642 | let sig = db.callable_item_signature(def); | ||
643 | Some(sig.subst(&a_ty.parameters)) | ||
644 | } | ||
645 | TypeCtor::Closure { .. } => { | ||
646 | let sig_param = &a_ty.parameters[0]; | ||
647 | sig_param.callable_sig(db) | ||
648 | } | ||
649 | _ => None, | ||
650 | }, | ||
651 | _ => None, | ||
652 | } | ||
653 | } | ||
654 | |||
655 | /// If this is a type with type parameters (an ADT or function), replaces | ||
656 | /// the `Substs` for these type parameters with the given ones. (So e.g. if | ||
657 | /// `self` is `Option<_>` and the substs contain `u32`, we'll have | ||
658 | /// `Option<u32>` afterwards.) | ||
659 | pub fn apply_substs(self, substs: Substs) -> Ty { | ||
660 | match self { | ||
661 | Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => { | ||
662 | assert_eq!(previous_substs.len(), substs.len()); | ||
663 | Ty::Apply(ApplicationTy { ctor, parameters: substs }) | ||
664 | } | ||
665 | _ => self, | ||
666 | } | ||
667 | } | ||
668 | |||
669 | /// Returns the type parameters of this type if it has some (i.e. is an ADT | ||
670 | /// or function); so if `self` is `Option<u32>`, this returns the `u32`. | ||
671 | pub fn substs(&self) -> Option<Substs> { | ||
672 | match self { | ||
673 | Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), | ||
674 | _ => None, | ||
675 | } | ||
676 | } | ||
677 | |||
678 | /// If this is an `impl Trait` or `dyn Trait`, returns that trait. | ||
679 | pub fn inherent_trait(&self) -> Option<TraitId> { | ||
680 | match self { | ||
681 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
682 | predicates.iter().find_map(|pred| match pred { | ||
683 | GenericPredicate::Implemented(tr) => Some(tr.trait_), | ||
684 | _ => None, | ||
685 | }) | ||
686 | } | ||
687 | _ => None, | ||
688 | } | ||
689 | } | ||
690 | } | ||
691 | |||
692 | /// This allows walking structures that contain types to do something with those | ||
693 | /// types, similar to Chalk's `Fold` trait. | ||
694 | pub trait TypeWalk { | ||
695 | fn walk(&self, f: &mut impl FnMut(&Ty)); | ||
696 | fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { | ||
697 | self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); | ||
698 | } | ||
699 | /// Walk the type, counting entered binders. | ||
700 | /// | ||
701 | /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers | ||
702 | /// to the innermost binder, 1 to the next, etc.. So when we want to | ||
703 | /// substitute a certain bound variable, we can't just walk the whole type | ||
704 | /// and blindly replace each instance of a certain index; when we 'enter' | ||
705 | /// things that introduce new bound variables, we have to keep track of | ||
706 | /// that. Currently, the only thing that introduces bound variables on our | ||
707 | /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound | ||
708 | /// variable for the self type. | ||
709 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); | ||
710 | |||
711 | fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self | ||
712 | where | ||
713 | Self: Sized, | ||
714 | { | ||
715 | self.walk_mut(&mut |ty_mut| { | ||
716 | let ty = mem::replace(ty_mut, Ty::Unknown); | ||
717 | *ty_mut = f(ty); | ||
718 | }); | ||
719 | self | ||
720 | } | ||
721 | |||
722 | /// Replaces type parameters in this type using the given `Substs`. (So e.g. | ||
723 | /// if `self` is `&[T]`, where type parameter T has index 0, and the | ||
724 | /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.) | ||
725 | fn subst(self, substs: &Substs) -> Self | ||
726 | where | ||
727 | Self: Sized, | ||
728 | { | ||
729 | self.fold(&mut |ty| match ty { | ||
730 | Ty::Param { idx, name } => { | ||
731 | substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) | ||
732 | } | ||
733 | ty => ty, | ||
734 | }) | ||
735 | } | ||
736 | |||
737 | /// Substitutes `Ty::Bound` vars (as opposed to type parameters). | ||
738 | fn subst_bound_vars(mut self, substs: &Substs) -> Self | ||
739 | where | ||
740 | Self: Sized, | ||
741 | { | ||
742 | self.walk_mut_binders( | ||
743 | &mut |ty, binders| match ty { | ||
744 | &mut Ty::Bound(idx) => { | ||
745 | if idx as usize >= binders && (idx as usize - binders) < substs.len() { | ||
746 | *ty = substs.0[idx as usize - binders].clone(); | ||
747 | } | ||
748 | } | ||
749 | _ => {} | ||
750 | }, | ||
751 | 0, | ||
752 | ); | ||
753 | self | ||
754 | } | ||
755 | |||
756 | /// Shifts up `Ty::Bound` vars by `n`. | ||
757 | fn shift_bound_vars(self, n: i32) -> Self | ||
758 | where | ||
759 | Self: Sized, | ||
760 | { | ||
761 | self.fold(&mut |ty| match ty { | ||
762 | Ty::Bound(idx) => { | ||
763 | assert!(idx as i32 >= -n); | ||
764 | Ty::Bound((idx as i32 + n) as u32) | ||
765 | } | ||
766 | ty => ty, | ||
767 | }) | ||
768 | } | ||
769 | } | ||
770 | |||
771 | impl TypeWalk for Ty { | ||
772 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
773 | match self { | ||
774 | Ty::Apply(a_ty) => { | ||
775 | for t in a_ty.parameters.iter() { | ||
776 | t.walk(f); | ||
777 | } | ||
778 | } | ||
779 | Ty::Projection(p_ty) => { | ||
780 | for t in p_ty.parameters.iter() { | ||
781 | t.walk(f); | ||
782 | } | ||
783 | } | ||
784 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
785 | for p in predicates.iter() { | ||
786 | p.walk(f); | ||
787 | } | ||
788 | } | ||
789 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
790 | } | ||
791 | f(self); | ||
792 | } | ||
793 | |||
794 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
795 | match self { | ||
796 | Ty::Apply(a_ty) => { | ||
797 | a_ty.parameters.walk_mut_binders(f, binders); | ||
798 | } | ||
799 | Ty::Projection(p_ty) => { | ||
800 | p_ty.parameters.walk_mut_binders(f, binders); | ||
801 | } | ||
802 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
803 | for p in make_mut_slice(predicates) { | ||
804 | p.walk_mut_binders(f, binders + 1); | ||
805 | } | ||
806 | } | ||
807 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
808 | } | ||
809 | f(self, binders); | ||
810 | } | ||
811 | } | ||
812 | |||
813 | impl HirDisplay for &Ty { | ||
814 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
815 | HirDisplay::hir_fmt(*self, f) | ||
816 | } | ||
817 | } | ||
818 | |||
819 | impl HirDisplay for ApplicationTy { | ||
820 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
821 | if f.should_truncate() { | ||
822 | return write!(f, "…"); | ||
823 | } | ||
824 | |||
825 | match self.ctor { | ||
826 | TypeCtor::Bool => write!(f, "bool")?, | ||
827 | TypeCtor::Char => write!(f, "char")?, | ||
828 | TypeCtor::Int(t) => write!(f, "{}", t)?, | ||
829 | TypeCtor::Float(t) => write!(f, "{}", t)?, | ||
830 | TypeCtor::Str => write!(f, "str")?, | ||
831 | TypeCtor::Slice => { | ||
832 | let t = self.parameters.as_single(); | ||
833 | write!(f, "[{}]", t.display(f.db))?; | ||
834 | } | ||
835 | TypeCtor::Array => { | ||
836 | let t = self.parameters.as_single(); | ||
837 | write!(f, "[{};_]", t.display(f.db))?; | ||
838 | } | ||
839 | TypeCtor::RawPtr(m) => { | ||
840 | let t = self.parameters.as_single(); | ||
841 | write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?; | ||
842 | } | ||
843 | TypeCtor::Ref(m) => { | ||
844 | let t = self.parameters.as_single(); | ||
845 | write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; | ||
846 | } | ||
847 | TypeCtor::Never => write!(f, "!")?, | ||
848 | TypeCtor::Tuple { .. } => { | ||
849 | let ts = &self.parameters; | ||
850 | if ts.len() == 1 { | ||
851 | write!(f, "({},)", ts[0].display(f.db))?; | ||
852 | } else { | ||
853 | write!(f, "(")?; | ||
854 | f.write_joined(&*ts.0, ", ")?; | ||
855 | write!(f, ")")?; | ||
856 | } | ||
857 | } | ||
858 | TypeCtor::FnPtr { .. } => { | ||
859 | let sig = FnSig::from_fn_ptr_substs(&self.parameters); | ||
860 | write!(f, "fn(")?; | ||
861 | f.write_joined(sig.params(), ", ")?; | ||
862 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
863 | } | ||
864 | TypeCtor::FnDef(def) => { | ||
865 | let sig = f.db.callable_item_signature(def); | ||
866 | let name = match def { | ||
867 | CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), | ||
868 | CallableDef::StructId(s) => { | ||
869 | f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing) | ||
870 | } | ||
871 | CallableDef::EnumVariantId(e) => { | ||
872 | let enum_data = f.db.enum_data(e.parent); | ||
873 | enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing) | ||
874 | } | ||
875 | }; | ||
876 | match def { | ||
877 | CallableDef::FunctionId(_) => write!(f, "fn {}", name)?, | ||
878 | CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => { | ||
879 | write!(f, "{}", name)? | ||
880 | } | ||
881 | } | ||
882 | if self.parameters.len() > 0 { | ||
883 | write!(f, "<")?; | ||
884 | f.write_joined(&*self.parameters.0, ", ")?; | ||
885 | write!(f, ">")?; | ||
886 | } | ||
887 | write!(f, "(")?; | ||
888 | f.write_joined(sig.params(), ", ")?; | ||
889 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
890 | } | ||
891 | TypeCtor::Adt(def_id) => { | ||
892 | let name = match def_id { | ||
893 | AdtId::StructId(it) => f.db.struct_data(it).name.clone(), | ||
894 | AdtId::UnionId(it) => f.db.union_data(it).name.clone(), | ||
895 | AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), | ||
896 | } | ||
897 | .unwrap_or_else(Name::missing); | ||
898 | write!(f, "{}", name)?; | ||
899 | if self.parameters.len() > 0 { | ||
900 | write!(f, "<")?; | ||
901 | f.write_joined(&*self.parameters.0, ", ")?; | ||
902 | write!(f, ">")?; | ||
903 | } | ||
904 | } | ||
905 | TypeCtor::AssociatedType(type_alias) => { | ||
906 | let trait_ = match type_alias.lookup(f.db).container { | ||
907 | ContainerId::TraitId(it) => it, | ||
908 | _ => panic!("not an associated type"), | ||
909 | }; | ||
910 | let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing); | ||
911 | let name = f.db.type_alias_data(type_alias).name.clone(); | ||
912 | write!(f, "{}::{}", trait_name, name)?; | ||
913 | if self.parameters.len() > 0 { | ||
914 | write!(f, "<")?; | ||
915 | f.write_joined(&*self.parameters.0, ", ")?; | ||
916 | write!(f, ">")?; | ||
917 | } | ||
918 | } | ||
919 | TypeCtor::Closure { .. } => { | ||
920 | let sig = self.parameters[0] | ||
921 | .callable_sig(f.db) | ||
922 | .expect("first closure parameter should contain signature"); | ||
923 | write!(f, "|")?; | ||
924 | f.write_joined(sig.params(), ", ")?; | ||
925 | write!(f, "| -> {}", sig.ret().display(f.db))?; | ||
926 | } | ||
927 | } | ||
928 | Ok(()) | ||
929 | } | ||
930 | } | ||
931 | |||
932 | impl HirDisplay for ProjectionTy { | ||
933 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
934 | if f.should_truncate() { | ||
935 | return write!(f, "…"); | ||
936 | } | ||
937 | |||
938 | let trait_name = | ||
939 | f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing); | ||
940 | write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; | ||
941 | if self.parameters.len() > 1 { | ||
942 | write!(f, "<")?; | ||
943 | f.write_joined(&self.parameters[1..], ", ")?; | ||
944 | write!(f, ">")?; | ||
945 | } | ||
946 | write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; | ||
947 | Ok(()) | ||
948 | } | ||
949 | } | ||
950 | |||
951 | impl HirDisplay for Ty { | ||
952 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
953 | if f.should_truncate() { | ||
954 | return write!(f, "…"); | ||
955 | } | ||
956 | |||
957 | match self { | ||
958 | Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, | ||
959 | Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, | ||
960 | Ty::Param { name, .. } => write!(f, "{}", name)?, | ||
961 | Ty::Bound(idx) => write!(f, "?{}", idx)?, | ||
962 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
963 | match self { | ||
964 | Ty::Dyn(_) => write!(f, "dyn ")?, | ||
965 | Ty::Opaque(_) => write!(f, "impl ")?, | ||
966 | _ => unreachable!(), | ||
967 | }; | ||
968 | // Note: This code is written to produce nice results (i.e. | ||
969 | // corresponding to surface Rust) for types that can occur in | ||
970 | // actual Rust. It will have weird results if the predicates | ||
971 | // aren't as expected (i.e. self types = $0, projection | ||
972 | // predicates for a certain trait come after the Implemented | ||
973 | // predicate for that trait). | ||
974 | let mut first = true; | ||
975 | let mut angle_open = false; | ||
976 | for p in predicates.iter() { | ||
977 | match p { | ||
978 | GenericPredicate::Implemented(trait_ref) => { | ||
979 | if angle_open { | ||
980 | write!(f, ">")?; | ||
981 | } | ||
982 | if !first { | ||
983 | write!(f, " + ")?; | ||
984 | } | ||
985 | // We assume that the self type is $0 (i.e. the | ||
986 | // existential) here, which is the only thing that's | ||
987 | // possible in actual Rust, and hence don't print it | ||
988 | write!( | ||
989 | f, | ||
990 | "{}", | ||
991 | f.db.trait_data(trait_ref.trait_) | ||
992 | .name | ||
993 | .clone() | ||
994 | .unwrap_or_else(Name::missing) | ||
995 | )?; | ||
996 | if trait_ref.substs.len() > 1 { | ||
997 | write!(f, "<")?; | ||
998 | f.write_joined(&trait_ref.substs[1..], ", ")?; | ||
999 | // there might be assoc type bindings, so we leave the angle brackets open | ||
1000 | angle_open = true; | ||
1001 | } | ||
1002 | } | ||
1003 | GenericPredicate::Projection(projection_pred) => { | ||
1004 | // in types in actual Rust, these will always come | ||
1005 | // after the corresponding Implemented predicate | ||
1006 | if angle_open { | ||
1007 | write!(f, ", ")?; | ||
1008 | } else { | ||
1009 | write!(f, "<")?; | ||
1010 | angle_open = true; | ||
1011 | } | ||
1012 | let name = | ||
1013 | f.db.type_alias_data(projection_pred.projection_ty.associated_ty) | ||
1014 | .name | ||
1015 | .clone(); | ||
1016 | write!(f, "{} = ", name)?; | ||
1017 | projection_pred.ty.hir_fmt(f)?; | ||
1018 | } | ||
1019 | GenericPredicate::Error => { | ||
1020 | if angle_open { | ||
1021 | // impl Trait<X, {error}> | ||
1022 | write!(f, ", ")?; | ||
1023 | } else if !first { | ||
1024 | // impl Trait + {error} | ||
1025 | write!(f, " + ")?; | ||
1026 | } | ||
1027 | p.hir_fmt(f)?; | ||
1028 | } | ||
1029 | } | ||
1030 | first = false; | ||
1031 | } | ||
1032 | if angle_open { | ||
1033 | write!(f, ">")?; | ||
1034 | } | ||
1035 | } | ||
1036 | Ty::Unknown => write!(f, "{{unknown}}")?, | ||
1037 | Ty::Infer(..) => write!(f, "_")?, | ||
1038 | } | ||
1039 | Ok(()) | ||
1040 | } | ||
1041 | } | ||
1042 | |||
1043 | impl TraitRef { | ||
1044 | fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { | ||
1045 | if f.should_truncate() { | ||
1046 | return write!(f, "…"); | ||
1047 | } | ||
1048 | |||
1049 | self.substs[0].hir_fmt(f)?; | ||
1050 | if use_as { | ||
1051 | write!(f, " as ")?; | ||
1052 | } else { | ||
1053 | write!(f, ": ")?; | ||
1054 | } | ||
1055 | write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?; | ||
1056 | if self.substs.len() > 1 { | ||
1057 | write!(f, "<")?; | ||
1058 | f.write_joined(&self.substs[1..], ", ")?; | ||
1059 | write!(f, ">")?; | ||
1060 | } | ||
1061 | Ok(()) | ||
1062 | } | ||
1063 | } | ||
1064 | |||
1065 | impl HirDisplay for TraitRef { | ||
1066 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1067 | self.hir_fmt_ext(f, false) | ||
1068 | } | ||
1069 | } | ||
1070 | |||
1071 | impl HirDisplay for &GenericPredicate { | ||
1072 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1073 | HirDisplay::hir_fmt(*self, f) | ||
1074 | } | ||
1075 | } | ||
1076 | |||
1077 | impl HirDisplay for GenericPredicate { | ||
1078 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1079 | if f.should_truncate() { | ||
1080 | return write!(f, "…"); | ||
1081 | } | ||
1082 | |||
1083 | match self { | ||
1084 | GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?, | ||
1085 | GenericPredicate::Projection(projection_pred) => { | ||
1086 | write!(f, "<")?; | ||
1087 | projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; | ||
1088 | write!( | ||
1089 | f, | ||
1090 | ">::{} = {}", | ||
1091 | f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, | ||
1092 | projection_pred.ty.display(f.db) | ||
1093 | )?; | ||
1094 | } | ||
1095 | GenericPredicate::Error => write!(f, "{{error}}")?, | ||
1096 | } | ||
1097 | Ok(()) | ||
1098 | } | ||
1099 | } | ||
1100 | |||
1101 | impl HirDisplay for Obligation { | ||
1102 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1103 | match self { | ||
1104 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), | ||
1105 | Obligation::Projection(proj) => write!( | ||
1106 | f, | ||
1107 | "Normalize({} => {})", | ||
1108 | proj.projection_ty.display(f.db), | ||
1109 | proj.ty.display(f.db) | ||
1110 | ), | ||
1111 | } | ||
1112 | } | ||
1113 | } | ||
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir/src/ty/autoderef.rs deleted file mode 100644 index ae68234ac..000000000 --- a/crates/ra_hir/src/ty/autoderef.rs +++ /dev/null | |||
@@ -1,108 +0,0 @@ | |||
1 | //! In certain situations, rust automatically inserts derefs as necessary: for | ||
2 | //! example, field accesses `foo.bar` still work when `foo` is actually a | ||
3 | //! reference to a type with the field `bar`. This is an approximation of the | ||
4 | //! logic in rustc (which lives in librustc_typeck/check/autoderef.rs). | ||
5 | |||
6 | use std::iter::successors; | ||
7 | |||
8 | use hir_def::lang_item::LangItemTarget; | ||
9 | use hir_expand::name; | ||
10 | use log::{info, warn}; | ||
11 | use ra_db::CrateId; | ||
12 | |||
13 | use crate::db::HirDatabase; | ||
14 | |||
15 | use super::{ | ||
16 | traits::{InEnvironment, Solution}, | ||
17 | Canonical, Substs, Ty, TypeWalk, | ||
18 | }; | ||
19 | |||
20 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | ||
21 | |||
22 | pub(crate) fn autoderef<'a>( | ||
23 | db: &'a impl HirDatabase, | ||
24 | krate: Option<CrateId>, | ||
25 | ty: InEnvironment<Canonical<Ty>>, | ||
26 | ) -> impl Iterator<Item = Canonical<Ty>> + 'a { | ||
27 | let InEnvironment { value: ty, environment } = ty; | ||
28 | successors(Some(ty), move |ty| { | ||
29 | deref(db, krate?, InEnvironment { value: ty, environment: environment.clone() }) | ||
30 | }) | ||
31 | .take(AUTODEREF_RECURSION_LIMIT) | ||
32 | } | ||
33 | |||
34 | pub(crate) fn deref( | ||
35 | db: &impl HirDatabase, | ||
36 | krate: CrateId, | ||
37 | ty: InEnvironment<&Canonical<Ty>>, | ||
38 | ) -> Option<Canonical<Ty>> { | ||
39 | if let Some(derefed) = ty.value.value.builtin_deref() { | ||
40 | Some(Canonical { value: derefed, num_vars: ty.value.num_vars }) | ||
41 | } else { | ||
42 | deref_by_trait(db, krate, ty) | ||
43 | } | ||
44 | } | ||
45 | |||
46 | fn deref_by_trait( | ||
47 | db: &impl HirDatabase, | ||
48 | krate: CrateId, | ||
49 | ty: InEnvironment<&Canonical<Ty>>, | ||
50 | ) -> Option<Canonical<Ty>> { | ||
51 | let deref_trait = match db.lang_item(krate.into(), "deref".into())? { | ||
52 | LangItemTarget::TraitId(it) => it, | ||
53 | _ => return None, | ||
54 | }; | ||
55 | let target = db.trait_data(deref_trait).associated_type_by_name(&name::TARGET_TYPE)?; | ||
56 | |||
57 | let generic_params = db.generic_params(target.into()); | ||
58 | if generic_params.count_params_including_parent() != 1 { | ||
59 | // the Target type + Deref trait should only have one generic parameter, | ||
60 | // namely Deref's Self type | ||
61 | return None; | ||
62 | } | ||
63 | |||
64 | // FIXME make the Canonical handling nicer | ||
65 | |||
66 | let parameters = Substs::build_for_generics(&generic_params) | ||
67 | .push(ty.value.value.clone().shift_bound_vars(1)) | ||
68 | .build(); | ||
69 | |||
70 | let projection = super::traits::ProjectionPredicate { | ||
71 | ty: Ty::Bound(0), | ||
72 | projection_ty: super::ProjectionTy { associated_ty: target, parameters }, | ||
73 | }; | ||
74 | |||
75 | let obligation = super::Obligation::Projection(projection); | ||
76 | |||
77 | let in_env = InEnvironment { value: obligation, environment: ty.environment }; | ||
78 | |||
79 | let canonical = super::Canonical { num_vars: 1 + ty.value.num_vars, value: in_env }; | ||
80 | |||
81 | let solution = db.trait_solve(krate.into(), canonical)?; | ||
82 | |||
83 | match &solution { | ||
84 | Solution::Unique(vars) => { | ||
85 | // FIXME: vars may contain solutions for any inference variables | ||
86 | // that happened to be inside ty. To correctly handle these, we | ||
87 | // would have to pass the solution up to the inference context, but | ||
88 | // that requires a larger refactoring (especially if the deref | ||
89 | // happens during method resolution). So for the moment, we just | ||
90 | // check that we're not in the situation we're we would actually | ||
91 | // need to handle the values of the additional variables, i.e. | ||
92 | // they're just being 'passed through'. In the 'standard' case where | ||
93 | // we have `impl<T> Deref for Foo<T> { Target = T }`, that should be | ||
94 | // the case. | ||
95 | for i in 1..vars.0.num_vars { | ||
96 | if vars.0.value[i] != Ty::Bound((i - 1) as u32) { | ||
97 | warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution); | ||
98 | return None; | ||
99 | } | ||
100 | } | ||
101 | Some(Canonical { value: vars.0.value[0].clone(), num_vars: vars.0.num_vars }) | ||
102 | } | ||
103 | Solution::Ambig(_) => { | ||
104 | info!("Ambiguous solution for derefing {:?}: {:?}", ty.value, solution); | ||
105 | None | ||
106 | } | ||
107 | } | ||
108 | } | ||
diff --git a/crates/ra_hir/src/ty/display.rs b/crates/ra_hir/src/ty/display.rs deleted file mode 100644 index 9bb3ece6c..000000000 --- a/crates/ra_hir/src/ty/display.rs +++ /dev/null | |||
@@ -1,93 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | use crate::db::HirDatabase; | ||
6 | |||
7 | pub struct HirFormatter<'a, 'b, DB> { | ||
8 | pub db: &'a DB, | ||
9 | fmt: &'a mut fmt::Formatter<'b>, | ||
10 | buf: String, | ||
11 | curr_size: usize, | ||
12 | max_size: Option<usize>, | ||
13 | } | ||
14 | |||
15 | pub trait HirDisplay { | ||
16 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; | ||
17 | |||
18 | fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> | ||
19 | where | ||
20 | Self: Sized, | ||
21 | { | ||
22 | HirDisplayWrapper(db, self, None) | ||
23 | } | ||
24 | |||
25 | fn display_truncated<'a, DB>( | ||
26 | &'a self, | ||
27 | db: &'a DB, | ||
28 | max_size: Option<usize>, | ||
29 | ) -> HirDisplayWrapper<'a, DB, Self> | ||
30 | where | ||
31 | Self: Sized, | ||
32 | { | ||
33 | HirDisplayWrapper(db, self, max_size) | ||
34 | } | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> | ||
38 | where | ||
39 | DB: HirDatabase, | ||
40 | { | ||
41 | pub fn write_joined<T: HirDisplay>( | ||
42 | &mut self, | ||
43 | iter: impl IntoIterator<Item = T>, | ||
44 | sep: &str, | ||
45 | ) -> fmt::Result { | ||
46 | let mut first = true; | ||
47 | for e in iter { | ||
48 | if !first { | ||
49 | write!(self, "{}", sep)?; | ||
50 | } | ||
51 | first = false; | ||
52 | e.hir_fmt(self)?; | ||
53 | } | ||
54 | Ok(()) | ||
55 | } | ||
56 | |||
57 | /// This allows using the `write!` macro directly with a `HirFormatter`. | ||
58 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | ||
59 | // We write to a buffer first to track output size | ||
60 | self.buf.clear(); | ||
61 | fmt::write(&mut self.buf, args)?; | ||
62 | self.curr_size += self.buf.len(); | ||
63 | |||
64 | // Then we write to the internal formatter from the buffer | ||
65 | self.fmt.write_str(&self.buf) | ||
66 | } | ||
67 | |||
68 | pub fn should_truncate(&self) -> bool { | ||
69 | if let Some(max_size) = self.max_size { | ||
70 | self.curr_size >= max_size | ||
71 | } else { | ||
72 | false | ||
73 | } | ||
74 | } | ||
75 | } | ||
76 | |||
77 | pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>); | ||
78 | |||
79 | impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> | ||
80 | where | ||
81 | DB: HirDatabase, | ||
82 | T: HirDisplay, | ||
83 | { | ||
84 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
85 | self.1.hir_fmt(&mut HirFormatter { | ||
86 | db: self.0, | ||
87 | fmt: f, | ||
88 | buf: String::with_capacity(20), | ||
89 | curr_size: 0, | ||
90 | max_size: self.2, | ||
91 | }) | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs deleted file mode 100644 index 59e4e5f36..000000000 --- a/crates/ra_hir/src/ty/infer.rs +++ /dev/null | |||
@@ -1,723 +0,0 @@ | |||
1 | //! Type inference, i.e. the process of walking through the code and determining | ||
2 | //! the type of each expression and pattern. | ||
3 | //! | ||
4 | //! For type inference, compare the implementations in rustc (the various | ||
5 | //! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and | ||
6 | //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for | ||
7 | //! inference here is the `infer` function, which infers the types of all | ||
8 | //! expressions in a given function. | ||
9 | //! | ||
10 | //! During inference, types (i.e. the `Ty` struct) can contain type 'variables' | ||
11 | //! which represent currently unknown types; as we walk through the expressions, | ||
12 | //! we might determine that certain variables need to be equal to each other, or | ||
13 | //! to certain types. To record this, we use the union-find implementation from | ||
14 | //! the `ena` crate, which is extracted from rustc. | ||
15 | |||
16 | use std::borrow::Cow; | ||
17 | use std::mem; | ||
18 | use std::ops::Index; | ||
19 | use std::sync::Arc; | ||
20 | |||
21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; | ||
22 | use rustc_hash::FxHashMap; | ||
23 | |||
24 | use hir_def::{ | ||
25 | body::Body, | ||
26 | data::{ConstData, FunctionData}, | ||
27 | expr::{BindingAnnotation, ExprId, PatId}, | ||
28 | path::{known, Path}, | ||
29 | resolver::{HasResolver, Resolver, TypeNs}, | ||
30 | type_ref::{Mutability, TypeRef}, | ||
31 | AdtId, AssocItemId, DefWithBodyId, FunctionId, StructFieldId, TypeAliasId, VariantId, | ||
32 | }; | ||
33 | use hir_expand::{diagnostics::DiagnosticSink, name}; | ||
34 | use ra_arena::map::ArenaMap; | ||
35 | use ra_prof::profile; | ||
36 | use test_utils::tested_by; | ||
37 | |||
38 | use super::{ | ||
39 | primitive::{FloatTy, IntTy}, | ||
40 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | ||
41 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor, | ||
42 | TypeWalk, Uncertain, | ||
43 | }; | ||
44 | use crate::{db::HirDatabase, ty::infer::diagnostics::InferenceDiagnostic}; | ||
45 | |||
46 | macro_rules! ty_app { | ||
47 | ($ctor:pat, $param:pat) => { | ||
48 | crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
49 | }; | ||
50 | ($ctor:pat) => { | ||
51 | ty_app!($ctor, _) | ||
52 | }; | ||
53 | } | ||
54 | |||
55 | mod unify; | ||
56 | mod path; | ||
57 | mod expr; | ||
58 | mod pat; | ||
59 | mod coerce; | ||
60 | |||
61 | /// The entry point of type inference. | ||
62 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> { | ||
63 | let _p = profile("infer_query"); | ||
64 | let resolver = def.resolver(db); | ||
65 | let mut ctx = InferenceContext::new(db, def, resolver); | ||
66 | |||
67 | match def { | ||
68 | DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)), | ||
69 | DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)), | ||
70 | DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)), | ||
71 | } | ||
72 | |||
73 | ctx.infer_body(); | ||
74 | |||
75 | Arc::new(ctx.resolve_all()) | ||
76 | } | ||
77 | |||
78 | #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] | ||
79 | enum ExprOrPatId { | ||
80 | ExprId(ExprId), | ||
81 | PatId(PatId), | ||
82 | } | ||
83 | |||
84 | impl_froms!(ExprOrPatId: ExprId, PatId); | ||
85 | |||
86 | /// Binding modes inferred for patterns. | ||
87 | /// https://doc.rust-lang.org/reference/patterns.html#binding-modes | ||
88 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | ||
89 | enum BindingMode { | ||
90 | Move, | ||
91 | Ref(Mutability), | ||
92 | } | ||
93 | |||
94 | impl BindingMode { | ||
95 | pub fn convert(annotation: BindingAnnotation) -> BindingMode { | ||
96 | match annotation { | ||
97 | BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, | ||
98 | BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), | ||
99 | BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut), | ||
100 | } | ||
101 | } | ||
102 | } | ||
103 | |||
104 | impl Default for BindingMode { | ||
105 | fn default() -> Self { | ||
106 | BindingMode::Move | ||
107 | } | ||
108 | } | ||
109 | |||
110 | /// A mismatch between an expected and an inferred type. | ||
111 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
112 | pub struct TypeMismatch { | ||
113 | pub expected: Ty, | ||
114 | pub actual: Ty, | ||
115 | } | ||
116 | |||
117 | /// The result of type inference: A mapping from expressions and patterns to types. | ||
118 | #[derive(Clone, PartialEq, Eq, Debug, Default)] | ||
119 | pub struct InferenceResult { | ||
120 | /// For each method call expr, records the function it resolves to. | ||
121 | method_resolutions: FxHashMap<ExprId, FunctionId>, | ||
122 | /// For each field access expr, records the field it resolves to. | ||
123 | field_resolutions: FxHashMap<ExprId, StructFieldId>, | ||
124 | /// For each field in record literal, records the field it resolves to. | ||
125 | record_field_resolutions: FxHashMap<ExprId, StructFieldId>, | ||
126 | /// For each struct literal, records the variant it resolves to. | ||
127 | variant_resolutions: FxHashMap<ExprOrPatId, VariantId>, | ||
128 | /// For each associated item record what it resolves to | ||
129 | assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>, | ||
130 | diagnostics: Vec<InferenceDiagnostic>, | ||
131 | pub(super) type_of_expr: ArenaMap<ExprId, Ty>, | ||
132 | pub(super) type_of_pat: ArenaMap<PatId, Ty>, | ||
133 | pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>, | ||
134 | } | ||
135 | |||
136 | impl InferenceResult { | ||
137 | pub fn method_resolution(&self, expr: ExprId) -> Option<FunctionId> { | ||
138 | self.method_resolutions.get(&expr).copied() | ||
139 | } | ||
140 | pub fn field_resolution(&self, expr: ExprId) -> Option<StructFieldId> { | ||
141 | self.field_resolutions.get(&expr).copied() | ||
142 | } | ||
143 | pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructFieldId> { | ||
144 | self.record_field_resolutions.get(&expr).copied() | ||
145 | } | ||
146 | pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> { | ||
147 | self.variant_resolutions.get(&id.into()).copied() | ||
148 | } | ||
149 | pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> { | ||
150 | self.variant_resolutions.get(&id.into()).copied() | ||
151 | } | ||
152 | pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItemId> { | ||
153 | self.assoc_resolutions.get(&id.into()).copied() | ||
154 | } | ||
155 | pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItemId> { | ||
156 | self.assoc_resolutions.get(&id.into()).copied() | ||
157 | } | ||
158 | pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { | ||
159 | self.type_mismatches.get(expr) | ||
160 | } | ||
161 | pub(crate) fn add_diagnostics( | ||
162 | &self, | ||
163 | db: &impl HirDatabase, | ||
164 | owner: FunctionId, | ||
165 | sink: &mut DiagnosticSink, | ||
166 | ) { | ||
167 | self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink)) | ||
168 | } | ||
169 | } | ||
170 | |||
171 | impl Index<ExprId> for InferenceResult { | ||
172 | type Output = Ty; | ||
173 | |||
174 | fn index(&self, expr: ExprId) -> &Ty { | ||
175 | self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) | ||
176 | } | ||
177 | } | ||
178 | |||
179 | impl Index<PatId> for InferenceResult { | ||
180 | type Output = Ty; | ||
181 | |||
182 | fn index(&self, pat: PatId) -> &Ty { | ||
183 | self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) | ||
184 | } | ||
185 | } | ||
186 | |||
187 | /// The inference context contains all information needed during type inference. | ||
188 | #[derive(Clone, Debug)] | ||
189 | struct InferenceContext<'a, D: HirDatabase> { | ||
190 | db: &'a D, | ||
191 | owner: DefWithBodyId, | ||
192 | body: Arc<Body>, | ||
193 | resolver: Resolver, | ||
194 | var_unification_table: InPlaceUnificationTable<TypeVarId>, | ||
195 | trait_env: Arc<TraitEnvironment>, | ||
196 | obligations: Vec<Obligation>, | ||
197 | result: InferenceResult, | ||
198 | /// The return type of the function being inferred. | ||
199 | return_ty: Ty, | ||
200 | |||
201 | /// Impls of `CoerceUnsized` used in coercion. | ||
202 | /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index | ||
203 | // FIXME: Use trait solver for this. | ||
204 | // Chalk seems unable to work well with builtin impl of `Unsize` now. | ||
205 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | ||
206 | } | ||
207 | |||
208 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
209 | fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self { | ||
210 | InferenceContext { | ||
211 | result: InferenceResult::default(), | ||
212 | var_unification_table: InPlaceUnificationTable::new(), | ||
213 | obligations: Vec::default(), | ||
214 | return_ty: Ty::Unknown, // set in collect_fn_signature | ||
215 | trait_env: TraitEnvironment::lower(db, &resolver), | ||
216 | coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver), | ||
217 | db, | ||
218 | owner, | ||
219 | body: db.body(owner.into()), | ||
220 | resolver, | ||
221 | } | ||
222 | } | ||
223 | |||
224 | fn resolve_all(mut self) -> InferenceResult { | ||
225 | // FIXME resolve obligations as well (use Guidance if necessary) | ||
226 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | ||
227 | let mut tv_stack = Vec::new(); | ||
228 | for ty in result.type_of_expr.values_mut() { | ||
229 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
230 | *ty = resolved; | ||
231 | } | ||
232 | for ty in result.type_of_pat.values_mut() { | ||
233 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
234 | *ty = resolved; | ||
235 | } | ||
236 | result | ||
237 | } | ||
238 | |||
239 | fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) { | ||
240 | self.result.type_of_expr.insert(expr, ty); | ||
241 | } | ||
242 | |||
243 | fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId) { | ||
244 | self.result.method_resolutions.insert(expr, func); | ||
245 | } | ||
246 | |||
247 | fn write_field_resolution(&mut self, expr: ExprId, field: StructFieldId) { | ||
248 | self.result.field_resolutions.insert(expr, field); | ||
249 | } | ||
250 | |||
251 | fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) { | ||
252 | self.result.variant_resolutions.insert(id, variant); | ||
253 | } | ||
254 | |||
255 | fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) { | ||
256 | self.result.assoc_resolutions.insert(id, item.into()); | ||
257 | } | ||
258 | |||
259 | fn write_pat_ty(&mut self, pat: PatId, ty: Ty) { | ||
260 | self.result.type_of_pat.insert(pat, ty); | ||
261 | } | ||
262 | |||
263 | fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) { | ||
264 | self.result.diagnostics.push(diagnostic); | ||
265 | } | ||
266 | |||
267 | fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { | ||
268 | let ty = Ty::from_hir( | ||
269 | self.db, | ||
270 | // FIXME use right resolver for block | ||
271 | &self.resolver, | ||
272 | type_ref, | ||
273 | ); | ||
274 | let ty = self.insert_type_vars(ty); | ||
275 | self.normalize_associated_types_in(ty) | ||
276 | } | ||
277 | |||
278 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { | ||
279 | substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) | ||
280 | } | ||
281 | |||
282 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
283 | self.unify_inner(ty1, ty2, 0) | ||
284 | } | ||
285 | |||
286 | fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { | ||
287 | if depth > 1000 { | ||
288 | // prevent stackoverflows | ||
289 | panic!("infinite recursion in unification"); | ||
290 | } | ||
291 | if ty1 == ty2 { | ||
292 | return true; | ||
293 | } | ||
294 | // try to resolve type vars first | ||
295 | let ty1 = self.resolve_ty_shallow(ty1); | ||
296 | let ty2 = self.resolve_ty_shallow(ty2); | ||
297 | match (&*ty1, &*ty2) { | ||
298 | (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { | ||
299 | self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) | ||
300 | } | ||
301 | _ => self.unify_inner_trivial(&ty1, &ty2), | ||
302 | } | ||
303 | } | ||
304 | |||
305 | fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
306 | match (ty1, ty2) { | ||
307 | (Ty::Unknown, _) | (_, Ty::Unknown) => true, | ||
308 | |||
309 | (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) | ||
310 | | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) | ||
311 | | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) | ||
312 | | ( | ||
313 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), | ||
314 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), | ||
315 | ) => { | ||
316 | // both type vars are unknown since we tried to resolve them | ||
317 | self.var_unification_table.union(*tv1, *tv2); | ||
318 | true | ||
319 | } | ||
320 | |||
321 | // The order of MaybeNeverTypeVar matters here. | ||
322 | // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. | ||
323 | // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. | ||
324 | (Ty::Infer(InferTy::TypeVar(tv)), other) | ||
325 | | (other, Ty::Infer(InferTy::TypeVar(tv))) | ||
326 | | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) | ||
327 | | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) | ||
328 | | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) | ||
329 | | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) | ||
330 | | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) | ||
331 | | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { | ||
332 | // the type var is unknown since we tried to resolve it | ||
333 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); | ||
334 | true | ||
335 | } | ||
336 | |||
337 | _ => false, | ||
338 | } | ||
339 | } | ||
340 | |||
341 | fn new_type_var(&mut self) -> Ty { | ||
342 | Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
343 | } | ||
344 | |||
345 | fn new_integer_var(&mut self) -> Ty { | ||
346 | Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
347 | } | ||
348 | |||
349 | fn new_float_var(&mut self) -> Ty { | ||
350 | Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
351 | } | ||
352 | |||
353 | fn new_maybe_never_type_var(&mut self) -> Ty { | ||
354 | Ty::Infer(InferTy::MaybeNeverTypeVar( | ||
355 | self.var_unification_table.new_key(TypeVarValue::Unknown), | ||
356 | )) | ||
357 | } | ||
358 | |||
359 | /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. | ||
360 | fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { | ||
361 | match ty { | ||
362 | Ty::Unknown => self.new_type_var(), | ||
363 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => { | ||
364 | self.new_integer_var() | ||
365 | } | ||
366 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => { | ||
367 | self.new_float_var() | ||
368 | } | ||
369 | _ => ty, | ||
370 | } | ||
371 | } | ||
372 | |||
373 | fn insert_type_vars(&mut self, ty: Ty) -> Ty { | ||
374 | ty.fold(&mut |ty| self.insert_type_vars_shallow(ty)) | ||
375 | } | ||
376 | |||
377 | fn resolve_obligations_as_possible(&mut self) { | ||
378 | let obligations = mem::replace(&mut self.obligations, Vec::new()); | ||
379 | for obligation in obligations { | ||
380 | let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone()); | ||
381 | let canonicalized = self.canonicalizer().canonicalize_obligation(in_env); | ||
382 | let solution = self | ||
383 | .db | ||
384 | .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone()); | ||
385 | |||
386 | match solution { | ||
387 | Some(Solution::Unique(substs)) => { | ||
388 | canonicalized.apply_solution(self, substs.0); | ||
389 | } | ||
390 | Some(Solution::Ambig(Guidance::Definite(substs))) => { | ||
391 | canonicalized.apply_solution(self, substs.0); | ||
392 | self.obligations.push(obligation); | ||
393 | } | ||
394 | Some(_) => { | ||
395 | // FIXME use this when trying to resolve everything at the end | ||
396 | self.obligations.push(obligation); | ||
397 | } | ||
398 | None => { | ||
399 | // FIXME obligation cannot be fulfilled => diagnostic | ||
400 | } | ||
401 | }; | ||
402 | } | ||
403 | } | ||
404 | |||
405 | /// Resolves the type as far as currently possible, replacing type variables | ||
406 | /// by their known types. All types returned by the infer_* functions should | ||
407 | /// be resolved as far as possible, i.e. contain no type variables with | ||
408 | /// known type. | ||
409 | fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
410 | self.resolve_obligations_as_possible(); | ||
411 | |||
412 | ty.fold(&mut |ty| match ty { | ||
413 | Ty::Infer(tv) => { | ||
414 | let inner = tv.to_inner(); | ||
415 | if tv_stack.contains(&inner) { | ||
416 | tested_by!(type_var_cycles_resolve_as_possible); | ||
417 | // recursive type | ||
418 | return tv.fallback_value(); | ||
419 | } | ||
420 | if let Some(known_ty) = | ||
421 | self.var_unification_table.inlined_probe_value(inner).known() | ||
422 | { | ||
423 | // known_ty may contain other variables that are known by now | ||
424 | tv_stack.push(inner); | ||
425 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | ||
426 | tv_stack.pop(); | ||
427 | result | ||
428 | } else { | ||
429 | ty | ||
430 | } | ||
431 | } | ||
432 | _ => ty, | ||
433 | }) | ||
434 | } | ||
435 | |||
436 | /// If `ty` is a type variable with known type, returns that type; | ||
437 | /// otherwise, return ty. | ||
438 | fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { | ||
439 | let mut ty = Cow::Borrowed(ty); | ||
440 | // The type variable could resolve to a int/float variable. Hence try | ||
441 | // resolving up to three times; each type of variable shouldn't occur | ||
442 | // more than once | ||
443 | for i in 0..3 { | ||
444 | if i > 0 { | ||
445 | tested_by!(type_var_resolves_to_int_var); | ||
446 | } | ||
447 | match &*ty { | ||
448 | Ty::Infer(tv) => { | ||
449 | let inner = tv.to_inner(); | ||
450 | match self.var_unification_table.inlined_probe_value(inner).known() { | ||
451 | Some(known_ty) => { | ||
452 | // The known_ty can't be a type var itself | ||
453 | ty = Cow::Owned(known_ty.clone()); | ||
454 | } | ||
455 | _ => return ty, | ||
456 | } | ||
457 | } | ||
458 | _ => return ty, | ||
459 | } | ||
460 | } | ||
461 | log::error!("Inference variable still not resolved: {:?}", ty); | ||
462 | ty | ||
463 | } | ||
464 | |||
465 | /// Recurses through the given type, normalizing associated types mentioned | ||
466 | /// in it by replacing them by type variables and registering obligations to | ||
467 | /// resolve later. This should be done once for every type we get from some | ||
468 | /// type annotation (e.g. from a let type annotation, field type or function | ||
469 | /// call). `make_ty` handles this already, but e.g. for field types we need | ||
470 | /// to do it as well. | ||
471 | fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { | ||
472 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
473 | ty.fold(&mut |ty| match ty { | ||
474 | Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), | ||
475 | _ => ty, | ||
476 | }) | ||
477 | } | ||
478 | |||
479 | fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { | ||
480 | let var = self.new_type_var(); | ||
481 | let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() }; | ||
482 | let obligation = Obligation::Projection(predicate); | ||
483 | self.obligations.push(obligation); | ||
484 | var | ||
485 | } | ||
486 | |||
487 | /// Resolves the type completely; type variables without known type are | ||
488 | /// replaced by Ty::Unknown. | ||
489 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
490 | ty.fold(&mut |ty| match ty { | ||
491 | Ty::Infer(tv) => { | ||
492 | let inner = tv.to_inner(); | ||
493 | if tv_stack.contains(&inner) { | ||
494 | tested_by!(type_var_cycles_resolve_completely); | ||
495 | // recursive type | ||
496 | return tv.fallback_value(); | ||
497 | } | ||
498 | if let Some(known_ty) = | ||
499 | self.var_unification_table.inlined_probe_value(inner).known() | ||
500 | { | ||
501 | // known_ty may contain other variables that are known by now | ||
502 | tv_stack.push(inner); | ||
503 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | ||
504 | tv_stack.pop(); | ||
505 | result | ||
506 | } else { | ||
507 | tv.fallback_value() | ||
508 | } | ||
509 | } | ||
510 | _ => ty, | ||
511 | }) | ||
512 | } | ||
513 | |||
514 | fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantId>) { | ||
515 | let path = match path { | ||
516 | Some(path) => path, | ||
517 | None => return (Ty::Unknown, None), | ||
518 | }; | ||
519 | let resolver = &self.resolver; | ||
520 | // FIXME: this should resolve assoc items as well, see this example: | ||
521 | // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 | ||
522 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | ||
523 | Some(TypeNs::AdtId(AdtId::StructId(strukt))) => { | ||
524 | let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into()); | ||
525 | let ty = self.db.ty(strukt.into()); | ||
526 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
527 | (ty, Some(strukt.into())) | ||
528 | } | ||
529 | Some(TypeNs::EnumVariantId(var)) => { | ||
530 | let substs = Ty::substs_from_path(self.db, resolver, path, var.into()); | ||
531 | let ty = self.db.ty(var.parent.into()); | ||
532 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
533 | (ty, Some(var.into())) | ||
534 | } | ||
535 | Some(_) | None => (Ty::Unknown, None), | ||
536 | } | ||
537 | } | ||
538 | |||
539 | fn collect_const(&mut self, data: &ConstData) { | ||
540 | self.return_ty = self.make_ty(&data.type_ref); | ||
541 | } | ||
542 | |||
543 | fn collect_fn(&mut self, data: &FunctionData) { | ||
544 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
545 | for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { | ||
546 | let ty = self.make_ty(type_ref); | ||
547 | |||
548 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
549 | } | ||
550 | self.return_ty = self.make_ty(&data.ret_type); | ||
551 | } | ||
552 | |||
553 | fn infer_body(&mut self) { | ||
554 | self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone())); | ||
555 | } | ||
556 | |||
557 | fn resolve_into_iter_item(&self) -> Option<TypeAliasId> { | ||
558 | let path = known::std_iter_into_iterator(); | ||
559 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
560 | self.db.trait_data(trait_).associated_type_by_name(&name::ITEM_TYPE) | ||
561 | } | ||
562 | |||
563 | fn resolve_ops_try_ok(&self) -> Option<TypeAliasId> { | ||
564 | let path = known::std_ops_try(); | ||
565 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
566 | self.db.trait_data(trait_).associated_type_by_name(&name::OK_TYPE) | ||
567 | } | ||
568 | |||
569 | fn resolve_future_future_output(&self) -> Option<TypeAliasId> { | ||
570 | let path = known::std_future_future(); | ||
571 | let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; | ||
572 | self.db.trait_data(trait_).associated_type_by_name(&name::OUTPUT_TYPE) | ||
573 | } | ||
574 | |||
575 | fn resolve_boxed_box(&self) -> Option<AdtId> { | ||
576 | let path = known::std_boxed_box(); | ||
577 | let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; | ||
578 | Some(struct_.into()) | ||
579 | } | ||
580 | } | ||
581 | |||
582 | /// The ID of a type variable. | ||
583 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | ||
584 | pub struct TypeVarId(pub(super) u32); | ||
585 | |||
586 | impl UnifyKey for TypeVarId { | ||
587 | type Value = TypeVarValue; | ||
588 | |||
589 | fn index(&self) -> u32 { | ||
590 | self.0 | ||
591 | } | ||
592 | |||
593 | fn from_index(i: u32) -> Self { | ||
594 | TypeVarId(i) | ||
595 | } | ||
596 | |||
597 | fn tag() -> &'static str { | ||
598 | "TypeVarId" | ||
599 | } | ||
600 | } | ||
601 | |||
602 | /// The value of a type variable: either we already know the type, or we don't | ||
603 | /// know it yet. | ||
604 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
605 | pub enum TypeVarValue { | ||
606 | Known(Ty), | ||
607 | Unknown, | ||
608 | } | ||
609 | |||
610 | impl TypeVarValue { | ||
611 | fn known(&self) -> Option<&Ty> { | ||
612 | match self { | ||
613 | TypeVarValue::Known(ty) => Some(ty), | ||
614 | TypeVarValue::Unknown => None, | ||
615 | } | ||
616 | } | ||
617 | } | ||
618 | |||
619 | impl UnifyValue for TypeVarValue { | ||
620 | type Error = NoError; | ||
621 | |||
622 | fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> { | ||
623 | match (value1, value2) { | ||
624 | // We should never equate two type variables, both of which have | ||
625 | // known types. Instead, we recursively equate those types. | ||
626 | (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!( | ||
627 | "equating two type variables, both of which have known types: {:?} and {:?}", | ||
628 | t1, t2 | ||
629 | ), | ||
630 | |||
631 | // If one side is known, prefer that one. | ||
632 | (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()), | ||
633 | (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()), | ||
634 | |||
635 | (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown), | ||
636 | } | ||
637 | } | ||
638 | } | ||
639 | |||
640 | /// The kinds of placeholders we need during type inference. There's separate | ||
641 | /// values for general types, and for integer and float variables. The latter | ||
642 | /// two are used for inference of literal values (e.g. `100` could be one of | ||
643 | /// several integer types). | ||
644 | #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] | ||
645 | pub enum InferTy { | ||
646 | TypeVar(TypeVarId), | ||
647 | IntVar(TypeVarId), | ||
648 | FloatVar(TypeVarId), | ||
649 | MaybeNeverTypeVar(TypeVarId), | ||
650 | } | ||
651 | |||
652 | impl InferTy { | ||
653 | fn to_inner(self) -> TypeVarId { | ||
654 | match self { | ||
655 | InferTy::TypeVar(ty) | ||
656 | | InferTy::IntVar(ty) | ||
657 | | InferTy::FloatVar(ty) | ||
658 | | InferTy::MaybeNeverTypeVar(ty) => ty, | ||
659 | } | ||
660 | } | ||
661 | |||
662 | fn fallback_value(self) -> Ty { | ||
663 | match self { | ||
664 | InferTy::TypeVar(..) => Ty::Unknown, | ||
665 | InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))), | ||
666 | InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))), | ||
667 | InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never), | ||
668 | } | ||
669 | } | ||
670 | } | ||
671 | |||
672 | /// When inferring an expression, we propagate downward whatever type hint we | ||
673 | /// are able in the form of an `Expectation`. | ||
674 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
675 | struct Expectation { | ||
676 | ty: Ty, | ||
677 | // FIXME: In some cases, we need to be aware whether the expectation is that | ||
678 | // the type match exactly what we passed, or whether it just needs to be | ||
679 | // coercible to the expected type. See Expectation::rvalue_hint in rustc. | ||
680 | } | ||
681 | |||
682 | impl Expectation { | ||
683 | /// The expectation that the type of the expression needs to equal the given | ||
684 | /// type. | ||
685 | fn has_type(ty: Ty) -> Self { | ||
686 | Expectation { ty } | ||
687 | } | ||
688 | |||
689 | /// This expresses no expectation on the type. | ||
690 | fn none() -> Self { | ||
691 | Expectation { ty: Ty::Unknown } | ||
692 | } | ||
693 | } | ||
694 | |||
695 | mod diagnostics { | ||
696 | use hir_def::{expr::ExprId, FunctionId, HasSource, Lookup}; | ||
697 | use hir_expand::diagnostics::DiagnosticSink; | ||
698 | |||
699 | use crate::{db::HirDatabase, diagnostics::NoSuchField}; | ||
700 | |||
701 | #[derive(Debug, PartialEq, Eq, Clone)] | ||
702 | pub(super) enum InferenceDiagnostic { | ||
703 | NoSuchField { expr: ExprId, field: usize }, | ||
704 | } | ||
705 | |||
706 | impl InferenceDiagnostic { | ||
707 | pub(super) fn add_to( | ||
708 | &self, | ||
709 | db: &impl HirDatabase, | ||
710 | owner: FunctionId, | ||
711 | sink: &mut DiagnosticSink, | ||
712 | ) { | ||
713 | match self { | ||
714 | InferenceDiagnostic::NoSuchField { expr, field } => { | ||
715 | let file = owner.lookup(db).source(db).file_id; | ||
716 | let (_, source_map) = db.body_with_source_map(owner.into()); | ||
717 | let field = source_map.field_syntax(*expr, *field); | ||
718 | sink.push(NoSuchField { file, field }) | ||
719 | } | ||
720 | } | ||
721 | } | ||
722 | } | ||
723 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs deleted file mode 100644 index 3fb5d8a83..000000000 --- a/crates/ra_hir/src/ty/infer/coerce.rs +++ /dev/null | |||
@@ -1,357 +0,0 @@ | |||
1 | //! Coercion logic. Coercions are certain type conversions that can implicitly | ||
2 | //! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions | ||
3 | //! like going from `&Vec<T>` to `&[T]`. | ||
4 | //! | ||
5 | //! See: https://doc.rust-lang.org/nomicon/coercions.html | ||
6 | |||
7 | use hir_def::{ | ||
8 | lang_item::LangItemTarget, | ||
9 | resolver::{HasResolver, Resolver}, | ||
10 | type_ref::Mutability, | ||
11 | AdtId, | ||
12 | }; | ||
13 | use rustc_hash::FxHashMap; | ||
14 | use test_utils::tested_by; | ||
15 | |||
16 | use crate::{ | ||
17 | db::HirDatabase, | ||
18 | ty::{autoderef, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, | ||
19 | }; | ||
20 | |||
21 | use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue}; | ||
22 | |||
23 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
24 | /// Unify two types, but may coerce the first one to the second one | ||
25 | /// using "implicit coercion rules" if needed. | ||
26 | pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
27 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
28 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
29 | self.coerce_inner(from_ty, &to_ty) | ||
30 | } | ||
31 | |||
32 | /// Merge two types from different branches, with possible implicit coerce. | ||
33 | /// | ||
34 | /// Note that it is only possible that one type are coerced to another. | ||
35 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
36 | /// which will simply result in "incompatible types" error. | ||
37 | pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
38 | if self.coerce(ty1, ty2) { | ||
39 | ty2.clone() | ||
40 | } else if self.coerce(ty2, ty1) { | ||
41 | ty1.clone() | ||
42 | } else { | ||
43 | tested_by!(coerce_merge_fail_fallback); | ||
44 | // For incompatible types, we use the latter one as result | ||
45 | // to be better recovery for `if` without `else`. | ||
46 | ty2.clone() | ||
47 | } | ||
48 | } | ||
49 | |||
50 | pub(super) fn init_coerce_unsized_map( | ||
51 | db: &'a D, | ||
52 | resolver: &Resolver, | ||
53 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
54 | let krate = resolver.krate().unwrap(); | ||
55 | let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) { | ||
56 | Some(LangItemTarget::TraitId(trait_)) => { | ||
57 | db.impls_for_trait(krate.into(), trait_.into()) | ||
58 | } | ||
59 | _ => return FxHashMap::default(), | ||
60 | }; | ||
61 | |||
62 | impls | ||
63 | .iter() | ||
64 | .filter_map(|&impl_id| { | ||
65 | let impl_data = db.impl_data(impl_id); | ||
66 | let resolver = impl_id.resolver(db); | ||
67 | let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); | ||
68 | |||
69 | // `CoerseUnsized` has one generic parameter for the target type. | ||
70 | let trait_ref = TraitRef::from_hir( | ||
71 | db, | ||
72 | &resolver, | ||
73 | impl_data.target_trait.as_ref()?, | ||
74 | Some(target_ty), | ||
75 | )?; | ||
76 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
77 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
78 | |||
79 | match (&cur_from_ty, cur_to_ty) { | ||
80 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
81 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
82 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
83 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
84 | match (ty1, ty2) { | ||
85 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
86 | if p1 != p2 => | ||
87 | { | ||
88 | Some(((*ctor1, *ctor2), i)) | ||
89 | } | ||
90 | _ => None, | ||
91 | } | ||
92 | }) | ||
93 | } | ||
94 | _ => None, | ||
95 | } | ||
96 | }) | ||
97 | .collect() | ||
98 | } | ||
99 | |||
100 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
101 | match (&from_ty, to_ty) { | ||
102 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
103 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
104 | let var = self.new_maybe_never_type_var(); | ||
105 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
106 | return true; | ||
107 | } | ||
108 | (ty_app!(TypeCtor::Never), _) => return true, | ||
109 | |||
110 | // Trivial cases, this should go after `never` check to | ||
111 | // avoid infer result type to be never | ||
112 | _ => { | ||
113 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
114 | return true; | ||
115 | } | ||
116 | } | ||
117 | } | ||
118 | |||
119 | // Pointer weakening and function to pointer | ||
120 | match (&mut from_ty, to_ty) { | ||
121 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
122 | // `&mut T` -> `&T` | ||
123 | // `&mut T` -> `*mut T` | ||
124 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
125 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
126 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
127 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
128 | *c1 = *c2; | ||
129 | } | ||
130 | |||
131 | // Illegal mutablity conversion | ||
132 | ( | ||
133 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
134 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
135 | ) | ||
136 | | ( | ||
137 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
138 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
139 | ) => return false, | ||
140 | |||
141 | // `{function_type}` -> `fn()` | ||
142 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
143 | match from_ty.callable_sig(self.db) { | ||
144 | None => return false, | ||
145 | Some(sig) => { | ||
146 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
147 | from_ty = | ||
148 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
149 | } | ||
150 | } | ||
151 | } | ||
152 | |||
153 | _ => {} | ||
154 | } | ||
155 | |||
156 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
157 | return ret; | ||
158 | } | ||
159 | |||
160 | // Auto Deref if cannot coerce | ||
161 | match (&from_ty, to_ty) { | ||
162 | // FIXME: DerefMut | ||
163 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
164 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
165 | } | ||
166 | |||
167 | // Otherwise, normal unify | ||
168 | _ => self.unify(&from_ty, to_ty), | ||
169 | } | ||
170 | } | ||
171 | |||
172 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
173 | /// | ||
174 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
175 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
176 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
177 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
178 | _ => return None, | ||
179 | }; | ||
180 | |||
181 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
182 | |||
183 | // Check `Unsize` first | ||
184 | match self.check_unsize_and_coerce( | ||
185 | st1.0.get(coerce_generic_index)?, | ||
186 | st2.0.get(coerce_generic_index)?, | ||
187 | 0, | ||
188 | ) { | ||
189 | Some(true) => {} | ||
190 | ret => return ret, | ||
191 | } | ||
192 | |||
193 | let ret = st1 | ||
194 | .iter() | ||
195 | .zip(st2.iter()) | ||
196 | .enumerate() | ||
197 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
198 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
199 | |||
200 | Some(ret) | ||
201 | } | ||
202 | |||
203 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
204 | /// | ||
205 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
206 | /// | ||
207 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
208 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
209 | if depth > 1000 { | ||
210 | panic!("Infinite recursion in coercion"); | ||
211 | } | ||
212 | |||
213 | match (&from_ty, &to_ty) { | ||
214 | // `[T; N]` -> `[T]` | ||
215 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
216 | Some(self.unify(&st1[0], &st2[0])) | ||
217 | } | ||
218 | |||
219 | // `T` -> `dyn Trait` when `T: Trait` | ||
220 | (_, Ty::Dyn(_)) => { | ||
221 | // FIXME: Check predicates | ||
222 | Some(true) | ||
223 | } | ||
224 | |||
225 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
226 | ( | ||
227 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
228 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
229 | ) => { | ||
230 | if len1 != len2 || *len1 == 0 { | ||
231 | return None; | ||
232 | } | ||
233 | |||
234 | match self.check_unsize_and_coerce( | ||
235 | st1.last().unwrap(), | ||
236 | st2.last().unwrap(), | ||
237 | depth + 1, | ||
238 | ) { | ||
239 | Some(true) => {} | ||
240 | ret => return ret, | ||
241 | } | ||
242 | |||
243 | let ret = st1[..st1.len() - 1] | ||
244 | .iter() | ||
245 | .zip(&st2[..st2.len() - 1]) | ||
246 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
247 | |||
248 | Some(ret) | ||
249 | } | ||
250 | |||
251 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
252 | // - T: Unsize<U> | ||
253 | // - Foo is a struct | ||
254 | // - Only the last field of Foo has a type involving T | ||
255 | // - T is not part of the type of any other fields | ||
256 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
257 | ( | ||
258 | ty_app!(TypeCtor::Adt(AdtId::StructId(struct1)), st1), | ||
259 | ty_app!(TypeCtor::Adt(AdtId::StructId(struct2)), st2), | ||
260 | ) if struct1 == struct2 => { | ||
261 | let field_tys = self.db.field_types((*struct1).into()); | ||
262 | let struct_data = self.db.struct_data(*struct1); | ||
263 | |||
264 | let mut fields = struct_data.variant_data.fields().iter(); | ||
265 | let (last_field_id, _data) = fields.next_back()?; | ||
266 | |||
267 | // Get the generic parameter involved in the last field. | ||
268 | let unsize_generic_index = { | ||
269 | let mut index = None; | ||
270 | let mut multiple_param = false; | ||
271 | field_tys[last_field_id].walk(&mut |ty| match ty { | ||
272 | &Ty::Param { idx, .. } => { | ||
273 | if index.is_none() { | ||
274 | index = Some(idx); | ||
275 | } else if Some(idx) != index { | ||
276 | multiple_param = true; | ||
277 | } | ||
278 | } | ||
279 | _ => {} | ||
280 | }); | ||
281 | |||
282 | if multiple_param { | ||
283 | return None; | ||
284 | } | ||
285 | index? | ||
286 | }; | ||
287 | |||
288 | // Check other fields do not involve it. | ||
289 | let mut multiple_used = false; | ||
290 | fields.for_each(|(field_id, _data)| { | ||
291 | field_tys[field_id].walk(&mut |ty| match ty { | ||
292 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
293 | multiple_used = true | ||
294 | } | ||
295 | _ => {} | ||
296 | }) | ||
297 | }); | ||
298 | if multiple_used { | ||
299 | return None; | ||
300 | } | ||
301 | |||
302 | let unsize_generic_index = unsize_generic_index as usize; | ||
303 | |||
304 | // Check `Unsize` first | ||
305 | match self.check_unsize_and_coerce( | ||
306 | st1.get(unsize_generic_index)?, | ||
307 | st2.get(unsize_generic_index)?, | ||
308 | depth + 1, | ||
309 | ) { | ||
310 | Some(true) => {} | ||
311 | ret => return ret, | ||
312 | } | ||
313 | |||
314 | // Then unify other parameters | ||
315 | let ret = st1 | ||
316 | .iter() | ||
317 | .zip(st2.iter()) | ||
318 | .enumerate() | ||
319 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
320 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
321 | |||
322 | Some(ret) | ||
323 | } | ||
324 | |||
325 | _ => None, | ||
326 | } | ||
327 | } | ||
328 | |||
329 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
330 | /// | ||
331 | /// Note that the parameters are already stripped the outer reference. | ||
332 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
333 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
334 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
335 | // FIXME: Auto DerefMut | ||
336 | for derefed_ty in autoderef::autoderef( | ||
337 | self.db, | ||
338 | self.resolver.krate(), | ||
339 | InEnvironment { | ||
340 | value: canonicalized.value.clone(), | ||
341 | environment: self.trait_env.clone(), | ||
342 | }, | ||
343 | ) { | ||
344 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
345 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
346 | // Stop when constructor matches. | ||
347 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
348 | // It will not recurse to `coerce`. | ||
349 | return self.unify_substs(st1, st2, 0); | ||
350 | } | ||
351 | _ => {} | ||
352 | } | ||
353 | } | ||
354 | |||
355 | false | ||
356 | } | ||
357 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs deleted file mode 100644 index f9ededa23..000000000 --- a/crates/ra_hir/src/ty/infer/expr.rs +++ /dev/null | |||
@@ -1,689 +0,0 @@ | |||
1 | //! Type inference for expressions. | ||
2 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | builtin_type::Signedness, | ||
8 | expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | ||
9 | generics::GenericParams, | ||
10 | path::{GenericArg, GenericArgs}, | ||
11 | resolver::resolver_for_expr, | ||
12 | AdtId, ContainerId, Lookup, StructFieldId, | ||
13 | }; | ||
14 | use hir_expand::name::{self, Name}; | ||
15 | |||
16 | use crate::{ | ||
17 | db::HirDatabase, | ||
18 | ty::{ | ||
19 | autoderef, method_resolution, op, traits::InEnvironment, utils::variant_data, CallableDef, | ||
20 | InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs, | ||
21 | TraitRef, Ty, TypeCtor, TypeWalk, Uncertain, | ||
22 | }, | ||
23 | }; | ||
24 | |||
25 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
26 | |||
27 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
28 | pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
29 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
30 | let could_unify = self.unify(&ty, &expected.ty); | ||
31 | if !could_unify { | ||
32 | self.result.type_mismatches.insert( | ||
33 | tgt_expr, | ||
34 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
35 | ); | ||
36 | } | ||
37 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
38 | ty | ||
39 | } | ||
40 | |||
41 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
42 | /// Return the type after possible coercion. | ||
43 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
44 | let ty = self.infer_expr_inner(expr, &expected); | ||
45 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
46 | self.result | ||
47 | .type_mismatches | ||
48 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
49 | // Return actual type when type mismatch. | ||
50 | // This is needed for diagnostic when return type mismatch. | ||
51 | ty | ||
52 | } else if expected.ty == Ty::Unknown { | ||
53 | ty | ||
54 | } else { | ||
55 | expected.ty.clone() | ||
56 | }; | ||
57 | |||
58 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
59 | } | ||
60 | |||
61 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
62 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
63 | let ty = match &body[tgt_expr] { | ||
64 | Expr::Missing => Ty::Unknown, | ||
65 | Expr::If { condition, then_branch, else_branch } => { | ||
66 | // if let is desugared to match, so this is always simple if | ||
67 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
68 | |||
69 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
70 | let else_ty = match else_branch { | ||
71 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
72 | None => Ty::unit(), | ||
73 | }; | ||
74 | |||
75 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
76 | } | ||
77 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
78 | Expr::TryBlock { body } => { | ||
79 | let _inner = self.infer_expr(*body, expected); | ||
80 | // FIXME should be std::result::Result<{inner}, _> | ||
81 | Ty::Unknown | ||
82 | } | ||
83 | Expr::Loop { body } => { | ||
84 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
85 | // FIXME handle break with value | ||
86 | Ty::simple(TypeCtor::Never) | ||
87 | } | ||
88 | Expr::While { condition, body } => { | ||
89 | // while let is desugared to a match loop, so this is always simple while | ||
90 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
91 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
92 | Ty::unit() | ||
93 | } | ||
94 | Expr::For { iterable, body, pat } => { | ||
95 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
96 | |||
97 | let pat_ty = match self.resolve_into_iter_item() { | ||
98 | Some(into_iter_item_alias) => { | ||
99 | let pat_ty = self.new_type_var(); | ||
100 | let projection = ProjectionPredicate { | ||
101 | ty: pat_ty.clone(), | ||
102 | projection_ty: ProjectionTy { | ||
103 | associated_ty: into_iter_item_alias, | ||
104 | parameters: Substs::single(iterable_ty), | ||
105 | }, | ||
106 | }; | ||
107 | self.obligations.push(Obligation::Projection(projection)); | ||
108 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
109 | } | ||
110 | None => Ty::Unknown, | ||
111 | }; | ||
112 | |||
113 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
114 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
115 | Ty::unit() | ||
116 | } | ||
117 | Expr::Lambda { body, args, arg_types } => { | ||
118 | assert_eq!(args.len(), arg_types.len()); | ||
119 | |||
120 | let mut sig_tys = Vec::new(); | ||
121 | |||
122 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
123 | let expected = if let Some(type_ref) = arg_type { | ||
124 | self.make_ty(type_ref) | ||
125 | } else { | ||
126 | Ty::Unknown | ||
127 | }; | ||
128 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
129 | sig_tys.push(arg_ty); | ||
130 | } | ||
131 | |||
132 | // add return type | ||
133 | let ret_ty = self.new_type_var(); | ||
134 | sig_tys.push(ret_ty.clone()); | ||
135 | let sig_ty = Ty::apply( | ||
136 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
137 | Substs(sig_tys.into()), | ||
138 | ); | ||
139 | let closure_ty = Ty::apply_one( | ||
140 | TypeCtor::Closure { def: self.owner.into(), expr: tgt_expr }, | ||
141 | sig_ty, | ||
142 | ); | ||
143 | |||
144 | // Eagerly try to relate the closure type with the expected | ||
145 | // type, otherwise we often won't have enough information to | ||
146 | // infer the body. | ||
147 | self.coerce(&closure_ty, &expected.ty); | ||
148 | |||
149 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
150 | closure_ty | ||
151 | } | ||
152 | Expr::Call { callee, args } => { | ||
153 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
154 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
155 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
156 | None => { | ||
157 | // Not callable | ||
158 | // FIXME: report an error | ||
159 | (Vec::new(), Ty::Unknown) | ||
160 | } | ||
161 | }; | ||
162 | self.register_obligations_for_call(&callee_ty); | ||
163 | self.check_call_arguments(args, ¶m_tys); | ||
164 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
165 | ret_ty | ||
166 | } | ||
167 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
168 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
169 | Expr::Match { expr, arms } => { | ||
170 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
171 | |||
172 | let mut result_ty = self.new_maybe_never_type_var(); | ||
173 | |||
174 | for arm in arms { | ||
175 | for &pat in &arm.pats { | ||
176 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
177 | } | ||
178 | if let Some(guard_expr) = arm.guard { | ||
179 | self.infer_expr( | ||
180 | guard_expr, | ||
181 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
182 | ); | ||
183 | } | ||
184 | |||
185 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
186 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
187 | } | ||
188 | |||
189 | result_ty | ||
190 | } | ||
191 | Expr::Path(p) => { | ||
192 | // FIXME this could be more efficient... | ||
193 | let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr); | ||
194 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
195 | } | ||
196 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
197 | Expr::Break { expr } => { | ||
198 | if let Some(expr) = expr { | ||
199 | // FIXME handle break with value | ||
200 | self.infer_expr(*expr, &Expectation::none()); | ||
201 | } | ||
202 | Ty::simple(TypeCtor::Never) | ||
203 | } | ||
204 | Expr::Return { expr } => { | ||
205 | if let Some(expr) = expr { | ||
206 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
207 | } | ||
208 | Ty::simple(TypeCtor::Never) | ||
209 | } | ||
210 | Expr::RecordLit { path, fields, spread } => { | ||
211 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
212 | if let Some(variant) = def_id { | ||
213 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
214 | } | ||
215 | |||
216 | self.unify(&ty, &expected.ty); | ||
217 | |||
218 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
219 | let field_types = | ||
220 | def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
221 | let variant_data = def_id.map(|it| variant_data(self.db, it)); | ||
222 | for (field_idx, field) in fields.iter().enumerate() { | ||
223 | let field_def = | ||
224 | variant_data.as_ref().and_then(|it| match it.field(&field.name) { | ||
225 | Some(local_id) => { | ||
226 | Some(StructFieldId { parent: def_id.unwrap(), local_id }) | ||
227 | } | ||
228 | None => { | ||
229 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
230 | expr: tgt_expr, | ||
231 | field: field_idx, | ||
232 | }); | ||
233 | None | ||
234 | } | ||
235 | }); | ||
236 | if let Some(field_def) = field_def { | ||
237 | self.result.record_field_resolutions.insert(field.expr, field_def); | ||
238 | } | ||
239 | let field_ty = field_def | ||
240 | .map_or(Ty::Unknown, |it| field_types[it.local_id].clone()) | ||
241 | .subst(&substs); | ||
242 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
243 | } | ||
244 | if let Some(expr) = spread { | ||
245 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
246 | } | ||
247 | ty | ||
248 | } | ||
249 | Expr::Field { expr, name } => { | ||
250 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
251 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
252 | let ty = autoderef::autoderef( | ||
253 | self.db, | ||
254 | self.resolver.krate(), | ||
255 | InEnvironment { | ||
256 | value: canonicalized.value.clone(), | ||
257 | environment: self.trait_env.clone(), | ||
258 | }, | ||
259 | ) | ||
260 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
261 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
262 | TypeCtor::Tuple { .. } => name | ||
263 | .as_tuple_index() | ||
264 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
265 | TypeCtor::Adt(AdtId::StructId(s)) => { | ||
266 | self.db.struct_data(s).variant_data.field(name).map(|local_id| { | ||
267 | let field = StructFieldId { parent: s.into(), local_id }.into(); | ||
268 | self.write_field_resolution(tgt_expr, field); | ||
269 | self.db.field_types(s.into())[field.local_id] | ||
270 | .clone() | ||
271 | .subst(&a_ty.parameters) | ||
272 | }) | ||
273 | } | ||
274 | // FIXME: | ||
275 | TypeCtor::Adt(AdtId::UnionId(_)) => None, | ||
276 | _ => None, | ||
277 | }, | ||
278 | _ => None, | ||
279 | }) | ||
280 | .unwrap_or(Ty::Unknown); | ||
281 | let ty = self.insert_type_vars(ty); | ||
282 | self.normalize_associated_types_in(ty) | ||
283 | } | ||
284 | Expr::Await { expr } => { | ||
285 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
286 | let ty = match self.resolve_future_future_output() { | ||
287 | Some(future_future_output_alias) => { | ||
288 | let ty = self.new_type_var(); | ||
289 | let projection = ProjectionPredicate { | ||
290 | ty: ty.clone(), | ||
291 | projection_ty: ProjectionTy { | ||
292 | associated_ty: future_future_output_alias, | ||
293 | parameters: Substs::single(inner_ty), | ||
294 | }, | ||
295 | }; | ||
296 | self.obligations.push(Obligation::Projection(projection)); | ||
297 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
298 | } | ||
299 | None => Ty::Unknown, | ||
300 | }; | ||
301 | ty | ||
302 | } | ||
303 | Expr::Try { expr } => { | ||
304 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
305 | let ty = match self.resolve_ops_try_ok() { | ||
306 | Some(ops_try_ok_alias) => { | ||
307 | let ty = self.new_type_var(); | ||
308 | let projection = ProjectionPredicate { | ||
309 | ty: ty.clone(), | ||
310 | projection_ty: ProjectionTy { | ||
311 | associated_ty: ops_try_ok_alias, | ||
312 | parameters: Substs::single(inner_ty), | ||
313 | }, | ||
314 | }; | ||
315 | self.obligations.push(Obligation::Projection(projection)); | ||
316 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
317 | } | ||
318 | None => Ty::Unknown, | ||
319 | }; | ||
320 | ty | ||
321 | } | ||
322 | Expr::Cast { expr, type_ref } => { | ||
323 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
324 | let cast_ty = self.make_ty(type_ref); | ||
325 | // FIXME check the cast... | ||
326 | cast_ty | ||
327 | } | ||
328 | Expr::Ref { expr, mutability } => { | ||
329 | let expectation = | ||
330 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
331 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
332 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
333 | // which cannot be coerced | ||
334 | } | ||
335 | Expectation::has_type(Ty::clone(exp_inner)) | ||
336 | } else { | ||
337 | Expectation::none() | ||
338 | }; | ||
339 | // FIXME reference coercions etc. | ||
340 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
341 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
342 | } | ||
343 | Expr::Box { expr } => { | ||
344 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
345 | if let Some(box_) = self.resolve_boxed_box() { | ||
346 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
347 | } else { | ||
348 | Ty::Unknown | ||
349 | } | ||
350 | } | ||
351 | Expr::UnaryOp { expr, op } => { | ||
352 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
353 | match op { | ||
354 | UnaryOp::Deref => match self.resolver.krate() { | ||
355 | Some(krate) => { | ||
356 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
357 | match autoderef::deref( | ||
358 | self.db, | ||
359 | krate, | ||
360 | InEnvironment { | ||
361 | value: &canonicalized.value, | ||
362 | environment: self.trait_env.clone(), | ||
363 | }, | ||
364 | ) { | ||
365 | Some(derefed_ty) => { | ||
366 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
367 | } | ||
368 | None => Ty::Unknown, | ||
369 | } | ||
370 | } | ||
371 | None => Ty::Unknown, | ||
372 | }, | ||
373 | UnaryOp::Neg => { | ||
374 | match &inner_ty { | ||
375 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
376 | TypeCtor::Int(Uncertain::Unknown) | ||
377 | | TypeCtor::Int(Uncertain::Known(IntTy { | ||
378 | signedness: Signedness::Signed, | ||
379 | .. | ||
380 | })) | ||
381 | | TypeCtor::Float(..) => inner_ty, | ||
382 | _ => Ty::Unknown, | ||
383 | }, | ||
384 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
385 | inner_ty | ||
386 | } | ||
387 | // FIXME: resolve ops::Neg trait | ||
388 | _ => Ty::Unknown, | ||
389 | } | ||
390 | } | ||
391 | UnaryOp::Not => { | ||
392 | match &inner_ty { | ||
393 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
394 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
395 | _ => Ty::Unknown, | ||
396 | }, | ||
397 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
398 | // FIXME: resolve ops::Not trait for inner_ty | ||
399 | _ => Ty::Unknown, | ||
400 | } | ||
401 | } | ||
402 | } | ||
403 | } | ||
404 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
405 | Some(op) => { | ||
406 | let lhs_expectation = match op { | ||
407 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
408 | _ => Expectation::none(), | ||
409 | }; | ||
410 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
411 | // FIXME: find implementation of trait corresponding to operation | ||
412 | // symbol and resolve associated `Output` type | ||
413 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
414 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
415 | |||
416 | // FIXME: similar as above, return ty is often associated trait type | ||
417 | op::binary_op_return_ty(*op, rhs_ty) | ||
418 | } | ||
419 | _ => Ty::Unknown, | ||
420 | }, | ||
421 | Expr::Index { base, index } => { | ||
422 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
423 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
424 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
425 | Ty::Unknown | ||
426 | } | ||
427 | Expr::Tuple { exprs } => { | ||
428 | let mut tys = match &expected.ty { | ||
429 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
430 | .iter() | ||
431 | .cloned() | ||
432 | .chain(repeat_with(|| self.new_type_var())) | ||
433 | .take(exprs.len()) | ||
434 | .collect::<Vec<_>>(), | ||
435 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
436 | }; | ||
437 | |||
438 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
439 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
440 | } | ||
441 | |||
442 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
443 | } | ||
444 | Expr::Array(array) => { | ||
445 | let elem_ty = match &expected.ty { | ||
446 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
447 | st.as_single().clone() | ||
448 | } | ||
449 | _ => self.new_type_var(), | ||
450 | }; | ||
451 | |||
452 | match array { | ||
453 | Array::ElementList(items) => { | ||
454 | for expr in items.iter() { | ||
455 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
456 | } | ||
457 | } | ||
458 | Array::Repeat { initializer, repeat } => { | ||
459 | self.infer_expr_coerce( | ||
460 | *initializer, | ||
461 | &Expectation::has_type(elem_ty.clone()), | ||
462 | ); | ||
463 | self.infer_expr( | ||
464 | *repeat, | ||
465 | &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known( | ||
466 | IntTy::usize(), | ||
467 | )))), | ||
468 | ); | ||
469 | } | ||
470 | } | ||
471 | |||
472 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
473 | } | ||
474 | Expr::Literal(lit) => match lit { | ||
475 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
476 | Literal::String(..) => { | ||
477 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
478 | } | ||
479 | Literal::ByteString(..) => { | ||
480 | let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8()))); | ||
481 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
482 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
483 | } | ||
484 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
485 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())), | ||
486 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())), | ||
487 | }, | ||
488 | }; | ||
489 | // use a new type variable if we got Ty::Unknown here | ||
490 | let ty = self.insert_type_vars_shallow(ty); | ||
491 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
492 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
493 | ty | ||
494 | } | ||
495 | |||
496 | fn infer_block( | ||
497 | &mut self, | ||
498 | statements: &[Statement], | ||
499 | tail: Option<ExprId>, | ||
500 | expected: &Expectation, | ||
501 | ) -> Ty { | ||
502 | let mut diverges = false; | ||
503 | for stmt in statements { | ||
504 | match stmt { | ||
505 | Statement::Let { pat, type_ref, initializer } => { | ||
506 | let decl_ty = | ||
507 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
508 | |||
509 | // Always use the declared type when specified | ||
510 | let mut ty = decl_ty.clone(); | ||
511 | |||
512 | if let Some(expr) = initializer { | ||
513 | let actual_ty = | ||
514 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
515 | if decl_ty == Ty::Unknown { | ||
516 | ty = actual_ty; | ||
517 | } | ||
518 | } | ||
519 | |||
520 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
521 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
522 | } | ||
523 | Statement::Expr(expr) => { | ||
524 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
525 | diverges = true; | ||
526 | } | ||
527 | } | ||
528 | } | ||
529 | } | ||
530 | |||
531 | let ty = if let Some(expr) = tail { | ||
532 | self.infer_expr_coerce(expr, expected) | ||
533 | } else { | ||
534 | self.coerce(&Ty::unit(), &expected.ty); | ||
535 | Ty::unit() | ||
536 | }; | ||
537 | if diverges { | ||
538 | Ty::simple(TypeCtor::Never) | ||
539 | } else { | ||
540 | ty | ||
541 | } | ||
542 | } | ||
543 | |||
544 | fn infer_method_call( | ||
545 | &mut self, | ||
546 | tgt_expr: ExprId, | ||
547 | receiver: ExprId, | ||
548 | args: &[ExprId], | ||
549 | method_name: &Name, | ||
550 | generic_args: Option<&GenericArgs>, | ||
551 | ) -> Ty { | ||
552 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
553 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
554 | let resolved = method_resolution::lookup_method( | ||
555 | &canonicalized_receiver.value, | ||
556 | self.db, | ||
557 | method_name, | ||
558 | &self.resolver, | ||
559 | ); | ||
560 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
561 | Some((ty, func)) => { | ||
562 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
563 | self.write_method_resolution(tgt_expr, func); | ||
564 | (ty, self.db.value_ty(func.into()), Some(self.db.generic_params(func.into()))) | ||
565 | } | ||
566 | None => (receiver_ty, Ty::Unknown, None), | ||
567 | }; | ||
568 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
569 | let method_ty = method_ty.apply_substs(substs); | ||
570 | let method_ty = self.insert_type_vars(method_ty); | ||
571 | self.register_obligations_for_call(&method_ty); | ||
572 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
573 | Some(sig) => { | ||
574 | if !sig.params().is_empty() { | ||
575 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
576 | } else { | ||
577 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
578 | } | ||
579 | } | ||
580 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
581 | }; | ||
582 | // Apply autoref so the below unification works correctly | ||
583 | // FIXME: return correct autorefs from lookup_method | ||
584 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
585 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
586 | _ => derefed_receiver_ty, | ||
587 | }; | ||
588 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
589 | |||
590 | self.check_call_arguments(args, ¶m_tys); | ||
591 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
592 | ret_ty | ||
593 | } | ||
594 | |||
595 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
596 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
597 | // We do this in a pretty awful way: first we type-check any arguments | ||
598 | // that are not closures, then we type-check the closures. This is so | ||
599 | // that we have more information about the types of arguments when we | ||
600 | // type-check the functions. This isn't really the right way to do this. | ||
601 | for &check_closures in &[false, true] { | ||
602 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
603 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
604 | let is_closure = match &self.body[arg] { | ||
605 | Expr::Lambda { .. } => true, | ||
606 | _ => false, | ||
607 | }; | ||
608 | |||
609 | if is_closure != check_closures { | ||
610 | continue; | ||
611 | } | ||
612 | |||
613 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
614 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
615 | } | ||
616 | } | ||
617 | } | ||
618 | |||
619 | fn substs_for_method_call( | ||
620 | &mut self, | ||
621 | def_generics: Option<Arc<GenericParams>>, | ||
622 | generic_args: Option<&GenericArgs>, | ||
623 | receiver_ty: &Ty, | ||
624 | ) -> Substs { | ||
625 | let (parent_param_count, param_count) = | ||
626 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
627 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
628 | // Parent arguments are unknown, except for the receiver type | ||
629 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
630 | for param in &parent_generics.params { | ||
631 | if param.name == name::SELF_TYPE { | ||
632 | substs.push(receiver_ty.clone()); | ||
633 | } else { | ||
634 | substs.push(Ty::Unknown); | ||
635 | } | ||
636 | } | ||
637 | } | ||
638 | // handle provided type arguments | ||
639 | if let Some(generic_args) = generic_args { | ||
640 | // if args are provided, it should be all of them, but we can't rely on that | ||
641 | for arg in generic_args.args.iter().take(param_count) { | ||
642 | match arg { | ||
643 | GenericArg::Type(type_ref) => { | ||
644 | let ty = self.make_ty(type_ref); | ||
645 | substs.push(ty); | ||
646 | } | ||
647 | } | ||
648 | } | ||
649 | }; | ||
650 | let supplied_params = substs.len(); | ||
651 | for _ in supplied_params..parent_param_count + param_count { | ||
652 | substs.push(Ty::Unknown); | ||
653 | } | ||
654 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
655 | Substs(substs.into()) | ||
656 | } | ||
657 | |||
658 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
659 | if let Ty::Apply(a_ty) = callable_ty { | ||
660 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
661 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
662 | for predicate in generic_predicates.iter() { | ||
663 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
664 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
665 | self.obligations.push(obligation); | ||
666 | } | ||
667 | } | ||
668 | // add obligation for trait implementation, if this is a trait method | ||
669 | match def { | ||
670 | CallableDef::FunctionId(f) => { | ||
671 | if let ContainerId::TraitId(trait_) = f.lookup(self.db).container { | ||
672 | // construct a TraitDef | ||
673 | let substs = a_ty.parameters.prefix( | ||
674 | self.db | ||
675 | .generic_params(trait_.into()) | ||
676 | .count_params_including_parent(), | ||
677 | ); | ||
678 | self.obligations.push(Obligation::Trait(TraitRef { | ||
679 | trait_: trait_.into(), | ||
680 | substs, | ||
681 | })); | ||
682 | } | ||
683 | } | ||
684 | CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {} | ||
685 | } | ||
686 | } | ||
687 | } | ||
688 | } | ||
689 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir/src/ty/infer/pat.rs deleted file mode 100644 index a14774607..000000000 --- a/crates/ra_hir/src/ty/infer/pat.rs +++ /dev/null | |||
@@ -1,189 +0,0 @@ | |||
1 | //! Type inference for patterns. | ||
2 | |||
3 | use std::iter::repeat; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, | ||
8 | path::Path, | ||
9 | type_ref::Mutability, | ||
10 | }; | ||
11 | use hir_expand::name::Name; | ||
12 | use test_utils::tested_by; | ||
13 | |||
14 | use super::{BindingMode, InferenceContext}; | ||
15 | use crate::{ | ||
16 | db::HirDatabase, | ||
17 | ty::{utils::variant_data, Substs, Ty, TypeCtor, TypeWalk}, | ||
18 | }; | ||
19 | |||
20 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
21 | fn infer_tuple_struct_pat( | ||
22 | &mut self, | ||
23 | path: Option<&Path>, | ||
24 | subpats: &[PatId], | ||
25 | expected: &Ty, | ||
26 | default_bm: BindingMode, | ||
27 | ) -> Ty { | ||
28 | let (ty, def) = self.resolve_variant(path); | ||
29 | let var_data = def.map(|it| variant_data(self.db, it)); | ||
30 | self.unify(&ty, expected); | ||
31 | |||
32 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
33 | |||
34 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
35 | |||
36 | for (i, &subpat) in subpats.iter().enumerate() { | ||
37 | let expected_ty = var_data | ||
38 | .as_ref() | ||
39 | .and_then(|d| d.field(&Name::new_tuple_field(i))) | ||
40 | .map_or(Ty::Unknown, |field| field_tys[field].clone()) | ||
41 | .subst(&substs); | ||
42 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
43 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
44 | } | ||
45 | |||
46 | ty | ||
47 | } | ||
48 | |||
49 | fn infer_record_pat( | ||
50 | &mut self, | ||
51 | path: Option<&Path>, | ||
52 | subpats: &[RecordFieldPat], | ||
53 | expected: &Ty, | ||
54 | default_bm: BindingMode, | ||
55 | id: PatId, | ||
56 | ) -> Ty { | ||
57 | let (ty, def) = self.resolve_variant(path); | ||
58 | let var_data = def.map(|it| variant_data(self.db, it)); | ||
59 | if let Some(variant) = def { | ||
60 | self.write_variant_resolution(id.into(), variant); | ||
61 | } | ||
62 | |||
63 | self.unify(&ty, expected); | ||
64 | |||
65 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
66 | |||
67 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
68 | for subpat in subpats { | ||
69 | let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name)); | ||
70 | let expected_ty = | ||
71 | matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs); | ||
72 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
73 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
74 | } | ||
75 | |||
76 | ty | ||
77 | } | ||
78 | |||
79 | pub(super) fn infer_pat( | ||
80 | &mut self, | ||
81 | pat: PatId, | ||
82 | mut expected: &Ty, | ||
83 | mut default_bm: BindingMode, | ||
84 | ) -> Ty { | ||
85 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
86 | |||
87 | let is_non_ref_pat = match &body[pat] { | ||
88 | Pat::Tuple(..) | ||
89 | | Pat::TupleStruct { .. } | ||
90 | | Pat::Record { .. } | ||
91 | | Pat::Range { .. } | ||
92 | | Pat::Slice { .. } => true, | ||
93 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
94 | Pat::Path(..) | Pat::Lit(..) => true, | ||
95 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
96 | }; | ||
97 | if is_non_ref_pat { | ||
98 | while let Some((inner, mutability)) = expected.as_reference() { | ||
99 | expected = inner; | ||
100 | default_bm = match default_bm { | ||
101 | BindingMode::Move => BindingMode::Ref(mutability), | ||
102 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
103 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
104 | } | ||
105 | } | ||
106 | } else if let Pat::Ref { .. } = &body[pat] { | ||
107 | tested_by!(match_ergonomics_ref); | ||
108 | // When you encounter a `&pat` pattern, reset to Move. | ||
109 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
110 | default_bm = BindingMode::Move; | ||
111 | } | ||
112 | |||
113 | // Lose mutability. | ||
114 | let default_bm = default_bm; | ||
115 | let expected = expected; | ||
116 | |||
117 | let ty = match &body[pat] { | ||
118 | Pat::Tuple(ref args) => { | ||
119 | let expectations = match expected.as_tuple() { | ||
120 | Some(parameters) => &*parameters.0, | ||
121 | _ => &[], | ||
122 | }; | ||
123 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
124 | |||
125 | let inner_tys = args | ||
126 | .iter() | ||
127 | .zip(expectations_iter) | ||
128 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
129 | .collect(); | ||
130 | |||
131 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
132 | } | ||
133 | Pat::Ref { pat, mutability } => { | ||
134 | let expectation = match expected.as_reference() { | ||
135 | Some((inner_ty, exp_mut)) => { | ||
136 | if *mutability != exp_mut { | ||
137 | // FIXME: emit type error? | ||
138 | } | ||
139 | inner_ty | ||
140 | } | ||
141 | _ => &Ty::Unknown, | ||
142 | }; | ||
143 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
144 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
145 | } | ||
146 | Pat::TupleStruct { path: p, args: subpats } => { | ||
147 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
148 | } | ||
149 | Pat::Record { path: p, args: fields } => { | ||
150 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
151 | } | ||
152 | Pat::Path(path) => { | ||
153 | // FIXME use correct resolver for the surrounding expression | ||
154 | let resolver = self.resolver.clone(); | ||
155 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
156 | } | ||
157 | Pat::Bind { mode, name: _, subpat } => { | ||
158 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
159 | default_bm | ||
160 | } else { | ||
161 | BindingMode::convert(*mode) | ||
162 | }; | ||
163 | let inner_ty = if let Some(subpat) = subpat { | ||
164 | self.infer_pat(*subpat, expected, default_bm) | ||
165 | } else { | ||
166 | expected.clone() | ||
167 | }; | ||
168 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
169 | |||
170 | let bound_ty = match mode { | ||
171 | BindingMode::Ref(mutability) => { | ||
172 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
173 | } | ||
174 | BindingMode::Move => inner_ty.clone(), | ||
175 | }; | ||
176 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
177 | self.write_pat_ty(pat, bound_ty); | ||
178 | return inner_ty; | ||
179 | } | ||
180 | _ => Ty::Unknown, | ||
181 | }; | ||
182 | // use a new type variable if we got Ty::Unknown here | ||
183 | let ty = self.insert_type_vars_shallow(ty); | ||
184 | self.unify(&ty, expected); | ||
185 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
186 | self.write_pat_ty(pat, ty.clone()); | ||
187 | ty | ||
188 | } | ||
189 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs deleted file mode 100644 index 09ff79728..000000000 --- a/crates/ra_hir/src/ty/infer/path.rs +++ /dev/null | |||
@@ -1,273 +0,0 @@ | |||
1 | //! Path expression resolution. | ||
2 | |||
3 | use hir_def::{ | ||
4 | path::{Path, PathSegment}, | ||
5 | resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, | ||
6 | AssocItemId, ContainerId, Lookup, | ||
7 | }; | ||
8 | use hir_expand::name::Name; | ||
9 | |||
10 | use crate::{ | ||
11 | db::HirDatabase, | ||
12 | ty::{method_resolution, Substs, Ty, TypeWalk, ValueTyDefId}, | ||
13 | }; | ||
14 | |||
15 | use super::{ExprOrPatId, InferenceContext, TraitRef}; | ||
16 | |||
17 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
18 | pub(super) fn infer_path( | ||
19 | &mut self, | ||
20 | resolver: &Resolver, | ||
21 | path: &Path, | ||
22 | id: ExprOrPatId, | ||
23 | ) -> Option<Ty> { | ||
24 | let ty = self.resolve_value_path(resolver, path, id)?; | ||
25 | let ty = self.insert_type_vars(ty); | ||
26 | let ty = self.normalize_associated_types_in(ty); | ||
27 | Some(ty) | ||
28 | } | ||
29 | |||
30 | fn resolve_value_path( | ||
31 | &mut self, | ||
32 | resolver: &Resolver, | ||
33 | path: &Path, | ||
34 | id: ExprOrPatId, | ||
35 | ) -> Option<Ty> { | ||
36 | let (value, self_subst) = if let crate::PathKind::Type(type_ref) = &path.kind { | ||
37 | if path.segments.is_empty() { | ||
38 | // This can't actually happen syntax-wise | ||
39 | return None; | ||
40 | } | ||
41 | let ty = self.make_ty(type_ref); | ||
42 | let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1]; | ||
43 | let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); | ||
44 | self.resolve_ty_assoc_item( | ||
45 | ty, | ||
46 | &path.segments.last().expect("path had at least one segment").name, | ||
47 | id, | ||
48 | )? | ||
49 | } else { | ||
50 | let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?; | ||
51 | |||
52 | match value_or_partial { | ||
53 | ResolveValueResult::ValueNs(it) => (it, None), | ||
54 | ResolveValueResult::Partial(def, remaining_index) => { | ||
55 | self.resolve_assoc_item(def, path, remaining_index, id)? | ||
56 | } | ||
57 | } | ||
58 | }; | ||
59 | |||
60 | let typable: ValueTyDefId = match value { | ||
61 | ValueNs::LocalBinding(pat) => { | ||
62 | let ty = self.result.type_of_pat.get(pat)?.clone(); | ||
63 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
64 | return Some(ty); | ||
65 | } | ||
66 | ValueNs::FunctionId(it) => it.into(), | ||
67 | ValueNs::ConstId(it) => it.into(), | ||
68 | ValueNs::StaticId(it) => it.into(), | ||
69 | ValueNs::StructId(it) => it.into(), | ||
70 | ValueNs::EnumVariantId(it) => it.into(), | ||
71 | }; | ||
72 | |||
73 | let mut ty = self.db.value_ty(typable); | ||
74 | if let Some(self_subst) = self_subst { | ||
75 | ty = ty.subst(&self_subst); | ||
76 | } | ||
77 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); | ||
78 | let ty = ty.subst(&substs); | ||
79 | Some(ty) | ||
80 | } | ||
81 | |||
82 | fn resolve_assoc_item( | ||
83 | &mut self, | ||
84 | def: TypeNs, | ||
85 | path: &Path, | ||
86 | remaining_index: usize, | ||
87 | id: ExprOrPatId, | ||
88 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
89 | assert!(remaining_index < path.segments.len()); | ||
90 | // there may be more intermediate segments between the resolved one and | ||
91 | // the end. Only the last segment needs to be resolved to a value; from | ||
92 | // the segments before that, we need to get either a type or a trait ref. | ||
93 | |||
94 | let resolved_segment = &path.segments[remaining_index - 1]; | ||
95 | let remaining_segments = &path.segments[remaining_index..]; | ||
96 | let is_before_last = remaining_segments.len() == 1; | ||
97 | |||
98 | match (def, is_before_last) { | ||
99 | (TypeNs::TraitId(trait_), true) => { | ||
100 | let segment = | ||
101 | remaining_segments.last().expect("there should be at least one segment here"); | ||
102 | let trait_ref = TraitRef::from_resolved_path( | ||
103 | self.db, | ||
104 | &self.resolver, | ||
105 | trait_.into(), | ||
106 | resolved_segment, | ||
107 | None, | ||
108 | ); | ||
109 | self.resolve_trait_assoc_item(trait_ref, segment, id) | ||
110 | } | ||
111 | (def, _) => { | ||
112 | // Either we already have a type (e.g. `Vec::new`), or we have a | ||
113 | // trait but it's not the last segment, so the next segment | ||
114 | // should resolve to an associated type of that trait (e.g. `<T | ||
115 | // as Iterator>::Item::default`) | ||
116 | let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1]; | ||
117 | let ty = Ty::from_partly_resolved_hir_path( | ||
118 | self.db, | ||
119 | &self.resolver, | ||
120 | def, | ||
121 | resolved_segment, | ||
122 | remaining_segments_for_ty, | ||
123 | ); | ||
124 | if let Ty::Unknown = ty { | ||
125 | return None; | ||
126 | } | ||
127 | |||
128 | let ty = self.insert_type_vars(ty); | ||
129 | let ty = self.normalize_associated_types_in(ty); | ||
130 | |||
131 | let segment = | ||
132 | remaining_segments.last().expect("there should be at least one segment here"); | ||
133 | |||
134 | self.resolve_ty_assoc_item(ty, &segment.name, id) | ||
135 | } | ||
136 | } | ||
137 | } | ||
138 | |||
139 | fn resolve_trait_assoc_item( | ||
140 | &mut self, | ||
141 | trait_ref: TraitRef, | ||
142 | segment: &PathSegment, | ||
143 | id: ExprOrPatId, | ||
144 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
145 | let trait_ = trait_ref.trait_; | ||
146 | let item = self | ||
147 | .db | ||
148 | .trait_data(trait_) | ||
149 | .items | ||
150 | .iter() | ||
151 | .map(|(_name, id)| (*id).into()) | ||
152 | .find_map(|item| match item { | ||
153 | AssocItemId::FunctionId(func) => { | ||
154 | if segment.name == self.db.function_data(func).name { | ||
155 | Some(AssocItemId::FunctionId(func)) | ||
156 | } else { | ||
157 | None | ||
158 | } | ||
159 | } | ||
160 | |||
161 | AssocItemId::ConstId(konst) => { | ||
162 | if self.db.const_data(konst).name.as_ref().map_or(false, |n| n == &segment.name) | ||
163 | { | ||
164 | Some(AssocItemId::ConstId(konst)) | ||
165 | } else { | ||
166 | None | ||
167 | } | ||
168 | } | ||
169 | AssocItemId::TypeAliasId(_) => None, | ||
170 | })?; | ||
171 | let def = match item { | ||
172 | AssocItemId::FunctionId(f) => ValueNs::FunctionId(f), | ||
173 | AssocItemId::ConstId(c) => ValueNs::ConstId(c), | ||
174 | AssocItemId::TypeAliasId(_) => unreachable!(), | ||
175 | }; | ||
176 | let substs = Substs::build_for_def(self.db, item) | ||
177 | .use_parent_substs(&trait_ref.substs) | ||
178 | .fill_with_params() | ||
179 | .build(); | ||
180 | |||
181 | self.write_assoc_resolution(id, item); | ||
182 | Some((def, Some(substs))) | ||
183 | } | ||
184 | |||
185 | fn resolve_ty_assoc_item( | ||
186 | &mut self, | ||
187 | ty: Ty, | ||
188 | name: &Name, | ||
189 | id: ExprOrPatId, | ||
190 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
191 | if let Ty::Unknown = ty { | ||
192 | return None; | ||
193 | } | ||
194 | |||
195 | let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); | ||
196 | |||
197 | method_resolution::iterate_method_candidates( | ||
198 | &canonical_ty.value, | ||
199 | self.db, | ||
200 | &self.resolver.clone(), | ||
201 | Some(name), | ||
202 | method_resolution::LookupMode::Path, | ||
203 | move |_ty, item| { | ||
204 | let (def, container) = match item { | ||
205 | AssocItemId::FunctionId(f) => { | ||
206 | (ValueNs::FunctionId(f), f.lookup(self.db).container) | ||
207 | } | ||
208 | AssocItemId::ConstId(c) => (ValueNs::ConstId(c), c.lookup(self.db).container), | ||
209 | AssocItemId::TypeAliasId(_) => unreachable!(), | ||
210 | }; | ||
211 | let substs = match container { | ||
212 | ContainerId::ImplId(_) => self.find_self_types(&def, ty.clone()), | ||
213 | ContainerId::TraitId(trait_) => { | ||
214 | // we're picking this method | ||
215 | let trait_substs = Substs::build_for_def(self.db, trait_) | ||
216 | .push(ty.clone()) | ||
217 | .fill(std::iter::repeat_with(|| self.new_type_var())) | ||
218 | .build(); | ||
219 | let substs = Substs::build_for_def(self.db, item) | ||
220 | .use_parent_substs(&trait_substs) | ||
221 | .fill_with_params() | ||
222 | .build(); | ||
223 | self.obligations.push(super::Obligation::Trait(TraitRef { | ||
224 | trait_, | ||
225 | substs: trait_substs, | ||
226 | })); | ||
227 | Some(substs) | ||
228 | } | ||
229 | ContainerId::ModuleId(_) => None, | ||
230 | }; | ||
231 | |||
232 | self.write_assoc_resolution(id, item.into()); | ||
233 | Some((def, substs)) | ||
234 | }, | ||
235 | ) | ||
236 | } | ||
237 | |||
238 | fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option<Substs> { | ||
239 | if let ValueNs::FunctionId(func) = *def { | ||
240 | // We only do the infer if parent has generic params | ||
241 | let gen = self.db.generic_params(func.into()); | ||
242 | if gen.count_parent_params() == 0 { | ||
243 | return None; | ||
244 | } | ||
245 | |||
246 | let impl_id = match func.lookup(self.db).container { | ||
247 | ContainerId::ImplId(it) => it, | ||
248 | _ => return None, | ||
249 | }; | ||
250 | let resolver = impl_id.resolver(self.db); | ||
251 | let impl_data = self.db.impl_data(impl_id); | ||
252 | let impl_block = Ty::from_hir(self.db, &resolver, &impl_data.target_type); | ||
253 | let impl_block_substs = impl_block.substs()?; | ||
254 | let actual_substs = actual_def_ty.substs()?; | ||
255 | |||
256 | let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; | ||
257 | |||
258 | // The following code *link up* the function actual parma type | ||
259 | // and impl_block type param index | ||
260 | impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { | ||
261 | if let Ty::Param { idx, .. } = param { | ||
262 | if let Some(s) = new_substs.get_mut(*idx as usize) { | ||
263 | *s = pty.clone(); | ||
264 | } | ||
265 | } | ||
266 | }); | ||
267 | |||
268 | Some(Substs(new_substs.into())) | ||
269 | } else { | ||
270 | None | ||
271 | } | ||
272 | } | ||
273 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs deleted file mode 100644 index e27bb2f82..000000000 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ /dev/null | |||
@@ -1,166 +0,0 @@ | |||
1 | //! Unification and canonicalization logic. | ||
2 | |||
3 | use super::{InferenceContext, Obligation}; | ||
4 | use crate::{ | ||
5 | db::HirDatabase, | ||
6 | ty::{ | ||
7 | Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, | ||
8 | TypeWalk, | ||
9 | }, | ||
10 | util::make_mut_slice, | ||
11 | }; | ||
12 | |||
13 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
14 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> | ||
15 | where | ||
16 | 'a: 'b, | ||
17 | { | ||
18 | Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } | ||
19 | } | ||
20 | } | ||
21 | |||
22 | pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> | ||
23 | where | ||
24 | 'a: 'b, | ||
25 | { | ||
26 | ctx: &'b mut InferenceContext<'a, D>, | ||
27 | free_vars: Vec<InferTy>, | ||
28 | /// A stack of type variables that is used to detect recursive types (which | ||
29 | /// are an error, but we need to protect against them to avoid stack | ||
30 | /// overflows). | ||
31 | var_stack: Vec<super::TypeVarId>, | ||
32 | } | ||
33 | |||
34 | pub(super) struct Canonicalized<T> { | ||
35 | pub value: Canonical<T>, | ||
36 | free_vars: Vec<InferTy>, | ||
37 | } | ||
38 | |||
39 | impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> | ||
40 | where | ||
41 | 'a: 'b, | ||
42 | { | ||
43 | fn add(&mut self, free_var: InferTy) -> usize { | ||
44 | self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { | ||
45 | let next_index = self.free_vars.len(); | ||
46 | self.free_vars.push(free_var); | ||
47 | next_index | ||
48 | }) | ||
49 | } | ||
50 | |||
51 | fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { | ||
52 | ty.fold(&mut |ty| match ty { | ||
53 | Ty::Infer(tv) => { | ||
54 | let inner = tv.to_inner(); | ||
55 | if self.var_stack.contains(&inner) { | ||
56 | // recursive type | ||
57 | return tv.fallback_value(); | ||
58 | } | ||
59 | if let Some(known_ty) = | ||
60 | self.ctx.var_unification_table.inlined_probe_value(inner).known() | ||
61 | { | ||
62 | self.var_stack.push(inner); | ||
63 | let result = self.do_canonicalize_ty(known_ty.clone()); | ||
64 | self.var_stack.pop(); | ||
65 | result | ||
66 | } else { | ||
67 | let root = self.ctx.var_unification_table.find(inner); | ||
68 | let free_var = match tv { | ||
69 | InferTy::TypeVar(_) => InferTy::TypeVar(root), | ||
70 | InferTy::IntVar(_) => InferTy::IntVar(root), | ||
71 | InferTy::FloatVar(_) => InferTy::FloatVar(root), | ||
72 | InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root), | ||
73 | }; | ||
74 | let position = self.add(free_var); | ||
75 | Ty::Bound(position as u32) | ||
76 | } | ||
77 | } | ||
78 | _ => ty, | ||
79 | }) | ||
80 | } | ||
81 | |||
82 | fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { | ||
83 | for ty in make_mut_slice(&mut trait_ref.substs.0) { | ||
84 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
85 | } | ||
86 | trait_ref | ||
87 | } | ||
88 | |||
89 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { | ||
90 | Canonicalized { | ||
91 | value: Canonical { value: result, num_vars: self.free_vars.len() }, | ||
92 | free_vars: self.free_vars, | ||
93 | } | ||
94 | } | ||
95 | |||
96 | fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { | ||
97 | for ty in make_mut_slice(&mut projection_ty.parameters.0) { | ||
98 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
99 | } | ||
100 | projection_ty | ||
101 | } | ||
102 | |||
103 | fn do_canonicalize_projection_predicate( | ||
104 | &mut self, | ||
105 | projection: ProjectionPredicate, | ||
106 | ) -> ProjectionPredicate { | ||
107 | let ty = self.do_canonicalize_ty(projection.ty); | ||
108 | let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty); | ||
109 | |||
110 | ProjectionPredicate { ty, projection_ty } | ||
111 | } | ||
112 | |||
113 | // FIXME: add some point, we need to introduce a `Fold` trait that abstracts | ||
114 | // over all the things that can be canonicalized (like Chalk and rustc have) | ||
115 | |||
116 | pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized<Ty> { | ||
117 | let result = self.do_canonicalize_ty(ty); | ||
118 | self.into_canonicalized(result) | ||
119 | } | ||
120 | |||
121 | pub(crate) fn canonicalize_obligation( | ||
122 | mut self, | ||
123 | obligation: InEnvironment<Obligation>, | ||
124 | ) -> Canonicalized<InEnvironment<Obligation>> { | ||
125 | let result = match obligation.value { | ||
126 | Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)), | ||
127 | Obligation::Projection(pr) => { | ||
128 | Obligation::Projection(self.do_canonicalize_projection_predicate(pr)) | ||
129 | } | ||
130 | }; | ||
131 | self.into_canonicalized(InEnvironment { | ||
132 | value: result, | ||
133 | environment: obligation.environment, | ||
134 | }) | ||
135 | } | ||
136 | } | ||
137 | |||
138 | impl<T> Canonicalized<T> { | ||
139 | pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { | ||
140 | ty.walk_mut_binders( | ||
141 | &mut |ty, binders| match ty { | ||
142 | &mut Ty::Bound(idx) => { | ||
143 | if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { | ||
144 | *ty = Ty::Infer(self.free_vars[idx as usize - binders]); | ||
145 | } | ||
146 | } | ||
147 | _ => {} | ||
148 | }, | ||
149 | 0, | ||
150 | ); | ||
151 | ty | ||
152 | } | ||
153 | |||
154 | pub fn apply_solution( | ||
155 | &self, | ||
156 | ctx: &mut InferenceContext<'_, impl HirDatabase>, | ||
157 | solution: Canonical<Vec<Ty>>, | ||
158 | ) { | ||
159 | // the solution may contain new variables, which we need to convert to new inference vars | ||
160 | let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect()); | ||
161 | for (i, ty) in solution.value.into_iter().enumerate() { | ||
162 | let var = self.free_vars[i]; | ||
163 | ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); | ||
164 | } | ||
165 | } | ||
166 | } | ||
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs deleted file mode 100644 index 2d447f1ea..000000000 --- a/crates/ra_hir/src/ty/lower.rs +++ /dev/null | |||
@@ -1,755 +0,0 @@ | |||
1 | //! Methods for lowering the HIR to types. There are two main cases here: | ||
2 | //! | ||
3 | //! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a | ||
4 | //! type: The entry point for this is `Ty::from_hir`. | ||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | ||
6 | //! | ||
7 | //! This usually involves resolving names, collecting generic arguments etc. | ||
8 | use std::iter; | ||
9 | use std::sync::Arc; | ||
10 | |||
11 | use hir_def::{ | ||
12 | builtin_type::BuiltinType, | ||
13 | generics::WherePredicate, | ||
14 | path::{GenericArg, Path, PathSegment}, | ||
15 | resolver::{HasResolver, Resolver, TypeNs}, | ||
16 | type_ref::{TypeBound, TypeRef}, | ||
17 | AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, | ||
18 | LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, | ||
19 | }; | ||
20 | use ra_arena::map::ArenaMap; | ||
21 | use ra_db::CrateId; | ||
22 | |||
23 | use super::{ | ||
24 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, | ||
25 | Ty, TypeCtor, TypeWalk, | ||
26 | }; | ||
27 | use crate::{ | ||
28 | db::HirDatabase, | ||
29 | ty::{ | ||
30 | primitive::{FloatTy, IntTy}, | ||
31 | utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data}, | ||
32 | }, | ||
33 | util::make_mut_slice, | ||
34 | }; | ||
35 | |||
36 | impl Ty { | ||
37 | pub(crate) fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { | ||
38 | match type_ref { | ||
39 | TypeRef::Never => Ty::simple(TypeCtor::Never), | ||
40 | TypeRef::Tuple(inner) => { | ||
41 | let inner_tys: Arc<[Ty]> = | ||
42 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); | ||
43 | Ty::apply( | ||
44 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, | ||
45 | Substs(inner_tys), | ||
46 | ) | ||
47 | } | ||
48 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), | ||
49 | TypeRef::RawPtr(inner, mutability) => { | ||
50 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
51 | Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) | ||
52 | } | ||
53 | TypeRef::Array(inner) => { | ||
54 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
55 | Ty::apply_one(TypeCtor::Array, inner_ty) | ||
56 | } | ||
57 | TypeRef::Slice(inner) => { | ||
58 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
59 | Ty::apply_one(TypeCtor::Slice, inner_ty) | ||
60 | } | ||
61 | TypeRef::Reference(inner, mutability) => { | ||
62 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
63 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
64 | } | ||
65 | TypeRef::Placeholder => Ty::Unknown, | ||
66 | TypeRef::Fn(params) => { | ||
67 | let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); | ||
68 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) | ||
69 | } | ||
70 | TypeRef::DynTrait(bounds) => { | ||
71 | let self_ty = Ty::Bound(0); | ||
72 | let predicates = bounds | ||
73 | .iter() | ||
74 | .flat_map(|b| { | ||
75 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
76 | }) | ||
77 | .collect(); | ||
78 | Ty::Dyn(predicates) | ||
79 | } | ||
80 | TypeRef::ImplTrait(bounds) => { | ||
81 | let self_ty = Ty::Bound(0); | ||
82 | let predicates = bounds | ||
83 | .iter() | ||
84 | .flat_map(|b| { | ||
85 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
86 | }) | ||
87 | .collect(); | ||
88 | Ty::Opaque(predicates) | ||
89 | } | ||
90 | TypeRef::Error => Ty::Unknown, | ||
91 | } | ||
92 | } | ||
93 | |||
94 | /// This is only for `generic_predicates_for_param`, where we can't just | ||
95 | /// lower the self types of the predicates since that could lead to cycles. | ||
96 | /// So we just check here if the `type_ref` resolves to a generic param, and which. | ||
97 | fn from_hir_only_param( | ||
98 | db: &impl HirDatabase, | ||
99 | resolver: &Resolver, | ||
100 | type_ref: &TypeRef, | ||
101 | ) -> Option<u32> { | ||
102 | let path = match type_ref { | ||
103 | TypeRef::Path(path) => path, | ||
104 | _ => return None, | ||
105 | }; | ||
106 | if let crate::PathKind::Type(_) = &path.kind { | ||
107 | return None; | ||
108 | } | ||
109 | if path.segments.len() > 1 { | ||
110 | return None; | ||
111 | } | ||
112 | let resolution = match resolver.resolve_path_in_type_ns(db, path) { | ||
113 | Some((it, None)) => it, | ||
114 | _ => return None, | ||
115 | }; | ||
116 | if let TypeNs::GenericParam(idx) = resolution { | ||
117 | Some(idx) | ||
118 | } else { | ||
119 | None | ||
120 | } | ||
121 | } | ||
122 | |||
123 | pub(crate) fn from_type_relative_path( | ||
124 | db: &impl HirDatabase, | ||
125 | resolver: &Resolver, | ||
126 | ty: Ty, | ||
127 | remaining_segments: &[PathSegment], | ||
128 | ) -> Ty { | ||
129 | if remaining_segments.len() == 1 { | ||
130 | // resolve unselected assoc types | ||
131 | let segment = &remaining_segments[0]; | ||
132 | Ty::select_associated_type(db, resolver, ty, segment) | ||
133 | } else if remaining_segments.len() > 1 { | ||
134 | // FIXME report error (ambiguous associated type) | ||
135 | Ty::Unknown | ||
136 | } else { | ||
137 | ty | ||
138 | } | ||
139 | } | ||
140 | |||
141 | pub(crate) fn from_partly_resolved_hir_path( | ||
142 | db: &impl HirDatabase, | ||
143 | resolver: &Resolver, | ||
144 | resolution: TypeNs, | ||
145 | resolved_segment: &PathSegment, | ||
146 | remaining_segments: &[PathSegment], | ||
147 | ) -> Ty { | ||
148 | let ty = match resolution { | ||
149 | TypeNs::TraitId(trait_) => { | ||
150 | let trait_ref = | ||
151 | TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None); | ||
152 | return if remaining_segments.len() == 1 { | ||
153 | let segment = &remaining_segments[0]; | ||
154 | let associated_ty = associated_type_by_name_including_super_traits( | ||
155 | db, | ||
156 | trait_ref.trait_, | ||
157 | &segment.name, | ||
158 | ); | ||
159 | match associated_ty { | ||
160 | Some(associated_ty) => { | ||
161 | // FIXME handle type parameters on the segment | ||
162 | Ty::Projection(ProjectionTy { | ||
163 | associated_ty, | ||
164 | parameters: trait_ref.substs, | ||
165 | }) | ||
166 | } | ||
167 | None => { | ||
168 | // FIXME: report error (associated type not found) | ||
169 | Ty::Unknown | ||
170 | } | ||
171 | } | ||
172 | } else if remaining_segments.len() > 1 { | ||
173 | // FIXME report error (ambiguous associated type) | ||
174 | Ty::Unknown | ||
175 | } else { | ||
176 | Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) | ||
177 | }; | ||
178 | } | ||
179 | TypeNs::GenericParam(idx) => { | ||
180 | // FIXME: maybe return name in resolution? | ||
181 | let name = resolved_segment.name.clone(); | ||
182 | Ty::Param { idx, name } | ||
183 | } | ||
184 | TypeNs::SelfType(impl_id) => { | ||
185 | let impl_data = db.impl_data(impl_id); | ||
186 | let resolver = impl_id.resolver(db); | ||
187 | Ty::from_hir(db, &resolver, &impl_data.target_type) | ||
188 | } | ||
189 | TypeNs::AdtSelfType(adt) => db.ty(adt.into()), | ||
190 | |||
191 | TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), | ||
192 | TypeNs::BuiltinType(it) => { | ||
193 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
194 | } | ||
195 | TypeNs::TypeAliasId(it) => { | ||
196 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
197 | } | ||
198 | // FIXME: report error | ||
199 | TypeNs::EnumVariantId(_) => return Ty::Unknown, | ||
200 | }; | ||
201 | |||
202 | Ty::from_type_relative_path(db, resolver, ty, remaining_segments) | ||
203 | } | ||
204 | |||
205 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { | ||
206 | // Resolve the path (in type namespace) | ||
207 | if let crate::PathKind::Type(type_ref) = &path.kind { | ||
208 | let ty = Ty::from_hir(db, resolver, &type_ref); | ||
209 | let remaining_segments = &path.segments[..]; | ||
210 | return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); | ||
211 | } | ||
212 | let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) { | ||
213 | Some(it) => it, | ||
214 | None => return Ty::Unknown, | ||
215 | }; | ||
216 | let (resolved_segment, remaining_segments) = match remaining_index { | ||
217 | None => ( | ||
218 | path.segments.last().expect("resolved path has at least one element"), | ||
219 | &[] as &[PathSegment], | ||
220 | ), | ||
221 | Some(i) => (&path.segments[i - 1], &path.segments[i..]), | ||
222 | }; | ||
223 | Ty::from_partly_resolved_hir_path( | ||
224 | db, | ||
225 | resolver, | ||
226 | resolution, | ||
227 | resolved_segment, | ||
228 | remaining_segments, | ||
229 | ) | ||
230 | } | ||
231 | |||
232 | fn select_associated_type( | ||
233 | db: &impl HirDatabase, | ||
234 | resolver: &Resolver, | ||
235 | self_ty: Ty, | ||
236 | segment: &PathSegment, | ||
237 | ) -> Ty { | ||
238 | let param_idx = match self_ty { | ||
239 | Ty::Param { idx, .. } => idx, | ||
240 | _ => return Ty::Unknown, // Error: Ambiguous associated type | ||
241 | }; | ||
242 | let def = match resolver.generic_def() { | ||
243 | Some(def) => def, | ||
244 | None => return Ty::Unknown, // this can't actually happen | ||
245 | }; | ||
246 | let predicates = db.generic_predicates_for_param(def.into(), param_idx); | ||
247 | let traits_from_env = predicates.iter().filter_map(|pred| match pred { | ||
248 | GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), | ||
249 | _ => None, | ||
250 | }); | ||
251 | let traits = traits_from_env.flat_map(|t| all_super_traits(db, t)); | ||
252 | for t in traits { | ||
253 | if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) { | ||
254 | let substs = | ||
255 | Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build(); | ||
256 | // FIXME handle type parameters on the segment | ||
257 | return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); | ||
258 | } | ||
259 | } | ||
260 | Ty::Unknown | ||
261 | } | ||
262 | |||
263 | fn from_hir_path_inner( | ||
264 | db: &impl HirDatabase, | ||
265 | resolver: &Resolver, | ||
266 | segment: &PathSegment, | ||
267 | typable: TyDefId, | ||
268 | ) -> Ty { | ||
269 | let generic_def = match typable { | ||
270 | TyDefId::BuiltinType(_) => None, | ||
271 | TyDefId::AdtId(it) => Some(it.into()), | ||
272 | TyDefId::TypeAliasId(it) => Some(it.into()), | ||
273 | }; | ||
274 | let substs = substs_from_path_segment(db, resolver, segment, generic_def, false); | ||
275 | db.ty(typable).subst(&substs) | ||
276 | } | ||
277 | |||
278 | /// Collect generic arguments from a path into a `Substs`. See also | ||
279 | /// `create_substs_for_ast_path` and `def_to_ty` in rustc. | ||
280 | pub(super) fn substs_from_path( | ||
281 | db: &impl HirDatabase, | ||
282 | resolver: &Resolver, | ||
283 | path: &Path, | ||
284 | // Note that we don't call `db.value_type(resolved)` here, | ||
285 | // `ValueTyDefId` is just a convenient way to pass generics and | ||
286 | // special-case enum variants | ||
287 | resolved: ValueTyDefId, | ||
288 | ) -> Substs { | ||
289 | let last = path.segments.last().expect("path should have at least one segment"); | ||
290 | let (segment, generic_def) = match resolved { | ||
291 | ValueTyDefId::FunctionId(it) => (last, Some(it.into())), | ||
292 | ValueTyDefId::StructId(it) => (last, Some(it.into())), | ||
293 | ValueTyDefId::ConstId(it) => (last, Some(it.into())), | ||
294 | ValueTyDefId::StaticId(_) => (last, None), | ||
295 | ValueTyDefId::EnumVariantId(var) => { | ||
296 | // the generic args for an enum variant may be either specified | ||
297 | // on the segment referring to the enum, or on the segment | ||
298 | // referring to the variant. So `Option::<T>::None` and | ||
299 | // `Option::None::<T>` are both allowed (though the former is | ||
300 | // preferred). See also `def_ids_for_path_segments` in rustc. | ||
301 | let len = path.segments.len(); | ||
302 | let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() { | ||
303 | // Option::<T>::None | ||
304 | &path.segments[len - 2] | ||
305 | } else { | ||
306 | // Option::None::<T> | ||
307 | last | ||
308 | }; | ||
309 | (segment, Some(var.parent.into())) | ||
310 | } | ||
311 | }; | ||
312 | substs_from_path_segment(db, resolver, segment, generic_def, false) | ||
313 | } | ||
314 | } | ||
315 | |||
316 | pub(super) fn substs_from_path_segment( | ||
317 | db: &impl HirDatabase, | ||
318 | resolver: &Resolver, | ||
319 | segment: &PathSegment, | ||
320 | def_generic: Option<GenericDefId>, | ||
321 | add_self_param: bool, | ||
322 | ) -> Substs { | ||
323 | let mut substs = Vec::new(); | ||
324 | let def_generics = def_generic.map(|def| db.generic_params(def.into())); | ||
325 | |||
326 | let (parent_param_count, param_count) = | ||
327 | def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
328 | substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count)); | ||
329 | if add_self_param { | ||
330 | // FIXME this add_self_param argument is kind of a hack: Traits have the | ||
331 | // Self type as an implicit first type parameter, but it can't be | ||
332 | // actually provided in the type arguments | ||
333 | // (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`) | ||
334 | substs.push(Ty::Unknown); | ||
335 | } | ||
336 | if let Some(generic_args) = &segment.args_and_bindings { | ||
337 | // if args are provided, it should be all of them, but we can't rely on that | ||
338 | let self_param_correction = if add_self_param { 1 } else { 0 }; | ||
339 | let param_count = param_count - self_param_correction; | ||
340 | for arg in generic_args.args.iter().take(param_count) { | ||
341 | match arg { | ||
342 | GenericArg::Type(type_ref) => { | ||
343 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
344 | substs.push(ty); | ||
345 | } | ||
346 | } | ||
347 | } | ||
348 | } | ||
349 | // add placeholders for args that were not provided | ||
350 | let supplied_params = substs.len(); | ||
351 | for _ in supplied_params..parent_param_count + param_count { | ||
352 | substs.push(Ty::Unknown); | ||
353 | } | ||
354 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
355 | |||
356 | // handle defaults | ||
357 | if let Some(def_generic) = def_generic { | ||
358 | let default_substs = db.generic_defaults(def_generic.into()); | ||
359 | assert_eq!(substs.len(), default_substs.len()); | ||
360 | |||
361 | for (i, default_ty) in default_substs.iter().enumerate() { | ||
362 | if substs[i] == Ty::Unknown { | ||
363 | substs[i] = default_ty.clone(); | ||
364 | } | ||
365 | } | ||
366 | } | ||
367 | |||
368 | Substs(substs.into()) | ||
369 | } | ||
370 | |||
371 | impl TraitRef { | ||
372 | pub(crate) fn from_path( | ||
373 | db: &impl HirDatabase, | ||
374 | resolver: &Resolver, | ||
375 | path: &Path, | ||
376 | explicit_self_ty: Option<Ty>, | ||
377 | ) -> Option<Self> { | ||
378 | let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? { | ||
379 | TypeNs::TraitId(tr) => tr, | ||
380 | _ => return None, | ||
381 | }; | ||
382 | let segment = path.segments.last().expect("path should have at least one segment"); | ||
383 | Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) | ||
384 | } | ||
385 | |||
386 | pub(super) fn from_resolved_path( | ||
387 | db: &impl HirDatabase, | ||
388 | resolver: &Resolver, | ||
389 | resolved: TraitId, | ||
390 | segment: &PathSegment, | ||
391 | explicit_self_ty: Option<Ty>, | ||
392 | ) -> Self { | ||
393 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | ||
394 | if let Some(self_ty) = explicit_self_ty { | ||
395 | make_mut_slice(&mut substs.0)[0] = self_ty; | ||
396 | } | ||
397 | TraitRef { trait_: resolved, substs } | ||
398 | } | ||
399 | |||
400 | pub(crate) fn from_hir( | ||
401 | db: &impl HirDatabase, | ||
402 | resolver: &Resolver, | ||
403 | type_ref: &TypeRef, | ||
404 | explicit_self_ty: Option<Ty>, | ||
405 | ) -> Option<Self> { | ||
406 | let path = match type_ref { | ||
407 | TypeRef::Path(path) => path, | ||
408 | _ => return None, | ||
409 | }; | ||
410 | TraitRef::from_path(db, resolver, path, explicit_self_ty) | ||
411 | } | ||
412 | |||
413 | fn substs_from_path( | ||
414 | db: &impl HirDatabase, | ||
415 | resolver: &Resolver, | ||
416 | segment: &PathSegment, | ||
417 | resolved: TraitId, | ||
418 | ) -> Substs { | ||
419 | let has_self_param = | ||
420 | segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); | ||
421 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) | ||
422 | } | ||
423 | |||
424 | pub(crate) fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef { | ||
425 | let substs = Substs::identity(&db.generic_params(trait_.into())); | ||
426 | TraitRef { trait_, substs } | ||
427 | } | ||
428 | |||
429 | pub(crate) fn from_type_bound( | ||
430 | db: &impl HirDatabase, | ||
431 | resolver: &Resolver, | ||
432 | bound: &TypeBound, | ||
433 | self_ty: Ty, | ||
434 | ) -> Option<TraitRef> { | ||
435 | match bound { | ||
436 | TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), | ||
437 | TypeBound::Error => None, | ||
438 | } | ||
439 | } | ||
440 | } | ||
441 | |||
442 | impl GenericPredicate { | ||
443 | pub(crate) fn from_where_predicate<'a>( | ||
444 | db: &'a impl HirDatabase, | ||
445 | resolver: &'a Resolver, | ||
446 | where_predicate: &'a WherePredicate, | ||
447 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
448 | let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); | ||
449 | GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) | ||
450 | } | ||
451 | |||
452 | pub(crate) fn from_type_bound<'a>( | ||
453 | db: &'a impl HirDatabase, | ||
454 | resolver: &'a Resolver, | ||
455 | bound: &'a TypeBound, | ||
456 | self_ty: Ty, | ||
457 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
458 | let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); | ||
459 | iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) | ||
460 | .chain( | ||
461 | trait_ref.into_iter().flat_map(move |tr| { | ||
462 | assoc_type_bindings_from_type_bound(db, resolver, bound, tr) | ||
463 | }), | ||
464 | ) | ||
465 | } | ||
466 | } | ||
467 | |||
468 | fn assoc_type_bindings_from_type_bound<'a>( | ||
469 | db: &'a impl HirDatabase, | ||
470 | resolver: &'a Resolver, | ||
471 | bound: &'a TypeBound, | ||
472 | trait_ref: TraitRef, | ||
473 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
474 | let last_segment = match bound { | ||
475 | TypeBound::Path(path) => path.segments.last(), | ||
476 | TypeBound::Error => None, | ||
477 | }; | ||
478 | last_segment | ||
479 | .into_iter() | ||
480 | .flat_map(|segment| segment.args_and_bindings.iter()) | ||
481 | .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) | ||
482 | .map(move |(name, type_ref)| { | ||
483 | let associated_ty = | ||
484 | associated_type_by_name_including_super_traits(db, trait_ref.trait_, &name); | ||
485 | let associated_ty = match associated_ty { | ||
486 | None => return GenericPredicate::Error, | ||
487 | Some(t) => t, | ||
488 | }; | ||
489 | let projection_ty = | ||
490 | ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; | ||
491 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
492 | let projection_predicate = ProjectionPredicate { projection_ty, ty }; | ||
493 | GenericPredicate::Projection(projection_predicate) | ||
494 | }) | ||
495 | } | ||
496 | |||
497 | /// Build the signature of a callable item (function, struct or enum variant). | ||
498 | pub(crate) fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { | ||
499 | match def { | ||
500 | CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), | ||
501 | CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), | ||
502 | CallableDef::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e), | ||
503 | } | ||
504 | } | ||
505 | |||
506 | /// Build the type of all specific fields of a struct or enum variant. | ||
507 | pub(crate) fn field_types_query( | ||
508 | db: &impl HirDatabase, | ||
509 | variant_id: VariantId, | ||
510 | ) -> Arc<ArenaMap<LocalStructFieldId, Ty>> { | ||
511 | let var_data = variant_data(db, variant_id); | ||
512 | let resolver = match variant_id { | ||
513 | VariantId::StructId(it) => it.resolver(db), | ||
514 | VariantId::UnionId(it) => it.resolver(db), | ||
515 | VariantId::EnumVariantId(it) => it.parent.resolver(db), | ||
516 | }; | ||
517 | let mut res = ArenaMap::default(); | ||
518 | for (field_id, field_data) in var_data.fields().iter() { | ||
519 | res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) | ||
520 | } | ||
521 | Arc::new(res) | ||
522 | } | ||
523 | |||
524 | /// This query exists only to be used when resolving short-hand associated types | ||
525 | /// like `T::Item`. | ||
526 | /// | ||
527 | /// See the analogous query in rustc and its comment: | ||
528 | /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46 | ||
529 | /// This is a query mostly to handle cycles somewhat gracefully; e.g. the | ||
530 | /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but | ||
531 | /// these are fine: `T: Foo<U::Item>, U: Foo<()>`. | ||
532 | pub(crate) fn generic_predicates_for_param_query( | ||
533 | db: &impl HirDatabase, | ||
534 | def: GenericDefId, | ||
535 | param_idx: u32, | ||
536 | ) -> Arc<[GenericPredicate]> { | ||
537 | let resolver = def.resolver(db); | ||
538 | resolver | ||
539 | .where_predicates_in_scope() | ||
540 | // we have to filter out all other predicates *first*, before attempting to lower them | ||
541 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) | ||
542 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
543 | .collect() | ||
544 | } | ||
545 | |||
546 | impl TraitEnvironment { | ||
547 | pub(crate) fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { | ||
548 | let predicates = resolver | ||
549 | .where_predicates_in_scope() | ||
550 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
551 | .collect::<Vec<_>>(); | ||
552 | |||
553 | Arc::new(TraitEnvironment { predicates }) | ||
554 | } | ||
555 | } | ||
556 | |||
557 | /// Resolve the where clause(s) of an item with generics. | ||
558 | pub(crate) fn generic_predicates_query( | ||
559 | db: &impl HirDatabase, | ||
560 | def: GenericDefId, | ||
561 | ) -> Arc<[GenericPredicate]> { | ||
562 | let resolver = def.resolver(db); | ||
563 | resolver | ||
564 | .where_predicates_in_scope() | ||
565 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
566 | .collect() | ||
567 | } | ||
568 | |||
569 | /// Resolve the default type params from generics | ||
570 | pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs { | ||
571 | let resolver = def.resolver(db); | ||
572 | let generic_params = db.generic_params(def.into()); | ||
573 | |||
574 | let defaults = generic_params | ||
575 | .params_including_parent() | ||
576 | .into_iter() | ||
577 | .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) | ||
578 | .collect(); | ||
579 | |||
580 | Substs(defaults) | ||
581 | } | ||
582 | |||
583 | fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> FnSig { | ||
584 | let data = db.function_data(def); | ||
585 | let resolver = def.resolver(db); | ||
586 | let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>(); | ||
587 | let ret = Ty::from_hir(db, &resolver, &data.ret_type); | ||
588 | FnSig::from_params_and_return(params, ret) | ||
589 | } | ||
590 | |||
591 | /// Build the declared type of a function. This should not need to look at the | ||
592 | /// function body. | ||
593 | fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Ty { | ||
594 | let generics = db.generic_params(def.into()); | ||
595 | let substs = Substs::identity(&generics); | ||
596 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
597 | } | ||
598 | |||
599 | /// Build the declared type of a const. | ||
600 | fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Ty { | ||
601 | let data = db.const_data(def); | ||
602 | let resolver = def.resolver(db); | ||
603 | |||
604 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
605 | } | ||
606 | |||
607 | /// Build the declared type of a static. | ||
608 | fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Ty { | ||
609 | let data = db.static_data(def); | ||
610 | let resolver = def.resolver(db); | ||
611 | |||
612 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
613 | } | ||
614 | |||
615 | /// Build the declared type of a static. | ||
616 | fn type_for_builtin(def: BuiltinType) -> Ty { | ||
617 | Ty::simple(match def { | ||
618 | BuiltinType::Char => TypeCtor::Char, | ||
619 | BuiltinType::Bool => TypeCtor::Bool, | ||
620 | BuiltinType::Str => TypeCtor::Str, | ||
621 | BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()), | ||
622 | BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()), | ||
623 | }) | ||
624 | } | ||
625 | |||
626 | fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> FnSig { | ||
627 | let struct_data = db.struct_data(def.into()); | ||
628 | let fields = struct_data.variant_data.fields(); | ||
629 | let resolver = def.resolver(db); | ||
630 | let params = fields | ||
631 | .iter() | ||
632 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
633 | .collect::<Vec<_>>(); | ||
634 | let ret = type_for_adt(db, def.into()); | ||
635 | FnSig::from_params_and_return(params, ret) | ||
636 | } | ||
637 | |||
638 | /// Build the type of a tuple struct constructor. | ||
639 | fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Ty { | ||
640 | let struct_data = db.struct_data(def.into()); | ||
641 | if struct_data.variant_data.is_unit() { | ||
642 | return type_for_adt(db, def.into()); // Unit struct | ||
643 | } | ||
644 | let generics = db.generic_params(def.into()); | ||
645 | let substs = Substs::identity(&generics); | ||
646 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
647 | } | ||
648 | |||
649 | fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> FnSig { | ||
650 | let enum_data = db.enum_data(def.parent); | ||
651 | let var_data = &enum_data.variants[def.local_id]; | ||
652 | let fields = var_data.variant_data.fields(); | ||
653 | let resolver = def.parent.resolver(db); | ||
654 | let params = fields | ||
655 | .iter() | ||
656 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
657 | .collect::<Vec<_>>(); | ||
658 | let generics = db.generic_params(def.parent.into()); | ||
659 | let substs = Substs::identity(&generics); | ||
660 | let ret = type_for_adt(db, def.parent.into()).subst(&substs); | ||
661 | FnSig::from_params_and_return(params, ret) | ||
662 | } | ||
663 | |||
664 | /// Build the type of a tuple enum variant constructor. | ||
665 | fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Ty { | ||
666 | let enum_data = db.enum_data(def.parent); | ||
667 | let var_data = &enum_data.variants[def.local_id].variant_data; | ||
668 | if var_data.is_unit() { | ||
669 | return type_for_adt(db, def.parent.into()); // Unit variant | ||
670 | } | ||
671 | let generics = db.generic_params(def.parent.into()); | ||
672 | let substs = Substs::identity(&generics); | ||
673 | Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs) | ||
674 | } | ||
675 | |||
676 | fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Ty { | ||
677 | let generics = db.generic_params(adt.into()); | ||
678 | Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) | ||
679 | } | ||
680 | |||
681 | fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Ty { | ||
682 | let generics = db.generic_params(t.into()); | ||
683 | let resolver = t.resolver(db); | ||
684 | let type_ref = &db.type_alias_data(t).type_ref; | ||
685 | let substs = Substs::identity(&generics); | ||
686 | let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error)); | ||
687 | inner.subst(&substs) | ||
688 | } | ||
689 | |||
690 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
691 | pub enum CallableDef { | ||
692 | FunctionId(FunctionId), | ||
693 | StructId(StructId), | ||
694 | EnumVariantId(EnumVariantId), | ||
695 | } | ||
696 | impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId); | ||
697 | |||
698 | impl CallableDef { | ||
699 | pub fn krate(self, db: &impl HirDatabase) -> CrateId { | ||
700 | match self { | ||
701 | CallableDef::FunctionId(f) => f.lookup(db).module(db).krate, | ||
702 | CallableDef::StructId(s) => s.module(db).krate, | ||
703 | CallableDef::EnumVariantId(e) => e.parent.module(db).krate, | ||
704 | } | ||
705 | } | ||
706 | } | ||
707 | |||
708 | impl From<CallableDef> for GenericDefId { | ||
709 | fn from(def: CallableDef) -> GenericDefId { | ||
710 | match def { | ||
711 | CallableDef::FunctionId(f) => f.into(), | ||
712 | CallableDef::StructId(s) => s.into(), | ||
713 | CallableDef::EnumVariantId(e) => e.into(), | ||
714 | } | ||
715 | } | ||
716 | } | ||
717 | |||
718 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
719 | pub enum TyDefId { | ||
720 | BuiltinType(BuiltinType), | ||
721 | AdtId(AdtId), | ||
722 | TypeAliasId(TypeAliasId), | ||
723 | } | ||
724 | impl_froms!(TyDefId: BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId); | ||
725 | |||
726 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
727 | pub enum ValueTyDefId { | ||
728 | FunctionId(FunctionId), | ||
729 | StructId(StructId), | ||
730 | EnumVariantId(EnumVariantId), | ||
731 | ConstId(ConstId), | ||
732 | StaticId(StaticId), | ||
733 | } | ||
734 | impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId); | ||
735 | |||
736 | /// Build the declared type of an item. This depends on the namespace; e.g. for | ||
737 | /// `struct Foo(usize)`, we have two types: The type of the struct itself, and | ||
738 | /// the constructor function `(usize) -> Foo` which lives in the values | ||
739 | /// namespace. | ||
740 | pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Ty { | ||
741 | match def { | ||
742 | TyDefId::BuiltinType(it) => type_for_builtin(it), | ||
743 | TyDefId::AdtId(it) => type_for_adt(db, it), | ||
744 | TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), | ||
745 | } | ||
746 | } | ||
747 | pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty { | ||
748 | match def { | ||
749 | ValueTyDefId::FunctionId(it) => type_for_fn(db, it), | ||
750 | ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), | ||
751 | ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it), | ||
752 | ValueTyDefId::ConstId(it) => type_for_const(db, it), | ||
753 | ValueTyDefId::StaticId(it) => type_for_static(db, it), | ||
754 | } | ||
755 | } | ||
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs deleted file mode 100644 index 5cc249855..000000000 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ /dev/null | |||
@@ -1,362 +0,0 @@ | |||
1 | //! This module is concerned with finding methods that a given type provides. | ||
2 | //! For details about how this works in rustc, see the method lookup page in the | ||
3 | //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html) | ||
4 | //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs. | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use arrayvec::ArrayVec; | ||
8 | use hir_def::{ | ||
9 | lang_item::LangItemTarget, resolver::HasResolver, resolver::Resolver, type_ref::Mutability, | ||
10 | AssocItemId, AstItemDef, FunctionId, HasModule, ImplId, TraitId, | ||
11 | }; | ||
12 | use hir_expand::name::Name; | ||
13 | use ra_db::CrateId; | ||
14 | use ra_prof::profile; | ||
15 | use rustc_hash::FxHashMap; | ||
16 | |||
17 | use crate::{ | ||
18 | db::HirDatabase, | ||
19 | ty::primitive::{FloatBitness, Uncertain}, | ||
20 | ty::{utils::all_super_traits, Ty, TypeCtor}, | ||
21 | }; | ||
22 | |||
23 | use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef}; | ||
24 | |||
25 | /// This is used as a key for indexing impls. | ||
26 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
27 | pub enum TyFingerprint { | ||
28 | Apply(TypeCtor), | ||
29 | } | ||
30 | |||
31 | impl 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)] | ||
44 | pub struct CrateImplBlocks { | ||
45 | impls: FxHashMap<TyFingerprint, Vec<ImplId>>, | ||
46 | impls_by_trait: FxHashMap<TraitId, Vec<ImplId>>, | ||
47 | } | ||
48 | |||
49 | impl 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 | let impl_data = db.impl_data(impl_id); | ||
62 | let resolver = impl_id.resolver(db); | ||
63 | |||
64 | let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); | ||
65 | |||
66 | match &impl_data.target_trait { | ||
67 | Some(trait_ref) => { | ||
68 | if let Some(tr) = | ||
69 | TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty)) | ||
70 | { | ||
71 | res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); | ||
72 | } | ||
73 | } | ||
74 | None => { | ||
75 | if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { | ||
76 | res.impls.entry(target_ty_fp).or_default().push(impl_id); | ||
77 | } | ||
78 | } | ||
79 | } | ||
80 | } | ||
81 | } | ||
82 | |||
83 | Arc::new(res) | ||
84 | } | ||
85 | pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator<Item = ImplId> + '_ { | ||
86 | let fingerprint = TyFingerprint::for_impl(ty); | ||
87 | fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() | ||
88 | } | ||
89 | |||
90 | pub fn lookup_impl_blocks_for_trait(&self, tr: TraitId) -> impl Iterator<Item = ImplId> + '_ { | ||
91 | self.impls_by_trait.get(&tr).into_iter().flatten().copied() | ||
92 | } | ||
93 | |||
94 | pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplId> + 'a { | ||
95 | self.impls.values().chain(self.impls_by_trait.values()).flatten().copied() | ||
96 | } | ||
97 | } | ||
98 | |||
99 | impl Ty { | ||
100 | pub(crate) fn def_crates( | ||
101 | &self, | ||
102 | db: &impl HirDatabase, | ||
103 | cur_crate: CrateId, | ||
104 | ) -> Option<ArrayVec<[CrateId; 2]>> { | ||
105 | // Types like slice can have inherent impls in several crates, (core and alloc). | ||
106 | // The corresponding impls are marked with lang items, so we can use them to find the required crates. | ||
107 | macro_rules! lang_item_crate { | ||
108 | ($($name:expr),+ $(,)?) => {{ | ||
109 | let mut v = ArrayVec::<[LangItemTarget; 2]>::new(); | ||
110 | $( | ||
111 | v.extend(db.lang_item(cur_crate, $name.into())); | ||
112 | )+ | ||
113 | v | ||
114 | }}; | ||
115 | } | ||
116 | |||
117 | let lang_item_targets = match self { | ||
118 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
119 | TypeCtor::Adt(def_id) => { | ||
120 | return Some(std::iter::once(def_id.module(db).krate).collect()) | ||
121 | } | ||
122 | TypeCtor::Bool => lang_item_crate!("bool"), | ||
123 | TypeCtor::Char => lang_item_crate!("char"), | ||
124 | TypeCtor::Float(Uncertain::Known(f)) => match f.bitness { | ||
125 | // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime) | ||
126 | FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"), | ||
127 | FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"), | ||
128 | }, | ||
129 | TypeCtor::Int(Uncertain::Known(i)) => lang_item_crate!(i.ty_to_string()), | ||
130 | TypeCtor::Str => lang_item_crate!("str_alloc", "str"), | ||
131 | TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"), | ||
132 | TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"), | ||
133 | TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"), | ||
134 | _ => return None, | ||
135 | }, | ||
136 | _ => return None, | ||
137 | }; | ||
138 | let res = lang_item_targets | ||
139 | .into_iter() | ||
140 | .filter_map(|it| match it { | ||
141 | LangItemTarget::ImplBlockId(it) => Some(it), | ||
142 | _ => None, | ||
143 | }) | ||
144 | .map(|it| it.module(db).krate) | ||
145 | .collect(); | ||
146 | Some(res) | ||
147 | } | ||
148 | } | ||
149 | /// Look up the method with the given name, returning the actual autoderefed | ||
150 | /// receiver type (but without autoref applied yet). | ||
151 | pub(crate) fn lookup_method( | ||
152 | ty: &Canonical<Ty>, | ||
153 | db: &impl HirDatabase, | ||
154 | name: &Name, | ||
155 | resolver: &Resolver, | ||
156 | ) -> Option<(Ty, FunctionId)> { | ||
157 | iterate_method_candidates(ty, db, resolver, Some(name), LookupMode::MethodCall, |ty, f| match f | ||
158 | { | ||
159 | AssocItemId::FunctionId(f) => Some((ty.clone(), f)), | ||
160 | _ => None, | ||
161 | }) | ||
162 | } | ||
163 | |||
164 | /// Whether we're looking up a dotted method call (like `v.len()`) or a path | ||
165 | /// (like `Vec::new`). | ||
166 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] | ||
167 | pub enum LookupMode { | ||
168 | /// Looking up a method call like `v.len()`: We only consider candidates | ||
169 | /// that have a `self` parameter, and do autoderef. | ||
170 | MethodCall, | ||
171 | /// Looking up a path like `Vec::new` or `Vec::default`: We consider all | ||
172 | /// candidates including associated constants, but don't do autoderef. | ||
173 | Path, | ||
174 | } | ||
175 | |||
176 | // This would be nicer if it just returned an iterator, but that runs into | ||
177 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
178 | // FIXME add a context type here? | ||
179 | pub(crate) fn iterate_method_candidates<T>( | ||
180 | ty: &Canonical<Ty>, | ||
181 | db: &impl HirDatabase, | ||
182 | resolver: &Resolver, | ||
183 | name: Option<&Name>, | ||
184 | mode: LookupMode, | ||
185 | mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>, | ||
186 | ) -> Option<T> { | ||
187 | let krate = resolver.krate()?; | ||
188 | match mode { | ||
189 | LookupMode::MethodCall => { | ||
190 | // For method calls, rust first does any number of autoderef, and then one | ||
191 | // autoref (i.e. when the method takes &self or &mut self). We just ignore | ||
192 | // the autoref currently -- when we find a method matching the given name, | ||
193 | // we assume it fits. | ||
194 | |||
195 | // Also note that when we've got a receiver like &S, even if the method we | ||
196 | // find in the end takes &self, we still do the autoderef step (just as | ||
197 | // rustc does an autoderef and then autoref again). | ||
198 | let environment = TraitEnvironment::lower(db, resolver); | ||
199 | let ty = InEnvironment { value: ty.clone(), environment }; | ||
200 | for derefed_ty in autoderef::autoderef(db, resolver.krate(), ty) { | ||
201 | if let Some(result) = | ||
202 | iterate_inherent_methods(&derefed_ty, db, name, mode, krate, &mut callback) | ||
203 | { | ||
204 | return Some(result); | ||
205 | } | ||
206 | if let Some(result) = iterate_trait_method_candidates( | ||
207 | &derefed_ty, | ||
208 | db, | ||
209 | resolver, | ||
210 | name, | ||
211 | mode, | ||
212 | &mut callback, | ||
213 | ) { | ||
214 | return Some(result); | ||
215 | } | ||
216 | } | ||
217 | } | ||
218 | LookupMode::Path => { | ||
219 | // No autoderef for path lookups | ||
220 | if let Some(result) = | ||
221 | iterate_inherent_methods(&ty, db, name, mode, krate.into(), &mut callback) | ||
222 | { | ||
223 | return Some(result); | ||
224 | } | ||
225 | if let Some(result) = | ||
226 | iterate_trait_method_candidates(&ty, db, resolver, name, mode, &mut callback) | ||
227 | { | ||
228 | return Some(result); | ||
229 | } | ||
230 | } | ||
231 | } | ||
232 | None | ||
233 | } | ||
234 | |||
235 | fn iterate_trait_method_candidates<T>( | ||
236 | ty: &Canonical<Ty>, | ||
237 | db: &impl HirDatabase, | ||
238 | resolver: &Resolver, | ||
239 | name: Option<&Name>, | ||
240 | mode: LookupMode, | ||
241 | mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>, | ||
242 | ) -> Option<T> { | ||
243 | let krate = resolver.krate()?; | ||
244 | // FIXME: maybe put the trait_env behind a query (need to figure out good input parameters for that) | ||
245 | let env = TraitEnvironment::lower(db, resolver); | ||
246 | // if ty is `impl Trait` or `dyn Trait`, the trait doesn't need to be in scope | ||
247 | let inherent_trait = ty.value.inherent_trait().into_iter(); | ||
248 | // if we have `T: Trait` in the param env, the trait doesn't need to be in scope | ||
249 | let traits_from_env = env | ||
250 | .trait_predicates_for_self_ty(&ty.value) | ||
251 | .map(|tr| tr.trait_) | ||
252 | .flat_map(|t| all_super_traits(db, t)); | ||
253 | let traits = | ||
254 | inherent_trait.chain(traits_from_env).chain(resolver.traits_in_scope(db).into_iter()); | ||
255 | 'traits: for t in traits { | ||
256 | let data = db.trait_data(t); | ||
257 | |||
258 | // we'll be lazy about checking whether the type implements the | ||
259 | // trait, but if we find out it doesn't, we'll skip the rest of the | ||
260 | // iteration | ||
261 | let mut known_implemented = false; | ||
262 | for (_name, item) in data.items.iter() { | ||
263 | if !is_valid_candidate(db, name, mode, (*item).into()) { | ||
264 | continue; | ||
265 | } | ||
266 | if !known_implemented { | ||
267 | let goal = generic_implements_goal(db, env.clone(), t, ty.clone()); | ||
268 | if db.trait_solve(krate.into(), goal).is_none() { | ||
269 | continue 'traits; | ||
270 | } | ||
271 | } | ||
272 | known_implemented = true; | ||
273 | if let Some(result) = callback(&ty.value, (*item).into()) { | ||
274 | return Some(result); | ||
275 | } | ||
276 | } | ||
277 | } | ||
278 | None | ||
279 | } | ||
280 | |||
281 | fn iterate_inherent_methods<T>( | ||
282 | ty: &Canonical<Ty>, | ||
283 | db: &impl HirDatabase, | ||
284 | name: Option<&Name>, | ||
285 | mode: LookupMode, | ||
286 | krate: CrateId, | ||
287 | mut callback: impl FnMut(&Ty, AssocItemId) -> Option<T>, | ||
288 | ) -> Option<T> { | ||
289 | for krate in ty.value.def_crates(db, krate)? { | ||
290 | let impls = db.impls_in_crate(krate); | ||
291 | |||
292 | for impl_block in impls.lookup_impl_blocks(&ty.value) { | ||
293 | for &item in db.impl_data(impl_block).items.iter() { | ||
294 | if !is_valid_candidate(db, name, mode, item) { | ||
295 | continue; | ||
296 | } | ||
297 | if let Some(result) = callback(&ty.value, item.into()) { | ||
298 | return Some(result); | ||
299 | } | ||
300 | } | ||
301 | } | ||
302 | } | ||
303 | None | ||
304 | } | ||
305 | |||
306 | fn is_valid_candidate( | ||
307 | db: &impl HirDatabase, | ||
308 | name: Option<&Name>, | ||
309 | mode: LookupMode, | ||
310 | item: AssocItemId, | ||
311 | ) -> bool { | ||
312 | match item { | ||
313 | AssocItemId::FunctionId(m) => { | ||
314 | let data = db.function_data(m); | ||
315 | name.map_or(true, |name| &data.name == name) | ||
316 | && (data.has_self_param || mode == LookupMode::Path) | ||
317 | } | ||
318 | AssocItemId::ConstId(c) => { | ||
319 | let data = db.const_data(c); | ||
320 | name.map_or(true, |name| data.name.as_ref() == Some(name)) && (mode == LookupMode::Path) | ||
321 | } | ||
322 | _ => false, | ||
323 | } | ||
324 | } | ||
325 | |||
326 | pub(crate) fn implements_trait( | ||
327 | ty: &Canonical<Ty>, | ||
328 | db: &impl HirDatabase, | ||
329 | resolver: &Resolver, | ||
330 | krate: CrateId, | ||
331 | trait_: TraitId, | ||
332 | ) -> bool { | ||
333 | if ty.value.inherent_trait() == Some(trait_) { | ||
334 | // FIXME this is a bit of a hack, since Chalk should say the same thing | ||
335 | // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet | ||
336 | return true; | ||
337 | } | ||
338 | let env = TraitEnvironment::lower(db, resolver); | ||
339 | let goal = generic_implements_goal(db, env, trait_, ty.clone()); | ||
340 | let solution = db.trait_solve(krate.into(), goal); | ||
341 | |||
342 | solution.is_some() | ||
343 | } | ||
344 | |||
345 | /// This creates Substs for a trait with the given Self type and type variables | ||
346 | /// for all other parameters, to query Chalk with it. | ||
347 | fn generic_implements_goal( | ||
348 | db: &impl HirDatabase, | ||
349 | env: Arc<TraitEnvironment>, | ||
350 | trait_: TraitId, | ||
351 | self_ty: Canonical<Ty>, | ||
352 | ) -> Canonical<InEnvironment<super::Obligation>> { | ||
353 | let num_vars = self_ty.num_vars; | ||
354 | let substs = super::Substs::build_for_def(db, trait_) | ||
355 | .push(self_ty.value) | ||
356 | .fill_with_bound_vars(num_vars as u32) | ||
357 | .build(); | ||
358 | let num_vars = substs.len() - 1 + self_ty.num_vars; | ||
359 | let trait_ref = TraitRef { trait_, substs }; | ||
360 | let obligation = super::Obligation::Trait(trait_ref); | ||
361 | Canonical { num_vars, value: InEnvironment::new(env, obligation) } | ||
362 | } | ||
diff --git a/crates/ra_hir/src/ty/op.rs b/crates/ra_hir/src/ty/op.rs deleted file mode 100644 index cc6e244f4..000000000 --- a/crates/ra_hir/src/ty/op.rs +++ /dev/null | |||
@@ -1,50 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | use hir_def::expr::{BinaryOp, CmpOp}; | ||
3 | |||
4 | use super::{InferTy, Ty, TypeCtor}; | ||
5 | use crate::ty::ApplicationTy; | ||
6 | |||
7 | pub(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 | |||
22 | pub(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/src/ty/primitive.rs b/crates/ra_hir/src/ty/primitive.rs deleted file mode 100644 index 12dc96572..000000000 --- a/crates/ra_hir/src/ty/primitive.rs +++ /dev/null | |||
@@ -1,3 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | pub use hir_ty::primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness, Uncertain}; | ||
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs deleted file mode 100644 index 98eb863cb..000000000 --- a/crates/ra_hir/src/ty/tests.rs +++ /dev/null | |||
@@ -1,4896 +0,0 @@ | |||
1 | mod never_type; | ||
2 | mod coercion; | ||
3 | |||
4 | use std::fmt::Write; | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use insta::assert_snapshot; | ||
8 | use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; | ||
9 | use ra_syntax::{ | ||
10 | algo, | ||
11 | ast::{self, AstNode}, | ||
12 | SyntaxKind::*, | ||
13 | }; | ||
14 | use rustc_hash::FxHashSet; | ||
15 | use test_utils::covers; | ||
16 | |||
17 | use crate::{ | ||
18 | expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, Source, | ||
19 | SourceAnalyzer, | ||
20 | }; | ||
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] | ||
27 | fn cfg_impl_block() { | ||
28 | let (db, pos) = TestDB::with_position( | ||
29 | r#" | ||
30 | //- /main.rs crate:main deps:foo cfg:test | ||
31 | use foo::S as T; | ||
32 | struct S; | ||
33 | |||
34 | #[cfg(test)] | ||
35 | impl S { | ||
36 | fn foo1(&self) -> i32 { 0 } | ||
37 | } | ||
38 | |||
39 | #[cfg(not(test))] | ||
40 | impl S { | ||
41 | fn foo2(&self) -> i32 { 0 } | ||
42 | } | ||
43 | |||
44 | fn test() { | ||
45 | let t = (S.foo1(), S.foo2(), T.foo3(), T.foo4()); | ||
46 | t<|>; | ||
47 | } | ||
48 | |||
49 | //- /foo.rs crate:foo | ||
50 | struct S; | ||
51 | |||
52 | #[cfg(not(test))] | ||
53 | impl S { | ||
54 | fn foo3(&self) -> i32 { 0 } | ||
55 | } | ||
56 | |||
57 | #[cfg(test)] | ||
58 | impl 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] | ||
67 | fn infer_await() { | ||
68 | let (db, pos) = TestDB::with_position( | ||
69 | r#" | ||
70 | //- /main.rs crate:main deps:std | ||
71 | |||
72 | struct IntFuture; | ||
73 | |||
74 | impl Future for IntFuture { | ||
75 | type Output = u64; | ||
76 | } | ||
77 | |||
78 | fn test() { | ||
79 | let r = IntFuture; | ||
80 | let v = r.await; | ||
81 | v<|>; | ||
82 | } | ||
83 | |||
84 | //- /std.rs crate:std | ||
85 | #[prelude_import] use future::*; | ||
86 | mod 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] | ||
98 | fn infer_box() { | ||
99 | let (db, pos) = TestDB::with_position( | ||
100 | r#" | ||
101 | //- /main.rs crate:main deps:std | ||
102 | |||
103 | fn 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::*; | ||
111 | mod prelude {} | ||
112 | |||
113 | mod 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] | ||
125 | fn infer_adt_self() { | ||
126 | let (db, pos) = TestDB::with_position( | ||
127 | r#" | ||
128 | //- /main.rs | ||
129 | enum Nat { Succ(Self), Demo(Nat), Zero } | ||
130 | |||
131 | fn 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] | ||
144 | fn infer_try() { | ||
145 | let (db, pos) = TestDB::with_position( | ||
146 | r#" | ||
147 | //- /main.rs crate:main deps:std | ||
148 | |||
149 | fn 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::*; | ||
158 | mod ops { | ||
159 | trait Try { | ||
160 | type Ok; | ||
161 | type Error; | ||
162 | } | ||
163 | } | ||
164 | |||
165 | #[prelude_import] use result::*; | ||
166 | mod 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] | ||
184 | fn infer_for_loop() { | ||
185 | let (db, pos) = TestDB::with_position( | ||
186 | r#" | ||
187 | //- /main.rs crate:main deps:std | ||
188 | |||
189 | use std::collections::Vec; | ||
190 | |||
191 | fn 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::*; | ||
202 | mod iter { | ||
203 | trait IntoIterator { | ||
204 | type Item; | ||
205 | } | ||
206 | } | ||
207 | |||
208 | mod 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] | ||
225 | fn infer_while_let() { | ||
226 | let (db, pos) = TestDB::with_position( | ||
227 | r#" | ||
228 | //- /main.rs | ||
229 | enum Option<T> { Some(T), None } | ||
230 | |||
231 | fn 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] | ||
244 | fn infer_basics() { | ||
245 | assert_snapshot!( | ||
246 | infer(r#" | ||
247 | fn 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] | ||
276 | fn infer_let() { | ||
277 | assert_snapshot!( | ||
278 | infer(r#" | ||
279 | fn 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] | ||
305 | fn infer_paths() { | ||
306 | assert_snapshot!( | ||
307 | infer(r#" | ||
308 | fn a() -> u32 { 1 } | ||
309 | |||
310 | mod b { | ||
311 | fn c() -> u32 { 1 } | ||
312 | } | ||
313 | |||
314 | fn 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] | ||
334 | fn infer_path_type() { | ||
335 | assert_snapshot!( | ||
336 | infer(r#" | ||
337 | struct S; | ||
338 | |||
339 | impl S { | ||
340 | fn foo() -> i32 { 1 } | ||
341 | } | ||
342 | |||
343 | fn 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] | ||
361 | fn infer_slice_method() { | ||
362 | assert_snapshot!( | ||
363 | infer(r#" | ||
364 | #[lang = "slice"] | ||
365 | impl<T> [T] { | ||
366 | fn foo(&self) -> T { | ||
367 | loop {} | ||
368 | } | ||
369 | } | ||
370 | |||
371 | #[lang = "slice_alloc"] | ||
372 | impl<T> [T] {} | ||
373 | |||
374 | fn 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] | ||
392 | fn infer_struct() { | ||
393 | assert_snapshot!( | ||
394 | infer(r#" | ||
395 | struct A { | ||
396 | b: B, | ||
397 | c: C, | ||
398 | } | ||
399 | struct B; | ||
400 | struct C(usize); | ||
401 | |||
402 | fn 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] | ||
432 | fn infer_enum() { | ||
433 | assert_snapshot!( | ||
434 | infer(r#" | ||
435 | enum E { | ||
436 | V1 { field: u32 }, | ||
437 | V2 | ||
438 | } | ||
439 | fn 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] | ||
453 | fn infer_refs() { | ||
454 | assert_snapshot!( | ||
455 | infer(r#" | ||
456 | fn 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] | ||
499 | fn infer_literals() { | ||
500 | assert_snapshot!( | ||
501 | infer(r##" | ||
502 | fn 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] | ||
542 | fn infer_unary_op() { | ||
543 | assert_snapshot!( | ||
544 | infer(r#" | ||
545 | enum SomeType {} | ||
546 | |||
547 | fn 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] | ||
612 | fn infer_backwards() { | ||
613 | assert_snapshot!( | ||
614 | infer(r#" | ||
615 | fn takes_u32(x: u32) {} | ||
616 | |||
617 | struct S { i32_field: i32 } | ||
618 | |||
619 | fn 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] | ||
654 | fn infer_self() { | ||
655 | assert_snapshot!( | ||
656 | infer(r#" | ||
657 | struct S; | ||
658 | |||
659 | impl 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] | ||
690 | fn infer_binary_op() { | ||
691 | assert_snapshot!( | ||
692 | infer(r#" | ||
693 | fn f(x: bool) -> i32 { | ||
694 | 0i32 | ||
695 | } | ||
696 | |||
697 | fn 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] | ||
769 | fn infer_field_autoderef() { | ||
770 | assert_snapshot!( | ||
771 | infer(r#" | ||
772 | struct A { | ||
773 | b: B, | ||
774 | } | ||
775 | struct B; | ||
776 | |||
777 | fn 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 | |||
790 | fn 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] | ||
844 | fn infer_argument_autoderef() { | ||
845 | assert_snapshot!( | ||
846 | infer(r#" | ||
847 | #[lang = "deref"] | ||
848 | pub trait Deref { | ||
849 | type Target; | ||
850 | fn deref(&self) -> &Self::Target; | ||
851 | } | ||
852 | |||
853 | struct A<T>(T); | ||
854 | |||
855 | impl<T> A<T> { | ||
856 | fn foo(&self) -> &T { | ||
857 | &self.0 | ||
858 | } | ||
859 | } | ||
860 | |||
861 | struct B<T>(T); | ||
862 | |||
863 | impl<T> Deref for B<T> { | ||
864 | type Target = T; | ||
865 | fn deref(&self) -> &Self::Target { | ||
866 | &self.0 | ||
867 | } | ||
868 | } | ||
869 | |||
870 | fn 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] | ||
904 | fn infer_method_argument_autoderef() { | ||
905 | assert_snapshot!( | ||
906 | infer(r#" | ||
907 | #[lang = "deref"] | ||
908 | pub trait Deref { | ||
909 | type Target; | ||
910 | fn deref(&self) -> &Self::Target; | ||
911 | } | ||
912 | |||
913 | struct A<T>(*mut T); | ||
914 | |||
915 | impl<T> A<T> { | ||
916 | fn foo(&self, x: &A<T>) -> &T { | ||
917 | &*x.0 | ||
918 | } | ||
919 | } | ||
920 | |||
921 | struct B<T>(T); | ||
922 | |||
923 | impl<T> Deref for B<T> { | ||
924 | type Target = T; | ||
925 | fn deref(&self) -> &Self::Target { | ||
926 | &self.0 | ||
927 | } | ||
928 | } | ||
929 | |||
930 | fn 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] | ||
968 | fn bug_484() { | ||
969 | assert_snapshot!( | ||
970 | infer(r#" | ||
971 | fn 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] | ||
986 | fn infer_in_elseif() { | ||
987 | assert_snapshot!( | ||
988 | infer(r#" | ||
989 | struct Foo { field: i32 } | ||
990 | fn 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] | ||
1014 | fn infer_if_match_with_return() { | ||
1015 | assert_snapshot!( | ||
1016 | infer(r#" | ||
1017 | fn 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] | ||
1075 | fn infer_inherent_method() { | ||
1076 | assert_snapshot!( | ||
1077 | infer(r#" | ||
1078 | struct A; | ||
1079 | |||
1080 | impl A { | ||
1081 | fn foo(self, x: u32) -> i32 {} | ||
1082 | } | ||
1083 | |||
1084 | mod b { | ||
1085 | impl super::A { | ||
1086 | fn bar(&self, x: u64) -> i64 {} | ||
1087 | } | ||
1088 | } | ||
1089 | |||
1090 | fn 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] | ||
1120 | fn infer_inherent_method_str() { | ||
1121 | assert_snapshot!( | ||
1122 | infer(r#" | ||
1123 | #[lang = "str"] | ||
1124 | impl str { | ||
1125 | fn foo(&self) -> i32 {} | ||
1126 | } | ||
1127 | |||
1128 | fn 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] | ||
1143 | fn infer_tuple() { | ||
1144 | assert_snapshot!( | ||
1145 | infer(r#" | ||
1146 | fn 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] | ||
1188 | fn infer_array() { | ||
1189 | assert_snapshot!( | ||
1190 | infer(r#" | ||
1191 | fn 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] | ||
1267 | fn infer_pattern() { | ||
1268 | assert_snapshot!( | ||
1269 | infer(r#" | ||
1270 | fn 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] | ||
1345 | fn infer_pattern_match_ergonomics() { | ||
1346 | assert_snapshot!( | ||
1347 | infer(r#" | ||
1348 | struct A<T>(T); | ||
1349 | |||
1350 | fn 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] | ||
1374 | fn infer_pattern_match_ergonomics_ref() { | ||
1375 | covers!(match_ergonomics_ref); | ||
1376 | assert_snapshot!( | ||
1377 | infer(r#" | ||
1378 | fn 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] | ||
1401 | fn infer_adt_pattern() { | ||
1402 | assert_snapshot!( | ||
1403 | infer(r#" | ||
1404 | enum E { | ||
1405 | A { x: usize }, | ||
1406 | B | ||
1407 | } | ||
1408 | |||
1409 | struct S(u32, E); | ||
1410 | |||
1411 | fn 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] | ||
1458 | fn infer_struct_generics() { | ||
1459 | assert_snapshot!( | ||
1460 | infer(r#" | ||
1461 | struct A<T> { | ||
1462 | x: T, | ||
1463 | } | ||
1464 | |||
1465 | fn 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] | ||
1494 | fn infer_tuple_struct_generics() { | ||
1495 | assert_snapshot!( | ||
1496 | infer(r#" | ||
1497 | struct A<T>(T); | ||
1498 | enum Option<T> { Some(T), None } | ||
1499 | use Option::*; | ||
1500 | |||
1501 | fn 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] | ||
1532 | fn infer_generics_in_patterns() { | ||
1533 | assert_snapshot!( | ||
1534 | infer(r#" | ||
1535 | struct A<T> { | ||
1536 | x: T, | ||
1537 | } | ||
1538 | |||
1539 | enum Option<T> { | ||
1540 | Some(T), | ||
1541 | None, | ||
1542 | } | ||
1543 | |||
1544 | fn 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] | ||
1576 | fn infer_function_generics() { | ||
1577 | assert_snapshot!( | ||
1578 | infer(r#" | ||
1579 | fn id<T>(t: T) -> T { t } | ||
1580 | |||
1581 | fn 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] | ||
1607 | fn infer_impl_generics() { | ||
1608 | assert_snapshot!( | ||
1609 | infer(r#" | ||
1610 | struct A<T1, T2> { | ||
1611 | x: T1, | ||
1612 | y: T2, | ||
1613 | } | ||
1614 | impl<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 | |||
1626 | fn 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] | ||
1672 | fn infer_impl_generics_with_autoderef() { | ||
1673 | assert_snapshot!( | ||
1674 | infer(r#" | ||
1675 | enum Option<T> { | ||
1676 | Some(T), | ||
1677 | None, | ||
1678 | } | ||
1679 | impl<T> Option<T> { | ||
1680 | fn as_ref(&self) -> Option<&T> {} | ||
1681 | } | ||
1682 | fn 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] | ||
1702 | fn infer_generic_chain() { | ||
1703 | assert_snapshot!( | ||
1704 | infer(r#" | ||
1705 | struct A<T> { | ||
1706 | x: T, | ||
1707 | } | ||
1708 | impl<T2> A<T2> { | ||
1709 | fn x(self) -> T2 { | ||
1710 | self.x | ||
1711 | } | ||
1712 | } | ||
1713 | fn id<T>(t: T) -> T { t } | ||
1714 | |||
1715 | fn 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] | ||
1759 | fn infer_associated_const() { | ||
1760 | assert_snapshot!( | ||
1761 | infer(r#" | ||
1762 | struct Struct; | ||
1763 | |||
1764 | impl Struct { | ||
1765 | const FOO: u32 = 1; | ||
1766 | } | ||
1767 | |||
1768 | enum Enum {} | ||
1769 | |||
1770 | impl Enum { | ||
1771 | const BAR: u32 = 2; | ||
1772 | } | ||
1773 | |||
1774 | trait Trait { | ||
1775 | const ID: u32; | ||
1776 | } | ||
1777 | |||
1778 | struct TraitTest; | ||
1779 | |||
1780 | impl Trait for TraitTest { | ||
1781 | const ID: u32 = 5; | ||
1782 | } | ||
1783 | |||
1784 | fn 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] | ||
1806 | fn infer_associated_method_struct() { | ||
1807 | assert_snapshot!( | ||
1808 | infer(r#" | ||
1809 | struct A { x: u32 } | ||
1810 | |||
1811 | impl A { | ||
1812 | fn new() -> A { | ||
1813 | A { x: 0 } | ||
1814 | } | ||
1815 | } | ||
1816 | fn 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] | ||
1836 | fn infer_associated_method_enum() { | ||
1837 | assert_snapshot!( | ||
1838 | infer(r#" | ||
1839 | enum A { B, C } | ||
1840 | |||
1841 | impl A { | ||
1842 | pub fn b() -> A { | ||
1843 | A::B | ||
1844 | } | ||
1845 | pub fn c() -> A { | ||
1846 | A::C | ||
1847 | } | ||
1848 | } | ||
1849 | fn 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] | ||
1875 | fn infer_associated_method_with_modules() { | ||
1876 | assert_snapshot!( | ||
1877 | infer(r#" | ||
1878 | mod a { | ||
1879 | struct A; | ||
1880 | impl A { pub fn thing() -> A { A {} }} | ||
1881 | } | ||
1882 | |||
1883 | mod 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 | } | ||
1892 | use b::c; | ||
1893 | |||
1894 | fn 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] | ||
1922 | fn infer_associated_method_generics() { | ||
1923 | assert_snapshot!( | ||
1924 | infer(r#" | ||
1925 | struct Gen<T> { | ||
1926 | val: T | ||
1927 | } | ||
1928 | |||
1929 | impl<T> Gen<T> { | ||
1930 | pub fn make(val: T) -> Gen<T> { | ||
1931 | Gen { val } | ||
1932 | } | ||
1933 | } | ||
1934 | |||
1935 | fn 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] | ||
1954 | fn infer_associated_method_generics_with_default_param() { | ||
1955 | assert_snapshot!( | ||
1956 | infer(r#" | ||
1957 | struct Gen<T=u32> { | ||
1958 | val: T | ||
1959 | } | ||
1960 | |||
1961 | impl<T> Gen<T> { | ||
1962 | pub fn make() -> Gen<T> { | ||
1963 | loop { } | ||
1964 | } | ||
1965 | } | ||
1966 | |||
1967 | fn 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] | ||
1984 | fn infer_associated_method_generics_with_default_tuple_param() { | ||
1985 | let t = type_at( | ||
1986 | r#" | ||
1987 | //- /main.rs | ||
1988 | struct Gen<T=()> { | ||
1989 | val: T | ||
1990 | } | ||
1991 | |||
1992 | impl<T> Gen<T> { | ||
1993 | pub fn make() -> Gen<T> { | ||
1994 | loop { } | ||
1995 | } | ||
1996 | } | ||
1997 | |||
1998 | fn test() { | ||
1999 | let a = Gen::make(); | ||
2000 | a.val<|>; | ||
2001 | } | ||
2002 | "#, | ||
2003 | ); | ||
2004 | assert_eq!(t, "()"); | ||
2005 | } | ||
2006 | |||
2007 | #[test] | ||
2008 | fn infer_associated_method_generics_without_args() { | ||
2009 | assert_snapshot!( | ||
2010 | infer(r#" | ||
2011 | struct Gen<T> { | ||
2012 | val: T | ||
2013 | } | ||
2014 | |||
2015 | impl<T> Gen<T> { | ||
2016 | pub fn make() -> Gen<T> { | ||
2017 | loop { } | ||
2018 | } | ||
2019 | } | ||
2020 | |||
2021 | fn 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] | ||
2038 | fn infer_associated_method_generics_2_type_params_without_args() { | ||
2039 | assert_snapshot!( | ||
2040 | infer(r#" | ||
2041 | struct Gen<T, U> { | ||
2042 | val: T, | ||
2043 | val2: U, | ||
2044 | } | ||
2045 | |||
2046 | impl<T> Gen<u32, T> { | ||
2047 | pub fn make() -> Gen<u32,T> { | ||
2048 | loop { } | ||
2049 | } | ||
2050 | } | ||
2051 | |||
2052 | fn 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] | ||
2069 | fn infer_type_alias() { | ||
2070 | assert_snapshot!( | ||
2071 | infer(r#" | ||
2072 | struct A<X, Y> { x: X, y: Y } | ||
2073 | type Foo = A<u32, i128>; | ||
2074 | type Bar<T> = A<T, u128>; | ||
2075 | type Baz<U, V> = A<V, U>; | ||
2076 | fn 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 | ||
2108 | fn recursive_type_alias() { | ||
2109 | assert_snapshot!( | ||
2110 | infer(r#" | ||
2111 | struct A<X> {} | ||
2112 | type Foo = Foo; | ||
2113 | type Bar = A<Bar>; | ||
2114 | fn test(x: Foo) {} | ||
2115 | "#), | ||
2116 | @"" | ||
2117 | ) | ||
2118 | } | ||
2119 | |||
2120 | #[test] | ||
2121 | fn no_panic_on_field_of_enum() { | ||
2122 | assert_snapshot!( | ||
2123 | infer(r#" | ||
2124 | enum X {} | ||
2125 | |||
2126 | fn 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] | ||
2140 | fn bug_585() { | ||
2141 | assert_snapshot!( | ||
2142 | infer(r#" | ||
2143 | fn 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] | ||
2165 | fn bug_651() { | ||
2166 | assert_snapshot!( | ||
2167 | infer(r#" | ||
2168 | fn 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] | ||
2185 | fn recursive_vars() { | ||
2186 | covers!(type_var_cycles_resolve_completely); | ||
2187 | covers!(type_var_cycles_resolve_as_possible); | ||
2188 | assert_snapshot!( | ||
2189 | infer(r#" | ||
2190 | fn 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] | ||
2208 | fn recursive_vars_2() { | ||
2209 | covers!(type_var_cycles_resolve_completely); | ||
2210 | covers!(type_var_cycles_resolve_as_possible); | ||
2211 | assert_snapshot!( | ||
2212 | infer(r#" | ||
2213 | fn 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] | ||
2239 | fn infer_type_param() { | ||
2240 | assert_snapshot!( | ||
2241 | infer(r#" | ||
2242 | fn id<T>(x: T) -> T { | ||
2243 | x | ||
2244 | } | ||
2245 | |||
2246 | fn clone<T>(x: &T) -> T { | ||
2247 | *x | ||
2248 | } | ||
2249 | |||
2250 | fn 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] | ||
2283 | fn infer_std_crash_1() { | ||
2284 | // caused stack overflow, taken from std | ||
2285 | assert_snapshot!( | ||
2286 | infer(r#" | ||
2287 | enum Maybe<T> { | ||
2288 | Real(T), | ||
2289 | Fake, | ||
2290 | } | ||
2291 | |||
2292 | fn 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] | ||
2310 | fn 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#" | ||
2315 | fn 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] | ||
2332 | fn infer_std_crash_3() { | ||
2333 | // taken from rustc | ||
2334 | assert_snapshot!( | ||
2335 | infer(r#" | ||
2336 | pub 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] | ||
2355 | fn infer_std_crash_4() { | ||
2356 | // taken from rustc | ||
2357 | assert_snapshot!( | ||
2358 | infer(r#" | ||
2359 | pub 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] | ||
2379 | fn infer_std_crash_5() { | ||
2380 | // taken from rustc | ||
2381 | assert_snapshot!( | ||
2382 | infer(r#" | ||
2383 | fn 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] | ||
2428 | fn infer_nested_generics_crash() { | ||
2429 | // another crash found typechecking rustc | ||
2430 | assert_snapshot!( | ||
2431 | infer(r#" | ||
2432 | struct Canonical<V> { | ||
2433 | value: V, | ||
2434 | } | ||
2435 | struct QueryResponse<V> { | ||
2436 | value: V, | ||
2437 | } | ||
2438 | fn 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] | ||
2453 | fn bug_1030() { | ||
2454 | assert_snapshot!(infer(r#" | ||
2455 | struct HashSet<T, H>; | ||
2456 | struct FxHasher; | ||
2457 | type FxHashSet<T> = HashSet<T, FxHasher>; | ||
2458 | |||
2459 | impl<T, H> HashSet<T, H> { | ||
2460 | fn default() -> HashSet<T, H> {} | ||
2461 | } | ||
2462 | |||
2463 | pub 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] | ||
2477 | fn cross_crate_associated_method_call() { | ||
2478 | let (db, pos) = TestDB::with_position( | ||
2479 | r#" | ||
2480 | //- /main.rs crate:main deps:other_crate | ||
2481 | fn test() { | ||
2482 | let x = other_crate::foo::S::thing(); | ||
2483 | x<|>; | ||
2484 | } | ||
2485 | |||
2486 | //- /lib.rs crate:other_crate | ||
2487 | mod 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] | ||
2499 | fn infer_const() { | ||
2500 | assert_snapshot!( | ||
2501 | infer(r#" | ||
2502 | struct Foo; | ||
2503 | impl Foo { const ASSOC_CONST: u32 = 0; } | ||
2504 | const GLOBAL_CONST: u32 = 101; | ||
2505 | fn 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] | ||
2527 | fn infer_static() { | ||
2528 | assert_snapshot!( | ||
2529 | infer(r#" | ||
2530 | static GLOBAL_STATIC: u32 = 101; | ||
2531 | static mut GLOBAL_STATIC_MUT: u32 = 101; | ||
2532 | fn 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] | ||
2558 | fn infer_trait_method_simple() { | ||
2559 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2560 | assert_snapshot!( | ||
2561 | infer(r#" | ||
2562 | trait Trait1 { | ||
2563 | fn method(&self) -> u32; | ||
2564 | } | ||
2565 | struct S1; | ||
2566 | impl Trait1 for S1 {} | ||
2567 | trait Trait2 { | ||
2568 | fn method(&self) -> i128; | ||
2569 | } | ||
2570 | struct S2; | ||
2571 | impl Trait2 for S2 {} | ||
2572 | fn 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] | ||
2590 | fn infer_trait_method_scoped() { | ||
2591 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2592 | assert_snapshot!( | ||
2593 | infer(r#" | ||
2594 | struct S; | ||
2595 | mod foo { | ||
2596 | pub trait Trait1 { | ||
2597 | fn method(&self) -> u32; | ||
2598 | } | ||
2599 | impl Trait1 for super::S {} | ||
2600 | } | ||
2601 | mod bar { | ||
2602 | pub trait Trait2 { | ||
2603 | fn method(&self) -> i128; | ||
2604 | } | ||
2605 | impl Trait2 for super::S {} | ||
2606 | } | ||
2607 | |||
2608 | mod foo_test { | ||
2609 | use super::S; | ||
2610 | use super::foo::Trait1; | ||
2611 | fn test() { | ||
2612 | S.method(); // -> u32 | ||
2613 | } | ||
2614 | } | ||
2615 | |||
2616 | mod 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 | |||