From 4c43631829d8bac8b7533c994d8cf1241a95ce70 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 26 Nov 2019 14:35:23 +0300 Subject: Introduce hir_ty --- crates/ra_hir_ty/Cargo.toml | 32 +++++++ crates/ra_hir_ty/src/lib.rs | 3 + crates/ra_hir_ty/src/primitive.rs | 190 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 crates/ra_hir_ty/Cargo.toml create mode 100644 crates/ra_hir_ty/src/lib.rs create mode 100644 crates/ra_hir_ty/src/primitive.rs (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml new file mode 100644 index 000000000..70216ab24 --- /dev/null +++ b/crates/ra_hir_ty/Cargo.toml @@ -0,0 +1,32 @@ +[package] +edition = "2018" +name = "ra_hir_ty" +version = "0.1.0" +authors = ["rust-analyzer developers"] + +[lib] +doctest = false + +[dependencies] +log = "0.4.5" +rustc-hash = "1.0" +parking_lot = "0.9.0" +ena = "0.13" + +ra_syntax = { path = "../ra_syntax" } +ra_arena = { path = "../ra_arena" } +ra_db = { path = "../ra_db" } +hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } +hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } +test_utils = { path = "../test_utils" } +ra_prof = { path = "../ra_prof" } + +# https://github.com/rust-lang/chalk/pull/294 +chalk-solve = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" } +chalk-rust-ir = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" } +chalk-ir = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" } + +lalrpop-intern = "0.15.1" + +[dev-dependencies] +insta = "0.12.0" diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs new file mode 100644 index 000000000..25bfc1d15 --- /dev/null +++ b/crates/ra_hir_ty/src/lib.rs @@ -0,0 +1,3 @@ +//! FIXME: write short doc here + +pub mod primitive; diff --git a/crates/ra_hir_ty/src/primitive.rs b/crates/ra_hir_ty/src/primitive.rs new file mode 100644 index 000000000..afa22448d --- /dev/null +++ b/crates/ra_hir_ty/src/primitive.rs @@ -0,0 +1,190 @@ +//! FIXME: write short doc here + +use std::fmt; + +pub use hir_def::builtin_type::{BuiltinFloat, BuiltinInt, FloatBitness, IntBitness, Signedness}; + +#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] +pub enum Uncertain { + Unknown, + Known(T), +} + +impl From for Uncertain { + fn from(ty: IntTy) -> Self { + Uncertain::Known(ty) + } +} + +impl fmt::Display for Uncertain { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Uncertain::Unknown => write!(f, "{{integer}}"), + Uncertain::Known(ty) => write!(f, "{}", ty), + } + } +} + +impl From for Uncertain { + fn from(ty: FloatTy) -> Self { + Uncertain::Known(ty) + } +} + +impl fmt::Display for Uncertain { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Uncertain::Unknown => write!(f, "{{float}}"), + Uncertain::Known(ty) => write!(f, "{}", ty), + } + } +} + +#[derive(Copy, Clone, Eq, PartialEq, Hash)] +pub struct IntTy { + pub signedness: Signedness, + pub bitness: IntBitness, +} + +impl fmt::Debug for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.ty_to_string()) + } +} + +impl IntTy { + pub fn isize() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::Xsize } + } + + pub fn i8() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::X8 } + } + + pub fn i16() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::X16 } + } + + pub fn i32() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::X32 } + } + + pub fn i64() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::X64 } + } + + pub fn i128() -> IntTy { + IntTy { signedness: Signedness::Signed, bitness: IntBitness::X128 } + } + + pub fn usize() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize } + } + + pub fn u8() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X8 } + } + + pub fn u16() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X16 } + } + + pub fn u32() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X32 } + } + + pub fn u64() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X64 } + } + + pub fn u128() -> IntTy { + IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X128 } + } + + pub fn ty_to_string(self) -> &'static str { + match (self.signedness, self.bitness) { + (Signedness::Signed, IntBitness::Xsize) => "isize", + (Signedness::Signed, IntBitness::X8) => "i8", + (Signedness::Signed, IntBitness::X16) => "i16", + (Signedness::Signed, IntBitness::X32) => "i32", + (Signedness::Signed, IntBitness::X64) => "i64", + (Signedness::Signed, IntBitness::X128) => "i128", + (Signedness::Unsigned, IntBitness::Xsize) => "usize", + (Signedness::Unsigned, IntBitness::X8) => "u8", + (Signedness::Unsigned, IntBitness::X16) => "u16", + (Signedness::Unsigned, IntBitness::X32) => "u32", + (Signedness::Unsigned, IntBitness::X64) => "u64", + (Signedness::Unsigned, IntBitness::X128) => "u128", + } + } +} + +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct FloatTy { + pub bitness: FloatBitness, +} + +impl fmt::Debug for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.ty_to_string()) + } +} + +impl FloatTy { + pub fn f32() -> FloatTy { + FloatTy { bitness: FloatBitness::X32 } + } + + pub fn f64() -> FloatTy { + FloatTy { bitness: FloatBitness::X64 } + } + + pub fn ty_to_string(self) -> &'static str { + match self.bitness { + FloatBitness::X32 => "f32", + FloatBitness::X64 => "f64", + } + } +} + +impl From for IntTy { + fn from(t: BuiltinInt) -> Self { + IntTy { signedness: t.signedness, bitness: t.bitness } + } +} + +impl From for FloatTy { + fn from(t: BuiltinFloat) -> Self { + FloatTy { bitness: t.bitness } + } +} + +impl From> for Uncertain { + fn from(t: Option) -> Self { + match t { + None => Uncertain::Unknown, + Some(t) => Uncertain::Known(t.into()), + } + } +} + +impl From> for Uncertain { + fn from(t: Option) -> Self { + match t { + None => Uncertain::Unknown, + Some(t) => Uncertain::Known(t.into()), + } + } +} -- cgit v1.2.3 From 4e17718a9aaba34533ba6a46d52b4aa959c662c7 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 26 Nov 2019 15:40:55 +0300 Subject: Doc primitives --- crates/ra_hir_ty/src/lib.rs | 3 ++- crates/ra_hir_ty/src/primitive.rs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index 25bfc1d15..28859ba63 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -1,3 +1,4 @@ -//! FIXME: write short doc here +//! Work in Progress: everything related to types, type inference and trait +//! solving. pub mod primitive; diff --git a/crates/ra_hir_ty/src/primitive.rs b/crates/ra_hir_ty/src/primitive.rs index afa22448d..02a8179d9 100644 --- a/crates/ra_hir_ty/src/primitive.rs +++ b/crates/ra_hir_ty/src/primitive.rs @@ -1,4 +1,7 @@ -//! FIXME: write short doc here +//! Defines primitive types, which have a couple of peculiarities: +//! +//! * during type inference, they can be uncertain (ie, `let x = 92;`) +//! * they don't belong to any particular crate. use std::fmt; -- cgit v1.2.3 From b81548c73a134cd63aefb9ceb20edb399bd3a16c Mon Sep 17 00:00:00 2001 From: Jeremy Kolb Date: Tue, 26 Nov 2019 08:20:40 -0500 Subject: Fix stale crates that snuck in --- crates/ra_hir_ty/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml index 70216ab24..027b50865 100644 --- a/crates/ra_hir_ty/Cargo.toml +++ b/crates/ra_hir_ty/Cargo.toml @@ -10,7 +10,7 @@ doctest = false [dependencies] log = "0.4.5" rustc-hash = "1.0" -parking_lot = "0.9.0" +parking_lot = "0.10.0" ena = "0.13" ra_syntax = { path = "../ra_syntax" } -- cgit v1.2.3 From a87579500a2c35597071efd0ad6983927f0c1815 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 17:46:02 +0300 Subject: Move Ty --- crates/ra_hir_ty/Cargo.toml | 1 + crates/ra_hir_ty/src/autoderef.rs | 108 + crates/ra_hir_ty/src/db.rs | 116 + crates/ra_hir_ty/src/diagnostics.rs | 91 + crates/ra_hir_ty/src/display.rs | 93 + crates/ra_hir_ty/src/expr.rs | 151 + crates/ra_hir_ty/src/infer.rs | 723 +++++ crates/ra_hir_ty/src/infer/coerce.rs | 354 ++ crates/ra_hir_ty/src/infer/expr.rs | 686 ++++ crates/ra_hir_ty/src/infer/pat.rs | 186 ++ crates/ra_hir_ty/src/infer/path.rs | 270 ++ crates/ra_hir_ty/src/infer/unify.rs | 162 + crates/ra_hir_ty/src/lib.rs | 1134 ++++++- crates/ra_hir_ty/src/lower.rs | 753 +++++ crates/ra_hir_ty/src/marks.rs | 9 + crates/ra_hir_ty/src/method_resolution.rs | 363 +++ crates/ra_hir_ty/src/op.rs | 50 + crates/ra_hir_ty/src/test_db.rs | 144 + crates/ra_hir_ty/src/tests.rs | 4958 +++++++++++++++++++++++++++++ crates/ra_hir_ty/src/tests/coercion.rs | 369 +++ crates/ra_hir_ty/src/tests/never_type.rs | 246 ++ crates/ra_hir_ty/src/traits.rs | 328 ++ crates/ra_hir_ty/src/traits/chalk.rs | 906 ++++++ crates/ra_hir_ty/src/utils.rs | 84 + 24 files changed, 12283 insertions(+), 2 deletions(-) create mode 100644 crates/ra_hir_ty/src/autoderef.rs create mode 100644 crates/ra_hir_ty/src/db.rs create mode 100644 crates/ra_hir_ty/src/diagnostics.rs create mode 100644 crates/ra_hir_ty/src/display.rs create mode 100644 crates/ra_hir_ty/src/expr.rs create mode 100644 crates/ra_hir_ty/src/infer.rs create mode 100644 crates/ra_hir_ty/src/infer/coerce.rs create mode 100644 crates/ra_hir_ty/src/infer/expr.rs create mode 100644 crates/ra_hir_ty/src/infer/pat.rs create mode 100644 crates/ra_hir_ty/src/infer/path.rs create mode 100644 crates/ra_hir_ty/src/infer/unify.rs create mode 100644 crates/ra_hir_ty/src/lower.rs create mode 100644 crates/ra_hir_ty/src/marks.rs create mode 100644 crates/ra_hir_ty/src/method_resolution.rs create mode 100644 crates/ra_hir_ty/src/op.rs create mode 100644 crates/ra_hir_ty/src/test_db.rs create mode 100644 crates/ra_hir_ty/src/tests.rs create mode 100644 crates/ra_hir_ty/src/tests/coercion.rs create mode 100644 crates/ra_hir_ty/src/tests/never_type.rs create mode 100644 crates/ra_hir_ty/src/traits.rs create mode 100644 crates/ra_hir_ty/src/traits/chalk.rs create mode 100644 crates/ra_hir_ty/src/utils.rs (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml index 027b50865..199afff49 100644 --- a/crates/ra_hir_ty/Cargo.toml +++ b/crates/ra_hir_ty/Cargo.toml @@ -8,6 +8,7 @@ authors = ["rust-analyzer developers"] doctest = false [dependencies] +arrayvec = "0.5.1" log = "0.4.5" rustc-hash = "1.0" parking_lot = "0.10.0" diff --git a/crates/ra_hir_ty/src/autoderef.rs b/crates/ra_hir_ty/src/autoderef.rs new file mode 100644 index 000000000..9d1d4e48c --- /dev/null +++ b/crates/ra_hir_ty/src/autoderef.rs @@ -0,0 +1,108 @@ +//! In certain situations, rust automatically inserts derefs as necessary: for +//! example, field accesses `foo.bar` still work when `foo` is actually a +//! reference to a type with the field `bar`. This is an approximation of the +//! logic in rustc (which lives in librustc_typeck/check/autoderef.rs). + +use std::iter::successors; + +use hir_def::lang_item::LangItemTarget; +use hir_expand::name; +use log::{info, warn}; +use ra_db::CrateId; + +use crate::db::HirDatabase; + +use super::{ + traits::{InEnvironment, Solution}, + Canonical, Substs, Ty, TypeWalk, +}; + +const AUTODEREF_RECURSION_LIMIT: usize = 10; + +pub fn autoderef<'a>( + db: &'a impl HirDatabase, + krate: Option, + ty: InEnvironment>, +) -> impl Iterator> + 'a { + let InEnvironment { value: ty, environment } = ty; + successors(Some(ty), move |ty| { + deref(db, krate?, InEnvironment { value: ty, environment: environment.clone() }) + }) + .take(AUTODEREF_RECURSION_LIMIT) +} + +pub(crate) fn deref( + db: &impl HirDatabase, + krate: CrateId, + ty: InEnvironment<&Canonical>, +) -> Option> { + if let Some(derefed) = ty.value.value.builtin_deref() { + Some(Canonical { value: derefed, num_vars: ty.value.num_vars }) + } else { + deref_by_trait(db, krate, ty) + } +} + +fn deref_by_trait( + db: &impl HirDatabase, + krate: CrateId, + ty: InEnvironment<&Canonical>, +) -> Option> { + let deref_trait = match db.lang_item(krate.into(), "deref".into())? { + LangItemTarget::TraitId(it) => it, + _ => return None, + }; + let target = db.trait_data(deref_trait).associated_type_by_name(&name::TARGET_TYPE)?; + + let generic_params = db.generic_params(target.into()); + if generic_params.count_params_including_parent() != 1 { + // the Target type + Deref trait should only have one generic parameter, + // namely Deref's Self type + return None; + } + + // FIXME make the Canonical handling nicer + + let parameters = Substs::build_for_generics(&generic_params) + .push(ty.value.value.clone().shift_bound_vars(1)) + .build(); + + let projection = super::traits::ProjectionPredicate { + ty: Ty::Bound(0), + projection_ty: super::ProjectionTy { associated_ty: target, parameters }, + }; + + let obligation = super::Obligation::Projection(projection); + + let in_env = InEnvironment { value: obligation, environment: ty.environment }; + + let canonical = super::Canonical { num_vars: 1 + ty.value.num_vars, value: in_env }; + + let solution = db.trait_solve(krate.into(), canonical)?; + + match &solution { + Solution::Unique(vars) => { + // FIXME: vars may contain solutions for any inference variables + // that happened to be inside ty. To correctly handle these, we + // would have to pass the solution up to the inference context, but + // that requires a larger refactoring (especially if the deref + // happens during method resolution). So for the moment, we just + // check that we're not in the situation we're we would actually + // need to handle the values of the additional variables, i.e. + // they're just being 'passed through'. In the 'standard' case where + // we have `impl Deref for Foo { Target = T }`, that should be + // the case. + for i in 1..vars.0.num_vars { + if vars.0.value[i] != Ty::Bound((i - 1) as u32) { + warn!("complex solution for derefing {:?}: {:?}, ignoring", ty.value, solution); + return None; + } + } + Some(Canonical { value: vars.0.value[0].clone(), num_vars: vars.0.num_vars }) + } + Solution::Ambig(_) => { + info!("Ambiguous solution for derefing {:?}: {:?}", ty.value, solution); + None + } + } +} diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs new file mode 100644 index 000000000..aa2659c4b --- /dev/null +++ b/crates/ra_hir_ty/src/db.rs @@ -0,0 +1,116 @@ +//! FIXME: write short doc here + +use std::sync::Arc; + +use hir_def::{ + db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId, +}; +use ra_arena::map::ArenaMap; +use ra_db::{salsa, CrateId}; + +use crate::{ + method_resolution::CrateImplBlocks, + traits::{AssocTyValue, Impl}, + CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor, + ValueTyDefId, +}; + +#[salsa::query_group(HirDatabaseStorage)] +#[salsa::requires(salsa::Database)] +pub trait HirDatabase: DefDatabase { + #[salsa::invoke(crate::infer_query)] + fn infer(&self, def: DefWithBodyId) -> Arc; + + #[salsa::invoke(crate::lower::ty_query)] + fn ty(&self, def: TyDefId) -> Ty; + + #[salsa::invoke(crate::lower::value_ty_query)] + fn value_ty(&self, def: ValueTyDefId) -> Ty; + + #[salsa::invoke(crate::lower::field_types_query)] + fn field_types(&self, var: VariantId) -> Arc>; + + #[salsa::invoke(crate::callable_item_sig)] + fn callable_item_signature(&self, def: CallableDef) -> FnSig; + + #[salsa::invoke(crate::lower::generic_predicates_for_param_query)] + fn generic_predicates_for_param( + &self, + def: GenericDefId, + param_idx: u32, + ) -> Arc<[GenericPredicate]>; + + #[salsa::invoke(crate::lower::generic_predicates_query)] + fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>; + + #[salsa::invoke(crate::lower::generic_defaults_query)] + fn generic_defaults(&self, def: GenericDefId) -> Substs; + + #[salsa::invoke(crate::method_resolution::CrateImplBlocks::impls_in_crate_query)] + fn impls_in_crate(&self, krate: CrateId) -> Arc; + + #[salsa::invoke(crate::traits::impls_for_trait_query)] + fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>; + + /// This provides the Chalk trait solver instance. Because Chalk always + /// works from a specific crate, this query is keyed on the crate; and + /// because Chalk does its own internal caching, the solver is wrapped in a + /// Mutex and the query does an untracked read internally, to make sure the + /// cached state is thrown away when input facts change. + #[salsa::invoke(crate::traits::trait_solver_query)] + fn trait_solver(&self, krate: CrateId) -> crate::traits::TraitSolver; + + // Interned IDs for Chalk integration + #[salsa::interned] + fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId; + #[salsa::interned] + fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId; + #[salsa::interned] + fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId; + + #[salsa::invoke(crate::traits::chalk::associated_ty_data_query)] + fn associated_ty_data( + &self, + id: chalk_ir::TypeId, + ) -> Arc>; + + #[salsa::invoke(crate::traits::chalk::trait_datum_query)] + fn trait_datum( + &self, + krate: CrateId, + trait_id: chalk_ir::TraitId, + ) -> Arc>; + + #[salsa::invoke(crate::traits::chalk::struct_datum_query)] + fn struct_datum( + &self, + krate: CrateId, + struct_id: chalk_ir::StructId, + ) -> Arc>; + + #[salsa::invoke(crate::traits::chalk::impl_datum_query)] + fn impl_datum( + &self, + krate: CrateId, + impl_id: chalk_ir::ImplId, + ) -> Arc>; + + #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)] + fn associated_ty_value( + &self, + krate: CrateId, + id: chalk_rust_ir::AssociatedTyValueId, + ) -> Arc>; + + #[salsa::invoke(crate::traits::trait_solve_query)] + fn trait_solve( + &self, + krate: CrateId, + goal: crate::Canonical>, + ) -> Option; +} + +#[test] +fn hir_database_is_object_safe() { + fn _assert_object_safe(_: &dyn HirDatabase) {} +} diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs new file mode 100644 index 000000000..4a13fac23 --- /dev/null +++ b/crates/ra_hir_ty/src/diagnostics.rs @@ -0,0 +1,91 @@ +//! FIXME: write short doc here + +use std::any::Any; + +use hir_expand::{db::AstDatabase, name::Name, HirFileId, Source}; +use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; + +pub use hir_def::diagnostics::UnresolvedModule; +pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; + +#[derive(Debug)] +pub struct NoSuchField { + pub file: HirFileId, + pub field: AstPtr, +} + +impl Diagnostic for NoSuchField { + fn message(&self) -> String { + "no such field".to_string() + } + + fn source(&self) -> Source { + Source { file_id: self.file, value: self.field.into() } + } + + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +#[derive(Debug)] +pub struct MissingFields { + pub file: HirFileId, + pub field_list: AstPtr, + pub missed_fields: Vec, +} + +impl Diagnostic for MissingFields { + fn message(&self) -> String { + use std::fmt::Write; + let mut message = String::from("Missing structure fields:\n"); + for field in &self.missed_fields { + write!(message, "- {}\n", field).unwrap(); + } + message + } + fn source(&self) -> Source { + Source { file_id: self.file, value: self.field_list.into() } + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +impl AstDiagnostic for MissingFields { + type AST = ast::RecordFieldList; + + fn ast(&self, db: &impl AstDatabase) -> Self::AST { + let root = db.parse_or_expand(self.source().file_id).unwrap(); + let node = self.source().value.to_node(&root); + ast::RecordFieldList::cast(node).unwrap() + } +} + +#[derive(Debug)] +pub struct MissingOkInTailExpr { + pub file: HirFileId, + pub expr: AstPtr, +} + +impl Diagnostic for MissingOkInTailExpr { + fn message(&self) -> String { + "wrap return expression in Ok".to_string() + } + fn source(&self) -> Source { + Source { file_id: self.file, value: self.expr.into() } + } + fn as_any(&self) -> &(dyn Any + Send + 'static) { + self + } +} + +impl AstDiagnostic for MissingOkInTailExpr { + type AST = ast::Expr; + + fn ast(&self, db: &impl AstDatabase) -> Self::AST { + let root = db.parse_or_expand(self.file).unwrap(); + let node = self.source().value.to_node(&root); + ast::Expr::cast(node).unwrap() + } +} diff --git a/crates/ra_hir_ty/src/display.rs b/crates/ra_hir_ty/src/display.rs new file mode 100644 index 000000000..9bb3ece6c --- /dev/null +++ b/crates/ra_hir_ty/src/display.rs @@ -0,0 +1,93 @@ +//! FIXME: write short doc here + +use std::fmt; + +use crate::db::HirDatabase; + +pub struct HirFormatter<'a, 'b, DB> { + pub db: &'a DB, + fmt: &'a mut fmt::Formatter<'b>, + buf: String, + curr_size: usize, + max_size: Option, +} + +pub trait HirDisplay { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result; + + fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> + where + Self: Sized, + { + HirDisplayWrapper(db, self, None) + } + + fn display_truncated<'a, DB>( + &'a self, + db: &'a DB, + max_size: Option, + ) -> HirDisplayWrapper<'a, DB, Self> + where + Self: Sized, + { + HirDisplayWrapper(db, self, max_size) + } +} + +impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> +where + DB: HirDatabase, +{ + pub fn write_joined( + &mut self, + iter: impl IntoIterator, + sep: &str, + ) -> fmt::Result { + let mut first = true; + for e in iter { + if !first { + write!(self, "{}", sep)?; + } + first = false; + e.hir_fmt(self)?; + } + Ok(()) + } + + /// This allows using the `write!` macro directly with a `HirFormatter`. + pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { + // We write to a buffer first to track output size + self.buf.clear(); + fmt::write(&mut self.buf, args)?; + self.curr_size += self.buf.len(); + + // Then we write to the internal formatter from the buffer + self.fmt.write_str(&self.buf) + } + + pub fn should_truncate(&self) -> bool { + if let Some(max_size) = self.max_size { + self.curr_size >= max_size + } else { + false + } + } +} + +pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option); + +impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> +where + DB: HirDatabase, + T: HirDisplay, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.1.hir_fmt(&mut HirFormatter { + db: self.0, + fmt: f, + buf: String::with_capacity(20), + curr_size: 0, + max_size: self.2, + }) + } +} diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs new file mode 100644 index 000000000..5c65f9370 --- /dev/null +++ b/crates/ra_hir_ty/src/expr.rs @@ -0,0 +1,151 @@ +//! FIXME: write short doc here + +use std::sync::Arc; + +use hir_def::{ + path::{known, Path}, + resolver::HasResolver, + AdtId, FunctionId, +}; +use hir_expand::{diagnostics::DiagnosticSink, name::Name}; +use ra_syntax::ast; +use ra_syntax::AstPtr; +use rustc_hash::FxHashSet; + +use crate::{ + db::HirDatabase, + diagnostics::{MissingFields, MissingOkInTailExpr}, + ApplicationTy, InferenceResult, Ty, TypeCtor, +}; + +pub use hir_def::{ + body::{ + scope::{ExprScopes, ScopeEntry, ScopeId}, + Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource, + }, + expr::{ + ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp, + MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp, + }, +}; + +pub struct ExprValidator<'a, 'b: 'a> { + func: FunctionId, + infer: Arc, + sink: &'a mut DiagnosticSink<'b>, +} + +impl<'a, 'b> ExprValidator<'a, 'b> { + pub fn new( + func: FunctionId, + infer: Arc, + sink: &'a mut DiagnosticSink<'b>, + ) -> ExprValidator<'a, 'b> { + ExprValidator { func, infer, sink } + } + + pub fn validate_body(&mut self, db: &impl HirDatabase) { + let body = db.body(self.func.into()); + + for e in body.exprs.iter() { + if let (id, Expr::RecordLit { path, fields, spread }) = e { + self.validate_record_literal(id, path, fields, *spread, db); + } + } + + let body_expr = &body[body.body_expr]; + if let Expr::Block { statements: _, tail: Some(t) } = body_expr { + self.validate_results_in_tail_expr(body.body_expr, *t, db); + } + } + + fn validate_record_literal( + &mut self, + id: ExprId, + _path: &Option, + fields: &[RecordLitField], + spread: Option, + db: &impl HirDatabase, + ) { + if spread.is_some() { + return; + } + + let struct_def = match self.infer[id].as_adt() { + Some((AdtId::StructId(s), _)) => s, + _ => return, + }; + let struct_data = db.struct_data(struct_def); + + let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); + let missed_fields: Vec = struct_data + .variant_data + .fields() + .iter() + .filter_map(|(_f, d)| { + let name = d.name.clone(); + if lit_fields.contains(&name) { + None + } else { + Some(name) + } + }) + .collect(); + if missed_fields.is_empty() { + return; + } + let (_, source_map) = db.body_with_source_map(self.func.into()); + + if let Some(source_ptr) = source_map.expr_syntax(id) { + if let Some(expr) = source_ptr.value.a() { + let root = source_ptr.file_syntax(db); + if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) { + if let Some(field_list) = record_lit.record_field_list() { + self.sink.push(MissingFields { + file: source_ptr.file_id, + field_list: AstPtr::new(&field_list), + missed_fields, + }) + } + } + } + } + } + + fn validate_results_in_tail_expr( + &mut self, + body_id: ExprId, + id: ExprId, + db: &impl HirDatabase, + ) { + // the mismatch will be on the whole block currently + let mismatch = match self.infer.type_mismatch_for_expr(body_id) { + Some(m) => m, + None => return, + }; + + let std_result_path = known::std_result_result(); + + let resolver = self.func.resolver(db); + let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { + Some(it) => it, + _ => return, + }; + + let std_result_ctor = TypeCtor::Adt(AdtId::EnumId(std_result_enum)); + let params = match &mismatch.expected { + Ty::Apply(ApplicationTy { ctor, parameters }) if ctor == &std_result_ctor => parameters, + _ => return, + }; + + if params.len() == 2 && ¶ms[0] == &mismatch.actual { + let (_, source_map) = db.body_with_source_map(self.func.into()); + + if let Some(source_ptr) = source_map.expr_syntax(id) { + if let Some(expr) = source_ptr.value.a() { + self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr }); + } + } + } + } +} diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs new file mode 100644 index 000000000..1e9f4b208 --- /dev/null +++ b/crates/ra_hir_ty/src/infer.rs @@ -0,0 +1,723 @@ +//! Type inference, i.e. the process of walking through the code and determining +//! the type of each expression and pattern. +//! +//! For type inference, compare the implementations in rustc (the various +//! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and +//! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for +//! inference here is the `infer` function, which infers the types of all +//! expressions in a given function. +//! +//! During inference, types (i.e. the `Ty` struct) can contain type 'variables' +//! which represent currently unknown types; as we walk through the expressions, +//! we might determine that certain variables need to be equal to each other, or +//! to certain types. To record this, we use the union-find implementation from +//! the `ena` crate, which is extracted from rustc. + +use std::borrow::Cow; +use std::mem; +use std::ops::Index; +use std::sync::Arc; + +use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; +use rustc_hash::FxHashMap; + +use hir_def::{ + body::Body, + data::{ConstData, FunctionData}, + expr::{BindingAnnotation, ExprId, PatId}, + path::{known, Path}, + resolver::{HasResolver, Resolver, TypeNs}, + type_ref::{Mutability, TypeRef}, + AdtId, AssocItemId, DefWithBodyId, FunctionId, StructFieldId, TypeAliasId, VariantId, +}; +use hir_expand::{diagnostics::DiagnosticSink, name}; +use ra_arena::map::ArenaMap; +use ra_prof::profile; +use test_utils::tested_by; + +use super::{ + primitive::{FloatTy, IntTy}, + traits::{Guidance, Obligation, ProjectionPredicate, Solution}, + ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor, + TypeWalk, Uncertain, +}; +use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic}; + +macro_rules! ty_app { + ($ctor:pat, $param:pat) => { + crate::Ty::Apply(crate::ApplicationTy { ctor: $ctor, parameters: $param }) + }; + ($ctor:pat) => { + ty_app!($ctor, _) + }; +} + +mod unify; +mod path; +mod expr; +mod pat; +mod coerce; + +/// The entry point of type inference. +pub fn infer_query(db: &impl HirDatabase, def: DefWithBodyId) -> Arc { + let _p = profile("infer_query"); + let resolver = def.resolver(db); + let mut ctx = InferenceContext::new(db, def, resolver); + + match def { + DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)), + DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)), + DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)), + } + + ctx.infer_body(); + + Arc::new(ctx.resolve_all()) +} + +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +enum ExprOrPatId { + ExprId(ExprId), + PatId(PatId), +} + +impl_froms!(ExprOrPatId: ExprId, PatId); + +/// Binding modes inferred for patterns. +/// https://doc.rust-lang.org/reference/patterns.html#binding-modes +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +enum BindingMode { + Move, + Ref(Mutability), +} + +impl BindingMode { + pub fn convert(annotation: BindingAnnotation) -> BindingMode { + match annotation { + BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, + BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), + BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut), + } + } +} + +impl Default for BindingMode { + fn default() -> Self { + BindingMode::Move + } +} + +/// A mismatch between an expected and an inferred type. +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub struct TypeMismatch { + pub expected: Ty, + pub actual: Ty, +} + +/// The result of type inference: A mapping from expressions and patterns to types. +#[derive(Clone, PartialEq, Eq, Debug, Default)] +pub struct InferenceResult { + /// For each method call expr, records the function it resolves to. + method_resolutions: FxHashMap, + /// For each field access expr, records the field it resolves to. + field_resolutions: FxHashMap, + /// For each field in record literal, records the field it resolves to. + record_field_resolutions: FxHashMap, + /// For each struct literal, records the variant it resolves to. + variant_resolutions: FxHashMap, + /// For each associated item record what it resolves to + assoc_resolutions: FxHashMap, + diagnostics: Vec, + pub type_of_expr: ArenaMap, + pub type_of_pat: ArenaMap, + pub(super) type_mismatches: ArenaMap, +} + +impl InferenceResult { + pub fn method_resolution(&self, expr: ExprId) -> Option { + self.method_resolutions.get(&expr).copied() + } + pub fn field_resolution(&self, expr: ExprId) -> Option { + self.field_resolutions.get(&expr).copied() + } + pub fn record_field_resolution(&self, expr: ExprId) -> Option { + self.record_field_resolutions.get(&expr).copied() + } + pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option { + self.variant_resolutions.get(&id.into()).copied() + } + pub fn variant_resolution_for_pat(&self, id: PatId) -> Option { + self.variant_resolutions.get(&id.into()).copied() + } + pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option { + self.assoc_resolutions.get(&id.into()).copied() + } + pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option { + self.assoc_resolutions.get(&id.into()).copied() + } + pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { + self.type_mismatches.get(expr) + } + pub fn add_diagnostics( + &self, + db: &impl HirDatabase, + owner: FunctionId, + sink: &mut DiagnosticSink, + ) { + self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink)) + } +} + +impl Index for InferenceResult { + type Output = Ty; + + fn index(&self, expr: ExprId) -> &Ty { + self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) + } +} + +impl Index for InferenceResult { + type Output = Ty; + + fn index(&self, pat: PatId) -> &Ty { + self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) + } +} + +/// The inference context contains all information needed during type inference. +#[derive(Clone, Debug)] +struct InferenceContext<'a, D: HirDatabase> { + db: &'a D, + owner: DefWithBodyId, + body: Arc, + resolver: Resolver, + var_unification_table: InPlaceUnificationTable, + trait_env: Arc, + obligations: Vec, + result: InferenceResult, + /// The return type of the function being inferred. + return_ty: Ty, + + /// Impls of `CoerceUnsized` used in coercion. + /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index + // FIXME: Use trait solver for this. + // Chalk seems unable to work well with builtin impl of `Unsize` now. + coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, +} + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + fn new(db: &'a D, owner: DefWithBodyId, resolver: Resolver) -> Self { + InferenceContext { + result: InferenceResult::default(), + var_unification_table: InPlaceUnificationTable::new(), + obligations: Vec::default(), + return_ty: Ty::Unknown, // set in collect_fn_signature + trait_env: TraitEnvironment::lower(db, &resolver), + coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver), + db, + owner, + body: db.body(owner.into()), + resolver, + } + } + + fn resolve_all(mut self) -> InferenceResult { + // FIXME resolve obligations as well (use Guidance if necessary) + let mut result = mem::replace(&mut self.result, InferenceResult::default()); + let mut tv_stack = Vec::new(); + for ty in result.type_of_expr.values_mut() { + let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); + *ty = resolved; + } + for ty in result.type_of_pat.values_mut() { + let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); + *ty = resolved; + } + result + } + + fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) { + self.result.type_of_expr.insert(expr, ty); + } + + fn write_method_resolution(&mut self, expr: ExprId, func: FunctionId) { + self.result.method_resolutions.insert(expr, func); + } + + fn write_field_resolution(&mut self, expr: ExprId, field: StructFieldId) { + self.result.field_resolutions.insert(expr, field); + } + + fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantId) { + self.result.variant_resolutions.insert(id, variant); + } + + fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItemId) { + self.result.assoc_resolutions.insert(id, item.into()); + } + + fn write_pat_ty(&mut self, pat: PatId, ty: Ty) { + self.result.type_of_pat.insert(pat, ty); + } + + fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) { + self.result.diagnostics.push(diagnostic); + } + + fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { + let ty = Ty::from_hir( + self.db, + // FIXME use right resolver for block + &self.resolver, + type_ref, + ); + let ty = self.insert_type_vars(ty); + self.normalize_associated_types_in(ty) + } + + fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { + substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) + } + + fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { + self.unify_inner(ty1, ty2, 0) + } + + fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { + if depth > 1000 { + // prevent stackoverflows + panic!("infinite recursion in unification"); + } + if ty1 == ty2 { + return true; + } + // try to resolve type vars first + let ty1 = self.resolve_ty_shallow(ty1); + let ty2 = self.resolve_ty_shallow(ty2); + match (&*ty1, &*ty2) { + (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { + self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) + } + _ => self.unify_inner_trivial(&ty1, &ty2), + } + } + + fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { + match (ty1, ty2) { + (Ty::Unknown, _) | (_, Ty::Unknown) => true, + + (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) + | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) + | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) + | ( + Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), + Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), + ) => { + // both type vars are unknown since we tried to resolve them + self.var_unification_table.union(*tv1, *tv2); + true + } + + // The order of MaybeNeverTypeVar matters here. + // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. + // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. + (Ty::Infer(InferTy::TypeVar(tv)), other) + | (other, Ty::Infer(InferTy::TypeVar(tv))) + | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) + | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) + | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) + | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) + | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) + | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { + // the type var is unknown since we tried to resolve it + self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); + true + } + + _ => false, + } + } + + fn new_type_var(&mut self) -> Ty { + Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) + } + + fn new_integer_var(&mut self) -> Ty { + Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) + } + + fn new_float_var(&mut self) -> Ty { + Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) + } + + fn new_maybe_never_type_var(&mut self) -> Ty { + Ty::Infer(InferTy::MaybeNeverTypeVar( + self.var_unification_table.new_key(TypeVarValue::Unknown), + )) + } + + /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. + fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { + match ty { + Ty::Unknown => self.new_type_var(), + Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => { + self.new_integer_var() + } + Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => { + self.new_float_var() + } + _ => ty, + } + } + + fn insert_type_vars(&mut self, ty: Ty) -> Ty { + ty.fold(&mut |ty| self.insert_type_vars_shallow(ty)) + } + + fn resolve_obligations_as_possible(&mut self) { + let obligations = mem::replace(&mut self.obligations, Vec::new()); + for obligation in obligations { + let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone()); + let canonicalized = self.canonicalizer().canonicalize_obligation(in_env); + let solution = self + .db + .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone()); + + match solution { + Some(Solution::Unique(substs)) => { + canonicalized.apply_solution(self, substs.0); + } + Some(Solution::Ambig(Guidance::Definite(substs))) => { + canonicalized.apply_solution(self, substs.0); + self.obligations.push(obligation); + } + Some(_) => { + // FIXME use this when trying to resolve everything at the end + self.obligations.push(obligation); + } + None => { + // FIXME obligation cannot be fulfilled => diagnostic + } + }; + } + } + + /// Resolves the type as far as currently possible, replacing type variables + /// by their known types. All types returned by the infer_* functions should + /// be resolved as far as possible, i.e. contain no type variables with + /// known type. + fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec, ty: Ty) -> Ty { + self.resolve_obligations_as_possible(); + + ty.fold(&mut |ty| match ty { + Ty::Infer(tv) => { + let inner = tv.to_inner(); + if tv_stack.contains(&inner) { + tested_by!(type_var_cycles_resolve_as_possible); + // recursive type + return tv.fallback_value(); + } + if let Some(known_ty) = + self.var_unification_table.inlined_probe_value(inner).known() + { + // known_ty may contain other variables that are known by now + tv_stack.push(inner); + let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); + tv_stack.pop(); + result + } else { + ty + } + } + _ => ty, + }) + } + + /// If `ty` is a type variable with known type, returns that type; + /// otherwise, return ty. + fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { + let mut ty = Cow::Borrowed(ty); + // The type variable could resolve to a int/float variable. Hence try + // resolving up to three times; each type of variable shouldn't occur + // more than once + for i in 0..3 { + if i > 0 { + tested_by!(type_var_resolves_to_int_var); + } + match &*ty { + Ty::Infer(tv) => { + let inner = tv.to_inner(); + match self.var_unification_table.inlined_probe_value(inner).known() { + Some(known_ty) => { + // The known_ty can't be a type var itself + ty = Cow::Owned(known_ty.clone()); + } + _ => return ty, + } + } + _ => return ty, + } + } + log::error!("Inference variable still not resolved: {:?}", ty); + ty + } + + /// Recurses through the given type, normalizing associated types mentioned + /// in it by replacing them by type variables and registering obligations to + /// resolve later. This should be done once for every type we get from some + /// type annotation (e.g. from a let type annotation, field type or function + /// call). `make_ty` handles this already, but e.g. for field types we need + /// to do it as well. + fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + ty.fold(&mut |ty| match ty { + Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), + _ => ty, + }) + } + + fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { + let var = self.new_type_var(); + let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() }; + let obligation = Obligation::Projection(predicate); + self.obligations.push(obligation); + var + } + + /// Resolves the type completely; type variables without known type are + /// replaced by Ty::Unknown. + fn resolve_ty_completely(&mut self, tv_stack: &mut Vec, ty: Ty) -> Ty { + ty.fold(&mut |ty| match ty { + Ty::Infer(tv) => { + let inner = tv.to_inner(); + if tv_stack.contains(&inner) { + tested_by!(type_var_cycles_resolve_completely); + // recursive type + return tv.fallback_value(); + } + if let Some(known_ty) = + self.var_unification_table.inlined_probe_value(inner).known() + { + // known_ty may contain other variables that are known by now + tv_stack.push(inner); + let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); + tv_stack.pop(); + result + } else { + tv.fallback_value() + } + } + _ => ty, + }) + } + + fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option) { + let path = match path { + Some(path) => path, + None => return (Ty::Unknown, None), + }; + let resolver = &self.resolver; + // FIXME: this should resolve assoc items as well, see this example: + // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 + match resolver.resolve_path_in_type_ns_fully(self.db, &path) { + Some(TypeNs::AdtId(AdtId::StructId(strukt))) => { + let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into()); + let ty = self.db.ty(strukt.into()); + let ty = self.insert_type_vars(ty.apply_substs(substs)); + (ty, Some(strukt.into())) + } + Some(TypeNs::EnumVariantId(var)) => { + let substs = Ty::substs_from_path(self.db, resolver, path, var.into()); + let ty = self.db.ty(var.parent.into()); + let ty = self.insert_type_vars(ty.apply_substs(substs)); + (ty, Some(var.into())) + } + Some(_) | None => (Ty::Unknown, None), + } + } + + fn collect_const(&mut self, data: &ConstData) { + self.return_ty = self.make_ty(&data.type_ref); + } + + fn collect_fn(&mut self, data: &FunctionData) { + let body = Arc::clone(&self.body); // avoid borrow checker problem + for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { + let ty = self.make_ty(type_ref); + + self.infer_pat(*pat, &ty, BindingMode::default()); + } + self.return_ty = self.make_ty(&data.ret_type); + } + + fn infer_body(&mut self) { + self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone())); + } + + fn resolve_into_iter_item(&self) -> Option { + let path = known::std_iter_into_iterator(); + let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; + self.db.trait_data(trait_).associated_type_by_name(&name::ITEM_TYPE) + } + + fn resolve_ops_try_ok(&self) -> Option { + let path = known::std_ops_try(); + let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; + self.db.trait_data(trait_).associated_type_by_name(&name::OK_TYPE) + } + + fn resolve_future_future_output(&self) -> Option { + let path = known::std_future_future(); + let trait_ = self.resolver.resolve_known_trait(self.db, &path)?; + self.db.trait_data(trait_).associated_type_by_name(&name::OUTPUT_TYPE) + } + + fn resolve_boxed_box(&self) -> Option { + let path = known::std_boxed_box(); + let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; + Some(struct_.into()) + } +} + +/// The ID of a type variable. +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +pub struct TypeVarId(pub(super) u32); + +impl UnifyKey for TypeVarId { + type Value = TypeVarValue; + + fn index(&self) -> u32 { + self.0 + } + + fn from_index(i: u32) -> Self { + TypeVarId(i) + } + + fn tag() -> &'static str { + "TypeVarId" + } +} + +/// The value of a type variable: either we already know the type, or we don't +/// know it yet. +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum TypeVarValue { + Known(Ty), + Unknown, +} + +impl TypeVarValue { + fn known(&self) -> Option<&Ty> { + match self { + TypeVarValue::Known(ty) => Some(ty), + TypeVarValue::Unknown => None, + } + } +} + +impl UnifyValue for TypeVarValue { + type Error = NoError; + + fn unify_values(value1: &Self, value2: &Self) -> Result { + match (value1, value2) { + // We should never equate two type variables, both of which have + // known types. Instead, we recursively equate those types. + (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!( + "equating two type variables, both of which have known types: {:?} and {:?}", + t1, t2 + ), + + // If one side is known, prefer that one. + (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()), + (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()), + + (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown), + } + } +} + +/// The kinds of placeholders we need during type inference. There's separate +/// values for general types, and for integer and float variables. The latter +/// two are used for inference of literal values (e.g. `100` could be one of +/// several integer types). +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum InferTy { + TypeVar(TypeVarId), + IntVar(TypeVarId), + FloatVar(TypeVarId), + MaybeNeverTypeVar(TypeVarId), +} + +impl InferTy { + fn to_inner(self) -> TypeVarId { + match self { + InferTy::TypeVar(ty) + | InferTy::IntVar(ty) + | InferTy::FloatVar(ty) + | InferTy::MaybeNeverTypeVar(ty) => ty, + } + } + + fn fallback_value(self) -> Ty { + match self { + InferTy::TypeVar(..) => Ty::Unknown, + InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))), + InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))), + InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never), + } + } +} + +/// When inferring an expression, we propagate downward whatever type hint we +/// are able in the form of an `Expectation`. +#[derive(Clone, PartialEq, Eq, Debug)] +struct Expectation { + ty: Ty, + // FIXME: In some cases, we need to be aware whether the expectation is that + // the type match exactly what we passed, or whether it just needs to be + // coercible to the expected type. See Expectation::rvalue_hint in rustc. +} + +impl Expectation { + /// The expectation that the type of the expression needs to equal the given + /// type. + fn has_type(ty: Ty) -> Self { + Expectation { ty } + } + + /// This expresses no expectation on the type. + fn none() -> Self { + Expectation { ty: Ty::Unknown } + } +} + +mod diagnostics { + use hir_def::{expr::ExprId, FunctionId, HasSource, Lookup}; + use hir_expand::diagnostics::DiagnosticSink; + + use crate::{db::HirDatabase, diagnostics::NoSuchField}; + + #[derive(Debug, PartialEq, Eq, Clone)] + pub(super) enum InferenceDiagnostic { + NoSuchField { expr: ExprId, field: usize }, + } + + impl InferenceDiagnostic { + pub(super) fn add_to( + &self, + db: &impl HirDatabase, + owner: FunctionId, + sink: &mut DiagnosticSink, + ) { + match self { + InferenceDiagnostic::NoSuchField { expr, field } => { + let file = owner.lookup(db).source(db).file_id; + let (_, source_map) = db.body_with_source_map(owner.into()); + let field = source_map.field_syntax(*expr, *field); + sink.push(NoSuchField { file, field }) + } + } + } + } +} diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs new file mode 100644 index 000000000..d66a21932 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/coerce.rs @@ -0,0 +1,354 @@ +//! Coercion logic. Coercions are certain type conversions that can implicitly +//! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions +//! like going from `&Vec` to `&[T]`. +//! +//! See: https://doc.rust-lang.org/nomicon/coercions.html + +use hir_def::{ + lang_item::LangItemTarget, + resolver::{HasResolver, Resolver}, + type_ref::Mutability, + AdtId, +}; +use rustc_hash::FxHashMap; +use test_utils::tested_by; + +use crate::{autoderef, db::HirDatabase, Substs, TraitRef, Ty, TypeCtor, TypeWalk}; + +use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + /// Unify two types, but may coerce the first one to the second one + /// using "implicit coercion rules" if needed. + pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { + let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); + let to_ty = self.resolve_ty_shallow(to_ty); + self.coerce_inner(from_ty, &to_ty) + } + + /// Merge two types from different branches, with possible implicit coerce. + /// + /// Note that it is only possible that one type are coerced to another. + /// Coercing both types to another least upper bound type is not possible in rustc, + /// which will simply result in "incompatible types" error. + pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { + if self.coerce(ty1, ty2) { + ty2.clone() + } else if self.coerce(ty2, ty1) { + ty1.clone() + } else { + tested_by!(coerce_merge_fail_fallback); + // For incompatible types, we use the latter one as result + // to be better recovery for `if` without `else`. + ty2.clone() + } + } + + pub(super) fn init_coerce_unsized_map( + db: &'a D, + resolver: &Resolver, + ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { + let krate = resolver.krate().unwrap(); + let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) { + Some(LangItemTarget::TraitId(trait_)) => { + db.impls_for_trait(krate.into(), trait_.into()) + } + _ => return FxHashMap::default(), + }; + + impls + .iter() + .filter_map(|&impl_id| { + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + + // `CoerseUnsized` has one generic parameter for the target type. + let trait_ref = TraitRef::from_hir( + db, + &resolver, + impl_data.target_trait.as_ref()?, + Some(target_ty), + )?; + let cur_from_ty = trait_ref.substs.0.get(0)?; + let cur_to_ty = trait_ref.substs.0.get(1)?; + + match (&cur_from_ty, cur_to_ty) { + (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { + // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. + // This works for smart-pointer-like coercion, which covers all impls from std. + st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { + match (ty1, ty2) { + (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) + if p1 != p2 => + { + Some(((*ctor1, *ctor2), i)) + } + _ => None, + } + }) + } + _ => None, + } + }) + .collect() + } + + fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { + match (&from_ty, to_ty) { + // Never type will make type variable to fallback to Never Type instead of Unknown. + (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { + let var = self.new_maybe_never_type_var(); + self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); + return true; + } + (ty_app!(TypeCtor::Never), _) => return true, + + // Trivial cases, this should go after `never` check to + // avoid infer result type to be never + _ => { + if self.unify_inner_trivial(&from_ty, &to_ty) { + return true; + } + } + } + + // Pointer weakening and function to pointer + match (&mut from_ty, to_ty) { + // `*mut T`, `&mut T, `&T`` -> `*const T` + // `&mut T` -> `&T` + // `&mut T` -> `*mut T` + (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) + | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) + | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) + | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { + *c1 = *c2; + } + + // Illegal mutablity conversion + ( + ty_app!(TypeCtor::RawPtr(Mutability::Shared)), + ty_app!(TypeCtor::RawPtr(Mutability::Mut)), + ) + | ( + ty_app!(TypeCtor::Ref(Mutability::Shared)), + ty_app!(TypeCtor::Ref(Mutability::Mut)), + ) => return false, + + // `{function_type}` -> `fn()` + (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { + match from_ty.callable_sig(self.db) { + None => return false, + Some(sig) => { + let num_args = sig.params_and_return.len() as u16 - 1; + from_ty = + Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); + } + } + } + + _ => {} + } + + if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { + return ret; + } + + // Auto Deref if cannot coerce + match (&from_ty, to_ty) { + // FIXME: DerefMut + (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { + self.unify_autoderef_behind_ref(&st1[0], &st2[0]) + } + + // Otherwise, normal unify + _ => self.unify(&from_ty, to_ty), + } + } + + /// Coerce a type using `from_ty: CoerceUnsized` + /// + /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html + fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option { + let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { + (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), + _ => return None, + }; + + let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; + + // Check `Unsize` first + match self.check_unsize_and_coerce( + st1.0.get(coerce_generic_index)?, + st2.0.get(coerce_generic_index)?, + 0, + ) { + Some(true) => {} + ret => return ret, + } + + let ret = st1 + .iter() + .zip(st2.iter()) + .enumerate() + .filter(|&(idx, _)| idx != coerce_generic_index) + .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); + + Some(ret) + } + + /// Check if `from_ty: Unsize`, and coerce to `to_ty` if it holds. + /// + /// It should not be directly called. It is only used by `try_coerce_unsized`. + /// + /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html + fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option { + if depth > 1000 { + panic!("Infinite recursion in coercion"); + } + + match (&from_ty, &to_ty) { + // `[T; N]` -> `[T]` + (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { + Some(self.unify(&st1[0], &st2[0])) + } + + // `T` -> `dyn Trait` when `T: Trait` + (_, Ty::Dyn(_)) => { + // FIXME: Check predicates + Some(true) + } + + // `(..., T)` -> `(..., U)` when `T: Unsize` + ( + ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), + ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), + ) => { + if len1 != len2 || *len1 == 0 { + return None; + } + + match self.check_unsize_and_coerce( + st1.last().unwrap(), + st2.last().unwrap(), + depth + 1, + ) { + Some(true) => {} + ret => return ret, + } + + let ret = st1[..st1.len() - 1] + .iter() + .zip(&st2[..st2.len() - 1]) + .all(|(ty1, ty2)| self.unify(ty1, ty2)); + + Some(ret) + } + + // Foo<..., T, ...> is Unsize> if: + // - T: Unsize + // - Foo is a struct + // - Only the last field of Foo has a type involving T + // - T is not part of the type of any other fields + // - Bar: Unsize>, if the last field of Foo has type Bar + ( + ty_app!(TypeCtor::Adt(AdtId::StructId(struct1)), st1), + ty_app!(TypeCtor::Adt(AdtId::StructId(struct2)), st2), + ) if struct1 == struct2 => { + let field_tys = self.db.field_types((*struct1).into()); + let struct_data = self.db.struct_data(*struct1); + + let mut fields = struct_data.variant_data.fields().iter(); + let (last_field_id, _data) = fields.next_back()?; + + // Get the generic parameter involved in the last field. + let unsize_generic_index = { + let mut index = None; + let mut multiple_param = false; + field_tys[last_field_id].walk(&mut |ty| match ty { + &Ty::Param { idx, .. } => { + if index.is_none() { + index = Some(idx); + } else if Some(idx) != index { + multiple_param = true; + } + } + _ => {} + }); + + if multiple_param { + return None; + } + index? + }; + + // Check other fields do not involve it. + let mut multiple_used = false; + fields.for_each(|(field_id, _data)| { + field_tys[field_id].walk(&mut |ty| match ty { + &Ty::Param { idx, .. } if idx == unsize_generic_index => { + multiple_used = true + } + _ => {} + }) + }); + if multiple_used { + return None; + } + + let unsize_generic_index = unsize_generic_index as usize; + + // Check `Unsize` first + match self.check_unsize_and_coerce( + st1.get(unsize_generic_index)?, + st2.get(unsize_generic_index)?, + depth + 1, + ) { + Some(true) => {} + ret => return ret, + } + + // Then unify other parameters + let ret = st1 + .iter() + .zip(st2.iter()) + .enumerate() + .filter(|&(idx, _)| idx != unsize_generic_index) + .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); + + Some(ret) + } + + _ => None, + } + } + + /// Unify `from_ty` to `to_ty` with optional auto Deref + /// + /// Note that the parameters are already stripped the outer reference. + fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { + let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); + let to_ty = self.resolve_ty_shallow(&to_ty); + // FIXME: Auto DerefMut + for derefed_ty in autoderef::autoderef( + self.db, + self.resolver.krate(), + InEnvironment { + value: canonicalized.value.clone(), + environment: self.trait_env.clone(), + }, + ) { + let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); + match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { + // Stop when constructor matches. + (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { + // It will not recurse to `coerce`. + return self.unify_substs(st1, st2, 0); + } + _ => {} + } + } + + false + } +} diff --git a/crates/ra_hir_ty/src/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs new file mode 100644 index 000000000..2f9ca4bbb --- /dev/null +++ b/crates/ra_hir_ty/src/infer/expr.rs @@ -0,0 +1,686 @@ +//! Type inference for expressions. + +use std::iter::{repeat, repeat_with}; +use std::sync::Arc; + +use hir_def::{ + builtin_type::Signedness, + expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, + generics::GenericParams, + path::{GenericArg, GenericArgs}, + resolver::resolver_for_expr, + AdtId, ContainerId, Lookup, StructFieldId, +}; +use hir_expand::name::{self, Name}; + +use crate::{ + autoderef, db::HirDatabase, method_resolution, op, traits::InEnvironment, utils::variant_data, + CallableDef, InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs, + TraitRef, Ty, TypeCtor, TypeWalk, Uncertain, +}; + +use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { + let ty = self.infer_expr_inner(tgt_expr, expected); + let could_unify = self.unify(&ty, &expected.ty); + if !could_unify { + self.result.type_mismatches.insert( + tgt_expr, + TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, + ); + } + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + ty + } + + /// Infer type of expression with possibly implicit coerce to the expected type. + /// Return the type after possible coercion. + fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { + let ty = self.infer_expr_inner(expr, &expected); + let ty = if !self.coerce(&ty, &expected.ty) { + self.result + .type_mismatches + .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); + // Return actual type when type mismatch. + // This is needed for diagnostic when return type mismatch. + ty + } else if expected.ty == Ty::Unknown { + ty + } else { + expected.ty.clone() + }; + + self.resolve_ty_as_possible(&mut vec![], ty) + } + + fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { + let body = Arc::clone(&self.body); // avoid borrow checker problem + let ty = match &body[tgt_expr] { + Expr::Missing => Ty::Unknown, + Expr::If { condition, then_branch, else_branch } => { + // if let is desugared to match, so this is always simple if + self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); + + let then_ty = self.infer_expr_inner(*then_branch, &expected); + let else_ty = match else_branch { + Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), + None => Ty::unit(), + }; + + self.coerce_merge_branch(&then_ty, &else_ty) + } + Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), + Expr::TryBlock { body } => { + let _inner = self.infer_expr(*body, expected); + // FIXME should be std::result::Result<{inner}, _> + Ty::Unknown + } + Expr::Loop { body } => { + self.infer_expr(*body, &Expectation::has_type(Ty::unit())); + // FIXME handle break with value + Ty::simple(TypeCtor::Never) + } + Expr::While { condition, body } => { + // while let is desugared to a match loop, so this is always simple while + self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); + self.infer_expr(*body, &Expectation::has_type(Ty::unit())); + Ty::unit() + } + Expr::For { iterable, body, pat } => { + let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); + + let pat_ty = match self.resolve_into_iter_item() { + Some(into_iter_item_alias) => { + let pat_ty = self.new_type_var(); + let projection = ProjectionPredicate { + ty: pat_ty.clone(), + projection_ty: ProjectionTy { + associated_ty: into_iter_item_alias, + parameters: Substs::single(iterable_ty), + }, + }; + self.obligations.push(Obligation::Projection(projection)); + self.resolve_ty_as_possible(&mut vec![], pat_ty) + } + None => Ty::Unknown, + }; + + self.infer_pat(*pat, &pat_ty, BindingMode::default()); + self.infer_expr(*body, &Expectation::has_type(Ty::unit())); + Ty::unit() + } + Expr::Lambda { body, args, arg_types } => { + assert_eq!(args.len(), arg_types.len()); + + let mut sig_tys = Vec::new(); + + for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { + let expected = if let Some(type_ref) = arg_type { + self.make_ty(type_ref) + } else { + Ty::Unknown + }; + let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); + sig_tys.push(arg_ty); + } + + // add return type + let ret_ty = self.new_type_var(); + sig_tys.push(ret_ty.clone()); + let sig_ty = Ty::apply( + TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, + Substs(sig_tys.into()), + ); + let closure_ty = Ty::apply_one( + TypeCtor::Closure { def: self.owner.into(), expr: tgt_expr }, + sig_ty, + ); + + // Eagerly try to relate the closure type with the expected + // type, otherwise we often won't have enough information to + // infer the body. + self.coerce(&closure_ty, &expected.ty); + + self.infer_expr(*body, &Expectation::has_type(ret_ty)); + closure_ty + } + Expr::Call { callee, args } => { + let callee_ty = self.infer_expr(*callee, &Expectation::none()); + let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { + Some(sig) => (sig.params().to_vec(), sig.ret().clone()), + None => { + // Not callable + // FIXME: report an error + (Vec::new(), Ty::Unknown) + } + }; + self.register_obligations_for_call(&callee_ty); + self.check_call_arguments(args, ¶m_tys); + let ret_ty = self.normalize_associated_types_in(ret_ty); + ret_ty + } + Expr::MethodCall { receiver, args, method_name, generic_args } => self + .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), + Expr::Match { expr, arms } => { + let input_ty = self.infer_expr(*expr, &Expectation::none()); + + let mut result_ty = self.new_maybe_never_type_var(); + + for arm in arms { + for &pat in &arm.pats { + let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); + } + if let Some(guard_expr) = arm.guard { + self.infer_expr( + guard_expr, + &Expectation::has_type(Ty::simple(TypeCtor::Bool)), + ); + } + + let arm_ty = self.infer_expr_inner(arm.expr, &expected); + result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); + } + + result_ty + } + Expr::Path(p) => { + // FIXME this could be more efficient... + let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr); + self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) + } + Expr::Continue => Ty::simple(TypeCtor::Never), + Expr::Break { expr } => { + if let Some(expr) = expr { + // FIXME handle break with value + self.infer_expr(*expr, &Expectation::none()); + } + Ty::simple(TypeCtor::Never) + } + Expr::Return { expr } => { + if let Some(expr) = expr { + self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); + } + Ty::simple(TypeCtor::Never) + } + Expr::RecordLit { path, fields, spread } => { + let (ty, def_id) = self.resolve_variant(path.as_ref()); + if let Some(variant) = def_id { + self.write_variant_resolution(tgt_expr.into(), variant); + } + + self.unify(&ty, &expected.ty); + + let substs = ty.substs().unwrap_or_else(Substs::empty); + let field_types = + def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default(); + let variant_data = def_id.map(|it| variant_data(self.db, it)); + for (field_idx, field) in fields.iter().enumerate() { + let field_def = + variant_data.as_ref().and_then(|it| match it.field(&field.name) { + Some(local_id) => { + Some(StructFieldId { parent: def_id.unwrap(), local_id }) + } + None => { + self.push_diagnostic(InferenceDiagnostic::NoSuchField { + expr: tgt_expr, + field: field_idx, + }); + None + } + }); + if let Some(field_def) = field_def { + self.result.record_field_resolutions.insert(field.expr, field_def); + } + let field_ty = field_def + .map_or(Ty::Unknown, |it| field_types[it.local_id].clone()) + .subst(&substs); + self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); + } + if let Some(expr) = spread { + self.infer_expr(*expr, &Expectation::has_type(ty.clone())); + } + ty + } + Expr::Field { expr, name } => { + let receiver_ty = self.infer_expr(*expr, &Expectation::none()); + let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); + let ty = autoderef::autoderef( + self.db, + self.resolver.krate(), + InEnvironment { + value: canonicalized.value.clone(), + environment: self.trait_env.clone(), + }, + ) + .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::Tuple { .. } => name + .as_tuple_index() + .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), + TypeCtor::Adt(AdtId::StructId(s)) => { + self.db.struct_data(s).variant_data.field(name).map(|local_id| { + let field = StructFieldId { parent: s.into(), local_id }.into(); + self.write_field_resolution(tgt_expr, field); + self.db.field_types(s.into())[field.local_id] + .clone() + .subst(&a_ty.parameters) + }) + } + // FIXME: + TypeCtor::Adt(AdtId::UnionId(_)) => None, + _ => None, + }, + _ => None, + }) + .unwrap_or(Ty::Unknown); + let ty = self.insert_type_vars(ty); + self.normalize_associated_types_in(ty) + } + Expr::Await { expr } => { + let inner_ty = self.infer_expr(*expr, &Expectation::none()); + let ty = match self.resolve_future_future_output() { + Some(future_future_output_alias) => { + let ty = self.new_type_var(); + let projection = ProjectionPredicate { + ty: ty.clone(), + projection_ty: ProjectionTy { + associated_ty: future_future_output_alias, + parameters: Substs::single(inner_ty), + }, + }; + self.obligations.push(Obligation::Projection(projection)); + self.resolve_ty_as_possible(&mut vec![], ty) + } + None => Ty::Unknown, + }; + ty + } + Expr::Try { expr } => { + let inner_ty = self.infer_expr(*expr, &Expectation::none()); + let ty = match self.resolve_ops_try_ok() { + Some(ops_try_ok_alias) => { + let ty = self.new_type_var(); + let projection = ProjectionPredicate { + ty: ty.clone(), + projection_ty: ProjectionTy { + associated_ty: ops_try_ok_alias, + parameters: Substs::single(inner_ty), + }, + }; + self.obligations.push(Obligation::Projection(projection)); + self.resolve_ty_as_possible(&mut vec![], ty) + } + None => Ty::Unknown, + }; + ty + } + Expr::Cast { expr, type_ref } => { + let _inner_ty = self.infer_expr(*expr, &Expectation::none()); + let cast_ty = self.make_ty(type_ref); + // FIXME check the cast... + cast_ty + } + Expr::Ref { expr, mutability } => { + let expectation = + if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { + if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { + // FIXME: throw type error - expected mut reference but found shared ref, + // which cannot be coerced + } + Expectation::has_type(Ty::clone(exp_inner)) + } else { + Expectation::none() + }; + // FIXME reference coercions etc. + let inner_ty = self.infer_expr(*expr, &expectation); + Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) + } + Expr::Box { expr } => { + let inner_ty = self.infer_expr(*expr, &Expectation::none()); + if let Some(box_) = self.resolve_boxed_box() { + Ty::apply_one(TypeCtor::Adt(box_), inner_ty) + } else { + Ty::Unknown + } + } + Expr::UnaryOp { expr, op } => { + let inner_ty = self.infer_expr(*expr, &Expectation::none()); + match op { + UnaryOp::Deref => match self.resolver.krate() { + Some(krate) => { + let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); + match autoderef::deref( + self.db, + krate, + InEnvironment { + value: &canonicalized.value, + environment: self.trait_env.clone(), + }, + ) { + Some(derefed_ty) => { + canonicalized.decanonicalize_ty(derefed_ty.value) + } + None => Ty::Unknown, + } + } + None => Ty::Unknown, + }, + UnaryOp::Neg => { + match &inner_ty { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::Int(Uncertain::Unknown) + | TypeCtor::Int(Uncertain::Known(IntTy { + signedness: Signedness::Signed, + .. + })) + | TypeCtor::Float(..) => inner_ty, + _ => Ty::Unknown, + }, + Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { + inner_ty + } + // FIXME: resolve ops::Neg trait + _ => Ty::Unknown, + } + } + UnaryOp::Not => { + match &inner_ty { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, + _ => Ty::Unknown, + }, + Ty::Infer(InferTy::IntVar(..)) => inner_ty, + // FIXME: resolve ops::Not trait for inner_ty + _ => Ty::Unknown, + } + } + } + } + Expr::BinaryOp { lhs, rhs, op } => match op { + Some(op) => { + let lhs_expectation = match op { + BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), + _ => Expectation::none(), + }; + let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); + // FIXME: find implementation of trait corresponding to operation + // symbol and resolve associated `Output` type + let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); + let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); + + // FIXME: similar as above, return ty is often associated trait type + op::binary_op_return_ty(*op, rhs_ty) + } + _ => Ty::Unknown, + }, + Expr::Index { base, index } => { + let _base_ty = self.infer_expr(*base, &Expectation::none()); + let _index_ty = self.infer_expr(*index, &Expectation::none()); + // FIXME: use `std::ops::Index::Output` to figure out the real return type + Ty::Unknown + } + Expr::Tuple { exprs } => { + let mut tys = match &expected.ty { + ty_app!(TypeCtor::Tuple { .. }, st) => st + .iter() + .cloned() + .chain(repeat_with(|| self.new_type_var())) + .take(exprs.len()) + .collect::>(), + _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), + }; + + for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { + self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); + } + + Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) + } + Expr::Array(array) => { + let elem_ty = match &expected.ty { + ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { + st.as_single().clone() + } + _ => self.new_type_var(), + }; + + match array { + Array::ElementList(items) => { + for expr in items.iter() { + self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); + } + } + Array::Repeat { initializer, repeat } => { + self.infer_expr_coerce( + *initializer, + &Expectation::has_type(elem_ty.clone()), + ); + self.infer_expr( + *repeat, + &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known( + IntTy::usize(), + )))), + ); + } + } + + Ty::apply_one(TypeCtor::Array, elem_ty) + } + Expr::Literal(lit) => match lit { + Literal::Bool(..) => Ty::simple(TypeCtor::Bool), + Literal::String(..) => { + Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) + } + Literal::ByteString(..) => { + let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8()))); + let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); + Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) + } + Literal::Char(..) => Ty::simple(TypeCtor::Char), + Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())), + Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())), + }, + }; + // use a new type variable if we got Ty::Unknown here + let ty = self.insert_type_vars_shallow(ty); + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + self.write_expr_ty(tgt_expr, ty.clone()); + ty + } + + fn infer_block( + &mut self, + statements: &[Statement], + tail: Option, + expected: &Expectation, + ) -> Ty { + let mut diverges = false; + for stmt in statements { + match stmt { + Statement::Let { pat, type_ref, initializer } => { + let decl_ty = + type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); + + // Always use the declared type when specified + let mut ty = decl_ty.clone(); + + if let Some(expr) = initializer { + let actual_ty = + self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); + if decl_ty == Ty::Unknown { + ty = actual_ty; + } + } + + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + self.infer_pat(*pat, &ty, BindingMode::default()); + } + Statement::Expr(expr) => { + if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { + diverges = true; + } + } + } + } + + let ty = if let Some(expr) = tail { + self.infer_expr_coerce(expr, expected) + } else { + self.coerce(&Ty::unit(), &expected.ty); + Ty::unit() + }; + if diverges { + Ty::simple(TypeCtor::Never) + } else { + ty + } + } + + fn infer_method_call( + &mut self, + tgt_expr: ExprId, + receiver: ExprId, + args: &[ExprId], + method_name: &Name, + generic_args: Option<&GenericArgs>, + ) -> Ty { + let receiver_ty = self.infer_expr(receiver, &Expectation::none()); + let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); + let resolved = method_resolution::lookup_method( + &canonicalized_receiver.value, + self.db, + method_name, + &self.resolver, + ); + let (derefed_receiver_ty, method_ty, def_generics) = match resolved { + Some((ty, func)) => { + let ty = canonicalized_receiver.decanonicalize_ty(ty); + self.write_method_resolution(tgt_expr, func); + (ty, self.db.value_ty(func.into()), Some(self.db.generic_params(func.into()))) + } + None => (receiver_ty, Ty::Unknown, None), + }; + let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); + let method_ty = method_ty.apply_substs(substs); + let method_ty = self.insert_type_vars(method_ty); + self.register_obligations_for_call(&method_ty); + let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { + Some(sig) => { + if !sig.params().is_empty() { + (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) + } else { + (Ty::Unknown, Vec::new(), sig.ret().clone()) + } + } + None => (Ty::Unknown, Vec::new(), Ty::Unknown), + }; + // Apply autoref so the below unification works correctly + // FIXME: return correct autorefs from lookup_method + let actual_receiver_ty = match expected_receiver_ty.as_reference() { + Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), + _ => derefed_receiver_ty, + }; + self.unify(&expected_receiver_ty, &actual_receiver_ty); + + self.check_call_arguments(args, ¶m_tys); + let ret_ty = self.normalize_associated_types_in(ret_ty); + ret_ty + } + + fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { + // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- + // We do this in a pretty awful way: first we type-check any arguments + // that are not closures, then we type-check the closures. This is so + // that we have more information about the types of arguments when we + // type-check the functions. This isn't really the right way to do this. + for &check_closures in &[false, true] { + let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); + for (&arg, param_ty) in args.iter().zip(param_iter) { + let is_closure = match &self.body[arg] { + Expr::Lambda { .. } => true, + _ => false, + }; + + if is_closure != check_closures { + continue; + } + + let param_ty = self.normalize_associated_types_in(param_ty); + self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); + } + } + } + + fn substs_for_method_call( + &mut self, + def_generics: Option>, + generic_args: Option<&GenericArgs>, + receiver_ty: &Ty, + ) -> Substs { + let (parent_param_count, param_count) = + def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); + let mut substs = Vec::with_capacity(parent_param_count + param_count); + // Parent arguments are unknown, except for the receiver type + if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { + for param in &parent_generics.params { + if param.name == name::SELF_TYPE { + substs.push(receiver_ty.clone()); + } else { + substs.push(Ty::Unknown); + } + } + } + // handle provided type arguments + if let Some(generic_args) = generic_args { + // if args are provided, it should be all of them, but we can't rely on that + for arg in generic_args.args.iter().take(param_count) { + match arg { + GenericArg::Type(type_ref) => { + let ty = self.make_ty(type_ref); + substs.push(ty); + } + } + } + }; + let supplied_params = substs.len(); + for _ in supplied_params..parent_param_count + param_count { + substs.push(Ty::Unknown); + } + assert_eq!(substs.len(), parent_param_count + param_count); + Substs(substs.into()) + } + + fn register_obligations_for_call(&mut self, callable_ty: &Ty) { + if let Ty::Apply(a_ty) = callable_ty { + if let TypeCtor::FnDef(def) = a_ty.ctor { + let generic_predicates = self.db.generic_predicates(def.into()); + for predicate in generic_predicates.iter() { + let predicate = predicate.clone().subst(&a_ty.parameters); + if let Some(obligation) = Obligation::from_predicate(predicate) { + self.obligations.push(obligation); + } + } + // add obligation for trait implementation, if this is a trait method + match def { + CallableDef::FunctionId(f) => { + if let ContainerId::TraitId(trait_) = f.lookup(self.db).container { + // construct a TraitDef + let substs = a_ty.parameters.prefix( + self.db + .generic_params(trait_.into()) + .count_params_including_parent(), + ); + self.obligations.push(Obligation::Trait(TraitRef { + trait_: trait_.into(), + substs, + })); + } + } + CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {} + } + } + } + } +} diff --git a/crates/ra_hir_ty/src/infer/pat.rs b/crates/ra_hir_ty/src/infer/pat.rs new file mode 100644 index 000000000..1ebb36239 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/pat.rs @@ -0,0 +1,186 @@ +//! Type inference for patterns. + +use std::iter::repeat; +use std::sync::Arc; + +use hir_def::{ + expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, + path::Path, + type_ref::Mutability, +}; +use hir_expand::name::Name; +use test_utils::tested_by; + +use super::{BindingMode, InferenceContext}; +use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + fn infer_tuple_struct_pat( + &mut self, + path: Option<&Path>, + subpats: &[PatId], + expected: &Ty, + default_bm: BindingMode, + ) -> Ty { + let (ty, def) = self.resolve_variant(path); + let var_data = def.map(|it| variant_data(self.db, it)); + self.unify(&ty, expected); + + let substs = ty.substs().unwrap_or_else(Substs::empty); + + let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); + + for (i, &subpat) in subpats.iter().enumerate() { + let expected_ty = var_data + .as_ref() + .and_then(|d| d.field(&Name::new_tuple_field(i))) + .map_or(Ty::Unknown, |field| field_tys[field].clone()) + .subst(&substs); + let expected_ty = self.normalize_associated_types_in(expected_ty); + self.infer_pat(subpat, &expected_ty, default_bm); + } + + ty + } + + fn infer_record_pat( + &mut self, + path: Option<&Path>, + subpats: &[RecordFieldPat], + expected: &Ty, + default_bm: BindingMode, + id: PatId, + ) -> Ty { + let (ty, def) = self.resolve_variant(path); + let var_data = def.map(|it| variant_data(self.db, it)); + if let Some(variant) = def { + self.write_variant_resolution(id.into(), variant); + } + + self.unify(&ty, expected); + + let substs = ty.substs().unwrap_or_else(Substs::empty); + + let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); + for subpat in subpats { + let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name)); + let expected_ty = + matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs); + let expected_ty = self.normalize_associated_types_in(expected_ty); + self.infer_pat(subpat.pat, &expected_ty, default_bm); + } + + ty + } + + pub(super) fn infer_pat( + &mut self, + pat: PatId, + mut expected: &Ty, + mut default_bm: BindingMode, + ) -> Ty { + let body = Arc::clone(&self.body); // avoid borrow checker problem + + let is_non_ref_pat = match &body[pat] { + Pat::Tuple(..) + | Pat::TupleStruct { .. } + | Pat::Record { .. } + | Pat::Range { .. } + | Pat::Slice { .. } => true, + // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. + Pat::Path(..) | Pat::Lit(..) => true, + Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, + }; + if is_non_ref_pat { + while let Some((inner, mutability)) = expected.as_reference() { + expected = inner; + default_bm = match default_bm { + BindingMode::Move => BindingMode::Ref(mutability), + BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), + BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), + } + } + } else if let Pat::Ref { .. } = &body[pat] { + tested_by!(match_ergonomics_ref); + // When you encounter a `&pat` pattern, reset to Move. + // This is so that `w` is by value: `let (_, &w) = &(1, &2);` + default_bm = BindingMode::Move; + } + + // Lose mutability. + let default_bm = default_bm; + let expected = expected; + + let ty = match &body[pat] { + Pat::Tuple(ref args) => { + let expectations = match expected.as_tuple() { + Some(parameters) => &*parameters.0, + _ => &[], + }; + let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); + + let inner_tys = args + .iter() + .zip(expectations_iter) + .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) + .collect(); + + Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) + } + Pat::Ref { pat, mutability } => { + let expectation = match expected.as_reference() { + Some((inner_ty, exp_mut)) => { + if *mutability != exp_mut { + // FIXME: emit type error? + } + inner_ty + } + _ => &Ty::Unknown, + }; + let subty = self.infer_pat(*pat, expectation, default_bm); + Ty::apply_one(TypeCtor::Ref(*mutability), subty) + } + Pat::TupleStruct { path: p, args: subpats } => { + self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) + } + Pat::Record { path: p, args: fields } => { + self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) + } + Pat::Path(path) => { + // FIXME use correct resolver for the surrounding expression + let resolver = self.resolver.clone(); + self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) + } + Pat::Bind { mode, name: _, subpat } => { + let mode = if mode == &BindingAnnotation::Unannotated { + default_bm + } else { + BindingMode::convert(*mode) + }; + let inner_ty = if let Some(subpat) = subpat { + self.infer_pat(*subpat, expected, default_bm) + } else { + expected.clone() + }; + let inner_ty = self.insert_type_vars_shallow(inner_ty); + + let bound_ty = match mode { + BindingMode::Ref(mutability) => { + Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) + } + BindingMode::Move => inner_ty.clone(), + }; + let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); + self.write_pat_ty(pat, bound_ty); + return inner_ty; + } + _ => Ty::Unknown, + }; + // use a new type variable if we got Ty::Unknown here + let ty = self.insert_type_vars_shallow(ty); + self.unify(&ty, expected); + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + self.write_pat_ty(pat, ty.clone()); + ty + } +} diff --git a/crates/ra_hir_ty/src/infer/path.rs b/crates/ra_hir_ty/src/infer/path.rs new file mode 100644 index 000000000..e6676e1aa --- /dev/null +++ b/crates/ra_hir_ty/src/infer/path.rs @@ -0,0 +1,270 @@ +//! Path expression resolution. + +use hir_def::{ + path::{Path, PathKind, PathSegment}, + resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, + AssocItemId, ContainerId, Lookup, +}; +use hir_expand::name::Name; + +use crate::{db::HirDatabase, method_resolution, Substs, Ty, TypeWalk, ValueTyDefId}; + +use super::{ExprOrPatId, InferenceContext, TraitRef}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + pub(super) fn infer_path( + &mut self, + resolver: &Resolver, + path: &Path, + id: ExprOrPatId, + ) -> Option { + let ty = self.resolve_value_path(resolver, path, id)?; + let ty = self.insert_type_vars(ty); + let ty = self.normalize_associated_types_in(ty); + Some(ty) + } + + fn resolve_value_path( + &mut self, + resolver: &Resolver, + path: &Path, + id: ExprOrPatId, + ) -> Option { + let (value, self_subst) = if let PathKind::Type(type_ref) = &path.kind { + if path.segments.is_empty() { + // This can't actually happen syntax-wise + return None; + } + let ty = self.make_ty(type_ref); + let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1]; + let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); + self.resolve_ty_assoc_item( + ty, + &path.segments.last().expect("path had at least one segment").name, + id, + )? + } else { + let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?; + + match value_or_partial { + ResolveValueResult::ValueNs(it) => (it, None), + ResolveValueResult::Partial(def, remaining_index) => { + self.resolve_assoc_item(def, path, remaining_index, id)? + } + } + }; + + let typable: ValueTyDefId = match value { + ValueNs::LocalBinding(pat) => { + let ty = self.result.type_of_pat.get(pat)?.clone(); + let ty = self.resolve_ty_as_possible(&mut vec![], ty); + return Some(ty); + } + ValueNs::FunctionId(it) => it.into(), + ValueNs::ConstId(it) => it.into(), + ValueNs::StaticId(it) => it.into(), + ValueNs::StructId(it) => it.into(), + ValueNs::EnumVariantId(it) => it.into(), + }; + + let mut ty = self.db.value_ty(typable); + if let Some(self_subst) = self_subst { + ty = ty.subst(&self_subst); + } + let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); + let ty = ty.subst(&substs); + Some(ty) + } + + fn resolve_assoc_item( + &mut self, + def: TypeNs, + path: &Path, + remaining_index: usize, + id: ExprOrPatId, + ) -> Option<(ValueNs, Option)> { + assert!(remaining_index < path.segments.len()); + // there may be more intermediate segments between the resolved one and + // the end. Only the last segment needs to be resolved to a value; from + // the segments before that, we need to get either a type or a trait ref. + + let resolved_segment = &path.segments[remaining_index - 1]; + let remaining_segments = &path.segments[remaining_index..]; + let is_before_last = remaining_segments.len() == 1; + + match (def, is_before_last) { + (TypeNs::TraitId(trait_), true) => { + let segment = + remaining_segments.last().expect("there should be at least one segment here"); + let trait_ref = TraitRef::from_resolved_path( + self.db, + &self.resolver, + trait_.into(), + resolved_segment, + None, + ); + self.resolve_trait_assoc_item(trait_ref, segment, id) + } + (def, _) => { + // Either we already have a type (e.g. `Vec::new`), or we have a + // trait but it's not the last segment, so the next segment + // should resolve to an associated type of that trait (e.g. `::Item::default`) + let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1]; + let ty = Ty::from_partly_resolved_hir_path( + self.db, + &self.resolver, + def, + resolved_segment, + remaining_segments_for_ty, + ); + if let Ty::Unknown = ty { + return None; + } + + let ty = self.insert_type_vars(ty); + let ty = self.normalize_associated_types_in(ty); + + let segment = + remaining_segments.last().expect("there should be at least one segment here"); + + self.resolve_ty_assoc_item(ty, &segment.name, id) + } + } + } + + fn resolve_trait_assoc_item( + &mut self, + trait_ref: TraitRef, + segment: &PathSegment, + id: ExprOrPatId, + ) -> Option<(ValueNs, Option)> { + let trait_ = trait_ref.trait_; + let item = self + .db + .trait_data(trait_) + .items + .iter() + .map(|(_name, id)| (*id).into()) + .find_map(|item| match item { + AssocItemId::FunctionId(func) => { + if segment.name == self.db.function_data(func).name { + Some(AssocItemId::FunctionId(func)) + } else { + None + } + } + + AssocItemId::ConstId(konst) => { + if self.db.const_data(konst).name.as_ref().map_or(false, |n| n == &segment.name) + { + Some(AssocItemId::ConstId(konst)) + } else { + None + } + } + AssocItemId::TypeAliasId(_) => None, + })?; + let def = match item { + AssocItemId::FunctionId(f) => ValueNs::FunctionId(f), + AssocItemId::ConstId(c) => ValueNs::ConstId(c), + AssocItemId::TypeAliasId(_) => unreachable!(), + }; + let substs = Substs::build_for_def(self.db, item) + .use_parent_substs(&trait_ref.substs) + .fill_with_params() + .build(); + + self.write_assoc_resolution(id, item); + Some((def, Some(substs))) + } + + fn resolve_ty_assoc_item( + &mut self, + ty: Ty, + name: &Name, + id: ExprOrPatId, + ) -> Option<(ValueNs, Option)> { + if let Ty::Unknown = ty { + return None; + } + + let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); + + method_resolution::iterate_method_candidates( + &canonical_ty.value, + self.db, + &self.resolver.clone(), + Some(name), + method_resolution::LookupMode::Path, + move |_ty, item| { + let (def, container) = match item { + AssocItemId::FunctionId(f) => { + (ValueNs::FunctionId(f), f.lookup(self.db).container) + } + AssocItemId::ConstId(c) => (ValueNs::ConstId(c), c.lookup(self.db).container), + AssocItemId::TypeAliasId(_) => unreachable!(), + }; + let substs = match container { + ContainerId::ImplId(_) => self.find_self_types(&def, ty.clone()), + ContainerId::TraitId(trait_) => { + // we're picking this method + let trait_substs = Substs::build_for_def(self.db, trait_) + .push(ty.clone()) + .fill(std::iter::repeat_with(|| self.new_type_var())) + .build(); + let substs = Substs::build_for_def(self.db, item) + .use_parent_substs(&trait_substs) + .fill_with_params() + .build(); + self.obligations.push(super::Obligation::Trait(TraitRef { + trait_, + substs: trait_substs, + })); + Some(substs) + } + ContainerId::ModuleId(_) => None, + }; + + self.write_assoc_resolution(id, item.into()); + Some((def, substs)) + }, + ) + } + + fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option { + if let ValueNs::FunctionId(func) = *def { + // We only do the infer if parent has generic params + let gen = self.db.generic_params(func.into()); + if gen.count_parent_params() == 0 { + return None; + } + + let impl_id = match func.lookup(self.db).container { + ContainerId::ImplId(it) => it, + _ => return None, + }; + let resolver = impl_id.resolver(self.db); + let impl_data = self.db.impl_data(impl_id); + let impl_block = Ty::from_hir(self.db, &resolver, &impl_data.target_type); + let impl_block_substs = impl_block.substs()?; + let actual_substs = actual_def_ty.substs()?; + + let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; + + // The following code *link up* the function actual parma type + // and impl_block type param index + impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { + if let Ty::Param { idx, .. } = param { + if let Some(s) = new_substs.get_mut(*idx as usize) { + *s = pty.clone(); + } + } + }); + + Some(Substs(new_substs.into())) + } else { + None + } + } +} diff --git a/crates/ra_hir_ty/src/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs new file mode 100644 index 000000000..f3a875678 --- /dev/null +++ b/crates/ra_hir_ty/src/infer/unify.rs @@ -0,0 +1,162 @@ +//! Unification and canonicalization logic. + +use super::{InferenceContext, Obligation}; +use crate::{ + db::HirDatabase, utils::make_mut_slice, Canonical, InEnvironment, InferTy, ProjectionPredicate, + ProjectionTy, Substs, TraitRef, Ty, TypeWalk, +}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> + where + 'a: 'b, + { + Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } + } +} + +pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> +where + 'a: 'b, +{ + ctx: &'b mut InferenceContext<'a, D>, + free_vars: Vec, + /// A stack of type variables that is used to detect recursive types (which + /// are an error, but we need to protect against them to avoid stack + /// overflows). + var_stack: Vec, +} + +pub(super) struct Canonicalized { + pub value: Canonical, + free_vars: Vec, +} + +impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> +where + 'a: 'b, +{ + fn add(&mut self, free_var: InferTy) -> usize { + self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { + let next_index = self.free_vars.len(); + self.free_vars.push(free_var); + next_index + }) + } + + fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { + ty.fold(&mut |ty| match ty { + Ty::Infer(tv) => { + let inner = tv.to_inner(); + if self.var_stack.contains(&inner) { + // recursive type + return tv.fallback_value(); + } + if let Some(known_ty) = + self.ctx.var_unification_table.inlined_probe_value(inner).known() + { + self.var_stack.push(inner); + let result = self.do_canonicalize_ty(known_ty.clone()); + self.var_stack.pop(); + result + } else { + let root = self.ctx.var_unification_table.find(inner); + let free_var = match tv { + InferTy::TypeVar(_) => InferTy::TypeVar(root), + InferTy::IntVar(_) => InferTy::IntVar(root), + InferTy::FloatVar(_) => InferTy::FloatVar(root), + InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root), + }; + let position = self.add(free_var); + Ty::Bound(position as u32) + } + } + _ => ty, + }) + } + + fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { + for ty in make_mut_slice(&mut trait_ref.substs.0) { + *ty = self.do_canonicalize_ty(ty.clone()); + } + trait_ref + } + + fn into_canonicalized(self, result: T) -> Canonicalized { + Canonicalized { + value: Canonical { value: result, num_vars: self.free_vars.len() }, + free_vars: self.free_vars, + } + } + + fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { + for ty in make_mut_slice(&mut projection_ty.parameters.0) { + *ty = self.do_canonicalize_ty(ty.clone()); + } + projection_ty + } + + fn do_canonicalize_projection_predicate( + &mut self, + projection: ProjectionPredicate, + ) -> ProjectionPredicate { + let ty = self.do_canonicalize_ty(projection.ty); + let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty); + + ProjectionPredicate { ty, projection_ty } + } + + // FIXME: add some point, we need to introduce a `Fold` trait that abstracts + // over all the things that can be canonicalized (like Chalk and rustc have) + + pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized { + let result = self.do_canonicalize_ty(ty); + self.into_canonicalized(result) + } + + pub(crate) fn canonicalize_obligation( + mut self, + obligation: InEnvironment, + ) -> Canonicalized> { + let result = match obligation.value { + Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)), + Obligation::Projection(pr) => { + Obligation::Projection(self.do_canonicalize_projection_predicate(pr)) + } + }; + self.into_canonicalized(InEnvironment { + value: result, + environment: obligation.environment, + }) + } +} + +impl Canonicalized { + pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { + ty.walk_mut_binders( + &mut |ty, binders| match ty { + &mut Ty::Bound(idx) => { + if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { + *ty = Ty::Infer(self.free_vars[idx as usize - binders]); + } + } + _ => {} + }, + 0, + ); + ty + } + + pub fn apply_solution( + &self, + ctx: &mut InferenceContext<'_, impl HirDatabase>, + solution: Canonical>, + ) { + // the solution may contain new variables, which we need to convert to new inference vars + let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect()); + for (i, ty) in solution.value.into_iter().enumerate() { + let var = self.free_vars[i]; + ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); + } + } +} diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index 28859ba63..f25846326 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -1,4 +1,1134 @@ -//! Work in Progress: everything related to types, type inference and trait -//! solving. +//! The type system. We currently use this to infer types for completion, hover +//! information and various assists. +macro_rules! impl_froms { + ($e:ident: $($v:ident $(($($sv:ident),*))?),*) => { + $( + impl From<$v> for $e { + fn from(it: $v) -> $e { + $e::$v(it) + } + } + $($( + impl From<$sv> for $e { + fn from(it: $sv) -> $e { + $e::$v($v::$sv(it)) + } + } + )*)? + )* + } +} + +mod autoderef; pub mod primitive; +pub mod traits; +pub mod method_resolution; +mod op; +mod lower; +mod infer; +pub mod display; +pub(crate) mod utils; +pub mod db; +pub mod diagnostics; +pub mod expr; + +#[cfg(test)] +mod tests; +#[cfg(test)] +mod test_db; +mod marks; + +use std::ops::Deref; +use std::sync::Arc; +use std::{fmt, iter, mem}; + +use hir_def::{ + expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId, + GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, +}; +use hir_expand::name::Name; +use ra_db::{impl_intern_key, salsa, CrateId}; + +use crate::{ + db::HirDatabase, + primitive::{FloatTy, IntTy, Uncertain}, + utils::make_mut_slice, +}; +use display::{HirDisplay, HirFormatter}; + +pub use autoderef::autoderef; +pub use infer::{infer_query, InferTy, InferenceResult}; +pub use lower::CallableDef; +pub use lower::{callable_item_sig, TyDefId, ValueTyDefId}; +pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; + +/// A type constructor or type name: this might be something like the primitive +/// type `bool`, a struct like `Vec`, or things like function pointers or +/// tuples. +#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] +pub enum TypeCtor { + /// The primitive boolean type. Written as `bool`. + Bool, + + /// The primitive character type; holds a Unicode scalar value + /// (a non-surrogate code point). Written as `char`. + Char, + + /// A primitive integer type. For example, `i32`. + Int(Uncertain), + + /// A primitive floating-point type. For example, `f64`. + Float(Uncertain), + + /// Structures, enumerations and unions. + Adt(AdtId), + + /// The pointee of a string slice. Written as `str`. + Str, + + /// The pointee of an array slice. Written as `[T]`. + Slice, + + /// An array with the given length. Written as `[T; n]`. + Array, + + /// A raw pointer. Written as `*mut T` or `*const T` + RawPtr(Mutability), + + /// A reference; a pointer with an associated lifetime. Written as + /// `&'a mut T` or `&'a T`. + Ref(Mutability), + + /// The anonymous type of a function declaration/definition. Each + /// function has a unique type, which is output (for a function + /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. + /// + /// This includes tuple struct / enum variant constructors as well. + /// + /// For example the type of `bar` here: + /// + /// ``` + /// fn foo() -> i32 { 1 } + /// let bar = foo; // bar: fn() -> i32 {foo} + /// ``` + FnDef(CallableDef), + + /// A pointer to a function. Written as `fn() -> i32`. + /// + /// For example the type of `bar` here: + /// + /// ``` + /// fn foo() -> i32 { 1 } + /// let bar: fn() -> i32 = foo; + /// ``` + FnPtr { num_args: u16 }, + + /// The never type `!`. + Never, + + /// A tuple type. For example, `(i32, bool)`. + Tuple { cardinality: u16 }, + + /// Represents an associated item like `Iterator::Item`. This is used + /// when we have tried to normalize a projection like `T::Item` but + /// couldn't find a better representation. In that case, we generate + /// an **application type** like `(Iterator::Item)`. + AssociatedType(TypeAliasId), + + /// The type of a specific closure. + /// + /// The closure signature is stored in a `FnPtr` type in the first type + /// parameter. + Closure { def: DefWithBodyId, expr: ExprId }, +} + +/// This exists just for Chalk, because Chalk just has a single `StructId` where +/// we have different kinds of ADTs, primitive types and special type +/// constructors like tuples and function pointers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct TypeCtorId(salsa::InternId); +impl_intern_key!(TypeCtorId); + +impl TypeCtor { + pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { + match self { + TypeCtor::Bool + | TypeCtor::Char + | TypeCtor::Int(_) + | TypeCtor::Float(_) + | TypeCtor::Str + | TypeCtor::Never => 0, + TypeCtor::Slice + | TypeCtor::Array + | TypeCtor::RawPtr(_) + | TypeCtor::Ref(_) + | TypeCtor::Closure { .. } // 1 param representing the signature of the closure + => 1, + TypeCtor::Adt(adt) => { + let generic_params = db.generic_params(AdtId::from(adt).into()); + generic_params.count_params_including_parent() + } + TypeCtor::FnDef(callable) => { + let generic_params = db.generic_params(callable.into()); + generic_params.count_params_including_parent() + } + TypeCtor::AssociatedType(type_alias) => { + let generic_params = db.generic_params(type_alias.into()); + generic_params.count_params_including_parent() + } + TypeCtor::FnPtr { num_args } => num_args as usize + 1, + TypeCtor::Tuple { cardinality } => cardinality as usize, + } + } + + pub fn krate(self, db: &impl HirDatabase) -> Option { + match self { + TypeCtor::Bool + | TypeCtor::Char + | TypeCtor::Int(_) + | TypeCtor::Float(_) + | TypeCtor::Str + | TypeCtor::Never + | TypeCtor::Slice + | TypeCtor::Array + | TypeCtor::RawPtr(_) + | TypeCtor::Ref(_) + | TypeCtor::FnPtr { .. } + | TypeCtor::Tuple { .. } => None, + // Closure's krate is irrelevant for coherence I would think? + TypeCtor::Closure { .. } => None, + TypeCtor::Adt(adt) => Some(adt.module(db).krate), + TypeCtor::FnDef(callable) => Some(callable.krate(db)), + TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate), + } + } + + pub fn as_generic_def(self) -> Option { + match self { + TypeCtor::Bool + | TypeCtor::Char + | TypeCtor::Int(_) + | TypeCtor::Float(_) + | TypeCtor::Str + | TypeCtor::Never + | TypeCtor::Slice + | TypeCtor::Array + | TypeCtor::RawPtr(_) + | TypeCtor::Ref(_) + | TypeCtor::FnPtr { .. } + | TypeCtor::Tuple { .. } + | TypeCtor::Closure { .. } => None, + TypeCtor::Adt(adt) => Some(adt.into()), + TypeCtor::FnDef(callable) => Some(callable.into()), + TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()), + } + } +} + +/// A nominal type with (maybe 0) type parameters. This might be a primitive +/// type like `bool`, a struct, tuple, function pointer, reference or +/// several other things. +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub struct ApplicationTy { + pub ctor: TypeCtor, + pub parameters: Substs, +} + +/// A "projection" type corresponds to an (unnormalized) +/// projection like `>::Foo`. Note that the +/// trait and all its parameters are fully known. +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub struct ProjectionTy { + pub associated_ty: TypeAliasId, + pub parameters: Substs, +} + +impl ProjectionTy { + pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { + TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() } + } + + fn trait_(&self, db: &impl HirDatabase) -> TraitId { + match self.associated_ty.lookup(db).container { + ContainerId::TraitId(it) => it, + _ => panic!("projection ty without parent trait"), + } + } +} + +impl TypeWalk for ProjectionTy { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + self.parameters.walk(f); + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.parameters.walk_mut_binders(f, binders); + } +} + +/// A type. +/// +/// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents +/// the same thing (but in a different way). +/// +/// This should be cheap to clone. +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum Ty { + /// A nominal type with (maybe 0) type parameters. This might be a primitive + /// type like `bool`, a struct, tuple, function pointer, reference or + /// several other things. + Apply(ApplicationTy), + + /// A "projection" type corresponds to an (unnormalized) + /// projection like `>::Foo`. Note that the + /// trait and all its parameters are fully known. + Projection(ProjectionTy), + + /// A type parameter; for example, `T` in `fn f(x: T) {} + Param { + /// The index of the parameter (starting with parameters from the + /// surrounding impl, then the current function). + idx: u32, + /// The name of the parameter, for displaying. + // FIXME get rid of this + name: Name, + }, + + /// A bound type variable. Used during trait resolution to represent Chalk + /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. + Bound(u32), + + /// A type variable used during type checking. Not to be confused with a + /// type parameter. + Infer(InferTy), + + /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). + /// + /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)` + /// represents the `Self` type inside the bounds. This is currently + /// implicit; Chalk has the `Binders` struct to make it explicit, but it + /// didn't seem worth the overhead yet. + Dyn(Arc<[GenericPredicate]>), + + /// An opaque type (`impl Trait`). + /// + /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for + /// more. + Opaque(Arc<[GenericPredicate]>), + + /// A placeholder for a type which could not be computed; this is propagated + /// to avoid useless error messages. Doubles as a placeholder where type + /// variables are inserted before type checking, since we want to try to + /// infer a better type here anyway -- for the IDE use case, we want to try + /// to infer as much as possible even in the presence of type errors. + Unknown, +} + +/// A list of substitutions for generic parameters. +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub struct Substs(Arc<[Ty]>); + +impl TypeWalk for Substs { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + for t in self.0.iter() { + t.walk(f); + } + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + for t in make_mut_slice(&mut self.0) { + t.walk_mut_binders(f, binders); + } + } +} + +impl Substs { + pub fn empty() -> Substs { + Substs(Arc::new([])) + } + + pub fn single(ty: Ty) -> Substs { + Substs(Arc::new([ty])) + } + + pub fn prefix(&self, n: usize) -> Substs { + Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) + } + + pub fn as_single(&self) -> &Ty { + if self.0.len() != 1 { + panic!("expected substs of len 1, got {:?}", self); + } + &self.0[0] + } + + /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). + pub fn identity(generic_params: &GenericParams) -> Substs { + Substs( + generic_params + .params_including_parent() + .into_iter() + .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) + .collect(), + ) + } + + /// Return Substs that replace each parameter by a bound variable. + pub fn bound_vars(generic_params: &GenericParams) -> Substs { + Substs( + generic_params + .params_including_parent() + .into_iter() + .map(|p| Ty::Bound(p.idx)) + .collect(), + ) + } + + pub fn build_for_def(db: &impl HirDatabase, def: impl Into) -> SubstsBuilder { + let def = def.into(); + let params = db.generic_params(def); + let param_count = params.count_params_including_parent(); + Substs::builder(param_count) + } + + pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder { + Substs::builder(generic_params.count_params_including_parent()) + } + + pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { + Substs::builder(type_ctor.num_ty_params(db)) + } + + fn builder(param_count: usize) -> SubstsBuilder { + SubstsBuilder { vec: Vec::with_capacity(param_count), param_count } + } +} + +#[derive(Debug, Clone)] +pub struct SubstsBuilder { + vec: Vec, + param_count: usize, +} + +impl SubstsBuilder { + pub fn build(self) -> Substs { + assert_eq!(self.vec.len(), self.param_count); + Substs(self.vec.into()) + } + + pub fn push(mut self, ty: Ty) -> Self { + self.vec.push(ty); + self + } + + fn remaining(&self) -> usize { + self.param_count - self.vec.len() + } + + pub fn fill_with_bound_vars(self, starting_from: u32) -> Self { + self.fill((starting_from..).map(Ty::Bound)) + } + + pub fn fill_with_params(self) -> Self { + let start = self.vec.len() as u32; + self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() })) + } + + pub fn fill_with_unknown(self) -> Self { + self.fill(iter::repeat(Ty::Unknown)) + } + + pub fn fill(mut self, filler: impl Iterator) -> Self { + self.vec.extend(filler.take(self.remaining())); + assert_eq!(self.remaining(), 0); + self + } + + pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { + assert!(self.vec.is_empty()); + assert!(parent_substs.len() <= self.param_count); + self.vec.extend(parent_substs.iter().cloned()); + self + } +} + +impl Deref for Substs { + type Target = [Ty]; + + fn deref(&self) -> &[Ty] { + &self.0 + } +} + +/// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. +/// Name to be bikeshedded: TraitBound? TraitImplements? +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub struct TraitRef { + /// FIXME name? + pub trait_: TraitId, + pub substs: Substs, +} + +impl TraitRef { + pub fn self_ty(&self) -> &Ty { + &self.substs[0] + } +} + +impl TypeWalk for TraitRef { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + self.substs.walk(f); + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.substs.walk_mut_binders(f, binders); + } +} + +/// Like `generics::WherePredicate`, but with resolved types: A condition on the +/// parameters of a generic item. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum GenericPredicate { + /// The given trait needs to be implemented for its type parameters. + Implemented(TraitRef), + /// An associated type bindings like in `Iterator`. + Projection(ProjectionPredicate), + /// We couldn't resolve the trait reference. (If some type parameters can't + /// be resolved, they will just be Unknown). + Error, +} + +impl GenericPredicate { + pub fn is_error(&self) -> bool { + match self { + GenericPredicate::Error => true, + _ => false, + } + } + + pub fn is_implemented(&self) -> bool { + match self { + GenericPredicate::Implemented(_) => true, + _ => false, + } + } + + pub fn trait_ref(&self, db: &impl HirDatabase) -> Option { + match self { + GenericPredicate::Implemented(tr) => Some(tr.clone()), + GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), + GenericPredicate::Error => None, + } + } +} + +impl TypeWalk for GenericPredicate { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + match self { + GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f), + GenericPredicate::Projection(projection_pred) => projection_pred.walk(f), + GenericPredicate::Error => {} + } + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + match self { + GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), + GenericPredicate::Projection(projection_pred) => { + projection_pred.walk_mut_binders(f, binders) + } + GenericPredicate::Error => {} + } + } +} + +/// Basically a claim (currently not validated / checked) that the contained +/// type / trait ref contains no inference variables; any inference variables it +/// contained have been replaced by bound variables, and `num_vars` tells us how +/// many there are. This is used to erase irrelevant differences between types +/// before using them in queries. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Canonical { + pub value: T, + pub num_vars: usize, +} + +/// A function signature as seen by type inference: Several parameter types and +/// one return type. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct FnSig { + params_and_return: Arc<[Ty]>, +} + +impl FnSig { + pub fn from_params_and_return(mut params: Vec, ret: Ty) -> FnSig { + params.push(ret); + FnSig { params_and_return: params.into() } + } + + pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig { + FnSig { params_and_return: Arc::clone(&substs.0) } + } + + pub fn params(&self) -> &[Ty] { + &self.params_and_return[0..self.params_and_return.len() - 1] + } + + pub fn ret(&self) -> &Ty { + &self.params_and_return[self.params_and_return.len() - 1] + } +} + +impl TypeWalk for FnSig { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + for t in self.params_and_return.iter() { + t.walk(f); + } + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + for t in make_mut_slice(&mut self.params_and_return) { + t.walk_mut_binders(f, binders); + } + } +} + +impl Ty { + pub fn simple(ctor: TypeCtor) -> Ty { + Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() }) + } + pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty { + Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) }) + } + pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty { + Ty::Apply(ApplicationTy { ctor, parameters }) + } + pub fn unit() -> Self { + Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) + } + + pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { + match self { + Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => { + Some((parameters.as_single(), *mutability)) + } + _ => None, + } + } + + pub fn as_adt(&self) -> Option<(AdtId, &Substs)> { + match self { + Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => { + Some((*adt_def, parameters)) + } + _ => None, + } + } + + pub fn as_tuple(&self) -> Option<&Substs> { + match self { + Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { + Some(parameters) + } + _ => None, + } + } + + pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> { + match self { + Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => { + Some((*callable_def, parameters)) + } + _ => None, + } + } + + fn builtin_deref(&self) -> Option { + match self { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())), + TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())), + _ => None, + }, + _ => None, + } + } + + fn callable_sig(&self, db: &impl HirDatabase) -> Option { + match self { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), + TypeCtor::FnDef(def) => { + let sig = db.callable_item_signature(def); + Some(sig.subst(&a_ty.parameters)) + } + TypeCtor::Closure { .. } => { + let sig_param = &a_ty.parameters[0]; + sig_param.callable_sig(db) + } + _ => None, + }, + _ => None, + } + } + + /// If this is a type with type parameters (an ADT or function), replaces + /// the `Substs` for these type parameters with the given ones. (So e.g. if + /// `self` is `Option<_>` and the substs contain `u32`, we'll have + /// `Option` afterwards.) + pub fn apply_substs(self, substs: Substs) -> Ty { + match self { + Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => { + assert_eq!(previous_substs.len(), substs.len()); + Ty::Apply(ApplicationTy { ctor, parameters: substs }) + } + _ => self, + } + } + + /// Returns the type parameters of this type if it has some (i.e. is an ADT + /// or function); so if `self` is `Option`, this returns the `u32`. + pub fn substs(&self) -> Option { + match self { + Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), + _ => None, + } + } + + /// If this is an `impl Trait` or `dyn Trait`, returns that trait. + pub fn inherent_trait(&self) -> Option { + match self { + Ty::Dyn(predicates) | Ty::Opaque(predicates) => { + predicates.iter().find_map(|pred| match pred { + GenericPredicate::Implemented(tr) => Some(tr.trait_), + _ => None, + }) + } + _ => None, + } + } +} + +/// This allows walking structures that contain types to do something with those +/// types, similar to Chalk's `Fold` trait. +pub trait TypeWalk { + fn walk(&self, f: &mut impl FnMut(&Ty)); + fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { + self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); + } + /// Walk the type, counting entered binders. + /// + /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers + /// to the innermost binder, 1 to the next, etc.. So when we want to + /// substitute a certain bound variable, we can't just walk the whole type + /// and blindly replace each instance of a certain index; when we 'enter' + /// things that introduce new bound variables, we have to keep track of + /// that. Currently, the only thing that introduces bound variables on our + /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound + /// variable for the self type. + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); + + fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self + where + Self: Sized, + { + self.walk_mut(&mut |ty_mut| { + let ty = mem::replace(ty_mut, Ty::Unknown); + *ty_mut = f(ty); + }); + self + } + + /// Replaces type parameters in this type using the given `Substs`. (So e.g. + /// if `self` is `&[T]`, where type parameter T has index 0, and the + /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.) + fn subst(self, substs: &Substs) -> Self + where + Self: Sized, + { + self.fold(&mut |ty| match ty { + Ty::Param { idx, name } => { + substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) + } + ty => ty, + }) + } + + /// Substitutes `Ty::Bound` vars (as opposed to type parameters). + fn subst_bound_vars(mut self, substs: &Substs) -> Self + where + Self: Sized, + { + self.walk_mut_binders( + &mut |ty, binders| match ty { + &mut Ty::Bound(idx) => { + if idx as usize >= binders && (idx as usize - binders) < substs.len() { + *ty = substs.0[idx as usize - binders].clone(); + } + } + _ => {} + }, + 0, + ); + self + } + + /// Shifts up `Ty::Bound` vars by `n`. + fn shift_bound_vars(self, n: i32) -> Self + where + Self: Sized, + { + self.fold(&mut |ty| match ty { + Ty::Bound(idx) => { + assert!(idx as i32 >= -n); + Ty::Bound((idx as i32 + n) as u32) + } + ty => ty, + }) + } +} + +impl TypeWalk for Ty { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + match self { + Ty::Apply(a_ty) => { + for t in a_ty.parameters.iter() { + t.walk(f); + } + } + Ty::Projection(p_ty) => { + for t in p_ty.parameters.iter() { + t.walk(f); + } + } + Ty::Dyn(predicates) | Ty::Opaque(predicates) => { + for p in predicates.iter() { + p.walk(f); + } + } + Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} + } + f(self); + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + match self { + Ty::Apply(a_ty) => { + a_ty.parameters.walk_mut_binders(f, binders); + } + Ty::Projection(p_ty) => { + p_ty.parameters.walk_mut_binders(f, binders); + } + Ty::Dyn(predicates) | Ty::Opaque(predicates) => { + for p in make_mut_slice(predicates) { + p.walk_mut_binders(f, binders + 1); + } + } + Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} + } + f(self, binders); + } +} + +impl HirDisplay for &Ty { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + HirDisplay::hir_fmt(*self, f) + } +} + +impl HirDisplay for ApplicationTy { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + if f.should_truncate() { + return write!(f, "…"); + } + + match self.ctor { + TypeCtor::Bool => write!(f, "bool")?, + TypeCtor::Char => write!(f, "char")?, + TypeCtor::Int(t) => write!(f, "{}", t)?, + TypeCtor::Float(t) => write!(f, "{}", t)?, + TypeCtor::Str => write!(f, "str")?, + TypeCtor::Slice => { + let t = self.parameters.as_single(); + write!(f, "[{}]", t.display(f.db))?; + } + TypeCtor::Array => { + let t = self.parameters.as_single(); + write!(f, "[{};_]", t.display(f.db))?; + } + TypeCtor::RawPtr(m) => { + let t = self.parameters.as_single(); + write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?; + } + TypeCtor::Ref(m) => { + let t = self.parameters.as_single(); + write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; + } + TypeCtor::Never => write!(f, "!")?, + TypeCtor::Tuple { .. } => { + let ts = &self.parameters; + if ts.len() == 1 { + write!(f, "({},)", ts[0].display(f.db))?; + } else { + write!(f, "(")?; + f.write_joined(&*ts.0, ", ")?; + write!(f, ")")?; + } + } + TypeCtor::FnPtr { .. } => { + let sig = FnSig::from_fn_ptr_substs(&self.parameters); + write!(f, "fn(")?; + f.write_joined(sig.params(), ", ")?; + write!(f, ") -> {}", sig.ret().display(f.db))?; + } + TypeCtor::FnDef(def) => { + let sig = f.db.callable_item_signature(def); + let name = match def { + CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), + CallableDef::StructId(s) => { + f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing) + } + CallableDef::EnumVariantId(e) => { + let enum_data = f.db.enum_data(e.parent); + enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing) + } + }; + match def { + CallableDef::FunctionId(_) => write!(f, "fn {}", name)?, + CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => { + write!(f, "{}", name)? + } + } + if self.parameters.len() > 0 { + write!(f, "<")?; + f.write_joined(&*self.parameters.0, ", ")?; + write!(f, ">")?; + } + write!(f, "(")?; + f.write_joined(sig.params(), ", ")?; + write!(f, ") -> {}", sig.ret().display(f.db))?; + } + TypeCtor::Adt(def_id) => { + let name = match def_id { + AdtId::StructId(it) => f.db.struct_data(it).name.clone(), + AdtId::UnionId(it) => f.db.union_data(it).name.clone(), + AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), + } + .unwrap_or_else(Name::missing); + write!(f, "{}", name)?; + if self.parameters.len() > 0 { + write!(f, "<")?; + f.write_joined(&*self.parameters.0, ", ")?; + write!(f, ">")?; + } + } + TypeCtor::AssociatedType(type_alias) => { + let trait_ = match type_alias.lookup(f.db).container { + ContainerId::TraitId(it) => it, + _ => panic!("not an associated type"), + }; + let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing); + let name = f.db.type_alias_data(type_alias).name.clone(); + write!(f, "{}::{}", trait_name, name)?; + if self.parameters.len() > 0 { + write!(f, "<")?; + f.write_joined(&*self.parameters.0, ", ")?; + write!(f, ">")?; + } + } + TypeCtor::Closure { .. } => { + let sig = self.parameters[0] + .callable_sig(f.db) + .expect("first closure parameter should contain signature"); + write!(f, "|")?; + f.write_joined(sig.params(), ", ")?; + write!(f, "| -> {}", sig.ret().display(f.db))?; + } + } + Ok(()) + } +} + +impl HirDisplay for ProjectionTy { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + if f.should_truncate() { + return write!(f, "…"); + } + + let trait_name = + f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing); + write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; + if self.parameters.len() > 1 { + write!(f, "<")?; + f.write_joined(&self.parameters[1..], ", ")?; + write!(f, ">")?; + } + write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; + Ok(()) + } +} + +impl HirDisplay for Ty { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + if f.should_truncate() { + return write!(f, "…"); + } + + match self { + Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, + Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, + Ty::Param { name, .. } => write!(f, "{}", name)?, + Ty::Bound(idx) => write!(f, "?{}", idx)?, + Ty::Dyn(predicates) | Ty::Opaque(predicates) => { + match self { + Ty::Dyn(_) => write!(f, "dyn ")?, + Ty::Opaque(_) => write!(f, "impl ")?, + _ => unreachable!(), + }; + // Note: This code is written to produce nice results (i.e. + // corresponding to surface Rust) for types that can occur in + // actual Rust. It will have weird results if the predicates + // aren't as expected (i.e. self types = $0, projection + // predicates for a certain trait come after the Implemented + // predicate for that trait). + let mut first = true; + let mut angle_open = false; + for p in predicates.iter() { + match p { + GenericPredicate::Implemented(trait_ref) => { + if angle_open { + write!(f, ">")?; + } + if !first { + write!(f, " + ")?; + } + // We assume that the self type is $0 (i.e. the + // existential) here, which is the only thing that's + // possible in actual Rust, and hence don't print it + write!( + f, + "{}", + f.db.trait_data(trait_ref.trait_) + .name + .clone() + .unwrap_or_else(Name::missing) + )?; + if trait_ref.substs.len() > 1 { + write!(f, "<")?; + f.write_joined(&trait_ref.substs[1..], ", ")?; + // there might be assoc type bindings, so we leave the angle brackets open + angle_open = true; + } + } + GenericPredicate::Projection(projection_pred) => { + // in types in actual Rust, these will always come + // after the corresponding Implemented predicate + if angle_open { + write!(f, ", ")?; + } else { + write!(f, "<")?; + angle_open = true; + } + let name = + f.db.type_alias_data(projection_pred.projection_ty.associated_ty) + .name + .clone(); + write!(f, "{} = ", name)?; + projection_pred.ty.hir_fmt(f)?; + } + GenericPredicate::Error => { + if angle_open { + // impl Trait + write!(f, ", ")?; + } else if !first { + // impl Trait + {error} + write!(f, " + ")?; + } + p.hir_fmt(f)?; + } + } + first = false; + } + if angle_open { + write!(f, ">")?; + } + } + Ty::Unknown => write!(f, "{{unknown}}")?, + Ty::Infer(..) => write!(f, "_")?, + } + Ok(()) + } +} + +impl TraitRef { + fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> fmt::Result { + if f.should_truncate() { + return write!(f, "…"); + } + + self.substs[0].hir_fmt(f)?; + if use_as { + write!(f, " as ")?; + } else { + write!(f, ": ")?; + } + write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?; + if self.substs.len() > 1 { + write!(f, "<")?; + f.write_joined(&self.substs[1..], ", ")?; + write!(f, ">")?; + } + Ok(()) + } +} + +impl HirDisplay for TraitRef { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + self.hir_fmt_ext(f, false) + } +} + +impl HirDisplay for &GenericPredicate { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + HirDisplay::hir_fmt(*self, f) + } +} + +impl HirDisplay for GenericPredicate { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + if f.should_truncate() { + return write!(f, "…"); + } + + match self { + GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?, + GenericPredicate::Projection(projection_pred) => { + write!(f, "<")?; + projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; + write!( + f, + ">::{} = {}", + f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, + projection_pred.ty.display(f.db) + )?; + } + GenericPredicate::Error => write!(f, "{{error}}")?, + } + Ok(()) + } +} + +impl HirDisplay for Obligation { + fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { + match self { + Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), + Obligation::Projection(proj) => write!( + f, + "Normalize({} => {})", + proj.projection_ty.display(f.db), + proj.ty.display(f.db) + ), + } + } +} diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs new file mode 100644 index 000000000..53d955a12 --- /dev/null +++ b/crates/ra_hir_ty/src/lower.rs @@ -0,0 +1,753 @@ +//! Methods for lowering the HIR to types. There are two main cases here: +//! +//! - Lowering a type reference like `&usize` or `Option` to a +//! type: The entry point for this is `Ty::from_hir`. +//! - Building the type for an item: This happens through the `type_for_def` query. +//! +//! This usually involves resolving names, collecting generic arguments etc. +use std::iter; +use std::sync::Arc; + +use hir_def::{ + builtin_type::BuiltinType, + generics::WherePredicate, + path::{GenericArg, Path, PathKind, PathSegment}, + resolver::{HasResolver, Resolver, TypeNs}, + type_ref::{TypeBound, TypeRef}, + AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, + LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, +}; +use ra_arena::map::ArenaMap; +use ra_db::CrateId; + +use super::{ + FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, + Ty, TypeCtor, TypeWalk, +}; +use crate::{ + db::HirDatabase, + primitive::{FloatTy, IntTy}, + utils::make_mut_slice, + utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data}, +}; + +impl Ty { + pub fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { + match type_ref { + TypeRef::Never => Ty::simple(TypeCtor::Never), + TypeRef::Tuple(inner) => { + let inner_tys: Arc<[Ty]> = + inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); + Ty::apply( + TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, + Substs(inner_tys), + ) + } + TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), + TypeRef::RawPtr(inner, mutability) => { + let inner_ty = Ty::from_hir(db, resolver, inner); + Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) + } + TypeRef::Array(inner) => { + let inner_ty = Ty::from_hir(db, resolver, inner); + Ty::apply_one(TypeCtor::Array, inner_ty) + } + TypeRef::Slice(inner) => { + let inner_ty = Ty::from_hir(db, resolver, inner); + Ty::apply_one(TypeCtor::Slice, inner_ty) + } + TypeRef::Reference(inner, mutability) => { + let inner_ty = Ty::from_hir(db, resolver, inner); + Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) + } + TypeRef::Placeholder => Ty::Unknown, + TypeRef::Fn(params) => { + let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); + Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) + } + TypeRef::DynTrait(bounds) => { + let self_ty = Ty::Bound(0); + let predicates = bounds + .iter() + .flat_map(|b| { + GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) + }) + .collect(); + Ty::Dyn(predicates) + } + TypeRef::ImplTrait(bounds) => { + let self_ty = Ty::Bound(0); + let predicates = bounds + .iter() + .flat_map(|b| { + GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) + }) + .collect(); + Ty::Opaque(predicates) + } + TypeRef::Error => Ty::Unknown, + } + } + + /// This is only for `generic_predicates_for_param`, where we can't just + /// lower the self types of the predicates since that could lead to cycles. + /// So we just check here if the `type_ref` resolves to a generic param, and which. + fn from_hir_only_param( + db: &impl HirDatabase, + resolver: &Resolver, + type_ref: &TypeRef, + ) -> Option { + let path = match type_ref { + TypeRef::Path(path) => path, + _ => return None, + }; + if let PathKind::Type(_) = &path.kind { + return None; + } + if path.segments.len() > 1 { + return None; + } + let resolution = match resolver.resolve_path_in_type_ns(db, path) { + Some((it, None)) => it, + _ => return None, + }; + if let TypeNs::GenericParam(idx) = resolution { + Some(idx) + } else { + None + } + } + + pub(crate) fn from_type_relative_path( + db: &impl HirDatabase, + resolver: &Resolver, + ty: Ty, + remaining_segments: &[PathSegment], + ) -> Ty { + if remaining_segments.len() == 1 { + // resolve unselected assoc types + let segment = &remaining_segments[0]; + Ty::select_associated_type(db, resolver, ty, segment) + } else if remaining_segments.len() > 1 { + // FIXME report error (ambiguous associated type) + Ty::Unknown + } else { + ty + } + } + + pub(crate) fn from_partly_resolved_hir_path( + db: &impl HirDatabase, + resolver: &Resolver, + resolution: TypeNs, + resolved_segment: &PathSegment, + remaining_segments: &[PathSegment], + ) -> Ty { + let ty = match resolution { + TypeNs::TraitId(trait_) => { + let trait_ref = + TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None); + return if remaining_segments.len() == 1 { + let segment = &remaining_segments[0]; + let associated_ty = associated_type_by_name_including_super_traits( + db, + trait_ref.trait_, + &segment.name, + ); + match associated_ty { + Some(associated_ty) => { + // FIXME handle type parameters on the segment + Ty::Projection(ProjectionTy { + associated_ty, + parameters: trait_ref.substs, + }) + } + None => { + // FIXME: report error (associated type not found) + Ty::Unknown + } + } + } else if remaining_segments.len() > 1 { + // FIXME report error (ambiguous associated type) + Ty::Unknown + } else { + Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) + }; + } + TypeNs::GenericParam(idx) => { + // FIXME: maybe return name in resolution? + let name = resolved_segment.name.clone(); + Ty::Param { idx, name } + } + TypeNs::SelfType(impl_id) => { + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + Ty::from_hir(db, &resolver, &impl_data.target_type) + } + TypeNs::AdtSelfType(adt) => db.ty(adt.into()), + + TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), + TypeNs::BuiltinType(it) => { + Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) + } + TypeNs::TypeAliasId(it) => { + Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) + } + // FIXME: report error + TypeNs::EnumVariantId(_) => return Ty::Unknown, + }; + + Ty::from_type_relative_path(db, resolver, ty, remaining_segments) + } + + pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { + // Resolve the path (in type namespace) + if let PathKind::Type(type_ref) = &path.kind { + let ty = Ty::from_hir(db, resolver, &type_ref); + let remaining_segments = &path.segments[..]; + return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); + } + let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) { + Some(it) => it, + None => return Ty::Unknown, + }; + let (resolved_segment, remaining_segments) = match remaining_index { + None => ( + path.segments.last().expect("resolved path has at least one element"), + &[] as &[PathSegment], + ), + Some(i) => (&path.segments[i - 1], &path.segments[i..]), + }; + Ty::from_partly_resolved_hir_path( + db, + resolver, + resolution, + resolved_segment, + remaining_segments, + ) + } + + fn select_associated_type( + db: &impl HirDatabase, + resolver: &Resolver, + self_ty: Ty, + segment: &PathSegment, + ) -> Ty { + let param_idx = match self_ty { + Ty::Param { idx, .. } => idx, + _ => return Ty::Unknown, // Error: Ambiguous associated type + }; + let def = match resolver.generic_def() { + Some(def) => def, + None => return Ty::Unknown, // this can't actually happen + }; + let predicates = db.generic_predicates_for_param(def.into(), param_idx); + let traits_from_env = predicates.iter().filter_map(|pred| match pred { + GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), + _ => None, + }); + let traits = traits_from_env.flat_map(|t| all_super_traits(db, t)); + for t in traits { + if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) { + let substs = + Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build(); + // FIXME handle type parameters on the segment + return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); + } + } + Ty::Unknown + } + + fn from_hir_path_inner( + db: &impl HirDatabase, + resolver: &Resolver, + segment: &PathSegment, + typable: TyDefId, + ) -> Ty { + let generic_def = match typable { + TyDefId::BuiltinType(_) => None, + TyDefId::AdtId(it) => Some(it.into()), + TyDefId::TypeAliasId(it) => Some(it.into()), + }; + let substs = substs_from_path_segment(db, resolver, segment, generic_def, false); + db.ty(typable).subst(&substs) + } + + /// Collect generic arguments from a path into a `Substs`. See also + /// `create_substs_for_ast_path` and `def_to_ty` in rustc. + pub(super) fn substs_from_path( + db: &impl HirDatabase, + resolver: &Resolver, + path: &Path, + // Note that we don't call `db.value_type(resolved)` here, + // `ValueTyDefId` is just a convenient way to pass generics and + // special-case enum variants + resolved: ValueTyDefId, + ) -> Substs { + let last = path.segments.last().expect("path should have at least one segment"); + let (segment, generic_def) = match resolved { + ValueTyDefId::FunctionId(it) => (last, Some(it.into())), + ValueTyDefId::StructId(it) => (last, Some(it.into())), + ValueTyDefId::ConstId(it) => (last, Some(it.into())), + ValueTyDefId::StaticId(_) => (last, None), + ValueTyDefId::EnumVariantId(var) => { + // the generic args for an enum variant may be either specified + // on the segment referring to the enum, or on the segment + // referring to the variant. So `Option::::None` and + // `Option::None::` are both allowed (though the former is + // preferred). See also `def_ids_for_path_segments` in rustc. + let len = path.segments.len(); + let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() { + // Option::::None + &path.segments[len - 2] + } else { + // Option::None:: + last + }; + (segment, Some(var.parent.into())) + } + }; + substs_from_path_segment(db, resolver, segment, generic_def, false) + } +} + +pub(super) fn substs_from_path_segment( + db: &impl HirDatabase, + resolver: &Resolver, + segment: &PathSegment, + def_generic: Option, + add_self_param: bool, +) -> Substs { + let mut substs = Vec::new(); + let def_generics = def_generic.map(|def| db.generic_params(def.into())); + + let (parent_param_count, param_count) = + def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); + substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count)); + if add_self_param { + // FIXME this add_self_param argument is kind of a hack: Traits have the + // Self type as an implicit first type parameter, but it can't be + // actually provided in the type arguments + // (well, actually sometimes it can, in the form of type-relative paths: `::default()`) + substs.push(Ty::Unknown); + } + if let Some(generic_args) = &segment.args_and_bindings { + // if args are provided, it should be all of them, but we can't rely on that + let self_param_correction = if add_self_param { 1 } else { 0 }; + let param_count = param_count - self_param_correction; + for arg in generic_args.args.iter().take(param_count) { + match arg { + GenericArg::Type(type_ref) => { + let ty = Ty::from_hir(db, resolver, type_ref); + substs.push(ty); + } + } + } + } + // add placeholders for args that were not provided + let supplied_params = substs.len(); + for _ in supplied_params..parent_param_count + param_count { + substs.push(Ty::Unknown); + } + assert_eq!(substs.len(), parent_param_count + param_count); + + // handle defaults + if let Some(def_generic) = def_generic { + let default_substs = db.generic_defaults(def_generic.into()); + assert_eq!(substs.len(), default_substs.len()); + + for (i, default_ty) in default_substs.iter().enumerate() { + if substs[i] == Ty::Unknown { + substs[i] = default_ty.clone(); + } + } + } + + Substs(substs.into()) +} + +impl TraitRef { + pub(crate) fn from_path( + db: &impl HirDatabase, + resolver: &Resolver, + path: &Path, + explicit_self_ty: Option, + ) -> Option { + let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? { + TypeNs::TraitId(tr) => tr, + _ => return None, + }; + let segment = path.segments.last().expect("path should have at least one segment"); + Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) + } + + pub(super) fn from_resolved_path( + db: &impl HirDatabase, + resolver: &Resolver, + resolved: TraitId, + segment: &PathSegment, + explicit_self_ty: Option, + ) -> Self { + let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); + if let Some(self_ty) = explicit_self_ty { + make_mut_slice(&mut substs.0)[0] = self_ty; + } + TraitRef { trait_: resolved, substs } + } + + pub(crate) fn from_hir( + db: &impl HirDatabase, + resolver: &Resolver, + type_ref: &TypeRef, + explicit_self_ty: Option, + ) -> Option { + let path = match type_ref { + TypeRef::Path(path) => path, + _ => return None, + }; + TraitRef::from_path(db, resolver, path, explicit_self_ty) + } + + fn substs_from_path( + db: &impl HirDatabase, + resolver: &Resolver, + segment: &PathSegment, + resolved: TraitId, + ) -> Substs { + let has_self_param = + segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); + substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) + } + + pub fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef { + let substs = Substs::identity(&db.generic_params(trait_.into())); + TraitRef { trait_, substs } + } + + pub(crate) fn from_type_bound( + db: &impl HirDatabase, + resolver: &Resolver, + bound: &TypeBound, + self_ty: Ty, + ) -> Option { + match bound { + TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), + TypeBound::Error => None, + } + } +} + +impl GenericPredicate { + pub(crate) fn from_where_predicate<'a>( + db: &'a impl HirDatabase, + resolver: &'a Resolver, + where_predicate: &'a WherePredicate, + ) -> impl Iterator + 'a { + let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); + GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) + } + + pub(crate) fn from_type_bound<'a>( + db: &'a impl HirDatabase, + resolver: &'a Resolver, + bound: &'a TypeBound, + self_ty: Ty, + ) -> impl Iterator + 'a { + let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); + iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) + .chain( + trait_ref.into_iter().flat_map(move |tr| { + assoc_type_bindings_from_type_bound(db, resolver, bound, tr) + }), + ) + } +} + +fn assoc_type_bindings_from_type_bound<'a>( + db: &'a impl HirDatabase, + resolver: &'a Resolver, + bound: &'a TypeBound, + trait_ref: TraitRef, +) -> impl Iterator + 'a { + let last_segment = match bound { + TypeBound::Path(path) => path.segments.last(), + TypeBound::Error => None, + }; + last_segment + .into_iter() + .flat_map(|segment| segment.args_and_bindings.iter()) + .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) + .map(move |(name, type_ref)| { + let associated_ty = + associated_type_by_name_including_super_traits(db, trait_ref.trait_, &name); + let associated_ty = match associated_ty { + None => return GenericPredicate::Error, + Some(t) => t, + }; + let projection_ty = + ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; + let ty = Ty::from_hir(db, resolver, type_ref); + let projection_predicate = ProjectionPredicate { projection_ty, ty }; + GenericPredicate::Projection(projection_predicate) + }) +} + +/// Build the signature of a callable item (function, struct or enum variant). +pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { + match def { + CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), + CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), + CallableDef::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e), + } +} + +/// Build the type of all specific fields of a struct or enum variant. +pub(crate) fn field_types_query( + db: &impl HirDatabase, + variant_id: VariantId, +) -> Arc> { + let var_data = variant_data(db, variant_id); + let resolver = match variant_id { + VariantId::StructId(it) => it.resolver(db), + VariantId::UnionId(it) => it.resolver(db), + VariantId::EnumVariantId(it) => it.parent.resolver(db), + }; + let mut res = ArenaMap::default(); + for (field_id, field_data) in var_data.fields().iter() { + res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) + } + Arc::new(res) +} + +/// This query exists only to be used when resolving short-hand associated types +/// like `T::Item`. +/// +/// See the analogous query in rustc and its comment: +/// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46 +/// This is a query mostly to handle cycles somewhat gracefully; e.g. the +/// following bounds are disallowed: `T: Foo, U: Foo`, but +/// these are fine: `T: Foo, U: Foo<()>`. +pub(crate) fn generic_predicates_for_param_query( + db: &impl HirDatabase, + def: GenericDefId, + param_idx: u32, +) -> Arc<[GenericPredicate]> { + let resolver = def.resolver(db); + resolver + .where_predicates_in_scope() + // we have to filter out all other predicates *first*, before attempting to lower them + .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) + .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) + .collect() +} + +impl TraitEnvironment { + pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc { + let predicates = resolver + .where_predicates_in_scope() + .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) + .collect::>(); + + Arc::new(TraitEnvironment { predicates }) + } +} + +/// Resolve the where clause(s) of an item with generics. +pub(crate) fn generic_predicates_query( + db: &impl HirDatabase, + def: GenericDefId, +) -> Arc<[GenericPredicate]> { + let resolver = def.resolver(db); + resolver + .where_predicates_in_scope() + .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) + .collect() +} + +/// Resolve the default type params from generics +pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs { + let resolver = def.resolver(db); + let generic_params = db.generic_params(def.into()); + + let defaults = generic_params + .params_including_parent() + .into_iter() + .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) + .collect(); + + Substs(defaults) +} + +fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> FnSig { + let data = db.function_data(def); + let resolver = def.resolver(db); + let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::>(); + let ret = Ty::from_hir(db, &resolver, &data.ret_type); + FnSig::from_params_and_return(params, ret) +} + +/// Build the declared type of a function. This should not need to look at the +/// function body. +fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Ty { + let generics = db.generic_params(def.into()); + let substs = Substs::identity(&generics); + Ty::apply(TypeCtor::FnDef(def.into()), substs) +} + +/// Build the declared type of a const. +fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Ty { + let data = db.const_data(def); + let resolver = def.resolver(db); + + Ty::from_hir(db, &resolver, &data.type_ref) +} + +/// Build the declared type of a static. +fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Ty { + let data = db.static_data(def); + let resolver = def.resolver(db); + + Ty::from_hir(db, &resolver, &data.type_ref) +} + +/// Build the declared type of a static. +fn type_for_builtin(def: BuiltinType) -> Ty { + Ty::simple(match def { + BuiltinType::Char => TypeCtor::Char, + BuiltinType::Bool => TypeCtor::Bool, + BuiltinType::Str => TypeCtor::Str, + BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()), + BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()), + }) +} + +fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> FnSig { + let struct_data = db.struct_data(def.into()); + let fields = struct_data.variant_data.fields(); + let resolver = def.resolver(db); + let params = fields + .iter() + .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) + .collect::>(); + let ret = type_for_adt(db, def.into()); + FnSig::from_params_and_return(params, ret) +} + +/// Build the type of a tuple struct constructor. +fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Ty { + let struct_data = db.struct_data(def.into()); + if struct_data.variant_data.is_unit() { + return type_for_adt(db, def.into()); // Unit struct + } + let generics = db.generic_params(def.into()); + let substs = Substs::identity(&generics); + Ty::apply(TypeCtor::FnDef(def.into()), substs) +} + +fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> FnSig { + let enum_data = db.enum_data(def.parent); + let var_data = &enum_data.variants[def.local_id]; + let fields = var_data.variant_data.fields(); + let resolver = def.parent.resolver(db); + let params = fields + .iter() + .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) + .collect::>(); + let generics = db.generic_params(def.parent.into()); + let substs = Substs::identity(&generics); + let ret = type_for_adt(db, def.parent.into()).subst(&substs); + FnSig::from_params_and_return(params, ret) +} + +/// Build the type of a tuple enum variant constructor. +fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Ty { + let enum_data = db.enum_data(def.parent); + let var_data = &enum_data.variants[def.local_id].variant_data; + if var_data.is_unit() { + return type_for_adt(db, def.parent.into()); // Unit variant + } + let generics = db.generic_params(def.parent.into()); + let substs = Substs::identity(&generics); + Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs) +} + +fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Ty { + let generics = db.generic_params(adt.into()); + Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) +} + +fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Ty { + let generics = db.generic_params(t.into()); + let resolver = t.resolver(db); + let type_ref = &db.type_alias_data(t).type_ref; + let substs = Substs::identity(&generics); + let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error)); + inner.subst(&substs) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CallableDef { + FunctionId(FunctionId), + StructId(StructId), + EnumVariantId(EnumVariantId), +} +impl_froms!(CallableDef: FunctionId, StructId, EnumVariantId); + +impl CallableDef { + pub fn krate(self, db: &impl HirDatabase) -> CrateId { + match self { + CallableDef::FunctionId(f) => f.lookup(db).module(db).krate, + CallableDef::StructId(s) => s.module(db).krate, + CallableDef::EnumVariantId(e) => e.parent.module(db).krate, + } + } +} + +impl From for GenericDefId { + fn from(def: CallableDef) -> GenericDefId { + match def { + CallableDef::FunctionId(f) => f.into(), + CallableDef::StructId(s) => s.into(), + CallableDef::EnumVariantId(e) => e.into(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum TyDefId { + BuiltinType(BuiltinType), + AdtId(AdtId), + TypeAliasId(TypeAliasId), +} +impl_froms!(TyDefId: BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ValueTyDefId { + FunctionId(FunctionId), + StructId(StructId), + EnumVariantId(EnumVariantId), + ConstId(ConstId), + StaticId(StaticId), +} +impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId); + +/// Build the declared type of an item. This depends on the namespace; e.g. for +/// `struct Foo(usize)`, we have two types: The type of the struct itself, and +/// the constructor function `(usize) -> Foo` which lives in the values +/// namespace. +pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Ty { + match def { + TyDefId::BuiltinType(it) => type_for_builtin(it), + TyDefId::AdtId(it) => type_for_adt(db, it), + TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), + } +} +pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty { + match def { + ValueTyDefId::FunctionId(it) => type_for_fn(db, it), + ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), + ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it), + ValueTyDefId::ConstId(it) => type_for_const(db, it), + ValueTyDefId::StaticId(it) => type_for_static(db, it), + } +} diff --git a/crates/ra_hir_ty/src/marks.rs b/crates/ra_hir_ty/src/marks.rs new file mode 100644 index 000000000..0f754eb9c --- /dev/null +++ b/crates/ra_hir_ty/src/marks.rs @@ -0,0 +1,9 @@ +//! See test_utils/src/marks.rs + +test_utils::marks!( + type_var_cycles_resolve_completely + type_var_cycles_resolve_as_possible + type_var_resolves_to_int_var + match_ergonomics_ref + coerce_merge_fail_fallback +); diff --git a/crates/ra_hir_ty/src/method_resolution.rs b/crates/ra_hir_ty/src/method_resolution.rs new file mode 100644 index 000000000..53c541eb8 --- /dev/null +++ b/crates/ra_hir_ty/src/method_resolution.rs @@ -0,0 +1,363 @@ +//! This module is concerned with finding methods that a given type provides. +//! For details about how this works in rustc, see the method lookup page in the +//! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html) +//! and the corresponding code mostly in librustc_typeck/check/method/probe.rs. +use std::sync::Arc; + +use arrayvec::ArrayVec; +use hir_def::{ + lang_item::LangItemTarget, resolver::HasResolver, resolver::Resolver, type_ref::Mutability, + AssocItemId, AstItemDef, FunctionId, HasModule, ImplId, TraitId, +}; +use hir_expand::name::Name; +use ra_db::CrateId; +use ra_prof::profile; +use rustc_hash::FxHashMap; + +use crate::{ + db::HirDatabase, + primitive::{FloatBitness, Uncertain}, + utils::all_super_traits, + Ty, TypeCtor, +}; + +use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef}; + +/// This is used as a key for indexing impls. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum TyFingerprint { + Apply(TypeCtor), +} + +impl TyFingerprint { + /// Creates a TyFingerprint for looking up an impl. Only certain types can + /// have impls: if we have some `struct S`, we can have an `impl S`, but not + /// `impl &S`. Hence, this will return `None` for reference types and such. + fn for_impl(ty: &Ty) -> Option { + match ty { + Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)), + _ => None, + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct CrateImplBlocks { + impls: FxHashMap>, + impls_by_trait: FxHashMap>, +} + +impl CrateImplBlocks { + pub(crate) fn impls_in_crate_query( + db: &impl HirDatabase, + krate: CrateId, + ) -> Arc { + let _p = profile("impls_in_crate_query"); + let mut res = + CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; + + let crate_def_map = db.crate_def_map(krate); + for (_module_id, module_data) in crate_def_map.modules.iter() { + for &impl_id in module_data.impls.iter() { + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + + let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + + match &impl_data.target_trait { + Some(trait_ref) => { + if let Some(tr) = + TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty)) + { + res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); + } + } + None => { + if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { + res.impls.entry(target_ty_fp).or_default().push(impl_id); + } + } + } + } + } + + Arc::new(res) + } + pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator + '_ { + let fingerprint = TyFingerprint::for_impl(ty); + fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() + } + + pub fn lookup_impl_blocks_for_trait(&self, tr: TraitId) -> impl Iterator + '_ { + self.impls_by_trait.get(&tr).into_iter().flatten().copied() + } + + pub fn all_impls<'a>(&'a self) -> impl Iterator + 'a { + self.impls.values().chain(self.impls_by_trait.values()).flatten().copied() + } +} + +impl Ty { + pub fn def_crates( + &self, + db: &impl HirDatabase, + cur_crate: CrateId, + ) -> Option> { + // Types like slice can have inherent impls in several crates, (core and alloc). + // The corresponding impls are marked with lang items, so we can use them to find the required crates. + macro_rules! lang_item_crate { + ($($name:expr),+ $(,)?) => {{ + let mut v = ArrayVec::<[LangItemTarget; 2]>::new(); + $( + v.extend(db.lang_item(cur_crate, $name.into())); + )+ + v + }}; + } + + let lang_item_targets = match self { + Ty::Apply(a_ty) => match a_ty.ctor { + TypeCtor::Adt(def_id) => { + return Some(std::iter::once(def_id.module(db).krate).collect()) + } + TypeCtor::Bool => lang_item_crate!("bool"), + TypeCtor::Char => lang_item_crate!("char"), + TypeCtor::Float(Uncertain::Known(f)) => match f.bitness { + // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime) + FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"), + FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"), + }, + TypeCtor::Int(Uncertain::Known(i)) => lang_item_crate!(i.ty_to_string()), + TypeCtor::Str => lang_item_crate!("str_alloc", "str"), + TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"), + TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"), + TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"), + _ => return None, + }, + _ => return None, + }; + let res = lang_item_targets + .into_iter() + .filter_map(|it| match it { + LangItemTarget::ImplBlockId(it) => Some(it), + _ => None, + }) + .map(|it| it.module(db).krate) + .collect(); + Some(res) + } +} +/// Look up the method with the given name, returning the actual autoderefed +/// receiver type (but without autoref applied yet). +pub(crate) fn lookup_method( + ty: &Canonical, + db: &impl HirDatabase, + name: &Name, + resolver: &Resolver, +) -> Option<(Ty, FunctionId)> { + iterate_method_candidates(ty, db, resolver, Some(name), LookupMode::MethodCall, |ty, f| match f + { + AssocItemId::FunctionId(f) => Some((ty.clone(), f)), + _ => None, + }) +} + +/// Whether we're looking up a dotted method call (like `v.len()`) or a path +/// (like `Vec::new`). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum LookupMode { + /// Looking up a method call like `v.len()`: We only consider candidates + /// that have a `self` parameter, and do autoderef. + MethodCall, + /// Looking up a path like `Vec::new` or `Vec::default`: We consider all + /// candidates including associated constants, but don't do autoderef. + Path, +} + +// This would be nicer if it just returned an iterator, but that runs into +// lifetime problems, because we need to borrow temp `CrateImplBlocks`. +// FIXME add a context type here? +pub fn iterate_method_candidates( + ty: &Canonical, + db: &impl HirDatabase, + resolver: &Resolver, + name: Option<&Name>, + mode: LookupMode, + mut callback: impl FnMut(&Ty, AssocItemId) -> Option, +) -> Option { + let krate = resolver.krate()?; + match mode { + LookupMode::MethodCall => { + // For method calls, rust first does any number of autoderef, and then one + // autoref (i.e. when the method takes &self or &mut self). We just ignore + // the autoref currently -- when we find a method matching the given name, + // we assume it fits. + + // Also note that when we've got a receiver like &S, even if the method we + // find in the end takes &self, we still do the autoderef step (just as + // rustc does an autoderef and then autoref again). + let environment = TraitEnvironment::lower(db, resolver); + let ty = InEnvironment { value: ty.clone(), environment }; + for derefed_ty in autoderef::autoderef(db, resolver.krate(), ty) { + if let Some(result) = + iterate_inherent_methods(&derefed_ty, db, name, mode, krate, &mut callback) + { + return Some(result); + } + if let Some(result) = iterate_trait_method_candidates( + &derefed_ty, + db, + resolver, + name, + mode, + &mut callback, + ) { + return Some(result); + } + } + } + LookupMode::Path => { + // No autoderef for path lookups + if let Some(result) = + iterate_inherent_methods(&ty, db, name, mode, krate.into(), &mut callback) + { + return Some(result); + } + if let Some(result) = + iterate_trait_method_candidates(&ty, db, resolver, name, mode, &mut callback) + { + return Some(result); + } + } + } + None +} + +fn iterate_trait_method_candidates( + ty: &Canonical, + db: &impl HirDatabase, + resolver: &Resolver, + name: Option<&Name>, + mode: LookupMode, + mut callback: impl FnMut(&Ty, AssocItemId) -> Option, +) -> Option { + let krate = resolver.krate()?; + // FIXME: maybe put the trait_env behind a query (need to figure out good input parameters for that) + let env = TraitEnvironment::lower(db, resolver); + // if ty is `impl Trait` or `dyn Trait`, the trait doesn't need to be in scope + let inherent_trait = ty.value.inherent_trait().into_iter(); + // if we have `T: Trait` in the param env, the trait doesn't need to be in scope + let traits_from_env = env + .trait_predicates_for_self_ty(&ty.value) + .map(|tr| tr.trait_) + .flat_map(|t| all_super_traits(db, t)); + let traits = + inherent_trait.chain(traits_from_env).chain(resolver.traits_in_scope(db).into_iter()); + 'traits: for t in traits { + let data = db.trait_data(t); + + // we'll be lazy about checking whether the type implements the + // trait, but if we find out it doesn't, we'll skip the rest of the + // iteration + let mut known_implemented = false; + for (_name, item) in data.items.iter() { + if !is_valid_candidate(db, name, mode, (*item).into()) { + continue; + } + if !known_implemented { + let goal = generic_implements_goal(db, env.clone(), t, ty.clone()); + if db.trait_solve(krate.into(), goal).is_none() { + continue 'traits; + } + } + known_implemented = true; + if let Some(result) = callback(&ty.value, (*item).into()) { + return Some(result); + } + } + } + None +} + +fn iterate_inherent_methods( + ty: &Canonical, + db: &impl HirDatabase, + name: Option<&Name>, + mode: LookupMode, + krate: CrateId, + mut callback: impl FnMut(&Ty, AssocItemId) -> Option, +) -> Option { + for krate in ty.value.def_crates(db, krate)? { + let impls = db.impls_in_crate(krate); + + for impl_block in impls.lookup_impl_blocks(&ty.value) { + for &item in db.impl_data(impl_block).items.iter() { + if !is_valid_candidate(db, name, mode, item) { + continue; + } + if let Some(result) = callback(&ty.value, item.into()) { + return Some(result); + } + } + } + } + None +} + +fn is_valid_candidate( + db: &impl HirDatabase, + name: Option<&Name>, + mode: LookupMode, + item: AssocItemId, +) -> bool { + match item { + AssocItemId::FunctionId(m) => { + let data = db.function_data(m); + name.map_or(true, |name| &data.name == name) + && (data.has_self_param || mode == LookupMode::Path) + } + AssocItemId::ConstId(c) => { + let data = db.const_data(c); + name.map_or(true, |name| data.name.as_ref() == Some(name)) && (mode == LookupMode::Path) + } + _ => false, + } +} + +pub fn implements_trait( + ty: &Canonical, + db: &impl HirDatabase, + resolver: &Resolver, + krate: CrateId, + trait_: TraitId, +) -> bool { + if ty.value.inherent_trait() == Some(trait_) { + // FIXME this is a bit of a hack, since Chalk should say the same thing + // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet + return true; + } + let env = TraitEnvironment::lower(db, resolver); + let goal = generic_implements_goal(db, env, trait_, ty.clone()); + let solution = db.trait_solve(krate.into(), goal); + + solution.is_some() +} + +/// This creates Substs for a trait with the given Self type and type variables +/// for all other parameters, to query Chalk with it. +fn generic_implements_goal( + db: &impl HirDatabase, + env: Arc, + trait_: TraitId, + self_ty: Canonical, +) -> Canonical> { + let num_vars = self_ty.num_vars; + let substs = super::Substs::build_for_def(db, trait_) + .push(self_ty.value) + .fill_with_bound_vars(num_vars as u32) + .build(); + let num_vars = substs.len() - 1 + self_ty.num_vars; + let trait_ref = TraitRef { trait_, substs }; + let obligation = super::Obligation::Trait(trait_ref); + Canonical { num_vars, value: InEnvironment::new(env, obligation) } +} diff --git a/crates/ra_hir_ty/src/op.rs b/crates/ra_hir_ty/src/op.rs new file mode 100644 index 000000000..09c47a76d --- /dev/null +++ b/crates/ra_hir_ty/src/op.rs @@ -0,0 +1,50 @@ +//! FIXME: write short doc here +use hir_def::expr::{BinaryOp, CmpOp}; + +use super::{InferTy, Ty, TypeCtor}; +use crate::ApplicationTy; + +pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty { + match op { + BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => Ty::simple(TypeCtor::Bool), + BinaryOp::Assignment { .. } => Ty::unit(), + BinaryOp::ArithOp(_) => match rhs_ty { + Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { + TypeCtor::Int(..) | TypeCtor::Float(..) => rhs_ty, + _ => Ty::Unknown, + }, + Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => rhs_ty, + _ => Ty::Unknown, + }, + } +} + +pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty { + match op { + BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool), + BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => { + match lhs_ty { + Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { + TypeCtor::Int(..) + | TypeCtor::Float(..) + | TypeCtor::Str + | TypeCtor::Char + | TypeCtor::Bool => lhs_ty, + _ => Ty::Unknown, + }, + Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, + _ => Ty::Unknown, + } + } + BinaryOp::CmpOp(CmpOp::Ord { .. }) + | BinaryOp::Assignment { op: Some(_) } + | BinaryOp::ArithOp(_) => match lhs_ty { + Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { + TypeCtor::Int(..) | TypeCtor::Float(..) => lhs_ty, + _ => Ty::Unknown, + }, + Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, + _ => Ty::Unknown, + }, + } +} diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs new file mode 100644 index 000000000..0e51f4130 --- /dev/null +++ b/crates/ra_hir_ty/src/test_db.rs @@ -0,0 +1,144 @@ +//! Database used for testing `hir`. + +use std::{panic, sync::Arc}; + +use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId}; +use hir_expand::diagnostics::DiagnosticSink; +use parking_lot::Mutex; +use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; + +use crate::{db::HirDatabase, expr::ExprValidator}; + +#[salsa::database( + ra_db::SourceDatabaseExtStorage, + ra_db::SourceDatabaseStorage, + hir_expand::db::AstDatabaseStorage, + hir_def::db::InternDatabaseStorage, + hir_def::db::DefDatabaseStorage, + crate::db::HirDatabaseStorage +)] +#[derive(Debug, Default)] +pub struct TestDB { + events: Mutex>>>, + runtime: salsa::Runtime, +} + +impl salsa::Database for TestDB { + fn salsa_runtime(&self) -> &salsa::Runtime { + &self.runtime + } + + fn salsa_runtime_mut(&mut self) -> &mut salsa::Runtime { + &mut self.runtime + } + + fn salsa_event(&self, event: impl Fn() -> salsa::Event) { + let mut events = self.events.lock(); + if let Some(events) = &mut *events { + events.push(event()); + } + } +} + +impl salsa::ParallelDatabase for TestDB { + fn snapshot(&self) -> salsa::Snapshot { + salsa::Snapshot::new(TestDB { + events: Default::default(), + runtime: self.runtime.snapshot(self), + }) + } +} + +impl panic::RefUnwindSafe for TestDB {} + +impl FileLoader for TestDB { + fn file_text(&self, file_id: FileId) -> Arc { + FileLoaderDelegate(self).file_text(file_id) + } + fn resolve_relative_path( + &self, + anchor: FileId, + relative_path: &RelativePath, + ) -> Option { + FileLoaderDelegate(self).resolve_relative_path(anchor, relative_path) + } + fn relevant_crates(&self, file_id: FileId) -> Arc> { + FileLoaderDelegate(self).relevant_crates(file_id) + } +} + +impl TestDB { + pub fn module_for_file(&self, file_id: FileId) -> ModuleId { + for &krate in self.relevant_crates(file_id).iter() { + let crate_def_map = self.crate_def_map(krate); + for (module_id, data) in crate_def_map.modules.iter() { + if data.definition == Some(file_id) { + return ModuleId { krate, module_id }; + } + } + } + panic!("Can't find module for file") + } + + // FIXME: don't duplicate this + pub fn diagnostics(&self) -> String { + let mut buf = String::new(); + let crate_graph = self.crate_graph(); + for krate in crate_graph.iter().next() { + let crate_def_map = self.crate_def_map(krate); + + let mut fns = Vec::new(); + for (module_id, _) in crate_def_map.modules.iter() { + for decl in crate_def_map[module_id].scope.declarations() { + match decl { + ModuleDefId::FunctionId(f) => fns.push(f), + _ => (), + } + } + + for &impl_id in crate_def_map[module_id].impls.iter() { + let impl_data = self.impl_data(impl_id); + for item in impl_data.items.iter() { + if let AssocItemId::FunctionId(f) = item { + fns.push(*f) + } + } + } + } + + for f in fns { + let infer = self.infer(f.into()); + let mut sink = DiagnosticSink::new(|d| { + buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message()); + }); + infer.add_diagnostics(self, f, &mut sink); + let mut validator = ExprValidator::new(f, infer, &mut sink); + validator.validate_body(self); + } + } + buf + } +} + +impl TestDB { + pub fn log(&self, f: impl FnOnce()) -> Vec> { + *self.events.lock() = Some(Vec::new()); + f(); + self.events.lock().take().unwrap() + } + + pub fn log_executed(&self, f: impl FnOnce()) -> Vec { + let events = self.log(f); + events + .into_iter() + .filter_map(|e| match e.kind { + // This pretty horrible, but `Debug` is the only way to inspect + // QueryDescriptor at the moment. + salsa::EventKind::WillExecute { database_key } => { + Some(format!("{:?}", database_key)) + } + _ => None, + }) + .collect() + } +} diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs new file mode 100644 index 000000000..c1744663a --- /dev/null +++ b/crates/ra_hir_ty/src/tests.rs @@ -0,0 +1,4958 @@ +mod never_type; +mod coercion; + +use std::fmt::Write; +use std::sync::Arc; + +use hir_def::{ + body::BodySourceMap, db::DefDatabase, nameres::CrateDefMap, AssocItemId, DefWithBodyId, + LocalModuleId, Lookup, ModuleDefId, +}; +use hir_expand::Source; +use insta::assert_snapshot; +use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; +use ra_syntax::{ + algo, + ast::{self, AstNode}, +}; +use test_utils::covers; + +use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult}; + +// These tests compare the inference results for all expressions in a file +// against snapshots of the expected results using insta. Use cargo-insta to +// update the snapshots. + +#[test] +fn cfg_impl_block() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:foo cfg:test +use foo::S as T; +struct S; + +#[cfg(test)] +impl S { + fn foo1(&self) -> i32 { 0 } +} + +#[cfg(not(test))] +impl S { + fn foo2(&self) -> i32 { 0 } +} + +fn test() { + let t = (S.foo1(), S.foo2(), T.foo3(), T.foo4()); + t<|>; +} + +//- /foo.rs crate:foo +struct S; + +#[cfg(not(test))] +impl S { + fn foo3(&self) -> i32 { 0 } +} + +#[cfg(test)] +impl S { + fn foo4(&self) -> i32 { 0 } +} +"#, + ); + assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos)); +} + +#[test] +fn infer_await() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std + +struct IntFuture; + +impl Future for IntFuture { + type Output = u64; +} + +fn test() { + let r = IntFuture; + let v = r.await; + v<|>; +} + +//- /std.rs crate:std +#[prelude_import] use future::*; +mod future { + trait Future { + type Output; + } +} + +"#, + ); + assert_eq!("u64", type_at_pos(&db, pos)); +} + +#[test] +fn infer_box() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std + +fn test() { + let x = box 1; + let t = (x, box x, box &1, box [1]); + t<|>; +} + +//- /std.rs crate:std +#[prelude_import] use prelude::*; +mod prelude {} + +mod boxed { + pub struct Box { + inner: *mut T, + } +} + +"#, + ); + assert_eq!("(Box, Box>, Box<&i32>, Box<[i32;_]>)", type_at_pos(&db, pos)); +} + +#[test] +fn infer_adt_self() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs +enum Nat { Succ(Self), Demo(Nat), Zero } + +fn test() { + let foo: Nat = Nat::Zero; + if let Nat::Succ(x) = foo { + x<|> + } +} + +"#, + ); + assert_eq!("Nat", type_at_pos(&db, pos)); +} + +#[test] +fn infer_try() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std + +fn test() { + let r: Result = Result::Ok(1); + let v = r?; + v<|>; +} + +//- /std.rs crate:std + +#[prelude_import] use ops::*; +mod ops { + trait Try { + type Ok; + type Error; + } +} + +#[prelude_import] use result::*; +mod result { + enum Result { + Ok(O), + Err(E) + } + + impl crate::ops::Try for Result { + type Ok = O; + type Error = E; + } +} + +"#, + ); + assert_eq!("i32", type_at_pos(&db, pos)); +} + +#[test] +fn infer_for_loop() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std + +use std::collections::Vec; + +fn test() { + let v = Vec::new(); + v.push("foo"); + for x in v { + x<|>; + } +} + +//- /std.rs crate:std + +#[prelude_import] use iter::*; +mod iter { + trait IntoIterator { + type Item; + } +} + +mod collections { + struct Vec {} + impl Vec { + fn new() -> Self { Vec {} } + fn push(&mut self, t: T) { } + } + + impl crate::iter::IntoIterator for Vec { + type Item=T; + } +} +"#, + ); + assert_eq!("&str", type_at_pos(&db, pos)); +} + +#[test] +fn infer_while_let() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs +enum Option { Some(T), None } + +fn test() { + let foo: Option = None; + while let Option::Some(x) = foo { + <|>x + } +} + +"#, + ); + assert_eq!("f32", type_at_pos(&db, pos)); +} + +#[test] +fn infer_basics() { + assert_snapshot!( + infer(r#" +fn test(a: u32, b: isize, c: !, d: &str) { + a; + b; + c; + d; + 1usize; + 1isize; + "test"; + 1.0f32; +}"#), + @r###" + [9; 10) 'a': u32 + [17; 18) 'b': isize + [27; 28) 'c': ! + [33; 34) 'd': &str + [42; 121) '{ ...f32; }': ! + [48; 49) 'a': u32 + [55; 56) 'b': isize + [62; 63) 'c': ! + [69; 70) 'd': &str + [76; 82) '1usize': usize + [88; 94) '1isize': isize + [100; 106) '"test"': &str + [112; 118) '1.0f32': f32 + "### + ); +} + +#[test] +fn infer_let() { + assert_snapshot!( + infer(r#" +fn test() { + let a = 1isize; + let b: usize = 1; + let c = b; + let d: u32; + let e; + let f: i32 = e; +} +"#), + @r###" + [11; 118) '{ ...= e; }': () + [21; 22) 'a': isize + [25; 31) '1isize': isize + [41; 42) 'b': usize + [52; 53) '1': usize + [63; 64) 'c': usize + [67; 68) 'b': usize + [78; 79) 'd': u32 + [94; 95) 'e': i32 + [105; 106) 'f': i32 + [114; 115) 'e': i32 + "### + ); +} + +#[test] +fn infer_paths() { + assert_snapshot!( + infer(r#" +fn a() -> u32 { 1 } + +mod b { + fn c() -> u32 { 1 } +} + +fn test() { + a(); + b::c(); +} +"#), + @r###" + [15; 20) '{ 1 }': u32 + [17; 18) '1': u32 + [48; 53) '{ 1 }': u32 + [50; 51) '1': u32 + [67; 91) '{ ...c(); }': () + [73; 74) 'a': fn a() -> u32 + [73; 76) 'a()': u32 + [82; 86) 'b::c': fn c() -> u32 + [82; 88) 'b::c()': u32 + "### + ); +} + +#[test] +fn infer_path_type() { + assert_snapshot!( + infer(r#" +struct S; + +impl S { + fn foo() -> i32 { 1 } +} + +fn test() { + S::foo(); + ::foo(); +} +"#), + @r###" + [41; 46) '{ 1 }': i32 + [43; 44) '1': i32 + [60; 93) '{ ...o(); }': () + [66; 72) 'S::foo': fn foo() -> i32 + [66; 74) 'S::foo()': i32 + [80; 88) '::foo': fn foo() -> i32 + [80; 90) '::foo()': i32 + "### + ); +} + +#[test] +fn infer_slice_method() { + assert_snapshot!( + infer(r#" +#[lang = "slice"] +impl [T] { + fn foo(&self) -> T { + loop {} + } +} + +#[lang = "slice_alloc"] +impl [T] {} + +fn test() { + <[_]>::foo(b"foo"); +} +"#), + @r###" + [45; 49) 'self': &[T] + [56; 79) '{ ... }': T + [66; 73) 'loop {}': ! + [71; 73) '{}': () + [133; 160) '{ ...o"); }': () + [139; 149) '<[_]>::foo': fn foo(&[T]) -> T + [139; 157) '<[_]>:..."foo")': u8 + [150; 156) 'b"foo"': &[u8] + "### + ); +} + +#[test] +fn infer_struct() { + assert_snapshot!( + infer(r#" +struct A { + b: B, + c: C, +} +struct B; +struct C(usize); + +fn test() { + let c = C(1); + B; + let a: A = A { b: B, c: C(1) }; + a.b; + a.c; +} +"#), + @r###" + [72; 154) '{ ...a.c; }': () + [82; 83) 'c': C + [86; 87) 'C': C(usize) -> C + [86; 90) 'C(1)': C + [88; 89) '1': usize + [96; 97) 'B': B + [107; 108) 'a': A + [114; 133) 'A { b:...C(1) }': A + [121; 122) 'B': B + [127; 128) 'C': C(usize) -> C + [127; 131) 'C(1)': C + [129; 130) '1': usize + [139; 140) 'a': A + [139; 142) 'a.b': B + [148; 149) 'a': A + [148; 151) 'a.c': C + "### + ); +} + +#[test] +fn infer_enum() { + assert_snapshot!( + infer(r#" +enum E { + V1 { field: u32 }, + V2 +} +fn test() { + E::V1 { field: 1 }; + E::V2; +}"#), + @r###" + [48; 82) '{ E:...:V2; }': () + [52; 70) 'E::V1 ...d: 1 }': E + [67; 68) '1': u32 + [74; 79) 'E::V2': E + "### + ); +} + +#[test] +fn infer_refs() { + assert_snapshot!( + infer(r#" +fn test(a: &u32, b: &mut u32, c: *const u32, d: *mut u32) { + a; + *a; + &a; + &mut a; + b; + *b; + &b; + c; + *c; + d; + *d; +} +"#), + @r###" + [9; 10) 'a': &u32 + [18; 19) 'b': &mut u32 + [31; 32) 'c': *const u32 + [46; 47) 'd': *mut u32 + [59; 150) '{ ... *d; }': () + [65; 66) 'a': &u32 + [72; 74) '*a': u32 + [73; 74) 'a': &u32 + [80; 82) '&a': &&u32 + [81; 82) 'a': &u32 + [88; 94) '&mut a': &mut &u32 + [93; 94) 'a': &u32 + [100; 101) 'b': &mut u32 + [107; 109) '*b': u32 + [108; 109) 'b': &mut u32 + [115; 117) '&b': &&mut u32 + [116; 117) 'b': &mut u32 + [123; 124) 'c': *const u32 + [130; 132) '*c': u32 + [131; 132) 'c': *const u32 + [138; 139) 'd': *mut u32 + [145; 147) '*d': u32 + [146; 147) 'd': *mut u32 + "### + ); +} + +#[test] +fn infer_literals() { + assert_snapshot!( + infer(r##" +fn test() { + 5i32; + 5f32; + 5f64; + "hello"; + b"bytes"; + 'c'; + b'b'; + 3.14; + 5000; + false; + true; + r#" + //! doc + // non-doc + mod foo {} + "#; + br#"yolo"#; +} +"##), + @r###" + [11; 221) '{ ...o"#; }': () + [17; 21) '5i32': i32 + [27; 31) '5f32': f32 + [37; 41) '5f64': f64 + [47; 54) '"hello"': &str + [60; 68) 'b"bytes"': &[u8] + [74; 77) ''c'': char + [83; 87) 'b'b'': u8 + [93; 97) '3.14': f64 + [103; 107) '5000': i32 + [113; 118) 'false': bool + [124; 128) 'true': bool + [134; 202) 'r#" ... "#': &str + [208; 218) 'br#"yolo"#': &[u8] + "### + ); +} + +#[test] +fn infer_unary_op() { + assert_snapshot!( + infer(r#" +enum SomeType {} + +fn test(x: SomeType) { + let b = false; + let c = !b; + let a = 100; + let d: i128 = -a; + let e = -100; + let f = !!!true; + let g = !42; + let h = !10u32; + let j = !a; + -3.14; + !3; + -x; + !x; + -"hello"; + !"hello"; +} +"#), + @r###" + [27; 28) 'x': SomeType + [40; 272) '{ ...lo"; }': () + [50; 51) 'b': bool + [54; 59) 'false': bool + [69; 70) 'c': bool + [73; 75) '!b': bool + [74; 75) 'b': bool + [85; 86) 'a': i128 + [89; 92) '100': i128 + [102; 103) 'd': i128 + [112; 114) '-a': i128 + [113; 114) 'a': i128 + [124; 125) 'e': i32 + [128; 132) '-100': i32 + [129; 132) '100': i32 + [142; 143) 'f': bool + [146; 153) '!!!true': bool + [147; 153) '!!true': bool + [148; 153) '!true': bool + [149; 153) 'true': bool + [163; 164) 'g': i32 + [167; 170) '!42': i32 + [168; 170) '42': i32 + [180; 181) 'h': u32 + [184; 190) '!10u32': u32 + [185; 190) '10u32': u32 + [200; 201) 'j': i128 + [204; 206) '!a': i128 + [205; 206) 'a': i128 + [212; 217) '-3.14': f64 + [213; 217) '3.14': f64 + [223; 225) '!3': i32 + [224; 225) '3': i32 + [231; 233) '-x': {unknown} + [232; 233) 'x': SomeType + [239; 241) '!x': {unknown} + [240; 241) 'x': SomeType + [247; 255) '-"hello"': {unknown} + [248; 255) '"hello"': &str + [261; 269) '!"hello"': {unknown} + [262; 269) '"hello"': &str + "### + ); +} + +#[test] +fn infer_backwards() { + assert_snapshot!( + infer(r#" +fn takes_u32(x: u32) {} + +struct S { i32_field: i32 } + +fn test() -> &mut &f64 { + let a = unknown_function(); + takes_u32(a); + let b = unknown_function(); + S { i32_field: b }; + let c = unknown_function(); + &mut &c +} +"#), + @r###" + [14; 15) 'x': u32 + [22; 24) '{}': () + [78; 231) '{ ...t &c }': &mut &f64 + [88; 89) 'a': u32 + [92; 108) 'unknow...nction': {unknown} + [92; 110) 'unknow...tion()': u32 + [116; 125) 'takes_u32': fn takes_u32(u32) -> () + [116; 128) 'takes_u32(a)': () + [126; 127) 'a': u32 + [138; 139) 'b': i32 + [142; 158) 'unknow...nction': {unknown} + [142; 160) 'unknow...tion()': i32 + [166; 184) 'S { i3...d: b }': S + [181; 182) 'b': i32 + [194; 195) 'c': f64 + [198; 214) 'unknow...nction': {unknown} + [198; 216) 'unknow...tion()': f64 + [222; 229) '&mut &c': &mut &f64 + [227; 229) '&c': &f64 + [228; 229) 'c': f64 + "### + ); +} + +#[test] +fn infer_self() { + assert_snapshot!( + infer(r#" +struct S; + +impl S { + fn test(&self) { + self; + } + fn test2(self: &Self) { + self; + } + fn test3() -> Self { + S {} + } + fn test4() -> Self { + Self {} + } +} +"#), + @r###" + [34; 38) 'self': &S + [40; 61) '{ ... }': () + [50; 54) 'self': &S + [75; 79) 'self': &S + [88; 109) '{ ... }': () + [98; 102) 'self': &S + [133; 153) '{ ... }': S + [143; 147) 'S {}': S + [177; 200) '{ ... }': S + [187; 194) 'Self {}': S + "### + ); +} + +#[test] +fn infer_binary_op() { + assert_snapshot!( + infer(r#" +fn f(x: bool) -> i32 { + 0i32 +} + +fn test() -> bool { + let x = a && b; + let y = true || false; + let z = x == y; + let t = x != y; + let minus_forty: isize = -40isize; + let h = minus_forty <= CONST_2; + let c = f(z || y) + 5; + let d = b; + let g = minus_forty ^= i; + let ten: usize = 10; + let ten_is_eleven = ten == some_num; + + ten < 3 +} +"#), + @r###" + [6; 7) 'x': bool + [22; 34) '{ 0i32 }': i32 + [28; 32) '0i32': i32 + [54; 370) '{ ... < 3 }': bool + [64; 65) 'x': bool + [68; 69) 'a': bool + [68; 74) 'a && b': bool + [73; 74) 'b': bool + [84; 85) 'y': bool + [88; 92) 'true': bool + [88; 101) 'true || false': bool + [96; 101) 'false': bool + [111; 112) 'z': bool + [115; 116) 'x': bool + [115; 121) 'x == y': bool + [120; 121) 'y': bool + [131; 132) 't': bool + [135; 136) 'x': bool + [135; 141) 'x != y': bool + [140; 141) 'y': bool + [151; 162) 'minus_forty': isize + [172; 180) '-40isize': isize + [173; 180) '40isize': isize + [190; 191) 'h': bool + [194; 205) 'minus_forty': isize + [194; 216) 'minus_...ONST_2': bool + [209; 216) 'CONST_2': isize + [226; 227) 'c': i32 + [230; 231) 'f': fn f(bool) -> i32 + [230; 239) 'f(z || y)': i32 + [230; 243) 'f(z || y) + 5': i32 + [232; 233) 'z': bool + [232; 238) 'z || y': bool + [237; 238) 'y': bool + [242; 243) '5': i32 + [253; 254) 'd': {unknown} + [257; 258) 'b': {unknown} + [268; 269) 'g': () + [272; 283) 'minus_forty': isize + [272; 288) 'minus_...y ^= i': () + [287; 288) 'i': isize + [298; 301) 'ten': usize + [311; 313) '10': usize + [323; 336) 'ten_is_eleven': bool + [339; 342) 'ten': usize + [339; 354) 'ten == some_num': bool + [346; 354) 'some_num': usize + [361; 364) 'ten': usize + [361; 368) 'ten < 3': bool + [367; 368) '3': usize + "### + ); +} + +#[test] +fn infer_field_autoderef() { + assert_snapshot!( + infer(r#" +struct A { + b: B, +} +struct B; + +fn test1(a: A) { + let a1 = a; + a1.b; + let a2 = &a; + a2.b; + let a3 = &mut a; + a3.b; + let a4 = &&&&&&&a; + a4.b; + let a5 = &mut &&mut &&mut a; + a5.b; +} + +fn test2(a1: *const A, a2: *mut A) { + a1.b; + a2.b; +} +"#), + @r###" + [44; 45) 'a': A + [50; 213) '{ ...5.b; }': () + [60; 62) 'a1': A + [65; 66) 'a': A + [72; 74) 'a1': A + [72; 76) 'a1.b': B + [86; 88) 'a2': &A + [91; 93) '&a': &A + [92; 93) 'a': A + [99; 101) 'a2': &A + [99; 103) 'a2.b': B + [113; 115) 'a3': &mut A + [118; 124) '&mut a': &mut A + [123; 124) 'a': A + [130; 132) 'a3': &mut A + [130; 134) 'a3.b': B + [144; 146) 'a4': &&&&&&&A + [149; 157) '&&&&&&&a': &&&&&&&A + [150; 157) '&&&&&&a': &&&&&&A + [151; 157) '&&&&&a': &&&&&A + [152; 157) '&&&&a': &&&&A + [153; 157) '&&&a': &&&A + [154; 157) '&&a': &&A + [155; 157) '&a': &A + [156; 157) 'a': A + [163; 165) 'a4': &&&&&&&A + [163; 167) 'a4.b': B + [177; 179) 'a5': &mut &&mut &&mut A + [182; 200) '&mut &...&mut a': &mut &&mut &&mut A + [187; 200) '&&mut &&mut a': &&mut &&mut A + [188; 200) '&mut &&mut a': &mut &&mut A + [193; 200) '&&mut a': &&mut A + [194; 200) '&mut a': &mut A + [199; 200) 'a': A + [206; 208) 'a5': &mut &&mut &&mut A + [206; 210) 'a5.b': B + [224; 226) 'a1': *const A + [238; 240) 'a2': *mut A + [250; 273) '{ ...2.b; }': () + [256; 258) 'a1': *const A + [256; 260) 'a1.b': B + [266; 268) 'a2': *mut A + [266; 270) 'a2.b': B + "### + ); +} + +#[test] +fn infer_argument_autoderef() { + assert_snapshot!( + infer(r#" +#[lang = "deref"] +pub trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct A(T); + +impl A { + fn foo(&self) -> &T { + &self.0 + } +} + +struct B(T); + +impl Deref for B { + type Target = T; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +fn test() { + let t = A::foo(&&B(B(A(42)))); +} +"#), + @r###" + [68; 72) 'self': &Self + [139; 143) 'self': &A + [151; 174) '{ ... }': &T + [161; 168) '&self.0': &T + [162; 166) 'self': &A + [162; 168) 'self.0': T + [255; 259) 'self': &B + [278; 301) '{ ... }': &T + [288; 295) '&self.0': &T + [289; 293) 'self': &B + [289; 295) 'self.0': T + [315; 353) '{ ...))); }': () + [325; 326) 't': &i32 + [329; 335) 'A::foo': fn foo(&A) -> &T + [329; 350) 'A::foo...42))))': &i32 + [336; 349) '&&B(B(A(42)))': &&B>> + [337; 349) '&B(B(A(42)))': &B>> + [338; 339) 'B': B>>(T) -> B + [338; 349) 'B(B(A(42)))': B>> + [340; 341) 'B': B>(T) -> B + [340; 348) 'B(A(42))': B> + [342; 343) 'A': A(T) -> A + [342; 347) 'A(42)': A + [344; 346) '42': i32 + "### + ); +} + +#[test] +fn infer_method_argument_autoderef() { + assert_snapshot!( + infer(r#" +#[lang = "deref"] +pub trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct A(*mut T); + +impl A { + fn foo(&self, x: &A) -> &T { + &*x.0 + } +} + +struct B(T); + +impl Deref for B { + type Target = T; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +fn test(a: A) { + let t = A(0 as *mut _).foo(&&B(B(a))); +} +"#), + @r###" + [68; 72) 'self': &Self + [144; 148) 'self': &A + [150; 151) 'x': &A + [166; 187) '{ ... }': &T + [176; 181) '&*x.0': &T + [177; 181) '*x.0': T + [178; 179) 'x': &A + [178; 181) 'x.0': *mut T + [268; 272) 'self': &B + [291; 314) '{ ... }': &T + [301; 308) '&self.0': &T + [302; 306) 'self': &B + [302; 308) 'self.0': T + [326; 327) 'a': A + [337; 383) '{ ...))); }': () + [347; 348) 't': &i32 + [351; 352) 'A': A(*mut T) -> A + [351; 365) 'A(0 as *mut _)': A + [351; 380) 'A(0 as...B(a)))': &i32 + [353; 354) '0': i32 + [353; 364) '0 as *mut _': *mut i32 + [370; 379) '&&B(B(a))': &&B>> + [371; 379) '&B(B(a))': &B>> + [372; 373) 'B': B>>(T) -> B + [372; 379) 'B(B(a))': B>> + [374; 375) 'B': B>(T) -> B + [374; 378) 'B(a)': B> + [376; 377) 'a': A + "### + ); +} + +#[test] +fn bug_484() { + assert_snapshot!( + infer(r#" +fn test() { + let x = if true {}; +} +"#), + @r###" + [11; 37) '{ l... {}; }': () + [20; 21) 'x': () + [24; 34) 'if true {}': () + [27; 31) 'true': bool + [32; 34) '{}': () + "### + ); +} + +#[test] +fn infer_in_elseif() { + assert_snapshot!( + infer(r#" +struct Foo { field: i32 } +fn main(foo: Foo) { + if true { + + } else if false { + foo.field + } +} +"#), + @r###" + [35; 38) 'foo': Foo + [45; 109) '{ ... } }': () + [51; 107) 'if tru... }': () + [54; 58) 'true': bool + [59; 67) '{ }': () + [73; 107) 'if fal... }': () + [76; 81) 'false': bool + [82; 107) '{ ... }': i32 + [92; 95) 'foo': Foo + [92; 101) 'foo.field': i32 + "### + ) +} + +#[test] +fn infer_if_match_with_return() { + assert_snapshot!( + infer(r#" +fn foo() { + let _x1 = if true { + 1 + } else { + return; + }; + let _x2 = if true { + 2 + } else { + return + }; + let _x3 = match true { + true => 3, + _ => { + return; + } + }; + let _x4 = match true { + true => 4, + _ => return + }; +}"#), + @r###" + [10; 323) '{ ... }; }': () + [20; 23) '_x1': i32 + [26; 80) 'if tru... }': i32 + [29; 33) 'true': bool + [34; 51) '{ ... }': i32 + [44; 45) '1': i32 + [57; 80) '{ ... }': ! + [67; 73) 'return': ! + [90; 93) '_x2': i32 + [96; 149) 'if tru... }': i32 + [99; 103) 'true': bool + [104; 121) '{ ... }': i32 + [114; 115) '2': i32 + [127; 149) '{ ... }': ! + [137; 143) 'return': ! + [159; 162) '_x3': i32 + [165; 247) 'match ... }': i32 + [171; 175) 'true': bool + [186; 190) 'true': bool + [194; 195) '3': i32 + [205; 206) '_': bool + [210; 241) '{ ... }': ! + [224; 230) 'return': ! + [257; 260) '_x4': i32 + [263; 320) 'match ... }': i32 + [269; 273) 'true': bool + [284; 288) 'true': bool + [292; 293) '4': i32 + [303; 304) '_': bool + [308; 314) 'return': ! + "### + ) +} + +#[test] +fn infer_inherent_method() { + assert_snapshot!( + infer(r#" +struct A; + +impl A { + fn foo(self, x: u32) -> i32 {} +} + +mod b { + impl super::A { + fn bar(&self, x: u64) -> i64 {} + } +} + +fn test(a: A) { + a.foo(1); + (&a).bar(1); + a.bar(1); +} +"#), + @r###" + [32; 36) 'self': A + [38; 39) 'x': u32 + [53; 55) '{}': () + [103; 107) 'self': &A + [109; 110) 'x': u64 + [124; 126) '{}': () + [144; 145) 'a': A + [150; 198) '{ ...(1); }': () + [156; 157) 'a': A + [156; 164) 'a.foo(1)': i32 + [162; 163) '1': u32 + [170; 181) '(&a).bar(1)': i64 + [171; 173) '&a': &A + [172; 173) 'a': A + [179; 180) '1': u64 + [187; 188) 'a': A + [187; 195) 'a.bar(1)': i64 + [193; 194) '1': u64 + "### + ); +} + +#[test] +fn infer_inherent_method_str() { + assert_snapshot!( + infer(r#" +#[lang = "str"] +impl str { + fn foo(&self) -> i32 {} +} + +fn test() { + "foo".foo(); +} +"#), + @r###" + [40; 44) 'self': &str + [53; 55) '{}': () + [69; 89) '{ ...o(); }': () + [75; 80) '"foo"': &str + [75; 86) '"foo".foo()': i32 + "### + ); +} + +#[test] +fn infer_tuple() { + assert_snapshot!( + infer(r#" +fn test(x: &str, y: isize) { + let a: (u32, &str) = (1, "a"); + let b = (a, x); + let c = (y, x); + let d = (c, x); + let e = (1, "e"); + let f = (e, "d"); +} +"#), + @r###" + [9; 10) 'x': &str + [18; 19) 'y': isize + [28; 170) '{ ...d"); }': () + [38; 39) 'a': (u32, &str) + [55; 63) '(1, "a")': (u32, &str) + [56; 57) '1': u32 + [59; 62) '"a"': &str + [73; 74) 'b': ((u32, &str), &str) + [77; 83) '(a, x)': ((u32, &str), &str) + [78; 79) 'a': (u32, &str) + [81; 82) 'x': &str + [93; 94) 'c': (isize, &str) + [97; 103) '(y, x)': (isize, &str) + [98; 99) 'y': isize + [101; 102) 'x': &str + [113; 114) 'd': ((isize, &str), &str) + [117; 123) '(c, x)': ((isize, &str), &str) + [118; 119) 'c': (isize, &str) + [121; 122) 'x': &str + [133; 134) 'e': (i32, &str) + [137; 145) '(1, "e")': (i32, &str) + [138; 139) '1': i32 + [141; 144) '"e"': &str + [155; 156) 'f': ((i32, &str), &str) + [159; 167) '(e, "d")': ((i32, &str), &str) + [160; 161) 'e': (i32, &str) + [163; 166) '"d"': &str + "### + ); +} + +#[test] +fn infer_array() { + assert_snapshot!( + infer(r#" +fn test(x: &str, y: isize) { + let a = [x]; + let b = [a, a]; + let c = [b, b]; + + let d = [y, 1, 2, 3]; + let d = [1, y, 2, 3]; + let e = [y]; + let f = [d, d]; + let g = [e, e]; + + let h = [1, 2]; + let i = ["a", "b"]; + + let b = [a, ["b"]]; + let x: [u8; 0] = []; +} +"#), + @r###" + [9; 10) 'x': &str + [18; 19) 'y': isize + [28; 293) '{ ... []; }': () + [38; 39) 'a': [&str;_] + [42; 45) '[x]': [&str;_] + [43; 44) 'x': &str + [55; 56) 'b': [[&str;_];_] + [59; 65) '[a, a]': [[&str;_];_] + [60; 61) 'a': [&str;_] + [63; 64) 'a': [&str;_] + [75; 76) 'c': [[[&str;_];_];_] + [79; 85) '[b, b]': [[[&str;_];_];_] + [80; 81) 'b': [[&str;_];_] + [83; 84) 'b': [[&str;_];_] + [96; 97) 'd': [isize;_] + [100; 112) '[y, 1, 2, 3]': [isize;_] + [101; 102) 'y': isize + [104; 105) '1': isize + [107; 108) '2': isize + [110; 111) '3': isize + [122; 123) 'd': [isize;_] + [126; 138) '[1, y, 2, 3]': [isize;_] + [127; 128) '1': isize + [130; 131) 'y': isize + [133; 134) '2': isize + [136; 137) '3': isize + [148; 149) 'e': [isize;_] + [152; 155) '[y]': [isize;_] + [153; 154) 'y': isize + [165; 166) 'f': [[isize;_];_] + [169; 175) '[d, d]': [[isize;_];_] + [170; 171) 'd': [isize;_] + [173; 174) 'd': [isize;_] + [185; 186) 'g': [[isize;_];_] + [189; 195) '[e, e]': [[isize;_];_] + [190; 191) 'e': [isize;_] + [193; 194) 'e': [isize;_] + [206; 207) 'h': [i32;_] + [210; 216) '[1, 2]': [i32;_] + [211; 212) '1': i32 + [214; 215) '2': i32 + [226; 227) 'i': [&str;_] + [230; 240) '["a", "b"]': [&str;_] + [231; 234) '"a"': &str + [236; 239) '"b"': &str + [251; 252) 'b': [[&str;_];_] + [255; 265) '[a, ["b"]]': [[&str;_];_] + [256; 257) 'a': [&str;_] + [259; 264) '["b"]': [&str;_] + [260; 263) '"b"': &str + [275; 276) 'x': [u8;_] + [288; 290) '[]': [u8;_] + "### + ); +} + +#[test] +fn infer_pattern() { + assert_snapshot!( + infer(r#" +fn test(x: &i32) { + let y = x; + let &z = x; + let a = z; + let (c, d) = (1, "hello"); + + for (e, f) in some_iter { + let g = e; + } + + if let [val] = opt { + let h = val; + } + + let lambda = |a: u64, b, c: i32| { a + b; c }; + + let ref ref_to_x = x; + let mut mut_x = x; + let ref mut mut_ref_to_x = x; + let k = mut_ref_to_x; +} +"#), + @r###" + [9; 10) 'x': &i32 + [18; 369) '{ ...o_x; }': () + [28; 29) 'y': &i32 + [32; 33) 'x': &i32 + [43; 45) '&z': &i32 + [44; 45) 'z': i32 + [48; 49) 'x': &i32 + [59; 60) 'a': i32 + [63; 64) 'z': i32 + [74; 80) '(c, d)': (i32, &str) + [75; 76) 'c': i32 + [78; 79) 'd': &str + [83; 95) '(1, "hello")': (i32, &str) + [84; 85) '1': i32 + [87; 94) '"hello"': &str + [102; 152) 'for (e... }': () + [106; 112) '(e, f)': ({unknown}, {unknown}) + [107; 108) 'e': {unknown} + [110; 111) 'f': {unknown} + [116; 125) 'some_iter': {unknown} + [126; 152) '{ ... }': () + [140; 141) 'g': {unknown} + [144; 145) 'e': {unknown} + [158; 205) 'if let... }': () + [165; 170) '[val]': {unknown} + [173; 176) 'opt': {unknown} + [177; 205) '{ ... }': () + [191; 192) 'h': {unknown} + [195; 198) 'val': {unknown} + [215; 221) 'lambda': |u64, u64, i32| -> i32 + [224; 256) '|a: u6...b; c }': |u64, u64, i32| -> i32 + [225; 226) 'a': u64 + [233; 234) 'b': u64 + [236; 237) 'c': i32 + [244; 256) '{ a + b; c }': i32 + [246; 247) 'a': u64 + [246; 251) 'a + b': u64 + [250; 251) 'b': u64 + [253; 254) 'c': i32 + [267; 279) 'ref ref_to_x': &&i32 + [282; 283) 'x': &i32 + [293; 302) 'mut mut_x': &i32 + [305; 306) 'x': &i32 + [316; 336) 'ref mu...f_to_x': &mut &i32 + [339; 340) 'x': &i32 + [350; 351) 'k': &mut &i32 + [354; 366) 'mut_ref_to_x': &mut &i32 + "### + ); +} + +#[test] +fn infer_pattern_match_ergonomics() { + assert_snapshot!( + infer(r#" +struct A(T); + +fn test() { + let A(n) = &A(1); + let A(n) = &mut A(1); +} +"#), + @r###" + [28; 79) '{ ...(1); }': () + [38; 42) 'A(n)': A + [40; 41) 'n': &i32 + [45; 50) '&A(1)': &A + [46; 47) 'A': A(T) -> A + [46; 50) 'A(1)': A + [48; 49) '1': i32 + [60; 64) 'A(n)': A + [62; 63) 'n': &mut i32 + [67; 76) '&mut A(1)': &mut A + [72; 73) 'A': A(T) -> A + [72; 76) 'A(1)': A + [74; 75) '1': i32 + "### + ); +} + +#[test] +fn infer_pattern_match_ergonomics_ref() { + covers!(match_ergonomics_ref); + assert_snapshot!( + infer(r#" +fn test() { + let v = &(1, &2); + let (_, &w) = v; +} +"#), + @r###" + [11; 57) '{ ...= v; }': () + [21; 22) 'v': &(i32, &i32) + [25; 33) '&(1, &2)': &(i32, &i32) + [26; 33) '(1, &2)': (i32, &i32) + [27; 28) '1': i32 + [30; 32) '&2': &i32 + [31; 32) '2': i32 + [43; 50) '(_, &w)': (i32, &i32) + [44; 45) '_': i32 + [47; 49) '&w': &i32 + [48; 49) 'w': i32 + [53; 54) 'v': &(i32, &i32) + "### + ); +} + +#[test] +fn infer_adt_pattern() { + assert_snapshot!( + infer(r#" +enum E { + A { x: usize }, + B +} + +struct S(u32, E); + +fn test() { + let e = E::A { x: 3 }; + + let S(y, z) = foo; + let E::A { x: new_var } = e; + + match e { + E::A { x } => x, + E::B if foo => 1, + E::B => 10, + }; + + let ref d @ E::A { .. } = e; + d; +} +"#), + @r###" + [68; 289) '{ ... d; }': () + [78; 79) 'e': E + [82; 95) 'E::A { x: 3 }': E + [92; 93) '3': usize + [106; 113) 'S(y, z)': S + [108; 109) 'y': u32 + [111; 112) 'z': E + [116; 119) 'foo': S + [129; 148) 'E::A {..._var }': E + [139; 146) 'new_var': usize + [151; 152) 'e': E + [159; 245) 'match ... }': usize + [165; 166) 'e': E + [177; 187) 'E::A { x }': E + [184; 185) 'x': usize + [191; 192) 'x': usize + [202; 206) 'E::B': E + [210; 213) 'foo': bool + [217; 218) '1': usize + [228; 232) 'E::B': E + [236; 238) '10': usize + [256; 275) 'ref d ...{ .. }': &E + [264; 275) 'E::A { .. }': E + [278; 279) 'e': E + [285; 286) 'd': &E + "### + ); +} + +#[test] +fn infer_struct_generics() { + assert_snapshot!( + infer(r#" +struct A { + x: T, +} + +fn test(a1: A, i: i32) { + a1.x; + let a2 = A { x: i }; + a2.x; + let a3 = A:: { x: 1 }; + a3.x; +} +"#), + @r###" + [36; 38) 'a1': A + [48; 49) 'i': i32 + [56; 147) '{ ...3.x; }': () + [62; 64) 'a1': A + [62; 66) 'a1.x': u32 + [76; 78) 'a2': A + [81; 91) 'A { x: i }': A + [88; 89) 'i': i32 + [97; 99) 'a2': A + [97; 101) 'a2.x': i32 + [111; 113) 'a3': A + [116; 134) 'A:: + [131; 132) '1': i128 + [140; 142) 'a3': A + [140; 144) 'a3.x': i128 + "### + ); +} + +#[test] +fn infer_tuple_struct_generics() { + assert_snapshot!( + infer(r#" +struct A(T); +enum Option { Some(T), None } +use Option::*; + +fn test() { + A(42); + A(42u128); + Some("x"); + Option::Some("x"); + None; + let x: Option = None; +} +"#), + @r###" + [76; 184) '{ ...one; }': () + [82; 83) 'A': A(T) -> A + [82; 87) 'A(42)': A + [84; 86) '42': i32 + [93; 94) 'A': A(T) -> A + [93; 102) 'A(42u128)': A + [95; 101) '42u128': u128 + [108; 112) 'Some': Some<&str>(T) -> Option + [108; 117) 'Some("x")': Option<&str> + [113; 116) '"x"': &str + [123; 135) 'Option::Some': Some<&str>(T) -> Option + [123; 140) 'Option...e("x")': Option<&str> + [136; 139) '"x"': &str + [146; 150) 'None': Option<{unknown}> + [160; 161) 'x': Option + [177; 181) 'None': Option + "### + ); +} + +#[test] +fn infer_generics_in_patterns() { + assert_snapshot!( + infer(r#" +struct A { + x: T, +} + +enum Option { + Some(T), + None, +} + +fn test(a1: A, o: Option) { + let A { x: x2 } = a1; + let A:: { x: x3 } = A { x: 1 }; + match o { + Option::Some(t) => t, + _ => 1, + }; +} +"#), + @r###" + [79; 81) 'a1': A + [91; 92) 'o': Option + [107; 244) '{ ... }; }': () + [117; 128) 'A { x: x2 }': A + [124; 126) 'x2': u32 + [131; 133) 'a1': A + [143; 161) 'A:: + [157; 159) 'x3': i64 + [164; 174) 'A { x: 1 }': A + [171; 172) '1': i64 + [180; 241) 'match ... }': u64 + [186; 187) 'o': Option + [198; 213) 'Option::Some(t)': Option + [211; 212) 't': u64 + [217; 218) 't': u64 + [228; 229) '_': Option + [233; 234) '1': u64 + "### + ); +} + +#[test] +fn infer_function_generics() { + assert_snapshot!( + infer(r#" +fn id(t: T) -> T { t } + +fn test() { + id(1u32); + id::(1); + let x: u64 = id(1); +} +"#), + @r###" + [10; 11) 't': T + [21; 26) '{ t }': T + [23; 24) 't': T + [38; 98) '{ ...(1); }': () + [44; 46) 'id': fn id(T) -> T + [44; 52) 'id(1u32)': u32 + [47; 51) '1u32': u32 + [58; 68) 'id::': fn id(T) -> T + [58; 71) 'id::(1)': i128 + [69; 70) '1': i128 + [81; 82) 'x': u64 + [90; 92) 'id': fn id(T) -> T + [90; 95) 'id(1)': u64 + [93; 94) '1': u64 + "### + ); +} + +#[test] +fn infer_impl_generics() { + assert_snapshot!( + infer(r#" +struct A { + x: T1, + y: T2, +} +impl A { + fn x(self) -> X { + self.x + } + fn y(self) -> Y { + self.y + } + fn z(self, t: T) -> (X, Y, T) { + (self.x, self.y, t) + } +} + +fn test() -> i128 { + let a = A { x: 1u64, y: 1i64 }; + a.x(); + a.y(); + a.z(1i128); + a.z::(1); +} +"#), + @r###" + [74; 78) 'self': A + [85; 107) '{ ... }': X + [95; 99) 'self': A + [95; 101) 'self.x': X + [117; 121) 'self': A + [128; 150) '{ ... }': Y + [138; 142) 'self': A + [138; 144) 'self.y': Y + [163; 167) 'self': A + [169; 170) 't': T + [188; 223) '{ ... }': (X, Y, T) + [198; 217) '(self.....y, t)': (X, Y, T) + [199; 203) 'self': A + [199; 205) 'self.x': X + [207; 211) 'self': A + [207; 213) 'self.y': Y + [215; 216) 't': T + [245; 342) '{ ...(1); }': () + [255; 256) 'a': A + [259; 281) 'A { x:...1i64 }': A + [266; 270) '1u64': u64 + [275; 279) '1i64': i64 + [287; 288) 'a': A + [287; 292) 'a.x()': u64 + [298; 299) 'a': A + [298; 303) 'a.y()': i64 + [309; 310) 'a': A + [309; 319) 'a.z(1i128)': (u64, i64, i128) + [313; 318) '1i128': i128 + [325; 326) 'a': A + [325; 339) 'a.z::(1)': (u64, i64, u128) + [337; 338) '1': u128 + "### + ); +} + +#[test] +fn infer_impl_generics_with_autoderef() { + assert_snapshot!( + infer(r#" +enum Option { + Some(T), + None, +} +impl Option { + fn as_ref(&self) -> Option<&T> {} +} +fn test(o: Option) { + (&o).as_ref(); + o.as_ref(); +} +"#), + @r###" + [78; 82) 'self': &Option + [98; 100) '{}': () + [111; 112) 'o': Option + [127; 165) '{ ...f(); }': () + [133; 146) '(&o).as_ref()': Option<&u32> + [134; 136) '&o': &Option + [135; 136) 'o': Option + [152; 153) 'o': Option + [152; 162) 'o.as_ref()': Option<&u32> + "### + ); +} + +#[test] +fn infer_generic_chain() { + assert_snapshot!( + infer(r#" +struct A { + x: T, +} +impl A { + fn x(self) -> T2 { + self.x + } +} +fn id(t: T) -> T { t } + +fn test() -> i128 { + let x = 1; + let y = id(x); + let a = A { x: id(y) }; + let z = id(a.x); + let b = A { x: z }; + b.x() +} +"#), + @r###" + [53; 57) 'self': A + [65; 87) '{ ... }': T2 + [75; 79) 'self': A + [75; 81) 'self.x': T2 + [99; 100) 't': T + [110; 115) '{ t }': T + [112; 113) 't': T + [135; 261) '{ ....x() }': i128 + [146; 147) 'x': i128 + [150; 151) '1': i128 + [162; 163) 'y': i128 + [166; 168) 'id': fn id(T) -> T + [166; 171) 'id(x)': i128 + [169; 170) 'x': i128 + [182; 183) 'a': A + [186; 200) 'A { x: id(y) }': A + [193; 195) 'id': fn id(T) -> T + [193; 198) 'id(y)': i128 + [196; 197) 'y': i128 + [211; 212) 'z': i128 + [215; 217) 'id': fn id(T) -> T + [215; 222) 'id(a.x)': i128 + [218; 219) 'a': A + [218; 221) 'a.x': i128 + [233; 234) 'b': A + [237; 247) 'A { x: z }': A + [244; 245) 'z': i128 + [254; 255) 'b': A + [254; 259) 'b.x()': i128 + "### + ); +} + +#[test] +fn infer_associated_const() { + assert_snapshot!( + infer(r#" +struct Struct; + +impl Struct { + const FOO: u32 = 1; +} + +enum Enum {} + +impl Enum { + const BAR: u32 = 2; +} + +trait Trait { + const ID: u32; +} + +struct TraitTest; + +impl Trait for TraitTest { + const ID: u32 = 5; +} + +fn test() { + let x = Struct::FOO; + let y = Enum::BAR; + let z = TraitTest::ID; +} +"#), + @r###" + [52; 53) '1': u32 + [105; 106) '2': u32 + [213; 214) '5': u32 + [229; 307) '{ ...:ID; }': () + [239; 240) 'x': u32 + [243; 254) 'Struct::FOO': u32 + [264; 265) 'y': u32 + [268; 277) 'Enum::BAR': u32 + [287; 288) 'z': u32 + [291; 304) 'TraitTest::ID': u32 + "### + ); +} + +#[test] +fn infer_associated_method_struct() { + assert_snapshot!( + infer(r#" +struct A { x: u32 } + +impl A { + fn new() -> A { + A { x: 0 } + } +} +fn test() { + let a = A::new(); + a.x; +} +"#), + @r###" + [49; 75) '{ ... }': A + [59; 69) 'A { x: 0 }': A + [66; 67) '0': u32 + [88; 122) '{ ...a.x; }': () + [98; 99) 'a': A + [102; 108) 'A::new': fn new() -> A + [102; 110) 'A::new()': A + [116; 117) 'a': A + [116; 119) 'a.x': u32 + "### + ); +} + +#[test] +fn infer_associated_method_enum() { + assert_snapshot!( + infer(r#" +enum A { B, C } + +impl A { + pub fn b() -> A { + A::B + } + pub fn c() -> A { + A::C + } +} +fn test() { + let a = A::b(); + a; + let c = A::c(); + c; +} +"#), + @r###" + [47; 67) '{ ... }': A + [57; 61) 'A::B': A + [88; 108) '{ ... }': A + [98; 102) 'A::C': A + [121; 178) '{ ... c; }': () + [131; 132) 'a': A + [135; 139) 'A::b': fn b() -> A + [135; 141) 'A::b()': A + [147; 148) 'a': A + [158; 159) 'c': A + [162; 166) 'A::c': fn c() -> A + [162; 168) 'A::c()': A + [174; 175) 'c': A + "### + ); +} + +#[test] +fn infer_associated_method_with_modules() { + assert_snapshot!( + infer(r#" +mod a { + struct A; + impl A { pub fn thing() -> A { A {} }} +} + +mod b { + struct B; + impl B { pub fn thing() -> u32 { 99 }} + + mod c { + struct C; + impl C { pub fn thing() -> C { C {} }} + } +} +use b::c; + +fn test() { + let x = a::A::thing(); + let y = b::B::thing(); + let z = c::C::thing(); +} +"#), + @r###" + [56; 64) '{ A {} }': A + [58; 62) 'A {}': A + [126; 132) '{ 99 }': u32 + [128; 130) '99': u32 + [202; 210) '{ C {} }': C + [204; 208) 'C {}': C + [241; 325) '{ ...g(); }': () + [251; 252) 'x': A + [255; 266) 'a::A::thing': fn thing() -> A + [255; 268) 'a::A::thing()': A + [278; 279) 'y': u32 + [282; 293) 'b::B::thing': fn thing() -> u32 + [282; 295) 'b::B::thing()': u32 + [305; 306) 'z': C + [309; 320) 'c::C::thing': fn thing() -> C + [309; 322) 'c::C::thing()': C + "### + ); +} + +#[test] +fn infer_associated_method_generics() { + assert_snapshot!( + infer(r#" +struct Gen { + val: T +} + +impl Gen { + pub fn make(val: T) -> Gen { + Gen { val } + } +} + +fn test() { + let a = Gen::make(0u32); +} +"#), + @r###" + [64; 67) 'val': T + [82; 109) '{ ... }': Gen + [92; 103) 'Gen { val }': Gen + [98; 101) 'val': T + [123; 155) '{ ...32); }': () + [133; 134) 'a': Gen + [137; 146) 'Gen::make': fn make(T) -> Gen + [137; 152) 'Gen::make(0u32)': Gen + [147; 151) '0u32': u32 + "### + ); +} + +#[test] +fn infer_associated_method_generics_with_default_param() { + assert_snapshot!( + infer(r#" +struct Gen { + val: T +} + +impl Gen { + pub fn make() -> Gen { + loop { } + } +} + +fn test() { + let a = Gen::make(); +} +"#), + @r###" + [80; 104) '{ ... }': Gen + [90; 98) 'loop { }': ! + [95; 98) '{ }': () + [118; 146) '{ ...e(); }': () + [128; 129) 'a': Gen + [132; 141) 'Gen::make': fn make() -> Gen + [132; 143) 'Gen::make()': Gen + "### + ); +} + +#[test] +fn infer_associated_method_generics_with_default_tuple_param() { + let t = type_at( + r#" +//- /main.rs +struct Gen { + val: T +} + +impl Gen { + pub fn make() -> Gen { + loop { } + } +} + +fn test() { + let a = Gen::make(); + a.val<|>; +} +"#, + ); + assert_eq!(t, "()"); +} + +#[test] +fn infer_associated_method_generics_without_args() { + assert_snapshot!( + infer(r#" +struct Gen { + val: T +} + +impl Gen { + pub fn make() -> Gen { + loop { } + } +} + +fn test() { + let a = Gen::::make(); +} +"#), + @r###" + [76; 100) '{ ... }': Gen + [86; 94) 'loop { }': ! + [91; 94) '{ }': () + [114; 149) '{ ...e(); }': () + [124; 125) 'a': Gen + [128; 144) 'Gen::<...::make': fn make() -> Gen + [128; 146) 'Gen::<...make()': Gen + "### + ); +} + +#[test] +fn infer_associated_method_generics_2_type_params_without_args() { + assert_snapshot!( + infer(r#" +struct Gen { + val: T, + val2: U, +} + +impl Gen { + pub fn make() -> Gen { + loop { } + } +} + +fn test() { + let a = Gen::::make(); +} +"#), + @r###" + [102; 126) '{ ... }': Gen + [112; 120) 'loop { }': ! + [117; 120) '{ }': () + [140; 180) '{ ...e(); }': () + [150; 151) 'a': Gen + [154; 175) 'Gen::<...::make': fn make() -> Gen + [154; 177) 'Gen::<...make()': Gen + "### + ); +} + +#[test] +fn infer_type_alias() { + assert_snapshot!( + infer(r#" +struct A { x: X, y: Y } +type Foo = A; +type Bar = A; +type Baz = A; +fn test(x: Foo, y: Bar<&str>, z: Baz) { + x.x; + x.y; + y.x; + y.y; + z.x; + z.y; +} +"#), + @r###" + [116; 117) 'x': A + [124; 125) 'y': A<&str, u128> + [138; 139) 'z': A + [154; 211) '{ ...z.y; }': () + [160; 161) 'x': A + [160; 163) 'x.x': u32 + [169; 170) 'x': A + [169; 172) 'x.y': i128 + [178; 179) 'y': A<&str, u128> + [178; 181) 'y.x': &str + [187; 188) 'y': A<&str, u128> + [187; 190) 'y.y': u128 + [196; 197) 'z': A + [196; 199) 'z.x': u8 + [205; 206) 'z': A + [205; 208) 'z.y': i8 + "### + ) +} + +#[test] +#[should_panic] // we currently can't handle this +fn recursive_type_alias() { + assert_snapshot!( + infer(r#" +struct A {} +type Foo = Foo; +type Bar = A; +fn test(x: Foo) {} +"#), + @"" + ) +} + +#[test] +fn no_panic_on_field_of_enum() { + assert_snapshot!( + infer(r#" +enum X {} + +fn test(x: X) { + x.some_field; +} +"#), + @r###" + [20; 21) 'x': X + [26; 47) '{ ...eld; }': () + [32; 33) 'x': X + [32; 44) 'x.some_field': {unknown} + "### + ); +} + +#[test] +fn bug_585() { + assert_snapshot!( + infer(r#" +fn test() { + X {}; + match x { + A::B {} => (), + A::Y() => (), + } +} +"#), + @r###" + [11; 89) '{ ... } }': () + [17; 21) 'X {}': {unknown} + [27; 87) 'match ... }': () + [33; 34) 'x': {unknown} + [45; 52) 'A::B {}': {unknown} + [56; 58) '()': () + [68; 74) 'A::Y()': {unknown} + [78; 80) '()': () + "### + ); +} + +#[test] +fn bug_651() { + assert_snapshot!( + infer(r#" +fn quux() { + let y = 92; + 1 + y; +} +"#), + @r###" + [11; 41) '{ ...+ y; }': () + [21; 22) 'y': i32 + [25; 27) '92': i32 + [33; 34) '1': i32 + [33; 38) '1 + y': i32 + [37; 38) 'y': i32 + "### + ); +} + +#[test] +fn recursive_vars() { + covers!(type_var_cycles_resolve_completely); + covers!(type_var_cycles_resolve_as_possible); + assert_snapshot!( + infer(r#" +fn test() { + let y = unknown; + [y, &y]; +} +"#), + @r###" + [11; 48) '{ ...&y]; }': () + [21; 22) 'y': &{unknown} + [25; 32) 'unknown': &{unknown} + [38; 45) '[y, &y]': [&&{unknown};_] + [39; 40) 'y': &{unknown} + [42; 44) '&y': &&{unknown} + [43; 44) 'y': &{unknown} + "### + ); +} + +#[test] +fn recursive_vars_2() { + covers!(type_var_cycles_resolve_completely); + covers!(type_var_cycles_resolve_as_possible); + assert_snapshot!( + infer(r#" +fn test() { + let x = unknown; + let y = unknown; + [(x, y), (&y, &x)]; +} +"#), + @r###" + [11; 80) '{ ...x)]; }': () + [21; 22) 'x': &&{unknown} + [25; 32) 'unknown': &&{unknown} + [42; 43) 'y': &&{unknown} + [46; 53) 'unknown': &&{unknown} + [59; 77) '[(x, y..., &x)]': [(&&&{unknown}, &&&{unknown});_] + [60; 66) '(x, y)': (&&&{unknown}, &&&{unknown}) + [61; 62) 'x': &&{unknown} + [64; 65) 'y': &&{unknown} + [68; 76) '(&y, &x)': (&&&{unknown}, &&&{unknown}) + [69; 71) '&y': &&&{unknown} + [70; 71) 'y': &&{unknown} + [73; 75) '&x': &&&{unknown} + [74; 75) 'x': &&{unknown} + "### + ); +} + +#[test] +fn infer_type_param() { + assert_snapshot!( + infer(r#" +fn id(x: T) -> T { + x +} + +fn clone(x: &T) -> T { + *x +} + +fn test() { + let y = 10u32; + id(y); + let x: bool = clone(z); + id::(1); +} +"#), + @r###" + [10; 11) 'x': T + [21; 30) '{ x }': T + [27; 28) 'x': T + [44; 45) 'x': &T + [56; 66) '{ *x }': T + [62; 64) '*x': T + [63; 64) 'x': &T + [78; 158) '{ ...(1); }': () + [88; 89) 'y': u32 + [92; 97) '10u32': u32 + [103; 105) 'id': fn id(T) -> T + [103; 108) 'id(y)': u32 + [106; 107) 'y': u32 + [118; 119) 'x': bool + [128; 133) 'clone': fn clone(&T) -> T + [128; 136) 'clone(z)': bool + [134; 135) 'z': &bool + [142; 152) 'id::': fn id(T) -> T + [142; 155) 'id::(1)': i128 + [153; 154) '1': i128 + "### + ); +} + +#[test] +fn infer_std_crash_1() { + // caused stack overflow, taken from std + assert_snapshot!( + infer(r#" +enum Maybe { + Real(T), + Fake, +} + +fn write() { + match something_unknown { + Maybe::Real(ref mut something) => (), + } +} +"#), + @r###" + [54; 139) '{ ... } }': () + [60; 137) 'match ... }': () + [66; 83) 'someth...nknown': Maybe<{unknown}> + [94; 124) 'Maybe:...thing)': Maybe<{unknown}> + [106; 123) 'ref mu...ething': &mut {unknown} + [128; 130) '()': () + "### + ); +} + +#[test] +fn infer_std_crash_2() { + covers!(type_var_resolves_to_int_var); + // caused "equating two type variables, ...", taken from std + assert_snapshot!( + infer(r#" +fn test_line_buffer() { + &[0, b'\n', 1, b'\n']; +} +"#), + @r###" + [23; 53) '{ ...n']; }': () + [29; 50) '&[0, b...b'\n']': &[u8;_] + [30; 50) '[0, b'...b'\n']': [u8;_] + [31; 32) '0': u8 + [34; 39) 'b'\n'': u8 + [41; 42) '1': u8 + [44; 49) 'b'\n'': u8 + "### + ); +} + +#[test] +fn infer_std_crash_3() { + // taken from rustc + assert_snapshot!( + infer(r#" +pub fn compute() { + match nope!() { + SizeSkeleton::Pointer { non_zero: true, tail } => {} + } +} +"#), + @r###" + [18; 108) '{ ... } }': () + [24; 106) 'match ... }': () + [30; 37) 'nope!()': {unknown} + [48; 94) 'SizeSk...tail }': {unknown} + [82; 86) 'true': {unknown} + [88; 92) 'tail': {unknown} + [98; 100) '{}': () + "### + ); +} + +#[test] +fn infer_std_crash_4() { + // taken from rustc + assert_snapshot!( + infer(r#" +pub fn primitive_type() { + match *self { + BorrowedRef { type_: Primitive(p), ..} => {}, + } +} +"#), + @r###" + [25; 106) '{ ... } }': () + [31; 104) 'match ... }': () + [37; 42) '*self': {unknown} + [38; 42) 'self': {unknown} + [53; 91) 'Borrow...), ..}': {unknown} + [74; 86) 'Primitive(p)': {unknown} + [84; 85) 'p': {unknown} + [95; 97) '{}': () + "### + ); +} + +#[test] +fn infer_std_crash_5() { + // taken from rustc + assert_snapshot!( + infer(r#" +fn extra_compiler_flags() { + for content in doesnt_matter { + let name = if doesnt_matter { + first + } else { + &content + }; + + let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { + name + } else { + content + }; + } +} +"#), + @r###" + [27; 323) '{ ... } }': () + [33; 321) 'for co... }': () + [37; 44) 'content': &{unknown} + [48; 61) 'doesnt_matter': {unknown} + [62; 321) '{ ... }': () + [76; 80) 'name': &&{unknown} + [83; 167) 'if doe... }': &&{unknown} + [86; 99) 'doesnt_matter': bool + [100; 129) '{ ... }': &&{unknown} + [114; 119) 'first': &&{unknown} + [135; 167) '{ ... }': &&{unknown} + [149; 157) '&content': &&{unknown} + [150; 157) 'content': &{unknown} + [182; 189) 'content': &{unknown} + [192; 314) 'if ICE... }': &{unknown} + [195; 232) 'ICE_RE..._VALUE': {unknown} + [195; 248) 'ICE_RE...&name)': bool + [242; 247) '&name': &&&{unknown} + [243; 247) 'name': &&{unknown} + [249; 277) '{ ... }': &&{unknown} + [263; 267) 'name': &&{unknown} + [283; 314) '{ ... }': &{unknown} + [297; 304) 'content': &{unknown} + "### + ); +} + +#[test] +fn infer_nested_generics_crash() { + // another crash found typechecking rustc + assert_snapshot!( + infer(r#" +struct Canonical { + value: V, +} +struct QueryResponse { + value: V, +} +fn test(query_response: Canonical>) { + &query_response.value; +} +"#), + @r###" + [92; 106) 'query_response': Canonical> + [137; 167) '{ ...lue; }': () + [143; 164) '&query....value': &QueryResponse + [144; 158) 'query_response': Canonical> + [144; 164) 'query_....value': QueryResponse + "### + ); +} + +#[test] +fn bug_1030() { + assert_snapshot!(infer(r#" +struct HashSet; +struct FxHasher; +type FxHashSet = HashSet; + +impl HashSet { + fn default() -> HashSet {} +} + +pub fn main_loop() { + FxHashSet::default(); +} +"#), + @r###" + [144; 146) '{}': () + [169; 198) '{ ...t(); }': () + [175; 193) 'FxHash...efault': fn default<{unknown}, FxHasher>() -> HashSet + [175; 195) 'FxHash...ault()': HashSet<{unknown}, FxHasher> + "### + ); +} + +#[test] +fn cross_crate_associated_method_call() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:other_crate +fn test() { + let x = other_crate::foo::S::thing(); + x<|>; +} + +//- /lib.rs crate:other_crate +mod foo { + struct S; + impl S { + fn thing() -> i128 {} + } +} +"#, + ); + assert_eq!("i128", type_at_pos(&db, pos)); +} + +#[test] +fn infer_const() { + assert_snapshot!( + infer(r#" +struct Foo; +impl Foo { const ASSOC_CONST: u32 = 0; } +const GLOBAL_CONST: u32 = 101; +fn test() { + const LOCAL_CONST: u32 = 99; + let x = LOCAL_CONST; + let z = GLOBAL_CONST; + let id = Foo::ASSOC_CONST; +} +"#), + @r###" + [49; 50) '0': u32 + [80; 83) '101': u32 + [95; 213) '{ ...NST; }': () + [138; 139) 'x': {unknown} + [142; 153) 'LOCAL_CONST': {unknown} + [163; 164) 'z': u32 + [167; 179) 'GLOBAL_CONST': u32 + [189; 191) 'id': u32 + [194; 210) 'Foo::A..._CONST': u32 + "### + ); +} + +#[test] +fn infer_static() { + assert_snapshot!( + infer(r#" +static GLOBAL_STATIC: u32 = 101; +static mut GLOBAL_STATIC_MUT: u32 = 101; +fn test() { + static LOCAL_STATIC: u32 = 99; + static mut LOCAL_STATIC_MUT: u32 = 99; + let x = LOCAL_STATIC; + let y = LOCAL_STATIC_MUT; + let z = GLOBAL_STATIC; + let w = GLOBAL_STATIC_MUT; +} +"#), + @r###" + [29; 32) '101': u32 + [70; 73) '101': u32 + [85; 280) '{ ...MUT; }': () + [173; 174) 'x': {unknown} + [177; 189) 'LOCAL_STATIC': {unknown} + [199; 200) 'y': {unknown} + [203; 219) 'LOCAL_...IC_MUT': {unknown} + [229; 230) 'z': u32 + [233; 246) 'GLOBAL_STATIC': u32 + [256; 257) 'w': u32 + [260; 277) 'GLOBAL...IC_MUT': u32 + "### + ); +} + +#[test] +fn infer_trait_method_simple() { + // the trait implementation is intentionally incomplete -- it shouldn't matter + assert_snapshot!( + infer(r#" +trait Trait1 { + fn method(&self) -> u32; +} +struct S1; +impl Trait1 for S1 {} +trait Trait2 { + fn method(&self) -> i128; +} +struct S2; +impl Trait2 for S2 {} +fn test() { + S1.method(); // -> u32 + S2.method(); // -> i128 +} +"#), + @r###" + [31; 35) 'self': &Self + [110; 114) 'self': &Self + [170; 228) '{ ...i128 }': () + [176; 178) 'S1': S1 + [176; 187) 'S1.method()': u32 + [203; 205) 'S2': S2 + [203; 214) 'S2.method()': i128 + "### + ); +} + +#[test] +fn infer_trait_method_scoped() { + // the trait implementation is intentionally incomplete -- it shouldn't matter + assert_snapshot!( + infer(r#" +struct S; +mod foo { + pub trait Trait1 { + fn method(&self) -> u32; + } + impl Trait1 for super::S {} +} +mod bar { + pub trait Trait2 { + fn method(&self) -> i128; + } + impl Trait2 for super::S {} +} + +mod foo_test { + use super::S; + use super::foo::Trait1; + fn test() { + S.method(); // -> u32 + } +} + +mod bar_test { + use super::S; + use super::bar::Trait2; + fn test() { + S.method(); // -> i128 + } +} +"#), + @r###" + [63; 67) 'self': &Self + [169; 173) 'self': &Self + [300; 337) '{ ... }': () + [310; 311) 'S': S + [310; 320) 'S.method()': u32 + [416; 454) '{ ... }': () + [426; 427) 'S': S + [426; 436) 'S.method()': i128 + "### + ); +} + +#[test] +fn infer_trait_method_generic_1() { + // the trait implementation is intentionally incomplete -- it shouldn't matter + assert_snapshot!( + infer(r#" +trait Trait { + fn method(&self) -> T; +} +struct S; +impl Trait for S {} +fn test() { + S.method(); +} +"#), + @r###" + [33; 37) 'self': &Self + [92; 111) '{ ...d(); }': () + [98; 99) 'S': S + [98; 108) 'S.method()': u32 + "### + ); +} + +#[test] +fn infer_trait_method_generic_more_params() { + // the trait implementation is intentionally incomplete -- it shouldn't matter + assert_snapshot!( + infer(r#" +trait Trait { + fn method1(&self) -> (T1, T2, T3); + fn method2(&self) -> (T3, T2, T1); +} +struct S1; +impl Trait for S1 {} +struct S2; +impl Trait for S2 {} +fn test() { + S1.method1(); // u8, u16, u32 + S1.method2(); // u32, u16, u8 + S2.method1(); // i8, i16, {unknown} + S2.method2(); // {unknown}, i16, i8 +} +"#), + @r###" + [43; 47) 'self': &Self + [82; 86) 'self': &Self + [210; 361) '{ ..., i8 }': () + [216; 218) 'S1': S1 + [216; 228) 'S1.method1()': (u8, u16, u32) + [250; 252) 'S1': S1 + [250; 262) 'S1.method2()': (u32, u16, u8) + [284; 286) 'S2': S2 + [284; 296) 'S2.method1()': (i8, i16, {unknown}) + [324; 326) 'S2': S2 + [324; 336) 'S2.method2()': ({unknown}, i16, i8) + "### + ); +} + +#[test] +fn infer_trait_method_generic_2() { + // the trait implementation is intentionally incomplete -- it shouldn't matter + assert_snapshot!( + infer(r#" +trait Trait { + fn method(&self) -> T; +} +struct S(T); +impl Trait for S {} +fn test() { + S(1u32).method(); +} +"#), + @r###" + [33; 37) 'self': &Self + [102; 127) '{ ...d(); }': () + [108; 109) 'S': S(T) -> S + [108; 115) 'S(1u32)': S + [108; 124) 'S(1u32...thod()': u32 + [110; 114) '1u32': u32 + "### + ); +} + +#[test] +fn infer_trait_assoc_method() { + assert_snapshot!( + infer(r#" +trait Default { + fn default() -> Self; +} +struct S; +impl Default for S {} +fn test() { + let s1: S = Default::default(); + let s2 = S::default(); + let s3 = ::default(); +} +"#), + @r###" + [87; 193) '{ ...t(); }': () + [97; 99) 's1': S + [105; 121) 'Defaul...efault': fn default() -> Self + [105; 123) 'Defaul...ault()': S + [133; 135) 's2': S + [138; 148) 'S::default': fn default() -> Self + [138; 150) 'S::default()': S + [160; 162) 's3': S + [165; 188) '() -> Self + [165; 190) ' { + fn make() -> T; +} +struct S; +impl Trait for S {} +struct G; +impl Trait for G {} +fn test() { + let a = S::make(); + let b = G::::make(); + let c: f64 = G::make(); +} +"#), + @r###" + [127; 211) '{ ...e(); }': () + [137; 138) 'a': u32 + [141; 148) 'S::make': fn make() -> T + [141; 150) 'S::make()': u32 + [160; 161) 'b': u64 + [164; 178) 'G::::make': fn make, u64>() -> T + [164; 180) 'G::, f64>() -> T + [199; 208) 'G::make()': f64 + "### + ); +} + +#[test] +fn infer_trait_assoc_method_generics_2() { + assert_snapshot!( + infer(r#" +trait Trait { + fn make() -> (T, U); +} +struct S; +impl Trait for S {} +struct G; +impl Trait for G {} +fn test() { + let a = S::make::(); + let b: (_, i64) = S::make(); + let c = G::::make::(); + let d: (u32, _) = G::make::(); + let e: (u32, i64) = G::make(); +} +"#), + @r###" + [135; 313) '{ ...e(); }': () + [145; 146) 'a': (u32, i64) + [149; 163) 'S::make::': fn make() -> (T, U) + [149; 165) 'S::mak...i64>()': (u32, i64) + [175; 176) 'b': (u32, i64) + [189; 196) 'S::make': fn make() -> (T, U) + [189; 198) 'S::make()': (u32, i64) + [208; 209) 'c': (u32, i64) + [212; 233) 'G::': fn make, u32, i64>() -> (T, U) + [212; 235) 'G::()': (u32, i64) + [245; 246) 'd': (u32, i64) + [259; 273) 'G::make::': fn make, u32, i64>() -> (T, U) + [259; 275) 'G::mak...i64>()': (u32, i64) + [285; 286) 'e': (u32, i64) + [301; 308) 'G::make': fn make, u32, i64>() -> (T, U) + [301; 310) 'G::make()': (u32, i64) + "### + ); +} + +#[test] +fn infer_trait_assoc_method_generics_3() { + assert_snapshot!( + infer(r#" +trait Trait { + fn make() -> (Self, T); +} +struct S; +impl Trait for S {} +fn test() { + let a = S::make(); +} +"#), + @r###" + [101; 127) '{ ...e(); }': () + [111; 112) 'a': (S, i64) + [115; 122) 'S::make': fn make, i64>() -> (Self, T) + [115; 124) 'S::make()': (S, i64) + "### + ); +} + +#[test] +fn infer_trait_assoc_method_generics_4() { + assert_snapshot!( + infer(r#" +trait Trait { + fn make() -> (Self, T); +} +struct S; +impl Trait for S {} +impl Trait for S {} +fn test() { + let a: (S, _) = S::make(); + let b: (_, i32) = S::make(); +} +"#), + @r###" + [131; 203) '{ ...e(); }': () + [141; 142) 'a': (S, i64) + [158; 165) 'S::make': fn make, i64>() -> (Self, T) + [158; 167) 'S::make()': (S, i64) + [177; 178) 'b': (S, i32) + [191; 198) 'S::make': fn make, i32>() -> (Self, T) + [191; 200) 'S::make()': (S, i32) + "### + ); +} + +#[test] +fn infer_trait_assoc_method_generics_5() { + assert_snapshot!( + infer(r#" +trait Trait { + fn make() -> (Self, T, U); +} +struct S; +impl Trait for S {} +fn test() { + let a = >::make::(); + let b: (S, _, _) = Trait::::make::(); +} +"#), + @r###" + [107; 211) '{ ...>(); }': () + [117; 118) 'a': (S, i64, u8) + [121; 150) '': fn make, i64, u8>() -> (Self, T, U) + [121; 152) '()': (S, i64, u8) + [162; 163) 'b': (S, i64, u8) + [182; 206) 'Trait:...::': fn make, i64, u8>() -> (Self, T, U) + [182; 208) 'Trait:...()': (S, i64, u8) + "### + ); +} + +#[test] +fn infer_from_bound_1() { + assert_snapshot!( + infer(r#" +trait Trait {} +struct S(T); +impl Trait for S {} +fn foo>(t: T) {} +fn test() { + let s = S(unknown); + foo(s); +} +"#), + @r###" + [86; 87) 't': T + [92; 94) '{}': () + [105; 144) '{ ...(s); }': () + [115; 116) 's': S + [119; 120) 'S': S(T) -> S + [119; 129) 'S(unknown)': S + [121; 128) 'unknown': u32 + [135; 138) 'foo': fn foo>(T) -> () + [135; 141) 'foo(s)': () + [139; 140) 's': S + "### + ); +} + +#[test] +fn infer_from_bound_2() { + assert_snapshot!( + infer(r#" +trait Trait {} +struct S(T); +impl Trait for S {} +fn foo>(t: T) -> U {} +fn test() { + let s = S(unknown); + let x: u32 = foo(s); +} +"#), + @r###" + [87; 88) 't': T + [98; 100) '{}': () + [111; 163) '{ ...(s); }': () + [121; 122) 's': S + [125; 126) 'S': S(T) -> S + [125; 135) 'S(unknown)': S + [127; 134) 'unknown': u32 + [145; 146) 'x': u32 + [154; 157) 'foo': fn foo>(T) -> U + [154; 160) 'foo(s)': u32 + [158; 159) 's': S + "### + ); +} + +#[test] +fn infer_call_trait_method_on_generic_param_1() { + assert_snapshot!( + infer(r#" +trait Trait { + fn method(&self) -> u32; +} +fn test(t: T) { + t.method(); +} +"#), + @r###" + [30; 34) 'self': &Self + [64; 65) 't': T + [70; 89) '{ ...d(); }': () + [76; 77) 't': T + [76; 86) 't.method()': u32 + "### + ); +} + +#[test] +fn infer_call_trait_method_on_generic_param_2() { + assert_snapshot!( + infer(r#" +trait Trait { + fn method(&self) -> T; +} +fn test>(t: T) { + t.method(); +} +"#), + @r###" + [33; 37) 'self': &Self + [71; 72) 't': T + [77; 96) '{ ...d(); }': () + [83; 84) 't': T + [83; 93) 't.method()': [missing name] + "### + ); +} + +#[test] +fn infer_with_multiple_trait_impls() { + assert_snapshot!( + infer(r#" +trait Into { + fn into(self) -> T; +} +struct S; +impl Into for S {} +impl Into for S {} +fn test() { + let x: u32 = S.into(); + let y: u64 = S.into(); + let z = Into::::into(S); +} +"#), + @r###" + [29; 33) 'self': Self + [111; 202) '{ ...(S); }': () + [121; 122) 'x': u32 + [130; 131) 'S': S + [130; 138) 'S.into()': u32 + [148; 149) 'y': u64 + [157; 158) 'S': S + [157; 165) 'S.into()': u64 + [175; 176) 'z': u64 + [179; 196) 'Into::...::into': fn into(Self) -> T + [179; 199) 'Into::...nto(S)': u64 + [197; 198) 'S': S + "### + ); +} + +#[test] +fn infer_project_associated_type() { + // y, z, a don't yet work because of https://github.com/rust-lang/chalk/issues/234 + assert_snapshot!( + infer(r#" +trait Iterable { + type Item; +} +struct S; +impl Iterable for S { type Item = u32; } +fn test() { + let x: ::Item = 1; + let y: ::Item = no_matter; + let z: T::Item = no_matter; + let a: ::Item = no_matter; +} +"#), + @r###" + [108; 261) '{ ...ter; }': () + [118; 119) 'x': u32 + [145; 146) '1': u32 + [156; 157) 'y': {unknown} + [183; 192) 'no_matter': {unknown} + [202; 203) 'z': {unknown} + [215; 224) 'no_matter': {unknown} + [234; 235) 'a': {unknown} + [249; 258) 'no_matter': {unknown} + "### + ); +} + +#[test] +fn infer_return_associated_type() { + assert_snapshot!( + infer(r#" +trait Iterable { + type Item; +} +struct S; +impl Iterable for S { type Item = u32; } +fn foo1(t: T) -> T::Item {} +fn foo2(t: T) -> ::Item {} +fn foo3(t: T) -> ::Item {} +fn test() { + let x = foo1(S); + let y = foo2(S); + let z = foo3(S); +} +"#), + @r###" + [106; 107) 't': T + [123; 125) '{}': () + [147; 148) 't': T + [178; 180) '{}': () + [202; 203) 't': T + [221; 223) '{}': () + [234; 300) '{ ...(S); }': () + [244; 245) 'x': u32 + [248; 252) 'foo1': fn foo1(T) -> ::Item + [248; 255) 'foo1(S)': u32 + [253; 254) 'S': S + [265; 266) 'y': u32 + [269; 273) 'foo2': fn foo2(T) -> ::Item + [269; 276) 'foo2(S)': u32 + [274; 275) 'S': S + [286; 287) 'z': u32 + [290; 294) 'foo3': fn foo3(T) -> ::Item + [290; 297) 'foo3(S)': u32 + [295; 296) 'S': S + "### + ); +} + +#[test] +fn infer_associated_type_bound() { + assert_snapshot!( + infer(r#" +trait Iterable { + type Item; +} +fn test>() { + let y: T::Item = unknown; +} +"#), + @r###" + [67; 100) '{ ...own; }': () + [77; 78) 'y': {unknown} + [90; 97) 'unknown': {unknown} + "### + ); +} + +#[test] +fn infer_const_body() { + assert_snapshot!( + infer(r#" +const A: u32 = 1 + 1; +static B: u64 = { let x = 1; x }; +"#), + @r###" + [16; 17) '1': u32 + [16; 21) '1 + 1': u32 + [20; 21) '1': u32 + [39; 55) '{ let ...1; x }': u64 + [45; 46) 'x': u64 + [49; 50) '1': u64 + [52; 53) 'x': u64 + "### + ); +} + +#[test] +fn tuple_struct_fields() { + assert_snapshot!( + infer(r#" +struct S(i32, u64); +fn test() -> u64 { + let a = S(4, 6); + let b = a.0; + a.1 +} +"#), + @r###" + [38; 87) '{ ... a.1 }': u64 + [48; 49) 'a': S + [52; 53) 'S': S(i32, u64) -> S + [52; 59) 'S(4, 6)': S + [54; 55) '4': i32 + [57; 58) '6': u64 + [69; 70) 'b': i32 + [73; 74) 'a': S + [73; 76) 'a.0': i32 + [82; 83) 'a': S + [82; 85) 'a.1': u64 + "### + ); +} + +#[test] +fn tuple_struct_with_fn() { + assert_snapshot!( + infer(r#" +struct S(fn(u32) -> u64); +fn test() -> u64 { + let a = S(|i| 2*i); + let b = a.0(4); + a.0(2) +} +"#), + @r###" + [44; 102) '{ ...0(2) }': u64 + [54; 55) 'a': S + [58; 59) 'S': S(fn(u32) -> u64) -> S + [58; 68) 'S(|i| 2*i)': S + [60; 67) '|i| 2*i': |i32| -> i32 + [61; 62) 'i': i32 + [64; 65) '2': i32 + [64; 67) '2*i': i32 + [66; 67) 'i': i32 + [78; 79) 'b': u64 + [82; 83) 'a': S + [82; 85) 'a.0': fn(u32) -> u64 + [82; 88) 'a.0(4)': u64 + [86; 87) '4': u32 + [94; 95) 'a': S + [94; 97) 'a.0': fn(u32) -> u64 + [94; 100) 'a.0(2)': u64 + [98; 99) '2': u32 + "### + ); +} + +#[test] +fn indexing_arrays() { + assert_snapshot!( + infer("fn main() { &mut [9][2]; }"), + @r###" + [10; 26) '{ &mut...[2]; }': () + [12; 23) '&mut [9][2]': &mut {unknown} + [17; 20) '[9]': [i32;_] + [17; 23) '[9][2]': {unknown} + [18; 19) '9': i32 + [21; 22) '2': i32 + "### + ) +} + +#[test] +fn infer_macros_expanded() { + assert_snapshot!( + infer(r#" +struct Foo(Vec); + +macro_rules! foo { + ($($item:expr),*) => { + { + Foo(vec![$($item,)*]) + } + }; +} + +fn main() { + let x = foo!(1,2); +} +"#), + @r###" + ![0; 17) '{Foo(v...,2,])}': Foo + ![1; 4) 'Foo': Foo({unknown}) -> Foo + ![1; 16) 'Foo(vec![1,2,])': Foo + ![5; 15) 'vec![1,2,]': {unknown} + [156; 182) '{ ...,2); }': () + [166; 167) 'x': Foo + "### + ); +} + +#[test] +fn infer_legacy_textual_scoped_macros_expanded() { + assert_snapshot!( + infer(r#" +struct Foo(Vec); + +#[macro_use] +mod m { + macro_rules! foo { + ($($item:expr),*) => { + { + Foo(vec![$($item,)*]) + } + }; + } +} + +fn main() { + let x = foo!(1,2); + let y = crate::foo!(1,2); +} +"#), + @r###" + ![0; 17) '{Foo(v...,2,])}': Foo + ![1; 4) 'Foo': Foo({unknown}) -> Foo + ![1; 16) 'Foo(vec![1,2,])': Foo + ![5; 15) 'vec![1,2,]': {unknown} + [195; 251) '{ ...,2); }': () + [205; 206) 'x': Foo + [228; 229) 'y': {unknown} + [232; 248) 'crate:...!(1,2)': {unknown} + "### + ); +} + +#[test] +fn infer_path_qualified_macros_expanded() { + assert_snapshot!( + infer(r#" +#[macro_export] +macro_rules! foo { + () => { 42i32 } +} + +mod m { + pub use super::foo as bar; +} + +fn main() { + let x = crate::foo!(); + let y = m::bar!(); +} +"#), + @r###" + ![0; 5) '42i32': i32 + ![0; 5) '42i32': i32 + [111; 164) '{ ...!(); }': () + [121; 122) 'x': i32 + [148; 149) 'y': i32 + "### + ); +} + +#[test] +fn infer_type_value_macro_having_same_name() { + assert_snapshot!( + infer(r#" +#[macro_export] +macro_rules! foo { + () => { + mod foo { + pub use super::foo; + } + }; + ($x:tt) => { + $x + }; +} + +foo!(); + +fn foo() { + let foo = foo::foo!(42i32); +} +"#), + @r###" + ![0; 5) '42i32': i32 + [171; 206) '{ ...32); }': () + [181; 184) 'foo': i32 + "### + ); +} + +#[test] +fn processes_impls_generated_by_macros() { + let t = type_at( + r#" +//- /main.rs +macro_rules! m { + ($ident:ident) => (impl Trait for $ident {}) +} +trait Trait { fn foo(self) -> u128 {} } +struct S; +m!(S); +fn test() { S.foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn infer_macro_with_dollar_crate_is_correct_in_expr() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:foo +fn test() { + let x = (foo::foo!(1), foo::foo!(2)); + x<|>; +} + +//- /lib.rs crate:foo +#[macro_export] +macro_rules! foo { + (1) => { $crate::bar!() }; + (2) => { 1 + $crate::baz() }; +} + +#[macro_export] +macro_rules! bar { + () => { 42 } +} + +pub fn baz() -> usize { 31usize } +"#, + ); + assert_eq!("(i32, usize)", type_at_pos(&db, pos)); +} + +#[ignore] +#[test] +fn method_resolution_trait_before_autoref() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl S { fn foo(&self) -> i8 { 0 } } +impl Trait for S { fn foo(self) -> u128 { 0 } } +fn test() { S.foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[ignore] +#[test] +fn method_resolution_by_value_before_autoref() { + let t = type_at( + r#" +//- /main.rs +trait Clone { fn clone(&self) -> Self; } +struct S; +impl Clone for S {} +impl Clone for &S {} +fn test() { (S.clone(), (&S).clone(), (&&S).clone())<|>; } +"#, + ); + assert_eq!(t, "(S, S, &S)"); +} + +#[test] +fn method_resolution_trait_before_autoderef() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl S { fn foo(self) -> i8 { 0 } } +impl Trait for &S { fn foo(self) -> u128 { 0 } } +fn test() { (&S).foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn method_resolution_impl_before_trait() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl S { fn foo(self) -> i8 { 0 } } +impl Trait for S { fn foo(self) -> u128 { 0 } } +fn test() { S.foo()<|>; } +"#, + ); + assert_eq!(t, "i8"); +} + +#[test] +fn method_resolution_trait_autoderef() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for S { fn foo(self) -> u128 { 0 } } +fn test() { (&S).foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn method_resolution_trait_from_prelude() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:other_crate +struct S; +impl Clone for S {} + +fn test() { + S.clone()<|>; +} + +//- /lib.rs crate:other_crate +#[prelude_import] use foo::*; + +mod foo { + trait Clone { + fn clone(&self) -> Self; + } +} +"#, + ); + assert_eq!("S", type_at_pos(&db, pos)); +} + +#[test] +fn method_resolution_where_clause_for_unknown_trait() { + // The blanket impl shouldn't apply because we can't even resolve UnknownTrait + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for T where T: UnknownTrait {} +fn test() { (&S).foo()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn method_resolution_where_clause_not_met() { + // The blanket impl shouldn't apply because we can't prove S: Clone + let t = type_at( + r#" +//- /main.rs +trait Clone {} +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for T where T: Clone {} +fn test() { (&S).foo()<|>; } +"#, + ); + // This is also to make sure that we don't resolve to the foo method just + // because that's the only method named foo we can find, which would make + // the below tests not work + assert_eq!(t, "{unknown}"); +} + +#[test] +fn method_resolution_where_clause_inline_not_met() { + // The blanket impl shouldn't apply because we can't prove S: Clone + let t = type_at( + r#" +//- /main.rs +trait Clone {} +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for T {} +fn test() { (&S).foo()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn method_resolution_where_clause_1() { + let t = type_at( + r#" +//- /main.rs +trait Clone {} +trait Trait { fn foo(self) -> u128; } +struct S; +impl Clone for S {} +impl Trait for T where T: Clone {} +fn test() { S.foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn method_resolution_where_clause_2() { + let t = type_at( + r#" +//- /main.rs +trait Into { fn into(self) -> T; } +trait From { fn from(other: T) -> Self; } +struct S1; +struct S2; +impl From for S1 {} +impl Into for T where U: From {} +fn test() { S2.into()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn method_resolution_where_clause_inline() { + let t = type_at( + r#" +//- /main.rs +trait Into { fn into(self) -> T; } +trait From { fn from(other: T) -> Self; } +struct S1; +struct S2; +impl From for S1 {} +impl> Into for T {} +fn test() { S2.into()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn method_resolution_encountering_fn_type() { + type_at( + r#" +//- /main.rs +fn foo() {} +trait FnOnce { fn call(self); } +fn test() { foo.call()<|>; } +"#, + ); +} + +#[test] +fn method_resolution_slow() { + // this can get quite slow if we set the solver size limit too high + let t = type_at( + r#" +//- /main.rs +trait SendX {} + +struct S1; impl SendX for S1 {} +struct S2; impl SendX for S2 {} +struct U1; + +trait Trait { fn method(self); } + +struct X1 {} +impl SendX for X1 where A: SendX, B: SendX {} + +struct S {} + +trait FnX {} + +impl Trait for S where C: FnX, B: SendX {} + +fn test() { (S {}).method()<|>; } +"#, + ); + assert_eq!(t, "()"); +} + +#[test] +fn shadowing_primitive() { + let t = type_at( + r#" +//- /main.rs +struct i32; +struct Foo; + +impl i32 { fn foo(&self) -> Foo { Foo } } + +fn main() { + let x: i32 = i32; + x.foo()<|>; +}"#, + ); + assert_eq!(t, "Foo"); +} + +#[test] +fn deref_trait() { + let t = type_at( + r#" +//- /main.rs +#[lang = "deref"] +trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct Arc; +impl Deref for Arc { + type Target = T; +} + +struct S; +impl S { + fn foo(&self) -> u128 {} +} + +fn test(s: Arc) { + (*s, s.foo())<|>; +} +"#, + ); + assert_eq!(t, "(S, u128)"); +} + +#[test] +fn deref_trait_with_inference_var() { + let t = type_at( + r#" +//- /main.rs +#[lang = "deref"] +trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct Arc; +fn new_arc() -> Arc {} +impl Deref for Arc { + type Target = T; +} + +struct S; +fn foo(a: Arc) {} + +fn test() { + let a = new_arc(); + let b = (*a)<|>; + foo(a); +} +"#, + ); + assert_eq!(t, "S"); +} + +#[test] +fn deref_trait_infinite_recursion() { + let t = type_at( + r#" +//- /main.rs +#[lang = "deref"] +trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct S; + +impl Deref for S { + type Target = S; +} + +fn test(s: S) { + s.foo()<|>; +} +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn deref_trait_with_question_mark_size() { + let t = type_at( + r#" +//- /main.rs +#[lang = "deref"] +trait Deref { + type Target; + fn deref(&self) -> &Self::Target; +} + +struct Arc; +impl Deref for Arc { + type Target = T; +} + +struct S; +impl S { + fn foo(&self) -> u128 {} +} + +fn test(s: Arc) { + (*s, s.foo())<|>; +} +"#, + ); + assert_eq!(t, "(S, u128)"); +} + +#[test] +fn obligation_from_function_clause() { + let t = type_at( + r#" +//- /main.rs +struct S; + +trait Trait {} +impl Trait for S {} + +fn foo, U>(t: T) -> U {} + +fn test(s: S) { + foo(s)<|>; +} +"#, + ); + assert_eq!(t, "u32"); +} + +#[test] +fn obligation_from_method_clause() { + let t = type_at( + r#" +//- /main.rs +struct S; + +trait Trait {} +impl Trait for S {} + +struct O; +impl O { + fn foo, U>(&self, t: T) -> U {} +} + +fn test() { + O.foo(S)<|>; +} +"#, + ); + assert_eq!(t, "isize"); +} + +#[test] +fn obligation_from_self_method_clause() { + let t = type_at( + r#" +//- /main.rs +struct S; + +trait Trait {} +impl Trait for S {} + +impl S { + fn foo(&self) -> U where Self: Trait {} +} + +fn test() { + S.foo()<|>; +} +"#, + ); + assert_eq!(t, "i64"); +} + +#[test] +fn obligation_from_impl_clause() { + let t = type_at( + r#" +//- /main.rs +struct S; + +trait Trait {} +impl Trait<&str> for S {} + +struct O; +impl> O { + fn foo(&self) -> U {} +} + +fn test(o: O) { + o.foo()<|>; +} +"#, + ); + assert_eq!(t, "&str"); +} + +#[test] +fn generic_param_env_1() { + let t = type_at( + r#" +//- /main.rs +trait Clone {} +trait Trait { fn foo(self) -> u128; } +struct S; +impl Clone for S {} +impl Trait for T where T: Clone {} +fn test(t: T) { t.foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn generic_param_env_1_not_met() { + let t = type_at( + r#" +//- /main.rs +trait Clone {} +trait Trait { fn foo(self) -> u128; } +struct S; +impl Clone for S {} +impl Trait for T where T: Clone {} +fn test(t: T) { t.foo()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn generic_param_env_2() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for S {} +fn test(t: T) { t.foo()<|>; } +"#, + ); + assert_eq!(t, "u128"); +} + +#[test] +fn generic_param_env_2_not_met() { + let t = type_at( + r#" +//- /main.rs +trait Trait { fn foo(self) -> u128; } +struct S; +impl Trait for S {} +fn test(t: T) { t.foo()<|>; } +"#, + ); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn generic_param_env_deref() { + let t = type_at( + r#" +//- /main.rs +#[lang = "deref"] +trait Deref { + type Target; +} +trait Trait {} +impl Deref for T where T: Trait { + type Target = i128; +} +fn test(t: T) { (*t)<|>; } +"#, + ); + assert_eq!(t, "i128"); +} + +#[test] +fn associated_type_placeholder() { + let t = type_at( + r#" +//- /main.rs +pub trait ApplyL { + type Out; +} + +pub struct RefMutL; + +impl ApplyL for RefMutL { + type Out = ::Out; +} + +fn test() { + let y: as ApplyL>::Out = no_matter; + y<|>; +} +"#, + ); + // inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types]. + // FIXME: fix type parameter names going missing when going through Chalk + assert_eq!(t, "ApplyL::Out<[missing name]>"); +} + +#[test] +fn associated_type_placeholder_2() { + let t = type_at( + r#" +//- /main.rs +pub trait ApplyL { + type Out; +} +fn foo(t: T) -> ::Out; + +fn test(t: T) { + let y = foo(t); + y<|>; +} +"#, + ); + // FIXME here Chalk doesn't normalize the type to a placeholder. I think we + // need to add a rule like Normalize(::Out -> ApplyL::Out) + // to the trait env ourselves here; probably Chalk can't do this by itself. + // assert_eq!(t, "ApplyL::Out<[missing name]>"); + assert_eq!(t, "{unknown}"); +} + +#[test] +fn impl_trait() { + assert_snapshot!( + infer(r#" +trait Trait { + fn foo(&self) -> T; + fn foo2(&self) -> i64; +} +fn bar() -> impl Trait {} + +fn test(x: impl Trait, y: &impl Trait) { + x; + y; + let z = bar(); + x.foo(); + y.foo(); + z.foo(); + x.foo2(); + y.foo2(); + z.foo2(); +} +"#), + @r###" + [30; 34) 'self': &Self + [55; 59) 'self': &Self + [99; 101) '{}': () + [111; 112) 'x': impl Trait + [131; 132) 'y': &impl Trait + [152; 269) '{ ...2(); }': () + [158; 159) 'x': impl Trait + [165; 166) 'y': &impl Trait + [176; 177) 'z': impl Trait + [180; 183) 'bar': fn bar() -> impl Trait + [180; 185) 'bar()': impl Trait + [191; 192) 'x': impl Trait + [191; 198) 'x.foo()': u64 + [204; 205) 'y': &impl Trait + [204; 211) 'y.foo()': u64 + [217; 218) 'z': impl Trait + [217; 224) 'z.foo()': u64 + [230; 231) 'x': impl Trait + [230; 238) 'x.foo2()': i64 + [244; 245) 'y': &impl Trait + [244; 252) 'y.foo2()': i64 + [258; 259) 'z': impl Trait + [258; 266) 'z.foo2()': i64 + "### + ); +} + +#[test] +fn dyn_trait() { + assert_snapshot!( + infer(r#" +trait Trait { + fn foo(&self) -> T; + fn foo2(&self) -> i64; +} +fn bar() -> dyn Trait {} + +fn test(x: dyn Trait, y: &dyn Trait) { + x; + y; + let z = bar(); + x.foo(); + y.foo(); + z.foo(); + x.foo2(); + y.foo2(); + z.foo2(); +} +"#), + @r###" + [30; 34) 'self': &Self + [55; 59) 'self': &Self + [98; 100) '{}': () + [110; 111) 'x': dyn Trait + [129; 130) 'y': &dyn Trait + [149; 266) '{ ...2(); }': () + [155; 156) 'x': dyn Trait + [162; 163) 'y': &dyn Trait + [173; 174) 'z': dyn Trait + [177; 180) 'bar': fn bar() -> dyn Trait + [177; 182) 'bar()': dyn Trait + [188; 189) 'x': dyn Trait + [188; 195) 'x.foo()': u64 + [201; 202) 'y': &dyn Trait + [201; 208) 'y.foo()': u64 + [214; 215) 'z': dyn Trait + [214; 221) 'z.foo()': u64 + [227; 228) 'x': dyn Trait + [227; 235) 'x.foo2()': i64 + [241; 242) 'y': &dyn Trait + [241; 249) 'y.foo2()': i64 + [255; 256) 'z': dyn Trait + [255; 263) 'z.foo2()': i64 + "### + ); +} + +#[test] +fn dyn_trait_bare() { + assert_snapshot!( + infer(r#" +trait Trait { + fn foo(&self) -> u64; +} +fn bar() -> Trait {} + +fn test(x: Trait, y: &Trait) -> u64 { + x; + y; + let z = bar(); + x.foo(); + y.foo(); + z.foo(); +} +"#), + @r###" + [27; 31) 'self': &Self + [61; 63) '{}': () + [73; 74) 'x': dyn Trait + [83; 84) 'y': &dyn Trait + [101; 176) '{ ...o(); }': () + [107; 108) 'x': dyn Trait + [114; 115) 'y': &dyn Trait + [125; 126) 'z': dyn Trait + [129; 132) 'bar': fn bar() -> dyn Trait + [129; 134) 'bar()': dyn Trait + [140; 141) 'x': dyn Trait + [140; 147) 'x.foo()': u64 + [153; 154) 'y': &dyn Trait + [153; 160) 'y.foo()': u64 + [166; 167) 'z': dyn Trait + [166; 173) 'z.foo()': u64 + "### + ); +} + +#[test] +fn weird_bounds() { + assert_snapshot!( + infer(r#" +trait Trait {} +fn test() { + let a: impl Trait + 'lifetime = foo; + let b: impl 'lifetime = foo; + let b: impl (Trait) = foo; + let b: impl ('lifetime) = foo; + let d: impl ?Sized = foo; + let e: impl Trait + ?Sized = foo; +} +"#), + @r###" + [26; 237) '{ ...foo; }': () + [36; 37) 'a': impl Trait + {error} + [64; 67) 'foo': impl Trait + {error} + [77; 78) 'b': impl {error} + [97; 100) 'foo': impl {error} + [110; 111) 'b': impl Trait + [128; 131) 'foo': impl Trait + [141; 142) 'b': impl {error} + [163; 166) 'foo': impl {error} + [176; 177) 'd': impl {error} + [193; 196) 'foo': impl {error} + [206; 207) 'e': impl Trait + {error} + [231; 234) 'foo': impl Trait + {error} + "### + ); +} + +#[test] +fn assoc_type_bindings() { + assert_snapshot!( + infer(r#" +trait Trait { + type Type; +} + +fn get(t: T) -> ::Type {} +fn get2>(t: T) -> U {} +fn set>(t: T) -> T {t} + +struct S; +impl Trait for S { type Type = T; } + +fn test>(x: T, y: impl Trait) { + get(x); + get2(x); + get(y); + get2(y); + get(set(S)); + get2(set(S)); + get2(S::); +} +"#), + @r###" + [50; 51) 't': T + [78; 80) '{}': () + [112; 113) 't': T + [123; 125) '{}': () + [155; 156) 't': T + [166; 169) '{t}': T + [167; 168) 't': T + [257; 258) 'x': T + [263; 264) 'y': impl Trait + [290; 398) '{ ...r>); }': () + [296; 299) 'get': fn get(T) -> ::Type + [296; 302) 'get(x)': {unknown} + [300; 301) 'x': T + [308; 312) 'get2': fn get2<{unknown}, T>(T) -> U + [308; 315) 'get2(x)': {unknown} + [313; 314) 'x': T + [321; 324) 'get': fn get>(T) -> ::Type + [321; 327) 'get(y)': {unknown} + [325; 326) 'y': impl Trait + [333; 337) 'get2': fn get2<{unknown}, impl Trait>(T) -> U + [333; 340) 'get2(y)': {unknown} + [338; 339) 'y': impl Trait + [346; 349) 'get': fn get>(T) -> ::Type + [346; 357) 'get(set(S))': u64 + [350; 353) 'set': fn set>(T) -> T + [350; 356) 'set(S)': S + [354; 355) 'S': S + [363; 367) 'get2': fn get2>(T) -> U + [363; 375) 'get2(set(S))': u64 + [368; 371) 'set': fn set>(T) -> T + [368; 374) 'set(S)': S + [372; 373) 'S': S + [381; 385) 'get2': fn get2>(T) -> U + [381; 395) 'get2(S::)': str + [386; 394) 'S::': S + "### + ); +} + +#[test] +fn impl_trait_assoc_binding_projection_bug() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std +pub trait Language { + type Kind; +} +pub enum RustLanguage {} +impl Language for RustLanguage { + type Kind = SyntaxKind; +} +struct SyntaxNode {} +fn foo() -> impl Iterator> {} + +trait Clone { + fn clone(&self) -> Self; +} + +fn api_walkthrough() { + for node in foo() { + node.clone()<|>; + } +} + +//- /std.rs crate:std +#[prelude_import] use iter::*; +mod iter { + trait IntoIterator { + type Item; + } + trait Iterator { + type Item; + } + impl IntoIterator for T { + type Item = ::Item; + } +} +"#, + ); + assert_eq!("{unknown}", type_at_pos(&db, pos)); +} + +#[test] +fn projection_eq_within_chalk() { + // std::env::set_var("CHALK_DEBUG", "1"); + assert_snapshot!( + infer(r#" +trait Trait1 { + type Type; +} +trait Trait2 { + fn foo(self) -> T; +} +impl Trait2 for U where U: Trait1 {} + +fn test>(x: T) { + x.foo(); +} +"#), + @r###" + [62; 66) 'self': Self + [164; 165) 'x': T + [170; 186) '{ ...o(); }': () + [176; 177) 'x': T + [176; 183) 'x.foo()': {unknown} + "### + ); +} + +#[test] +fn where_clause_trait_in_scope_for_method_resolution() { + let t = type_at( + r#" +//- /main.rs +mod foo { + trait Trait { + fn foo(&self) -> u32 {} + } +} + +fn test(x: T) { + x.foo()<|>; +} +"#, + ); + assert_eq!(t, "u32"); +} + +#[test] +fn super_trait_method_resolution() { + assert_snapshot!( + infer(r#" +mod foo { + trait SuperTrait { + fn foo(&self) -> u32 {} + } +} +trait Trait1: foo::SuperTrait {} +trait Trait2 where Self: foo::SuperTrait {} + +fn test(x: T, y: U) { + x.foo(); + y.foo(); +} +"#), + @r###" + [50; 54) 'self': &Self + [63; 65) '{}': () + [182; 183) 'x': T + [188; 189) 'y': U + [194; 223) '{ ...o(); }': () + [200; 201) 'x': T + [200; 207) 'x.foo()': u32 + [213; 214) 'y': U + [213; 220) 'y.foo()': u32 + "### + ); +} + +#[test] +fn super_trait_cycle() { + // This just needs to not crash + assert_snapshot!( + infer(r#" +trait A: B {} +trait B: A {} + +fn test(x: T) { + x.foo(); +} +"#), + @r###" + [44; 45) 'x': T + [50; 66) '{ ...o(); }': () + [56; 57) 'x': T + [56; 63) 'x.foo()': {unknown} + "### + ); +} + +#[test] +fn super_trait_assoc_type_bounds() { + assert_snapshot!( + infer(r#" +trait SuperTrait { type Type; } +trait Trait where Self: SuperTrait {} + +fn get2>(t: T) -> U {} +fn set>(t: T) -> T {t} + +struct S; +impl SuperTrait for S { type Type = T; } +impl Trait for S {} + +fn test() { + get2(set(S)); +} +"#), + @r###" + [103; 104) 't': T + [114; 116) '{}': () + [146; 147) 't': T + [157; 160) '{t}': T + [158; 159) 't': T + [259; 280) '{ ...S)); }': () + [265; 269) 'get2': fn get2>(T) -> U + [265; 277) 'get2(set(S))': u64 + [270; 273) 'set': fn set>(T) -> T + [270; 276) 'set(S)': S + [274; 275) 'S': S + "### + ); +} + +#[test] +fn fn_trait() { + assert_snapshot!( + infer(r#" +trait FnOnce { + type Output; + + fn call_once(self, args: Args) -> >::Output; +} + +fn test u128>(f: F) { + f.call_once((1, 2)); +} +"#), + @r###" + [57; 61) 'self': Self + [63; 67) 'args': Args + [150; 151) 'f': F + [156; 184) '{ ...2)); }': () + [162; 163) 'f': F + [162; 181) 'f.call...1, 2))': {unknown} + [174; 180) '(1, 2)': (u32, u64) + [175; 176) '1': u32 + [178; 179) '2': u64 + "### + ); +} + +#[test] +fn closure_1() { + assert_snapshot!( + infer(r#" +#[lang = "fn_once"] +trait FnOnce { + type Output; +} + +enum Option { Some(T), None } +impl Option { + fn map U>(self, f: F) -> Option {} +} + +fn test() { + let x = Option::Some(1u32); + x.map(|v| v + 1); + x.map(|_v| 1u64); + let y: Option = x.map(|_v| 1); +} +"#), + @r###" + [148; 152) 'self': Option + [154; 155) 'f': F + [173; 175) '{}': () + [189; 308) '{ ... 1); }': () + [199; 200) 'x': Option + [203; 215) 'Option::Some': Some(T) -> Option + [203; 221) 'Option...(1u32)': Option + [216; 220) '1u32': u32 + [227; 228) 'x': Option + [227; 243) 'x.map(...v + 1)': Option + [233; 242) '|v| v + 1': |u32| -> u32 + [234; 235) 'v': u32 + [237; 238) 'v': u32 + [237; 242) 'v + 1': u32 + [241; 242) '1': u32 + [249; 250) 'x': Option + [249; 265) 'x.map(... 1u64)': Option + [255; 264) '|_v| 1u64': |u32| -> u64 + [256; 258) '_v': u32 + [260; 264) '1u64': u64 + [275; 276) 'y': Option + [292; 293) 'x': Option + [292; 305) 'x.map(|_v| 1)': Option + [298; 304) '|_v| 1': |u32| -> i64 + [299; 301) '_v': u32 + [303; 304) '1': i64 + "### + ); +} + +#[test] +fn closure_2() { + assert_snapshot!( + infer(r#" +trait FnOnce { + type Output; +} + +fn test u64>(f: F) { + f(1); + let g = |v| v + 1; + g(1u64); + let h = |v| 1u128 + v; +} +"#), + @r###" + [73; 74) 'f': F + [79; 155) '{ ...+ v; }': () + [85; 86) 'f': F + [85; 89) 'f(1)': {unknown} + [87; 88) '1': i32 + [99; 100) 'g': |u64| -> i32 + [103; 112) '|v| v + 1': |u64| -> i32 + [104; 105) 'v': u64 + [107; 108) 'v': u64 + [107; 112) 'v + 1': i32 + [111; 112) '1': i32 + [118; 119) 'g': |u64| -> i32 + [118; 125) 'g(1u64)': i32 + [120; 124) '1u64': u64 + [135; 136) 'h': |u128| -> u128 + [139; 152) '|v| 1u128 + v': |u128| -> u128 + [140; 141) 'v': u128 + [143; 148) '1u128': u128 + [143; 152) '1u128 + v': u128 + [151; 152) 'v': u128 + "### + ); +} + +#[test] +fn closure_as_argument_inference_order() { + assert_snapshot!( + infer(r#" +#[lang = "fn_once"] +trait FnOnce { + type Output; +} + +fn foo1 U>(x: T, f: F) -> U {} +fn foo2 U>(f: F, x: T) -> U {} + +struct S; +impl S { + fn method(self) -> u64; + + fn foo1 U>(self, x: T, f: F) -> U {} + fn foo2 U>(self, f: F, x: T) -> U {} +} + +fn test() { + let x1 = foo1(S, |s| s.method()); + let x2 = foo2(|s| s.method(), S); + let x3 = S.foo1(S, |s| s.method()); + let x4 = S.foo2(|s| s.method(), S); +} +"#), + @r###" + [95; 96) 'x': T + [101; 102) 'f': F + [112; 114) '{}': () + [148; 149) 'f': F + [154; 155) 'x': T + [165; 167) '{}': () + [202; 206) 'self': S + [254; 258) 'self': S + [260; 261) 'x': T + [266; 267) 'f': F + [277; 279) '{}': () + [317; 321) 'self': S + [323; 324) 'f': F + [329; 330) 'x': T + [340; 342) '{}': () + [356; 515) '{ ... S); }': () + [366; 368) 'x1': u64 + [371; 375) 'foo1': fn foo1 u64>(T, F) -> U + [371; 394) 'foo1(S...hod())': u64 + [376; 377) 'S': S + [379; 393) '|s| s.method()': |S| -> u64 + [380; 381) 's': S + [383; 384) 's': S + [383; 393) 's.method()': u64 + [404; 406) 'x2': u64 + [409; 413) 'foo2': fn foo2 u64>(F, T) -> U + [409; 432) 'foo2(|...(), S)': u64 + [414; 428) '|s| s.method()': |S| -> u64 + [415; 416) 's': S + [418; 419) 's': S + [418; 428) 's.method()': u64 + [430; 431) 'S': S + [442; 444) 'x3': u64 + [447; 448) 'S': S + [447; 472) 'S.foo1...hod())': u64 + [454; 455) 'S': S + [457; 471) '|s| s.method()': |S| -> u64 + [458; 459) 's': S + [461; 462) 's': S + [461; 471) 's.method()': u64 + [482; 484) 'x4': u64 + [487; 488) 'S': S + [487; 512) 'S.foo2...(), S)': u64 + [494; 508) '|s| s.method()': |S| -> u64 + [495; 496) 's': S + [498; 499) 's': S + [498; 508) 's.method()': u64 + [510; 511) 'S': S + "### + ); +} + +#[test] +fn unselected_projection_in_trait_env_1() { + let t = type_at( + r#" +//- /main.rs +trait Trait { + type Item; +} + +trait Trait2 { + fn foo(&self) -> u32; +} + +fn test() where T::Item: Trait2 { + let x: T::Item = no_matter; + x.foo()<|>; +} +"#, + ); + assert_eq!(t, "u32"); +} + +#[test] +fn unselected_projection_in_trait_env_2() { + let t = type_at( + r#" +//- /main.rs +trait Trait { + type Item; +} + +trait Trait2 { + fn foo(&self) -> u32; +} + +fn test() where T::Item: Trait2, T: Trait, U: Trait<()> { + let x: T::Item = no_matter; + x.foo()<|>; +} +"#, + ); + assert_eq!(t, "u32"); +} + +#[test] +// FIXME this is currently a Salsa panic; it would be nicer if it just returned +// in Unknown, and we should be able to do that once Salsa allows us to handle +// the cycle. But at least it doesn't overflow for now. +#[should_panic] +fn unselected_projection_in_trait_env_cycle_1() { + let t = type_at( + r#" +//- /main.rs +trait Trait { + type Item; +} + +trait Trait2 {} + +fn test() where T: Trait2 { + let x: T::Item = no_matter<|>; +} +"#, + ); + // this is a legitimate cycle + assert_eq!(t, "{unknown}"); +} + +#[test] +// FIXME this is currently a Salsa panic; it would be nicer if it just returned +// in Unknown, and we should be able to do that once Salsa allows us to handle +// the cycle. But at least it doesn't overflow for now. +#[should_panic] +fn unselected_projection_in_trait_env_cycle_2() { + let t = type_at( + r#" +//- /main.rs +trait Trait { + type Item; +} + +fn test() where T: Trait, U: Trait { + let x: T::Item = no_matter<|>; +} +"#, + ); + // this is a legitimate cycle + assert_eq!(t, "{unknown}"); +} + +fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { + let file = db.parse(pos.file_id).ok().unwrap(); + let expr = algo::find_node_at_offset::(file.syntax(), pos.offset).unwrap(); + + let module = db.module_for_file(pos.file_id); + let crate_def_map = db.crate_def_map(module.krate); + for decl in crate_def_map[module.module_id].scope.declarations() { + if let ModuleDefId::FunctionId(func) = decl { + let (_body, source_map) = db.body_with_source_map(func.into()); + if let Some(expr_id) = source_map.node_expr(Source::new(pos.file_id.into(), &expr)) { + let infer = db.infer(func.into()); + let ty = &infer[expr_id]; + return ty.display(db).to_string(); + } + } + } + panic!("Can't find expression") +} + +fn type_at(content: &str) -> String { + let (db, file_pos) = TestDB::with_position(content); + type_at_pos(&db, file_pos) +} + +fn infer(content: &str) -> String { + let (db, file_id) = TestDB::with_single_file(content); + + let mut acc = String::new(); + + let mut infer_def = |inference_result: Arc, + body_source_map: Arc| { + let mut types = Vec::new(); + + for (pat, ty) in inference_result.type_of_pat.iter() { + let syntax_ptr = match body_source_map.pat_syntax(pat) { + Some(sp) => { + sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr())) + } + None => continue, + }; + types.push((syntax_ptr, ty)); + } + + for (expr, ty) in inference_result.type_of_expr.iter() { + let syntax_ptr = match body_source_map.expr_syntax(expr) { + Some(sp) => { + sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr())) + } + None => continue, + }; + types.push((syntax_ptr, ty)); + } + + // sort ranges for consistency + types.sort_by_key(|(src_ptr, _)| { + (src_ptr.value.range().start(), src_ptr.value.range().end()) + }); + for (src_ptr, ty) in &types { + let node = src_ptr.value.to_node(&src_ptr.file_syntax(&db)); + + let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) { + (self_param.self_kw_token().text_range(), "self".to_string()) + } else { + (src_ptr.value.range(), node.text().to_string().replace("\n", " ")) + }; + let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; + write!( + acc, + "{}{} '{}': {}\n", + macro_prefix, + range, + ellipsize(text, 15), + ty.display(&db) + ) + .unwrap(); + } + }; + + let module = db.module_for_file(file_id); + let crate_def_map = db.crate_def_map(module.krate); + + let mut defs: Vec = Vec::new(); + visit_module(&db, &crate_def_map, module.module_id, &mut |it| defs.push(it)); + defs.sort_by_key(|def| match def { + DefWithBodyId::FunctionId(it) => { + it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start() + } + DefWithBodyId::ConstId(it) => { + it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start() + } + DefWithBodyId::StaticId(it) => { + it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start() + } + }); + for def in defs { + let (_body, source_map) = db.body_with_source_map(def); + let infer = db.infer(def); + infer_def(infer, source_map); + } + + acc.truncate(acc.trim_end().len()); + acc +} + +fn visit_module( + db: &TestDB, + crate_def_map: &CrateDefMap, + module_id: LocalModuleId, + cb: &mut dyn FnMut(DefWithBodyId), +) { + for decl in crate_def_map[module_id].scope.declarations() { + match decl { + ModuleDefId::FunctionId(it) => cb(it.into()), + ModuleDefId::ConstId(it) => cb(it.into()), + ModuleDefId::StaticId(it) => cb(it.into()), + ModuleDefId::TraitId(it) => { + let trait_data = db.trait_data(it); + for &(_, item) in trait_data.items.iter() { + match item { + AssocItemId::FunctionId(it) => cb(it.into()), + AssocItemId::ConstId(it) => cb(it.into()), + AssocItemId::TypeAliasId(_) => (), + } + } + } + ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.module_id, cb), + _ => (), + } + } + for &impl_id in crate_def_map[module_id].impls.iter() { + let impl_data = db.impl_data(impl_id); + for &item in impl_data.items.iter() { + match item { + AssocItemId::FunctionId(it) => cb(it.into()), + AssocItemId::ConstId(it) => cb(it.into()), + AssocItemId::TypeAliasId(_) => (), + } + } + } +} + +fn ellipsize(mut text: String, max_len: usize) -> String { + if text.len() <= max_len { + return text; + } + let ellipsis = "..."; + let e_len = ellipsis.len(); + let mut prefix_len = (max_len - e_len) / 2; + while !text.is_char_boundary(prefix_len) { + prefix_len += 1; + } + let mut suffix_len = max_len - e_len - prefix_len; + while !text.is_char_boundary(text.len() - suffix_len) { + suffix_len += 1; + } + text.replace_range(prefix_len..text.len() - suffix_len, ellipsis); + text +} + +#[test] +fn typing_whitespace_inside_a_function_should_not_invalidate_types() { + let (mut db, pos) = TestDB::with_position( + " + //- /lib.rs + fn foo() -> i32 { + <|>1 + 1 + } + ", + ); + { + let events = db.log_executed(|| { + let module = db.module_for_file(pos.file_id); + let crate_def_map = db.crate_def_map(module.krate); + visit_module(&db, &crate_def_map, module.module_id, &mut |def| { + db.infer(def); + }); + }); + assert!(format!("{:?}", events).contains("infer")) + } + + let new_text = " + fn foo() -> i32 { + 1 + + + 1 + } + " + .to_string(); + + db.query_mut(ra_db::FileTextQuery).set(pos.file_id, Arc::new(new_text)); + + { + let events = db.log_executed(|| { + let module = db.module_for_file(pos.file_id); + let crate_def_map = db.crate_def_map(module.krate); + visit_module(&db, &crate_def_map, module.module_id, &mut |def| { + db.infer(def); + }); + }); + assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events) + } +} + +#[test] +fn no_such_field_diagnostics() { + let diagnostics = TestDB::with_files( + r" + //- /lib.rs + struct S { foo: i32, bar: () } + impl S { + fn new() -> S { + S { + foo: 92, + baz: 62, + } + } + } + ", + ) + .diagnostics(); + + assert_snapshot!(diagnostics, @r###" + "baz: 62": no such field + "{\n foo: 92,\n baz: 62,\n }": Missing structure fields: + - bar + "### + ); +} + +#[test] +fn infer_builtin_macros_line() { + assert_snapshot!( + infer(r#" +#[rustc_builtin_macro] +macro_rules! line {() => {}} + +fn main() { + let x = line!(); +} +"#), + @r###" + ![0; 1) '6': i32 + [64; 88) '{ ...!(); }': () + [74; 75) 'x': i32 + "### + ); +} + +#[test] +fn infer_builtin_macros_file() { + assert_snapshot!( + infer(r#" +#[rustc_builtin_macro] +macro_rules! file {() => {}} + +fn main() { + let x = file!(); +} +"#), + @r###" + ![0; 2) '""': &str + [64; 88) '{ ...!(); }': () + [74; 75) 'x': &str + "### + ); +} + +#[test] +fn infer_builtin_macros_column() { + assert_snapshot!( + infer(r#" +#[rustc_builtin_macro] +macro_rules! column {() => {}} + +fn main() { + let x = column!(); +} +"#), + @r###" + ![0; 2) '13': i32 + [66; 92) '{ ...!(); }': () + [76; 77) 'x': i32 + "### + ); +} diff --git a/crates/ra_hir_ty/src/tests/coercion.rs b/crates/ra_hir_ty/src/tests/coercion.rs new file mode 100644 index 000000000..1530fcc63 --- /dev/null +++ b/crates/ra_hir_ty/src/tests/coercion.rs @@ -0,0 +1,369 @@ +use insta::assert_snapshot; +use test_utils::covers; + +// Infer with some common definitions and impls. +fn infer(source: &str) -> String { + let defs = r#" + #[lang = "sized"] + pub trait Sized {} + #[lang = "unsize"] + pub trait Unsize {} + #[lang = "coerce_unsized"] + pub trait CoerceUnsized {} + + impl<'a, 'b: 'a, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized<&'a U> for &'b T {} + impl, U: ?Sized> CoerceUnsized<*mut U> for *mut T {} + "#; + + // Append to the end to keep positions unchanged. + super::infer(&format!("{}{}", source, defs)) +} + +#[test] +fn infer_block_expr_type_mismatch() { + assert_snapshot!( + infer(r#" +fn test() { + let a: i32 = { 1i64 }; +} +"#), + @r###" + [11; 41) '{ ...4 }; }': () + [21; 22) 'a': i32 + [30; 38) '{ 1i64 }': i64 + [32; 36) '1i64': i64 + "###); +} + +#[test] +fn coerce_places() { + assert_snapshot!( + infer(r#" +struct S { a: T } + +fn f(_: &[T]) -> T { loop {} } +fn g(_: S<&[T]>) -> T { loop {} } + +fn gen() -> *mut [T; 2] { loop {} } +fn test1() -> *mut [U] { + gen() +} + +fn test2() { + let arr: &[u8; 1] = &[1]; + + let a: &[_] = arr; + let b = f(arr); + let c: &[_] = { arr }; + let d = g(S { a: arr }); + let e: [&[_]; 1] = [arr]; + let f: [&[_]; 2] = [arr; 2]; + let g: (&[_], &[_]) = (arr, arr); +} +"#), + @r###" + [31; 32) '_': &[T] + [45; 56) '{ loop {} }': T + [47; 54) 'loop {}': ! + [52; 54) '{}': () + [65; 66) '_': S<&[T]> + [82; 93) '{ loop {} }': T + [84; 91) 'loop {}': ! + [89; 91) '{}': () + [122; 133) '{ loop {} }': *mut [T;_] + [124; 131) 'loop {}': ! + [129; 131) '{}': () + [160; 173) '{ gen() }': *mut [U] + [166; 169) 'gen': fn gen() -> *mut [T;_] + [166; 171) 'gen()': *mut [U;_] + [186; 420) '{ ...rr); }': () + [196; 199) 'arr': &[u8;_] + [212; 216) '&[1]': &[u8;_] + [213; 216) '[1]': [u8;_] + [214; 215) '1': u8 + [227; 228) 'a': &[u8] + [237; 240) 'arr': &[u8;_] + [250; 251) 'b': u8 + [254; 255) 'f': fn f(&[T]) -> T + [254; 260) 'f(arr)': u8 + [256; 259) 'arr': &[u8;_] + [270; 271) 'c': &[u8] + [280; 287) '{ arr }': &[u8] + [282; 285) 'arr': &[u8;_] + [297; 298) 'd': u8 + [301; 302) 'g': fn g(S<&[T]>) -> T + [301; 316) 'g(S { a: arr })': u8 + [303; 315) 'S { a: arr }': S<&[u8]> + [310; 313) 'arr': &[u8;_] + [326; 327) 'e': [&[u8];_] + [341; 346) '[arr]': [&[u8];_] + [342; 345) 'arr': &[u8;_] + [356; 357) 'f': [&[u8];_] + [371; 379) '[arr; 2]': [&[u8];_] + [372; 375) 'arr': &[u8;_] + [377; 378) '2': usize + [389; 390) 'g': (&[u8], &[u8]) + [407; 417) '(arr, arr)': (&[u8], &[u8]) + [408; 411) 'arr': &[u8;_] + [413; 416) 'arr': &[u8;_] + "### + ); +} + +#[test] +fn infer_let_stmt_coerce() { + assert_snapshot!( + infer(r#" +fn test() { + let x: &[i32] = &[1]; +} +"#), + @r###" + [11; 40) '{ ...[1]; }': () + [21; 22) 'x': &[i32] + [33; 37) '&[1]': &[i32;_] + [34; 37) '[1]': [i32;_] + [35; 36) '1': i32 + "###); +} + +#[test] +fn infer_custom_coerce_unsized() { + assert_snapshot!( + infer(r#" +struct A(*const T); +struct B(*const T); +struct C { inner: *const T } + +impl, U: ?Sized> CoerceUnsized> for B {} +impl, U: ?Sized> CoerceUnsized> for C {} + +fn foo1(x: A<[T]>) -> A<[T]> { x } +fn foo2(x: B<[T]>) -> B<[T]> { x } +fn foo3(x: C<[T]>) -> C<[T]> { x } + +fn test(a: A<[u8; 2]>, b: B<[u8; 2]>, c: C<[u8; 2]>) { + let d = foo1(a); + let e = foo2(b); + let f = foo3(c); +} +"#), + @r###" + [258; 259) 'x': A<[T]> + [279; 284) '{ x }': A<[T]> + [281; 282) 'x': A<[T]> + [296; 297) 'x': B<[T]> + [317; 322) '{ x }': B<[T]> + [319; 320) 'x': B<[T]> + [334; 335) 'x': C<[T]> + [355; 360) '{ x }': C<[T]> + [357; 358) 'x': C<[T]> + [370; 371) 'a': A<[u8;_]> + [385; 386) 'b': B<[u8;_]> + [400; 401) 'c': C<[u8;_]> + [415; 481) '{ ...(c); }': () + [425; 426) 'd': A<[{unknown}]> + [429; 433) 'foo1': fn foo1<{unknown}>(A<[T]>) -> A<[T]> + [429; 436) 'foo1(a)': A<[{unknown}]> + [434; 435) 'a': A<[u8;_]> + [446; 447) 'e': B<[u8]> + [450; 454) 'foo2': fn foo2(B<[T]>) -> B<[T]> + [450; 457) 'foo2(b)': B<[u8]> + [455; 456) 'b': B<[u8;_]> + [467; 468) 'f': C<[u8]> + [471; 475) 'foo3': fn foo3(C<[T]>) -> C<[T]> + [471; 478) 'foo3(c)': C<[u8]> + [476; 477) 'c': C<[u8;_]> + "### + ); +} + +#[test] +fn infer_if_coerce() { + assert_snapshot!( + infer(r#" +fn foo(x: &[T]) -> &[T] { loop {} } +fn test() { + let x = if true { + foo(&[1]) + } else { + &[1] + }; +} +"#), + @r###" + [11; 12) 'x': &[T] + [28; 39) '{ loop {} }': &[T] + [30; 37) 'loop {}': ! + [35; 37) '{}': () + [50; 126) '{ ... }; }': () + [60; 61) 'x': &[i32] + [64; 123) 'if tru... }': &[i32] + [67; 71) 'true': bool + [72; 97) '{ ... }': &[i32] + [82; 85) 'foo': fn foo(&[T]) -> &[T] + [82; 91) 'foo(&[1])': &[i32] + [86; 90) '&[1]': &[i32;_] + [87; 90) '[1]': [i32;_] + [88; 89) '1': i32 + [103; 123) '{ ... }': &[i32;_] + [113; 117) '&[1]': &[i32;_] + [114; 117) '[1]': [i32;_] + [115; 116) '1': i32 + "### + ); +} + +#[test] +fn infer_if_else_coerce() { + assert_snapshot!( + infer(r#" +fn foo(x: &[T]) -> &[T] { loop {} } +fn test() { + let x = if true { + &[1] + } else { + foo(&[1]) + }; +} +"#), + @r###" + [11; 12) 'x': &[T] + [28; 39) '{ loop {} }': &[T] + [30; 37) 'loop {}': ! + [35; 37) '{}': () + [50; 126) '{ ... }; }': () + [60; 61) 'x': &[i32] + [64; 123) 'if tru... }': &[i32] + [67; 71) 'true': bool + [72; 92) '{ ... }': &[i32;_] + [82; 86) '&[1]': &[i32;_] + [83; 86) '[1]': [i32;_] + [84; 85) '1': i32 + [98; 123) '{ ... }': &[i32] + [108; 111) 'foo': fn foo(&[T]) -> &[T] + [108; 117) 'foo(&[1])': &[i32] + [112; 116) '&[1]': &[i32;_] + [113; 116) '[1]': [i32;_] + [114; 115) '1': i32 + "### + ); +} + +#[test] +fn infer_match_first_coerce() { + assert_snapshot!( + infer(r#" +fn foo(x: &[T]) -> &[T] { loop {} } +fn test(i: i32) { + let x = match i { + 2 => foo(&[2]), + 1 => &[1], + _ => &[3], + }; +} +"#), + @r###" + [11; 12) 'x': &[T] + [28; 39) '{ loop {} }': &[T] + [30; 37) 'loop {}': ! + [35; 37) '{}': () + [48; 49) 'i': i32 + [56; 150) '{ ... }; }': () + [66; 67) 'x': &[i32] + [70; 147) 'match ... }': &[i32] + [76; 77) 'i': i32 + [88; 89) '2': i32 + [93; 96) 'foo': fn foo(&[T]) -> &[T] + [93; 102) 'foo(&[2])': &[i32] + [97; 101) '&[2]': &[i32;_] + [98; 101) '[2]': [i32;_] + [99; 100) '2': i32 + [112; 113) '1': i32 + [117; 121) '&[1]': &[i32;_] + [118; 121) '[1]': [i32;_] + [119; 120) '1': i32 + [131; 132) '_': i32 + [136; 140) '&[3]': &[i32;_] + [137; 140) '[3]': [i32;_] + [138; 139) '3': i32 + "### + ); +} + +#[test] +fn infer_match_second_coerce() { + assert_snapshot!( + infer(r#" +fn foo(x: &[T]) -> &[T] { loop {} } +fn test(i: i32) { + let x = match i { + 1 => &[1], + 2 => foo(&[2]), + _ => &[3], + }; +} +"#), + @r###" + [11; 12) 'x': &[T] + [28; 39) '{ loop {} }': &[T] + [30; 37) 'loop {}': ! + [35; 37) '{}': () + [48; 49) 'i': i32 + [56; 150) '{ ... }; }': () + [66; 67) 'x': &[i32] + [70; 147) 'match ... }': &[i32] + [76; 77) 'i': i32 + [88; 89) '1': i32 + [93; 97) '&[1]': &[i32;_] + [94; 97) '[1]': [i32;_] + [95; 96) '1': i32 + [107; 108) '2': i32 + [112; 115) 'foo': fn foo(&[T]) -> &[T] + [112; 121) 'foo(&[2])': &[i32] + [116; 120) '&[2]': &[i32;_] + [117; 120) '[2]': [i32;_] + [118; 119) '2': i32 + [131; 132) '_': i32 + [136; 140) '&[3]': &[i32;_] + [137; 140) '[3]': [i32;_] + [138; 139) '3': i32 + "### + ); +} + +#[test] +fn coerce_merge_one_by_one1() { + covers!(coerce_merge_fail_fallback); + + assert_snapshot!( + infer(r#" +fn test() { + let t = &mut 1; + let x = match 1 { + 1 => t as *mut i32, + 2 => t as &i32, + _ => t as *const i32, + }; +} +"#), + @r###" + [11; 145) '{ ... }; }': () + [21; 22) 't': &mut i32 + [25; 31) '&mut 1': &mut i32 + [30; 31) '1': i32 + [41; 42) 'x': *const i32 + [45; 142) 'match ... }': *const i32 + [51; 52) '1': i32 + [63; 64) '1': i32 + [68; 69) 't': &mut i32 + [68; 81) 't as *mut i32': *mut i32 + [91; 92) '2': i32 + [96; 97) 't': &mut i32 + [96; 105) 't as &i32': &i32 + [115; 116) '_': i32 + [120; 121) 't': &mut i32 + [120; 135) 't as *const i32': *const i32 + "### + ); +} diff --git a/crates/ra_hir_ty/src/tests/never_type.rs b/crates/ra_hir_ty/src/tests/never_type.rs new file mode 100644 index 000000000..c202f545a --- /dev/null +++ b/crates/ra_hir_ty/src/tests/never_type.rs @@ -0,0 +1,246 @@ +use super::type_at; + +#[test] +fn infer_never1() { + let t = type_at( + r#" +//- /main.rs +fn test() { + let t = return; + t<|>; +} +"#, + ); + assert_eq!(t, "!"); +} + +#[test] +fn infer_never2() { + let t = type_at( + r#" +//- /main.rs +fn gen() -> T { loop {} } + +fn test() { + let a = gen(); + if false { a } else { loop {} }; + a<|>; +} +"#, + ); + assert_eq!(t, "!"); +} + +#[test] +fn infer_never3() { + let t = type_at( + r#" +//- /main.rs +fn gen() -> T { loop {} } + +fn test() { + let a = gen(); + if false { loop {} } else { a }; + a<|>; +} +"#, + ); + assert_eq!(t, "!"); +} + +#[test] +fn never_type_in_generic_args() { + let t = type_at( + r#" +//- /main.rs +enum Option { None, Some(T) } + +fn test() { + let a = if true { Option::None } else { Option::Some(return) }; + a<|>; +} +"#, + ); + assert_eq!(t, "Option"); +} + +#[test] +fn never_type_can_be_reinferred1() { + let t = type_at( + r#" +//- /main.rs +fn gen() -> T { loop {} } + +fn test() { + let a = gen(); + if false { loop {} } else { a }; + a<|>; + if false { a }; +} +"#, + ); + assert_eq!(t, "()"); +} + +#[test] +fn never_type_can_be_reinferred2() { + let t = type_at( + r#" +//- /main.rs +enum Option { None, Some(T) } + +fn test() { + let a = if true { Option::None } else { Option::Some(return) }; + a<|>; + match 42 { + 42 => a, + _ => Option::Some(42), + }; +} +"#, + ); + assert_eq!(t, "Option"); +} +#[test] +fn never_type_can_be_reinferred3() { + let t = type_at( + r#" +//- /main.rs +enum Option { None, Some(T) } + +fn test() { + let a = if true { Option::None } else { Option::Some(return) }; + a<|>; + match 42 { + 42 => a, + _ => Option::Some("str"), + }; +} +"#, + ); + assert_eq!(t, "Option<&str>"); +} + +#[test] +fn match_no_arm() { + let t = type_at( + r#" +//- /main.rs +enum Void {} + +fn test(a: Void) { + let t = match a {}; + t<|>; +} +"#, + ); + assert_eq!(t, "!"); +} + +#[test] +fn if_never() { + let t = type_at( + r#" +//- /main.rs +fn test() { + let i = if true { + loop {} + } else { + 3.0 + }; + i<|>; +} +"#, + ); + assert_eq!(t, "f64"); +} + +#[test] +fn if_else_never() { + let t = type_at( + r#" +//- /main.rs +fn test(input: bool) { + let i = if input { + 2.0 + } else { + return + }; + i<|>; +} +"#, + ); + assert_eq!(t, "f64"); +} + +#[test] +fn match_first_arm_never() { + let t = type_at( + r#" +//- /main.rs +fn test(a: i32) { + let i = match a { + 1 => return, + 2 => 2.0, + 3 => loop {}, + _ => 3.0, + }; + i<|>; +} +"#, + ); + assert_eq!(t, "f64"); +} + +#[test] +fn match_second_arm_never() { + let t = type_at( + r#" +//- /main.rs +fn test(a: i32) { + let i = match a { + 1 => 3.0, + 2 => loop {}, + 3 => 3.0, + _ => return, + }; + i<|>; +} +"#, + ); + assert_eq!(t, "f64"); +} + +#[test] +fn match_all_arms_never() { + let t = type_at( + r#" +//- /main.rs +fn test(a: i32) { + let i = match a { + 2 => return, + _ => loop {}, + }; + i<|>; +} +"#, + ); + assert_eq!(t, "!"); +} + +#[test] +fn match_no_never_arms() { + let t = type_at( + r#" +//- /main.rs +fn test(a: i32) { + let i = match a { + 2 => 2.0, + _ => 3.0, + }; + i<|>; +} +"#, + ); + assert_eq!(t, "f64"); +} diff --git a/crates/ra_hir_ty/src/traits.rs b/crates/ra_hir_ty/src/traits.rs new file mode 100644 index 000000000..76189a60b --- /dev/null +++ b/crates/ra_hir_ty/src/traits.rs @@ -0,0 +1,328 @@ +//! Trait solving using Chalk. +use std::sync::{Arc, Mutex}; + +use chalk_ir::{cast::Cast, family::ChalkIr}; +use hir_def::{expr::ExprId, DefWithBodyId, ImplId, TraitId, TypeAliasId}; +use log::debug; +use ra_db::{impl_intern_key, salsa, CrateId}; +use ra_prof::profile; +use rustc_hash::FxHashSet; + +use crate::db::HirDatabase; + +use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk}; + +use self::chalk::{from_chalk, ToChalk}; + +pub(crate) mod chalk; + +#[derive(Debug, Clone)] +pub struct TraitSolver { + krate: CrateId, + inner: Arc>>, +} + +/// We need eq for salsa +impl PartialEq for TraitSolver { + fn eq(&self, other: &TraitSolver) -> bool { + Arc::ptr_eq(&self.inner, &other.inner) + } +} + +impl Eq for TraitSolver {} + +impl TraitSolver { + fn solve( + &self, + db: &impl HirDatabase, + goal: &chalk_ir::UCanonical>>, + ) -> Option> { + let context = ChalkContext { db, krate: self.krate }; + debug!("solve goal: {:?}", goal); + let mut solver = match self.inner.lock() { + Ok(it) => it, + // Our cancellation works via unwinding, but, as chalk is not + // panic-safe, we need to make sure to propagate the cancellation. + // Ideally, we should also make chalk panic-safe. + Err(_) => ra_db::Canceled::throw(), + }; + let solution = solver.solve(&context, goal); + debug!("solve({:?}) => {:?}", goal, solution); + solution + } +} + +/// This controls the maximum size of types Chalk considers. If we set this too +/// high, we can run into slow edge cases; if we set it too low, Chalk won't +/// find some solutions. +const CHALK_SOLVER_MAX_SIZE: usize = 4; + +#[derive(Debug, Copy, Clone)] +struct ChalkContext<'a, DB> { + db: &'a DB, + krate: CrateId, +} + +pub(crate) fn trait_solver_query( + db: &(impl HirDatabase + salsa::Database), + krate: CrateId, +) -> TraitSolver { + db.salsa_runtime().report_untracked_read(); + // krate parameter is just so we cache a unique solver per crate + let solver_choice = chalk_solve::SolverChoice::SLG { max_size: CHALK_SOLVER_MAX_SIZE }; + debug!("Creating new solver for crate {:?}", krate); + TraitSolver { krate, inner: Arc::new(Mutex::new(solver_choice.into_solver())) } +} + +/// Collects impls for the given trait in the whole dependency tree of `krate`. +pub(crate) fn impls_for_trait_query( + db: &impl HirDatabase, + krate: CrateId, + trait_: TraitId, +) -> Arc<[ImplId]> { + let mut impls = FxHashSet::default(); + // We call the query recursively here. On the one hand, this means we can + // reuse results from queries for different crates; on the other hand, this + // will only ever get called for a few crates near the root of the tree (the + // ones the user is editing), so this may actually be a waste of memory. I'm + // doing it like this mainly for simplicity for now. + for dep in db.crate_graph().dependencies(krate) { + impls.extend(db.impls_for_trait(dep.crate_id, trait_).iter()); + } + let crate_impl_blocks = db.impls_in_crate(krate); + impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_)); + impls.into_iter().collect() +} + +/// A set of clauses that we assume to be true. E.g. if we are inside this function: +/// ```rust +/// fn foo(t: T) {} +/// ``` +/// we assume that `T: Default`. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct TraitEnvironment { + pub predicates: Vec, +} + +impl TraitEnvironment { + /// Returns trait refs with the given self type which are supposed to hold + /// in this trait env. E.g. if we are in `foo()`, this will + /// find that `T: SomeTrait` if we call it for `T`. + pub(crate) fn trait_predicates_for_self_ty<'a>( + &'a self, + ty: &'a Ty, + ) -> impl Iterator + 'a { + self.predicates.iter().filter_map(move |pred| match pred { + GenericPredicate::Implemented(tr) if tr.self_ty() == ty => Some(tr), + _ => None, + }) + } +} + +/// Something (usually a goal), along with an environment. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct InEnvironment { + pub environment: Arc, + pub value: T, +} + +impl InEnvironment { + pub fn new(environment: Arc, value: T) -> InEnvironment { + InEnvironment { environment, value } + } +} + +/// Something that needs to be proven (by Chalk) during type checking, e.g. that +/// a certain type implements a certain trait. Proving the Obligation might +/// result in additional information about inference variables. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Obligation { + /// Prove that a certain type implements a trait (the type is the `Self` type + /// parameter to the `TraitRef`). + Trait(TraitRef), + Projection(ProjectionPredicate), +} + +impl Obligation { + pub fn from_predicate(predicate: GenericPredicate) -> Option { + match predicate { + GenericPredicate::Implemented(trait_ref) => Some(Obligation::Trait(trait_ref)), + GenericPredicate::Projection(projection_pred) => { + Some(Obligation::Projection(projection_pred)) + } + GenericPredicate::Error => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct ProjectionPredicate { + pub projection_ty: ProjectionTy, + pub ty: Ty, +} + +impl TypeWalk for ProjectionPredicate { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + self.projection_ty.walk(f); + self.ty.walk(f); + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.projection_ty.walk_mut_binders(f, binders); + self.ty.walk_mut_binders(f, binders); + } +} + +/// Solve a trait goal using Chalk. +pub(crate) fn trait_solve_query( + db: &impl HirDatabase, + krate: CrateId, + goal: Canonical>, +) -> Option { + let _p = profile("trait_solve_query"); + debug!("trait_solve_query({})", goal.value.value.display(db)); + + if let Obligation::Projection(pred) = &goal.value.value { + if let Ty::Bound(_) = &pred.projection_ty.parameters[0] { + // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible + return Some(Solution::Ambig(Guidance::Unknown)); + } + } + + let canonical = goal.to_chalk(db).cast(); + + // We currently don't deal with universes (I think / hope they're not yet + // relevant for our use cases?) + let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; + let solution = db.trait_solver(krate).solve(db, &u_canonical); + solution.map(|solution| solution_from_chalk(db, solution)) +} + +fn solution_from_chalk( + db: &impl HirDatabase, + solution: chalk_solve::Solution, +) -> Solution { + let convert_subst = |subst: chalk_ir::Canonical>| { + let value = subst + .value + .parameters + .into_iter() + .map(|p| { + let ty = match p { + chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), + chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), + }; + ty + }) + .collect(); + let result = Canonical { value, num_vars: subst.binders.len() }; + SolutionVariables(result) + }; + match solution { + chalk_solve::Solution::Unique(constr_subst) => { + let subst = chalk_ir::Canonical { + value: constr_subst.value.subst, + binders: constr_subst.binders, + }; + Solution::Unique(convert_subst(subst)) + } + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst)) => { + Solution::Ambig(Guidance::Definite(convert_subst(subst))) + } + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst)) => { + Solution::Ambig(Guidance::Suggested(convert_subst(subst))) + } + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown) => { + Solution::Ambig(Guidance::Unknown) + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SolutionVariables(pub Canonical>); + +#[derive(Clone, Debug, PartialEq, Eq)] +/// A (possible) solution for a proposed goal. +pub enum Solution { + /// The goal indeed holds, and there is a unique value for all existential + /// variables. + Unique(SolutionVariables), + + /// The goal may be provable in multiple ways, but regardless we may have some guidance + /// for type inference. In this case, we don't return any lifetime + /// constraints, since we have not "committed" to any particular solution + /// yet. + Ambig(Guidance), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +/// When a goal holds ambiguously (e.g., because there are multiple possible +/// solutions), we issue a set of *guidance* back to type inference. +pub enum Guidance { + /// The existential variables *must* have the given values if the goal is + /// ever to hold, but that alone isn't enough to guarantee the goal will + /// actually hold. + Definite(SolutionVariables), + + /// There are multiple plausible values for the existentials, but the ones + /// here are suggested as the preferred choice heuristically. These should + /// be used for inference fallback only. + Suggested(SolutionVariables), + + /// There's no useful information to feed back to type inference + Unknown, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum FnTrait { + FnOnce, + FnMut, + Fn, +} + +impl FnTrait { + fn lang_item_name(self) -> &'static str { + match self { + FnTrait::FnOnce => "fn_once", + FnTrait::FnMut => "fn_mut", + FnTrait::Fn => "fn", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ClosureFnTraitImplData { + def: DefWithBodyId, + expr: ExprId, + fn_trait: FnTrait, +} + +/// An impl. Usually this comes from an impl block, but some built-in types get +/// synthetic impls. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Impl { + /// A normal impl from an impl block. + ImplBlock(ImplId), + /// Closure types implement the Fn traits synthetically. + ClosureFnTraitImpl(ClosureFnTraitImplData), +} +/// This exists just for Chalk, because our ImplIds are only unique per module. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct GlobalImplId(salsa::InternId); +impl_intern_key!(GlobalImplId); + +/// An associated type value. Usually this comes from a `type` declaration +/// inside an impl block, but for built-in impls we have to synthesize it. +/// (We only need this because Chalk wants a unique ID for each of these.) +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum AssocTyValue { + /// A normal assoc type value from an impl block. + TypeAlias(TypeAliasId), + /// The output type of the Fn trait implementation. + ClosureFnTraitImplOutput(ClosureFnTraitImplData), +} +/// This exists just for Chalk, because it needs a unique ID for each associated +/// type value in an impl (even synthetic ones). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AssocTyValueId(salsa::InternId); +impl_intern_key!(AssocTyValueId); diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs new file mode 100644 index 000000000..810e8c21a --- /dev/null +++ b/crates/ra_hir_ty/src/traits/chalk.rs @@ -0,0 +1,906 @@ +//! Conversion code from/to Chalk. +use std::sync::Arc; + +use log::debug; + +use chalk_ir::{ + cast::Cast, family::ChalkIr, Identifier, Parameter, PlaceholderIndex, TypeId, TypeKindId, + TypeName, UniverseIndex, +}; +use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum}; +use ra_db::CrateId; + +use hir_def::{ + expr::Expr, lang_item::LangItemTarget, resolver::HasResolver, AssocItemId, AstItemDef, + ContainerId, GenericDefId, ImplId, Lookup, TraitId, TypeAliasId, +}; +use hir_expand::name; + +use ra_db::salsa::{InternId, InternKey}; + +use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; +use crate::{ + db::HirDatabase, + display::HirDisplay, + {ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, +}; + +/// This represents a trait whose name we could not resolve. +const UNKNOWN_TRAIT: chalk_ir::TraitId = + chalk_ir::TraitId(chalk_ir::RawId { index: u32::max_value() }); + +pub(super) trait ToChalk { + type Chalk; + fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; + fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; +} + +pub(super) fn from_chalk(db: &impl HirDatabase, chalk: ChalkT) -> T +where + T: ToChalk, +{ + T::from_chalk(db, chalk) +} + +impl ToChalk for Ty { + type Chalk = chalk_ir::Ty; + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { + match self { + Ty::Apply(apply_ty) => { + let name = match apply_ty.ctor { + TypeCtor::AssociatedType(type_alias) => { + let type_id = type_alias.to_chalk(db); + TypeName::AssociatedType(type_id) + } + _ => { + // other TypeCtors get interned and turned into a chalk StructId + let struct_id = apply_ty.ctor.to_chalk(db); + TypeName::TypeKindId(struct_id.into()) + } + }; + let parameters = apply_ty.parameters.to_chalk(db); + chalk_ir::ApplicationTy { name, parameters }.cast().intern() + } + Ty::Projection(proj_ty) => { + let associated_ty_id = proj_ty.associated_ty.to_chalk(db); + let parameters = proj_ty.parameters.to_chalk(db); + chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern() + } + Ty::Param { idx, .. } => { + PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::() + } + Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), + Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), + Ty::Dyn(predicates) => { + let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); + chalk_ir::TyData::Dyn(make_binders(where_clauses, 1)).intern() + } + Ty::Opaque(predicates) => { + let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); + chalk_ir::TyData::Opaque(make_binders(where_clauses, 1)).intern() + } + Ty::Unknown => { + let parameters = Vec::new(); + let name = TypeName::Error; + chalk_ir::ApplicationTy { name, parameters }.cast().intern() + } + } + } + fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { + match chalk.data().clone() { + chalk_ir::TyData::Apply(apply_ty) => { + // FIXME this is kind of hacky due to the fact that + // TypeName::Placeholder is a Ty::Param on our side + match apply_ty.name { + TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { + let ctor = from_chalk(db, struct_id); + let parameters = from_chalk(db, apply_ty.parameters); + Ty::Apply(ApplicationTy { ctor, parameters }) + } + TypeName::AssociatedType(type_id) => { + let ctor = TypeCtor::AssociatedType(from_chalk(db, type_id)); + let parameters = from_chalk(db, apply_ty.parameters); + Ty::Apply(ApplicationTy { ctor, parameters }) + } + TypeName::Error => Ty::Unknown, + // FIXME handle TypeKindId::Trait/Type here + TypeName::TypeKindId(_) => unimplemented!(), + TypeName::Placeholder(idx) => { + assert_eq!(idx.ui, UniverseIndex::ROOT); + Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } + } + } + } + chalk_ir::TyData::Projection(proj) => { + let associated_ty = from_chalk(db, proj.associated_ty_id); + let parameters = from_chalk(db, proj.parameters); + Ty::Projection(ProjectionTy { associated_ty, parameters }) + } + chalk_ir::TyData::ForAll(_) => unimplemented!(), + chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32), + chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown, + chalk_ir::TyData::Dyn(where_clauses) => { + assert_eq!(where_clauses.binders.len(), 1); + let predicates = + where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); + Ty::Dyn(predicates) + } + chalk_ir::TyData::Opaque(where_clauses) => { + assert_eq!(where_clauses.binders.len(), 1); + let predicates = + where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); + Ty::Opaque(predicates) + } + } + } +} + +impl ToChalk for Substs { + type Chalk = Vec>; + + fn to_chalk(self, db: &impl HirDatabase) -> Vec> { + self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect() + } + + fn from_chalk(db: &impl HirDatabase, parameters: Vec>) -> Substs { + let tys = parameters + .into_iter() + .map(|p| match p { + chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), + chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), + }) + .collect(); + Substs(tys) + } +} + +impl ToChalk for TraitRef { + type Chalk = chalk_ir::TraitRef; + + fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef { + let trait_id = self.trait_.to_chalk(db); + let parameters = self.substs.to_chalk(db); + chalk_ir::TraitRef { trait_id, parameters } + } + + fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef) -> Self { + let trait_ = from_chalk(db, trait_ref.trait_id); + let substs = from_chalk(db, trait_ref.parameters); + TraitRef { trait_, substs } + } +} + +impl ToChalk for TraitId { + type Chalk = chalk_ir::TraitId; + + fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TraitId { + chalk_ir::TraitId(id_to_chalk(self)) + } + + fn from_chalk(_db: &impl HirDatabase, trait_id: chalk_ir::TraitId) -> TraitId { + id_from_chalk(trait_id.0) + } +} + +impl ToChalk for TypeCtor { + type Chalk = chalk_ir::StructId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId { + db.intern_type_ctor(self).into() + } + + fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor { + db.lookup_intern_type_ctor(struct_id.into()) + } +} + +impl ToChalk for Impl { + type Chalk = chalk_ir::ImplId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { + db.intern_chalk_impl(self).into() + } + + fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> Impl { + db.lookup_intern_chalk_impl(impl_id.into()) + } +} + +impl ToChalk for TypeAliasId { + type Chalk = chalk_ir::TypeId; + + fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TypeId { + chalk_ir::TypeId(id_to_chalk(self)) + } + + fn from_chalk(_db: &impl HirDatabase, type_alias_id: chalk_ir::TypeId) -> TypeAliasId { + id_from_chalk(type_alias_id.0) + } +} + +impl ToChalk for AssocTyValue { + type Chalk = chalk_rust_ir::AssociatedTyValueId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId { + db.intern_assoc_ty_value(self).into() + } + + fn from_chalk( + db: &impl HirDatabase, + assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId, + ) -> AssocTyValue { + db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) + } +} + +impl ToChalk for GenericPredicate { + type Chalk = chalk_ir::QuantifiedWhereClause; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause { + match self { + GenericPredicate::Implemented(trait_ref) => { + make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0) + } + GenericPredicate::Projection(projection_pred) => make_binders( + chalk_ir::WhereClause::ProjectionEq(chalk_ir::ProjectionEq { + projection: projection_pred.projection_ty.to_chalk(db), + ty: projection_pred.ty.to_chalk(db), + }), + 0, + ), + GenericPredicate::Error => { + let impossible_trait_ref = chalk_ir::TraitRef { + trait_id: UNKNOWN_TRAIT, + parameters: vec![Ty::Unknown.to_chalk(db).cast()], + }; + make_binders(chalk_ir::WhereClause::Implemented(impossible_trait_ref), 0) + } + } + } + + fn from_chalk( + db: &impl HirDatabase, + where_clause: chalk_ir::QuantifiedWhereClause, + ) -> GenericPredicate { + match where_clause.value { + chalk_ir::WhereClause::Implemented(tr) => { + if tr.trait_id == UNKNOWN_TRAIT { + // FIXME we need an Error enum on the Chalk side to avoid this + return GenericPredicate::Error; + } + GenericPredicate::Implemented(from_chalk(db, tr)) + } + chalk_ir::WhereClause::ProjectionEq(projection_eq) => { + let projection_ty = from_chalk(db, projection_eq.projection); + let ty = from_chalk(db, projection_eq.ty); + GenericPredicate::Projection(super::ProjectionPredicate { projection_ty, ty }) + } + } + } +} + +impl ToChalk for ProjectionTy { + type Chalk = chalk_ir::ProjectionTy; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ProjectionTy { + chalk_ir::ProjectionTy { + associated_ty_id: self.associated_ty.to_chalk(db), + parameters: self.parameters.to_chalk(db), + } + } + + fn from_chalk( + db: &impl HirDatabase, + projection_ty: chalk_ir::ProjectionTy, + ) -> ProjectionTy { + ProjectionTy { + associated_ty: from_chalk(db, projection_ty.associated_ty_id), + parameters: from_chalk(db, projection_ty.parameters), + } + } +} + +impl ToChalk for super::ProjectionPredicate { + type Chalk = chalk_ir::Normalize; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize { + chalk_ir::Normalize { + projection: self.projection_ty.to_chalk(db), + ty: self.ty.to_chalk(db), + } + } + + fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize) -> Self { + unimplemented!() + } +} + +impl ToChalk for Obligation { + type Chalk = chalk_ir::DomainGoal; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal { + match self { + Obligation::Trait(tr) => tr.to_chalk(db).cast(), + Obligation::Projection(pr) => pr.to_chalk(db).cast(), + } + } + + fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal) -> Self { + unimplemented!() + } +} + +impl ToChalk for Canonical +where + T: ToChalk, +{ + type Chalk = chalk_ir::Canonical; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical { + let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); + let value = self.value.to_chalk(db); + let canonical = chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }; + canonical + } + + fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical) -> Canonical { + Canonical { num_vars: canonical.binders.len(), value: from_chalk(db, canonical.value) } + } +} + +impl ToChalk for Arc { + type Chalk = chalk_ir::Environment; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment { + let mut clauses = Vec::new(); + for pred in &self.predicates { + if pred.is_error() { + // for env, we just ignore errors + continue; + } + let program_clause: chalk_ir::ProgramClause = pred.clone().to_chalk(db).cast(); + clauses.push(program_clause.into_from_env_clause()); + } + chalk_ir::Environment::new().add_clauses(clauses) + } + + fn from_chalk( + _db: &impl HirDatabase, + _env: chalk_ir::Environment, + ) -> Arc { + unimplemented!() + } +} + +impl ToChalk for super::InEnvironment +where + T::Chalk: chalk_ir::family::HasTypeFamily, +{ + type Chalk = chalk_ir::InEnvironment; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::InEnvironment { + chalk_ir::InEnvironment { + environment: self.environment.to_chalk(db), + goal: self.value.to_chalk(db), + } + } + + fn from_chalk( + db: &impl HirDatabase, + in_env: chalk_ir::InEnvironment, + ) -> super::InEnvironment { + super::InEnvironment { + environment: from_chalk(db, in_env.environment), + value: from_chalk(db, in_env.goal), + } + } +} + +fn make_binders(value: T, num_vars: usize) -> chalk_ir::Binders { + chalk_ir::Binders { + value, + binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(), + } +} + +fn convert_where_clauses( + db: &impl HirDatabase, + def: GenericDefId, + substs: &Substs, +) -> Vec> { + let generic_predicates = db.generic_predicates(def); + let mut result = Vec::with_capacity(generic_predicates.len()); + for pred in generic_predicates.iter() { + if pred.is_error() { + // HACK: Return just the single predicate (which is always false + // anyway), otherwise Chalk can easily get into slow situations + return vec![pred.clone().subst(substs).to_chalk(db)]; + } + result.push(pred.clone().subst(substs).to_chalk(db)); + } + result +} + +impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> +where + DB: HirDatabase, +{ + fn associated_ty_data(&self, id: TypeId) -> Arc> { + self.db.associated_ty_data(id) + } + fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc> { + self.db.trait_datum(self.krate, trait_id) + } + fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc> { + self.db.struct_datum(self.krate, struct_id) + } + fn impl_datum(&self, impl_id: chalk_ir::ImplId) -> Arc> { + self.db.impl_datum(self.krate, impl_id) + } + fn impls_for_trait( + &self, + trait_id: chalk_ir::TraitId, + parameters: &[Parameter], + ) -> Vec { + debug!("impls_for_trait {:?}", trait_id); + if trait_id == UNKNOWN_TRAIT { + return Vec::new(); + } + let trait_: TraitId = from_chalk(self.db, trait_id); + let mut result: Vec<_> = self + .db + .impls_for_trait(self.krate, trait_.into()) + .iter() + .copied() + .map(|it| Impl::ImplBlock(it.into())) + .map(|impl_| impl_.to_chalk(self.db)) + .collect(); + + let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref().clone()); + if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { def, expr }, .. }) = ty { + for &fn_trait in + [super::FnTrait::FnOnce, super::FnTrait::FnMut, super::FnTrait::Fn].iter() + { + if let Some(actual_trait) = get_fn_trait(self.db, self.krate, fn_trait) { + if trait_ == actual_trait { + let impl_ = super::ClosureFnTraitImplData { def, expr, fn_trait }; + result.push(Impl::ClosureFnTraitImpl(impl_).to_chalk(self.db)); + } + } + } + } + + debug!("impls_for_trait returned {} impls", result.len()); + result + } + fn impl_provided_for( + &self, + auto_trait_id: chalk_ir::TraitId, + struct_id: chalk_ir::StructId, + ) -> bool { + debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); + false // FIXME + } + fn type_name(&self, _id: TypeKindId) -> Identifier { + unimplemented!() + } + fn associated_ty_value( + &self, + id: chalk_rust_ir::AssociatedTyValueId, + ) -> Arc> { + self.db.associated_ty_value(self.krate.into(), id) + } + fn custom_clauses(&self) -> Vec> { + vec![] + } + fn local_impls_to_coherence_check( + &self, + _trait_id: chalk_ir::TraitId, + ) -> Vec { + // We don't do coherence checking (yet) + unimplemented!() + } +} + +pub(crate) fn associated_ty_data_query( + db: &impl HirDatabase, + id: TypeId, +) -> Arc> { + debug!("associated_ty_data {:?}", id); + let type_alias: TypeAliasId = from_chalk(db, id); + let trait_ = match type_alias.lookup(db).container { + ContainerId::TraitId(t) => t, + _ => panic!("associated type not in trait"), + }; + let generic_params = db.generic_params(type_alias.into()); + let bound_data = chalk_rust_ir::AssociatedTyDatumBound { + // FIXME add bounds and where clauses + bounds: vec![], + where_clauses: vec![], + }; + let datum = AssociatedTyDatum { + trait_id: trait_.to_chalk(db), + id, + name: lalrpop_intern::intern(&db.type_alias_data(type_alias).name.to_string()), + binders: make_binders(bound_data, generic_params.count_params_including_parent()), + }; + Arc::new(datum) +} + +pub(crate) fn trait_datum_query( + db: &impl HirDatabase, + krate: CrateId, + trait_id: chalk_ir::TraitId, +) -> Arc> { + debug!("trait_datum {:?}", trait_id); + if trait_id == UNKNOWN_TRAIT { + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() }; + + let flags = chalk_rust_ir::TraitFlags { + auto: false, + marker: false, + upstream: true, + fundamental: false, + non_enumerable: true, + coinductive: false, + }; + return Arc::new(TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, 1), + flags, + associated_ty_ids: vec![], + }); + } + let trait_: TraitId = from_chalk(db, trait_id); + let trait_data = db.trait_data(trait_); + debug!("trait {:?} = {:?}", trait_id, trait_data.name); + let generic_params = db.generic_params(trait_.into()); + let bound_vars = Substs::bound_vars(&generic_params); + let flags = chalk_rust_ir::TraitFlags { + auto: trait_data.auto, + upstream: trait_.module(db).krate != krate, + non_enumerable: true, + coinductive: false, // only relevant for Chalk testing + // FIXME set these flags correctly + marker: false, + fundamental: false, + }; + let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars); + let associated_ty_ids = + trait_data.associated_types().map(|type_alias| type_alias.to_chalk(db)).collect(); + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses }; + let trait_datum = TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, bound_vars.len()), + flags, + associated_ty_ids, + }; + Arc::new(trait_datum) +} + +pub(crate) fn struct_datum_query( + db: &impl HirDatabase, + krate: CrateId, + struct_id: chalk_ir::StructId, +) -> Arc> { + debug!("struct_datum {:?}", struct_id); + let type_ctor: TypeCtor = from_chalk(db, struct_id); + debug!("struct {:?} = {:?}", struct_id, type_ctor); + let num_params = type_ctor.num_ty_params(db); + let upstream = type_ctor.krate(db) != Some(krate); + let where_clauses = type_ctor + .as_generic_def() + .map(|generic_def| { + let generic_params = db.generic_params(generic_def.into()); + let bound_vars = Substs::bound_vars(&generic_params); + convert_where_clauses(db, generic_def, &bound_vars) + }) + .unwrap_or_else(Vec::new); + let flags = chalk_rust_ir::StructFlags { + upstream, + // FIXME set fundamental flag correctly + fundamental: false, + }; + let struct_datum_bound = chalk_rust_ir::StructDatumBound { + fields: Vec::new(), // FIXME add fields (only relevant for auto traits) + where_clauses, + }; + let struct_datum = + StructDatum { id: struct_id, binders: make_binders(struct_datum_bound, num_params), flags }; + Arc::new(struct_datum) +} + +pub(crate) fn impl_datum_query( + db: &impl HirDatabase, + krate: CrateId, + impl_id: chalk_ir::ImplId, +) -> Arc> { + let _p = ra_prof::profile("impl_datum"); + debug!("impl_datum {:?}", impl_id); + let impl_: Impl = from_chalk(db, impl_id); + match impl_ { + Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block), + Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data), + } + .unwrap_or_else(invalid_impl_datum) +} + +fn impl_block_datum( + db: &impl HirDatabase, + krate: CrateId, + chalk_id: chalk_ir::ImplId, + impl_id: ImplId, +) -> Option>> { + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + + // `CoerseUnsized` has one generic parameter for the target type. + let trait_ref = + TraitRef::from_hir(db, &resolver, impl_data.target_trait.as_ref()?, Some(target_ty))?; + + let generic_params = db.generic_params(impl_id.into()); + let bound_vars = Substs::bound_vars(&generic_params); + let trait_ref = trait_ref.subst(&bound_vars); + let trait_ = trait_ref.trait_; + let impl_type = if impl_id.module(db).krate == krate { + chalk_rust_ir::ImplType::Local + } else { + chalk_rust_ir::ImplType::External + }; + let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars); + let negative = impl_data.is_negative; + debug!( + "impl {:?}: {}{} where {:?}", + chalk_id, + if negative { "!" } else { "" }, + trait_ref.display(db), + where_clauses + ); + let trait_ref = trait_ref.to_chalk(db); + + let polarity = if negative { + chalk_rust_ir::Polarity::Negative + } else { + chalk_rust_ir::Polarity::Positive + }; + + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses }; + let trait_data = db.trait_data(trait_); + let associated_ty_value_ids = impl_data + .items + .iter() + .filter_map(|item| match item { + AssocItemId::TypeAliasId(type_alias) => Some(*type_alias), + _ => None, + }) + .filter(|&type_alias| { + // don't include associated types that don't exist in the trait + let name = &db.type_alias_data(type_alias).name; + trait_data.associated_type_by_name(name).is_some() + }) + .map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db)) + .collect(); + debug!("impl_datum: {:?}", impl_datum_bound); + let impl_datum = ImplDatum { + binders: make_binders(impl_datum_bound, bound_vars.len()), + impl_type, + polarity, + associated_ty_value_ids, + }; + Some(Arc::new(impl_datum)) +} + +fn invalid_impl_datum() -> Arc> { + let trait_ref = chalk_ir::TraitRef { + trait_id: UNKNOWN_TRAIT, + parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()], + }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() }; + let impl_datum = ImplDatum { + binders: make_binders(impl_datum_bound, 1), + impl_type: chalk_rust_ir::ImplType::External, + polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: Vec::new(), + }; + Arc::new(impl_datum) +} + +fn closure_fn_trait_impl_datum( + db: &impl HirDatabase, + krate: CrateId, + data: super::ClosureFnTraitImplData, +) -> Option>> { + // for some closure |X, Y| -> Z: + // impl Fn<(T, U)> for closure V> { Output = V } + + let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait + + // validate FnOnce trait, since we need it in the assoc ty value definition + // and don't want to return a valid value only to find out later that FnOnce + // is broken + let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; + let _output = db.trait_data(fn_once_trait).associated_type_by_name(&name::OUTPUT_TYPE)?; + + let num_args: u16 = match &db.body(data.def.into())[data.expr] { + Expr::Lambda { args, .. } => args.len() as u16, + _ => { + log::warn!("closure for closure type {:?} not found", data); + 0 + } + }; + + let arg_ty = Ty::apply( + TypeCtor::Tuple { cardinality: num_args }, + Substs::builder(num_args as usize).fill_with_bound_vars(0).build(), + ); + let sig_ty = Ty::apply( + TypeCtor::FnPtr { num_args }, + Substs::builder(num_args as usize + 1).fill_with_bound_vars(0).build(), + ); + + let self_ty = Ty::apply_one(TypeCtor::Closure { def: data.def, expr: data.expr }, sig_ty); + + let trait_ref = TraitRef { + trait_: trait_.into(), + substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), + }; + + let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()).to_chalk(db); + + let impl_type = chalk_rust_ir::ImplType::External; + + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { + trait_ref: trait_ref.to_chalk(db), + where_clauses: Vec::new(), + }; + let impl_datum = ImplDatum { + binders: make_binders(impl_datum_bound, num_args as usize + 1), + impl_type, + polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: vec![output_ty_id], + }; + Some(Arc::new(impl_datum)) +} + +pub(crate) fn associated_ty_value_query( + db: &impl HirDatabase, + krate: CrateId, + id: chalk_rust_ir::AssociatedTyValueId, +) -> Arc> { + let data: AssocTyValue = from_chalk(db, id); + match data { + AssocTyValue::TypeAlias(type_alias) => { + type_alias_associated_ty_value(db, krate, type_alias) + } + AssocTyValue::ClosureFnTraitImplOutput(data) => { + closure_fn_trait_output_assoc_ty_value(db, krate, data) + } + } +} + +fn type_alias_associated_ty_value( + db: &impl HirDatabase, + _krate: CrateId, + type_alias: TypeAliasId, +) -> Arc> { + let type_alias_data = db.type_alias_data(type_alias); + let impl_id = match type_alias.lookup(db).container { + ContainerId::ImplId(it) => it, + _ => panic!("assoc ty value should be in impl"), + }; + + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + let target_trait = impl_data + .target_trait + .as_ref() + .and_then(|trait_ref| TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty))) + .expect("assoc ty value should not exist"); // we don't return any assoc ty values if the impl'd trait can't be resolved + + let assoc_ty = db + .trait_data(target_trait.trait_) + .associated_type_by_name(&type_alias_data.name) + .expect("assoc ty value should not exist"); // validated when building the impl data as well + let generic_params = db.generic_params(impl_id.into()); + let bound_vars = Substs::bound_vars(&generic_params); + let ty = db.ty(type_alias.into()).subst(&bound_vars); + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }; + let value = chalk_rust_ir::AssociatedTyValue { + impl_id: Impl::ImplBlock(impl_id.into()).to_chalk(db), + associated_ty_id: assoc_ty.to_chalk(db), + value: make_binders(value_bound, bound_vars.len()), + }; + Arc::new(value) +} + +fn closure_fn_trait_output_assoc_ty_value( + db: &impl HirDatabase, + krate: CrateId, + data: super::ClosureFnTraitImplData, +) -> Arc> { + let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); + + let num_args: u16 = match &db.body(data.def.into())[data.expr] { + Expr::Lambda { args, .. } => args.len() as u16, + _ => { + log::warn!("closure for closure type {:?} not found", data); + 0 + } + }; + + let output_ty = Ty::Bound(num_args.into()); + + let fn_once_trait = + get_fn_trait(db, krate, super::FnTrait::FnOnce).expect("assoc ty value should not exist"); + + let output_ty_id = db + .trait_data(fn_once_trait) + .associated_type_by_name(&name::OUTPUT_TYPE) + .expect("assoc ty value should not exist"); + + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }; + + let value = chalk_rust_ir::AssociatedTyValue { + associated_ty_id: output_ty_id.to_chalk(db), + impl_id, + value: make_binders(value_bound, num_args as usize + 1), + }; + Arc::new(value) +} + +fn get_fn_trait( + db: &impl HirDatabase, + krate: CrateId, + fn_trait: super::FnTrait, +) -> Option { + let target = db.lang_item(krate, fn_trait.lang_item_name().into())?; + match target { + LangItemTarget::TraitId(t) => Some(t), + _ => None, + } +} + +fn id_from_chalk(chalk_id: chalk_ir::RawId) -> T { + T::from_intern_id(InternId::from(chalk_id.index)) +} +fn id_to_chalk(salsa_id: T) -> chalk_ir::RawId { + chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } +} + +impl From for crate::TypeCtorId { + fn from(struct_id: chalk_ir::StructId) -> Self { + id_from_chalk(struct_id.0) + } +} + +impl From for chalk_ir::StructId { + fn from(type_ctor_id: crate::TypeCtorId) -> Self { + chalk_ir::StructId(id_to_chalk(type_ctor_id)) + } +} + +impl From for crate::traits::GlobalImplId { + fn from(impl_id: chalk_ir::ImplId) -> Self { + id_from_chalk(impl_id.0) + } +} + +impl From for chalk_ir::ImplId { + fn from(impl_id: crate::traits::GlobalImplId) -> Self { + chalk_ir::ImplId(id_to_chalk(impl_id)) + } +} + +impl From for crate::traits::AssocTyValueId { + fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self { + id_from_chalk(id.0) + } +} + +impl From for chalk_rust_ir::AssociatedTyValueId { + fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self { + chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id)) + } +} diff --git a/crates/ra_hir_ty/src/utils.rs b/crates/ra_hir_ty/src/utils.rs new file mode 100644 index 000000000..e4ba890ef --- /dev/null +++ b/crates/ra_hir_ty/src/utils.rs @@ -0,0 +1,84 @@ +//! Helper functions for working with def, which don't need to be a separate +//! query, but can't be computed directly from `*Data` (ie, which need a `db`). +use std::sync::Arc; + +use hir_def::{ + adt::VariantData, + db::DefDatabase, + resolver::{HasResolver, TypeNs}, + type_ref::TypeRef, + TraitId, TypeAliasId, VariantId, +}; +use hir_expand::name::{self, Name}; + +// FIXME: this is wrong, b/c it can't express `trait T: PartialEq<()>`. +// We should return a `TraitREf` here. +fn direct_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec { + let resolver = trait_.resolver(db); + // returning the iterator directly doesn't easily work because of + // lifetime problems, but since there usually shouldn't be more than a + // few direct traits this should be fine (we could even use some kind of + // SmallVec if performance is a concern) + db.generic_params(trait_.into()) + .where_predicates + .iter() + .filter_map(|pred| match &pred.type_ref { + TypeRef::Path(p) if p.as_ident() == Some(&name::SELF_TYPE) => pred.bound.as_path(), + _ => None, + }) + .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) { + Some(TypeNs::TraitId(t)) => Some(t), + _ => None, + }) + .collect() +} + +/// Returns an iterator over the whole super trait hierarchy (including the +/// trait itself). +pub(super) fn all_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec { + // we need to take care a bit here to avoid infinite loops in case of cycles + // (i.e. if we have `trait A: B; trait B: A;`) + let mut result = vec![trait_]; + let mut i = 0; + while i < result.len() { + let t = result[i]; + // yeah this is quadratic, but trait hierarchies should be flat + // enough that this doesn't matter + for tt in direct_super_traits(db, t) { + if !result.contains(&tt) { + result.push(tt); + } + } + i += 1; + } + result +} + +pub(super) fn associated_type_by_name_including_super_traits( + db: &impl DefDatabase, + trait_: TraitId, + name: &Name, +) -> Option { + all_super_traits(db, trait_) + .into_iter() + .find_map(|t| db.trait_data(t).associated_type_by_name(name)) +} + +pub(super) fn variant_data(db: &impl DefDatabase, var: VariantId) -> Arc { + match var { + VariantId::StructId(it) => db.struct_data(it).variant_data.clone(), + VariantId::UnionId(it) => db.union_data(it).variant_data.clone(), + VariantId::EnumVariantId(it) => { + db.enum_data(it.parent).variants[it.local_id].variant_data.clone() + } + } +} + +/// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices). +/// The underlying values are cloned if there are other strong references. +pub(crate) fn make_mut_slice(a: &mut Arc<[T]>) -> &mut [T] { + if Arc::get_mut(a).is_none() { + *a = a.iter().cloned().collect(); + } + Arc::get_mut(a).unwrap() +} -- cgit v1.2.3 From 47ec2ceb12df756b3482ddd2b1947e4b38f23706 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 21:23:31 +0300 Subject: prune deps --- crates/ra_hir_ty/Cargo.toml | 11 +++++------ crates/ra_hir_ty/src/test_db.rs | 12 +++++++----- 2 files changed, 12 insertions(+), 11 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml index 199afff49..429242870 100644 --- a/crates/ra_hir_ty/Cargo.toml +++ b/crates/ra_hir_ty/Cargo.toml @@ -9,18 +9,17 @@ doctest = false [dependencies] arrayvec = "0.5.1" +ena = "0.13" log = "0.4.5" rustc-hash = "1.0" -parking_lot = "0.10.0" -ena = "0.13" -ra_syntax = { path = "../ra_syntax" } +hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } +hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } ra_arena = { path = "../ra_arena" } ra_db = { path = "../ra_db" } -hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } -hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } -test_utils = { path = "../test_utils" } ra_prof = { path = "../ra_prof" } +ra_syntax = { path = "../ra_syntax" } +test_utils = { path = "../test_utils" } # https://github.com/rust-lang/chalk/pull/294 chalk-solve = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" } diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs index 0e51f4130..874357008 100644 --- a/crates/ra_hir_ty/src/test_db.rs +++ b/crates/ra_hir_ty/src/test_db.rs @@ -1,10 +1,12 @@ //! Database used for testing `hir`. -use std::{panic, sync::Arc}; +use std::{ + panic, + sync::{Arc, Mutex}, +}; use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId}; use hir_expand::diagnostics::DiagnosticSink; -use parking_lot::Mutex; use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; use crate::{db::HirDatabase, expr::ExprValidator}; @@ -33,7 +35,7 @@ impl salsa::Database for TestDB { } fn salsa_event(&self, event: impl Fn() -> salsa::Event) { - let mut events = self.events.lock(); + let mut events = self.events.lock().unwrap(); if let Some(events) = &mut *events { events.push(event()); } @@ -122,9 +124,9 @@ impl TestDB { impl TestDB { pub fn log(&self, f: impl FnOnce()) -> Vec> { - *self.events.lock() = Some(Vec::new()); + *self.events.lock().unwrap() = Some(Vec::new()); f(); - self.events.lock().take().unwrap() + self.events.lock().unwrap().take().unwrap() } pub fn log_executed(&self, f: impl FnOnce()) -> Vec { -- cgit v1.2.3 From d9a36a736bfb91578a36505e7237212959bb55fe Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 21:31:51 +0300 Subject: Rename module_id -> local_id --- crates/ra_hir_ty/src/test_db.rs | 4 ++-- crates/ra_hir_ty/src/tests.rs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs index 874357008..1dc9793f9 100644 --- a/crates/ra_hir_ty/src/test_db.rs +++ b/crates/ra_hir_ty/src/test_db.rs @@ -73,9 +73,9 @@ impl TestDB { pub fn module_for_file(&self, file_id: FileId) -> ModuleId { for &krate in self.relevant_crates(file_id).iter() { let crate_def_map = self.crate_def_map(krate); - for (module_id, data) in crate_def_map.modules.iter() { + for (local_id, data) in crate_def_map.modules.iter() { if data.definition == Some(file_id) { - return ModuleId { krate, module_id }; + return ModuleId { krate, local_id }; } } } diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs index c1744663a..c8461b447 100644 --- a/crates/ra_hir_ty/src/tests.rs +++ b/crates/ra_hir_ty/src/tests.rs @@ -4677,7 +4677,7 @@ fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { let module = db.module_for_file(pos.file_id); let crate_def_map = db.crate_def_map(module.krate); - for decl in crate_def_map[module.module_id].scope.declarations() { + for decl in crate_def_map[module.local_id].scope.declarations() { if let ModuleDefId::FunctionId(func) = decl { let (_body, source_map) = db.body_with_source_map(func.into()); if let Some(expr_id) = source_map.node_expr(Source::new(pos.file_id.into(), &expr)) { @@ -4753,7 +4753,7 @@ fn infer(content: &str) -> String { let crate_def_map = db.crate_def_map(module.krate); let mut defs: Vec = Vec::new(); - visit_module(&db, &crate_def_map, module.module_id, &mut |it| defs.push(it)); + visit_module(&db, &crate_def_map, module.local_id, &mut |it| defs.push(it)); defs.sort_by_key(|def| match def { DefWithBodyId::FunctionId(it) => { it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start() @@ -4796,7 +4796,7 @@ fn visit_module( } } } - ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.module_id, cb), + ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb), _ => (), } } @@ -4844,7 +4844,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() { let events = db.log_executed(|| { let module = db.module_for_file(pos.file_id); let crate_def_map = db.crate_def_map(module.krate); - visit_module(&db, &crate_def_map, module.module_id, &mut |def| { + visit_module(&db, &crate_def_map, module.local_id, &mut |def| { db.infer(def); }); }); @@ -4866,7 +4866,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() { let events = db.log_executed(|| { let module = db.module_for_file(pos.file_id); let crate_def_map = db.crate_def_map(module.krate); - visit_module(&db, &crate_def_map, module.module_id, &mut |def| { + visit_module(&db, &crate_def_map, module.local_id, &mut |def| { db.infer(def); }); }); -- cgit v1.2.3 From 8d3469682681d5b206d5ae31fc63fb97d9cedb3a Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 22:12:09 +0300 Subject: Memoize impl resolutions --- crates/ra_hir_ty/src/db.rs | 5 ++++- crates/ra_hir_ty/src/infer/coerce.rs | 22 ++++++------------- crates/ra_hir_ty/src/infer/path.rs | 10 ++++----- crates/ra_hir_ty/src/lib.rs | 15 +++++++++++++ crates/ra_hir_ty/src/lower.rs | 35 ++++++++++++++++++++----------- crates/ra_hir_ty/src/method_resolution.rs | 30 +++++++++----------------- crates/ra_hir_ty/src/traits/chalk.rs | 34 +++++++++++++----------------- 7 files changed, 76 insertions(+), 75 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs index aa2659c4b..9ce154593 100644 --- a/crates/ra_hir_ty/src/db.rs +++ b/crates/ra_hir_ty/src/db.rs @@ -11,7 +11,7 @@ use ra_db::{salsa, CrateId}; use crate::{ method_resolution::CrateImplBlocks, traits::{AssocTyValue, Impl}, - CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor, + CallableDef, FnSig, GenericPredicate, ImplTy, InferenceResult, Substs, Ty, TyDefId, TypeCtor, ValueTyDefId, }; @@ -27,6 +27,9 @@ pub trait HirDatabase: DefDatabase { #[salsa::invoke(crate::lower::value_ty_query)] fn value_ty(&self, def: ValueTyDefId) -> Ty; + #[salsa::invoke(crate::lower::impl_ty_query)] + fn impl_ty(&self, def: ImplId) -> ImplTy; + #[salsa::invoke(crate::lower::field_types_query)] fn field_types(&self, var: VariantId) -> Arc>; diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs index d66a21932..719a0f395 100644 --- a/crates/ra_hir_ty/src/infer/coerce.rs +++ b/crates/ra_hir_ty/src/infer/coerce.rs @@ -4,16 +4,11 @@ //! //! See: https://doc.rust-lang.org/nomicon/coercions.html -use hir_def::{ - lang_item::LangItemTarget, - resolver::{HasResolver, Resolver}, - type_ref::Mutability, - AdtId, -}; +use hir_def::{lang_item::LangItemTarget, resolver::Resolver, type_ref::Mutability, AdtId}; use rustc_hash::FxHashMap; use test_utils::tested_by; -use crate::{autoderef, db::HirDatabase, Substs, TraitRef, Ty, TypeCtor, TypeWalk}; +use crate::{autoderef, db::HirDatabase, ImplTy, Substs, Ty, TypeCtor, TypeWalk}; use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue}; @@ -59,17 +54,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { impls .iter() .filter_map(|&impl_id| { - let impl_data = db.impl_data(impl_id); - let resolver = impl_id.resolver(db); - let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + let trait_ref = match db.impl_ty(impl_id) { + ImplTy::TraitRef(it) => it, + ImplTy::Inherent(_) => return None, + }; // `CoerseUnsized` has one generic parameter for the target type. - let trait_ref = TraitRef::from_hir( - db, - &resolver, - impl_data.target_trait.as_ref()?, - Some(target_ty), - )?; let cur_from_ty = trait_ref.substs.0.get(0)?; let cur_to_ty = trait_ref.substs.0.get(1)?; diff --git a/crates/ra_hir_ty/src/infer/path.rs b/crates/ra_hir_ty/src/infer/path.rs index e6676e1aa..14be66836 100644 --- a/crates/ra_hir_ty/src/infer/path.rs +++ b/crates/ra_hir_ty/src/infer/path.rs @@ -2,7 +2,7 @@ use hir_def::{ path::{Path, PathKind, PathSegment}, - resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, + resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs}, AssocItemId, ContainerId, Lookup, }; use hir_expand::name::Name; @@ -244,17 +244,15 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { ContainerId::ImplId(it) => it, _ => return None, }; - let resolver = impl_id.resolver(self.db); - let impl_data = self.db.impl_data(impl_id); - let impl_block = Ty::from_hir(self.db, &resolver, &impl_data.target_type); - let impl_block_substs = impl_block.substs()?; + let self_ty = self.db.impl_ty(impl_id).self_type().clone(); + let self_ty_substs = self_ty.substs()?; let actual_substs = actual_def_ty.substs()?; let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; // The following code *link up* the function actual parma type // and impl_block type param index - impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { + self_ty_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { if let Ty::Param { idx, .. } = param { if let Some(s) = new_substs.get_mut(*idx as usize) { *s = pty.clone(); diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index f25846326..c9ee34008 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -486,6 +486,21 @@ impl TypeWalk for TraitRef { } } +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum ImplTy { + Inherent(Ty), + TraitRef(TraitRef), +} + +impl ImplTy { + pub(crate) fn self_type(&self) -> &Ty { + match self { + ImplTy::Inherent(it) => it, + ImplTy::TraitRef(tr) => &tr.substs[0], + } + } +} + /// Like `generics::WherePredicate`, but with resolved types: A condition on the /// parameters of a generic item. #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs index 53d955a12..f8331d257 100644 --- a/crates/ra_hir_ty/src/lower.rs +++ b/crates/ra_hir_ty/src/lower.rs @@ -14,21 +14,21 @@ use hir_def::{ path::{GenericArg, Path, PathKind, PathSegment}, resolver::{HasResolver, Resolver, TypeNs}, type_ref::{TypeBound, TypeRef}, - AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, + AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, ImplId, LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, }; use ra_arena::map::ArenaMap; use ra_db::CrateId; -use super::{ - FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, - Ty, TypeCtor, TypeWalk, -}; use crate::{ db::HirDatabase, primitive::{FloatTy, IntTy}, - utils::make_mut_slice, - utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data}, + utils::{ + all_super_traits, associated_type_by_name_including_super_traits, make_mut_slice, + variant_data, + }, + FnSig, GenericPredicate, ImplTy, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, + TraitRef, Ty, TypeCtor, TypeWalk, }; impl Ty { @@ -179,11 +179,7 @@ impl Ty { let name = resolved_segment.name.clone(); Ty::Param { idx, name } } - TypeNs::SelfType(impl_id) => { - let impl_data = db.impl_data(impl_id); - let resolver = impl_id.resolver(db); - Ty::from_hir(db, &resolver, &impl_data.target_type) - } + TypeNs::SelfType(impl_id) => db.impl_ty(impl_id).self_type().clone(), TypeNs::AdtSelfType(adt) => db.ty(adt.into()), TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), @@ -751,3 +747,18 @@ pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty { ValueTyDefId::StaticId(it) => type_for_static(db, it), } } + +pub(crate) fn impl_ty_query(db: &impl HirDatabase, impl_id: ImplId) -> ImplTy { + let impl_data = db.impl_data(impl_id); + let resolver = impl_id.resolver(db); + let self_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); + match impl_data.target_trait.as_ref() { + Some(trait_ref) => { + match TraitRef::from_hir(db, &resolver, trait_ref, Some(self_ty.clone())) { + Some(it) => ImplTy::TraitRef(it), + None => ImplTy::Inherent(self_ty), + } + } + None => ImplTy::Inherent(self_ty), + } +} diff --git a/crates/ra_hir_ty/src/method_resolution.rs b/crates/ra_hir_ty/src/method_resolution.rs index 53c541eb8..ee1936b0e 100644 --- a/crates/ra_hir_ty/src/method_resolution.rs +++ b/crates/ra_hir_ty/src/method_resolution.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use arrayvec::ArrayVec; use hir_def::{ - lang_item::LangItemTarget, resolver::HasResolver, resolver::Resolver, type_ref::Mutability, - AssocItemId, AstItemDef, FunctionId, HasModule, ImplId, TraitId, + lang_item::LangItemTarget, resolver::Resolver, type_ref::Mutability, AssocItemId, AstItemDef, + FunctionId, HasModule, ImplId, TraitId, }; use hir_expand::name::Name; use ra_db::CrateId; @@ -15,14 +15,13 @@ use ra_prof::profile; use rustc_hash::FxHashMap; use crate::{ + autoderef, db::HirDatabase, primitive::{FloatBitness, Uncertain}, utils::all_super_traits, - Ty, TypeCtor, + Canonical, ImplTy, InEnvironment, TraitEnvironment, TraitRef, Ty, TypeCtor, }; -use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef}; - /// This is used as a key for indexing impls. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum TyFingerprint { @@ -59,22 +58,13 @@ impl CrateImplBlocks { let crate_def_map = db.crate_def_map(krate); for (_module_id, module_data) in crate_def_map.modules.iter() { for &impl_id in module_data.impls.iter() { - let impl_data = db.impl_data(impl_id); - let resolver = impl_id.resolver(db); - - let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); - - match &impl_data.target_trait { - Some(trait_ref) => { - if let Some(tr) = - TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty)) - { - res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); - } + match db.impl_ty(impl_id) { + ImplTy::TraitRef(tr) => { + res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); } - None => { - if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { - res.impls.entry(target_ty_fp).or_default().push(impl_id); + ImplTy::Inherent(self_ty) => { + if let Some(self_ty_fp) = TyFingerprint::for_impl(&self_ty) { + res.impls.entry(self_ty_fp).or_default().push(impl_id); } } } diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs index 810e8c21a..35de37e6b 100644 --- a/crates/ra_hir_ty/src/traits/chalk.rs +++ b/crates/ra_hir_ty/src/traits/chalk.rs @@ -11,8 +11,8 @@ use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum use ra_db::CrateId; use hir_def::{ - expr::Expr, lang_item::LangItemTarget, resolver::HasResolver, AssocItemId, AstItemDef, - ContainerId, GenericDefId, ImplId, Lookup, TraitId, TypeAliasId, + expr::Expr, lang_item::LangItemTarget, AssocItemId, AstItemDef, ContainerId, GenericDefId, + ImplId, Lookup, TraitId, TypeAliasId, }; use hir_expand::name; @@ -20,9 +20,8 @@ use ra_db::salsa::{InternId, InternKey}; use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; use crate::{ - db::HirDatabase, - display::HirDisplay, - {ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, + db::HirDatabase, display::HirDisplay, ApplicationTy, GenericPredicate, ImplTy, ProjectionTy, + Substs, TraitRef, Ty, TypeCtor, TypeWalk, }; /// This represents a trait whose name we could not resolve. @@ -631,13 +630,11 @@ fn impl_block_datum( chalk_id: chalk_ir::ImplId, impl_id: ImplId, ) -> Option>> { + let trait_ref = match db.impl_ty(impl_id) { + ImplTy::TraitRef(it) => it, + ImplTy::Inherent(_) => return None, + }; let impl_data = db.impl_data(impl_id); - let resolver = impl_id.resolver(db); - let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); - - // `CoerseUnsized` has one generic parameter for the target type. - let trait_ref = - TraitRef::from_hir(db, &resolver, impl_data.target_trait.as_ref()?, Some(target_ty))?; let generic_params = db.generic_params(impl_id.into()); let bound_vars = Substs::bound_vars(&generic_params); @@ -790,17 +787,14 @@ fn type_alias_associated_ty_value( _ => panic!("assoc ty value should be in impl"), }; - let impl_data = db.impl_data(impl_id); - let resolver = impl_id.resolver(db); - let target_ty = Ty::from_hir(db, &resolver, &impl_data.target_type); - let target_trait = impl_data - .target_trait - .as_ref() - .and_then(|trait_ref| TraitRef::from_hir(db, &resolver, &trait_ref, Some(target_ty))) - .expect("assoc ty value should not exist"); // we don't return any assoc ty values if the impl'd trait can't be resolved + let trait_ref = match db.impl_ty(impl_id) { + ImplTy::TraitRef(it) => it, + // we don't return any assoc ty values if the impl'd trait can't be resolved + ImplTy::Inherent(_) => panic!("assoc ty value should not exist"), + }; let assoc_ty = db - .trait_data(target_trait.trait_) + .trait_data(trait_ref.trait_) .associated_type_by_name(&type_alias_data.name) .expect("assoc ty value should not exist"); // validated when building the impl data as well let generic_params = db.generic_params(impl_id.into()); -- cgit v1.2.3 From 04735abfaec30461252aecde10bb1d0d344728f1 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 22:21:01 +0300 Subject: Minimize API --- crates/ra_hir_ty/src/lower.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs index f8331d257..091c60f4f 100644 --- a/crates/ra_hir_ty/src/lower.rs +++ b/crates/ra_hir_ty/src/lower.rs @@ -363,7 +363,7 @@ pub(super) fn substs_from_path_segment( } impl TraitRef { - pub(crate) fn from_path( + fn from_path( db: &impl HirDatabase, resolver: &Resolver, path: &Path, @@ -377,7 +377,7 @@ impl TraitRef { Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) } - pub(super) fn from_resolved_path( + pub(crate) fn from_resolved_path( db: &impl HirDatabase, resolver: &Resolver, resolved: TraitId, @@ -391,7 +391,7 @@ impl TraitRef { TraitRef { trait_: resolved, substs } } - pub(crate) fn from_hir( + fn from_hir( db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef, @@ -415,11 +415,6 @@ impl TraitRef { substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) } - pub fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef { - let substs = Substs::identity(&db.generic_params(trait_.into())); - TraitRef { trait_, substs } - } - pub(crate) fn from_type_bound( db: &impl HirDatabase, resolver: &Resolver, -- cgit v1.2.3 From 1d14fd17372b42c3343daf6adc9a520fdf5e9810 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 27 Nov 2019 23:22:20 +0300 Subject: Use Name::missing consistently --- crates/ra_hir_ty/src/lib.rs | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index c9ee34008..b45c8f82f 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -901,12 +901,10 @@ impl HirDisplay for ApplicationTy { let sig = f.db.callable_item_signature(def); let name = match def { CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), - CallableDef::StructId(s) => { - f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing) - } + CallableDef::StructId(s) => f.db.struct_data(s).name.clone(), CallableDef::EnumVariantId(e) => { let enum_data = f.db.enum_data(e.parent); - enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing) + enum_data.variants[e.local_id].name.clone() } }; match def { @@ -929,8 +927,7 @@ impl HirDisplay for ApplicationTy { AdtId::StructId(it) => f.db.struct_data(it).name.clone(), AdtId::UnionId(it) => f.db.union_data(it).name.clone(), AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), - } - .unwrap_or_else(Name::missing); + }; write!(f, "{}", name)?; if self.parameters.len() > 0 { write!(f, "<")?; @@ -943,7 +940,7 @@ impl HirDisplay for ApplicationTy { ContainerId::TraitId(it) => it, _ => panic!("not an associated type"), }; - let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing); + let trait_name = f.db.trait_data(trait_).name.clone(); let name = f.db.type_alias_data(type_alias).name.clone(); write!(f, "{}::{}", trait_name, name)?; if self.parameters.len() > 0 { @@ -971,8 +968,7 @@ impl HirDisplay for ProjectionTy { return write!(f, "…"); } - let trait_name = - f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing); + let trait_name = f.db.trait_data(self.trait_(f.db)).name.clone(); write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; if self.parameters.len() > 1 { write!(f, "<")?; @@ -1021,14 +1017,7 @@ impl HirDisplay for Ty { // We assume that the self type is $0 (i.e. the // existential) here, which is the only thing that's // possible in actual Rust, and hence don't print it - write!( - f, - "{}", - f.db.trait_data(trait_ref.trait_) - .name - .clone() - .unwrap_or_else(Name::missing) - )?; + write!(f, "{}", f.db.trait_data(trait_ref.trait_).name.clone())?; if trait_ref.substs.len() > 1 { write!(f, "<")?; f.write_joined(&trait_ref.substs[1..], ", ")?; @@ -1088,7 +1077,7 @@ impl TraitRef { } else { write!(f, ": ")?; } - write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?; + write!(f, "{}", f.db.trait_data(self.trait_).name.clone())?; if self.substs.len() > 1 { write!(f, "<")?; f.write_joined(&self.substs[1..], ", ")?; -- cgit v1.2.3