3050: Refactor type parameters, implement argument position impl trait r=matklad a=flodiebold

I wanted to implement APIT by lowering to type parameters because we need to do that anyway for correctness and don't need Chalk support for it; this grew into some more wide-ranging refactoring of how type parameters are handled 😅 

 - use Ty::Bound instead of Ty::Param to represent polymorphism, and explicitly
   count binders. This gets us closer to Chalk's way of doing things, and means
   that we now only use Param as a placeholder for an unknown type, e.g. within
   a generic function. I.e. we're never using Param in a situation where we want
   to substitute it, and the method to do that is gone; `subst` now always works
   on bound variables. (This changes how the types of generic functions print; 
   previously, you'd get something like `fn identity<i32>(T) -> T`, but now we
   display the substituted signature `fn identity<i32>(i32) -> i32`, which I think 
   makes more sense.)
 - once we do this, it's more natural to represent `Param` by a globally unique
   ID; the use of indices was mostly to make substituting easier. This also
   means we fix the bug where `Param` loses its name when going through Chalk.
 - I would actually like to rename `Param` to `Placeholder` to better reflect its use and
   get closer to Chalk, but I'll leave that to a follow-up.
 - introduce a context for type lowering, to allow lowering `impl Trait` to
   different things depending on where we are. And since we have that, we can
   also lower type parameters directly to variables instead of placeholders.
   Also, we'll be able to use this later to collect diagnostics.
 - implement argument position impl trait by lowering it to type parameters.
   I've realized that this is necessary to correctly implement it; e.g. consider
   `fn foo(impl Display) -> impl Something`. It's observable that the return
   type of e.g. `foo(1u32)` unifies with itself, but doesn't unify with e.g.
   `foo(1i32)`; so the return type needs to be parameterized by the argument
   type.

   
This fixes a few bugs as well:
 - type parameters 'losing' their name when they go through Chalk, as mentioned
   above (i.e. getting `[missing name]` somewhere)
 - impl trait not being considered as implementing the super traits (very
   noticeable for the `db` in RA)
 - the fact that argument impl trait was only turned into variables when the
   function got called caused type mismatches when the function was used as a
   value (fixes a few type mismatches in RA)

The one thing I'm not so happy with here is how we're lowering `impl Trait` types to variables; since `TypeRef`s don't have an identity currently, we just count how many of them we have seen while going through the function signature. That's quite fragile though, since we have to do it while desugaring generics and while lowering the type signature, and in the exact same order in both cases. We could consider either giving only `TypeRef::ImplTrait` a local id, or maybe just giving all `TypeRef`s an identity after all (we talked about this before)...

Follow-up tasks:
 - handle return position impl trait; we basically need to create a variable and some trait obligations for that variable
 - rename `Param` to `Placeholder`

Co-authored-by: Florian Diebold <florian.diebold@freiheit.com>
Co-authored-by: Florian Diebold <flodiebold@gmail.com>
This commit is contained in:
bors[bot] 2020-02-09 11:35:08 +00:00 committed by GitHub
commit 01836a0f35
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 1173 additions and 613 deletions

View file

@ -1,5 +1,5 @@
use format_buf::format; use format_buf::format;
use hir::InFile; use hir::{Adt, InFile};
use join_to_string::join; use join_to_string::join;
use ra_syntax::{ use ra_syntax::{
ast::{ ast::{
@ -135,16 +135,22 @@ fn find_struct_impl(ctx: &AssistCtx, strukt: &ast::StructDef) -> Option<Option<a
})?; })?;
let mut sb = ctx.source_binder(); let mut sb = ctx.source_binder();
let struct_ty = { let struct_def = {
let src = InFile { file_id: ctx.frange.file_id.into(), value: strukt.clone() }; let src = InFile { file_id: ctx.frange.file_id.into(), value: strukt.clone() };
sb.to_def(src)?.ty(db) sb.to_def(src)?
}; };
let block = module.descendants().filter_map(ast::ImplBlock::cast).find_map(|impl_blk| { let block = module.descendants().filter_map(ast::ImplBlock::cast).find_map(|impl_blk| {
let src = InFile { file_id: ctx.frange.file_id.into(), value: impl_blk.clone() }; let src = InFile { file_id: ctx.frange.file_id.into(), value: impl_blk.clone() };
let blk = sb.to_def(src)?; let blk = sb.to_def(src)?;
let same_ty = blk.target_ty(db) == struct_ty; // FIXME: handle e.g. `struct S<T>; impl<U> S<U> {}`
// (we currently use the wrong type parameter)
// also we wouldn't want to use e.g. `impl S<u32>`
let same_ty = match blk.target_ty(db).as_adt() {
Some(def) => def == Adt::Struct(struct_def),
None => false,
};
let not_trait_impl = blk.target_trait(db).is_none(); let not_trait_impl = blk.target_trait(db).is_none();
if !(same_ty && not_trait_impl) { if !(same_ty && not_trait_impl) {

View file

@ -10,9 +10,9 @@ use hir_def::{
per_ns::PerNs, per_ns::PerNs,
resolver::HasResolver, resolver::HasResolver,
type_ref::{Mutability, TypeRef}, type_ref::{Mutability, TypeRef},
AdtId, ConstId, DefWithBodyId, EnumId, FunctionId, HasModule, ImplId, LocalEnumVariantId, AdtId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId,
LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId, LocalEnumVariantId, LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId,
TypeParamId, UnionId, TraitId, TypeAliasId, TypeParamId, UnionId,
}; };
use hir_expand::{ use hir_expand::{
diagnostics::DiagnosticSink, diagnostics::DiagnosticSink,
@ -21,7 +21,7 @@ use hir_expand::{
}; };
use hir_ty::{ use hir_ty::{
autoderef, display::HirFormatter, expr::ExprValidator, method_resolution, ApplicationTy, autoderef, display::HirFormatter, expr::ExprValidator, method_resolution, ApplicationTy,
Canonical, InEnvironment, TraitEnvironment, Ty, TyDefId, TypeCtor, TypeWalk, Canonical, InEnvironment, Substs, TraitEnvironment, Ty, TyDefId, TypeCtor,
}; };
use ra_db::{CrateId, Edition, FileId}; use ra_db::{CrateId, Edition, FileId};
use ra_prof::profile; use ra_prof::profile;
@ -270,7 +270,13 @@ impl StructField {
pub fn ty(&self, db: &impl HirDatabase) -> Type { pub fn ty(&self, db: &impl HirDatabase) -> Type {
let var_id = self.parent.into(); let var_id = self.parent.into();
let ty = db.field_types(var_id)[self.id].clone(); let generic_def_id: GenericDefId = match self.parent {
VariantDef::Struct(it) => it.id.into(),
VariantDef::Union(it) => it.id.into(),
VariantDef::EnumVariant(it) => it.parent.id.into(),
};
let substs = Substs::type_params(db, generic_def_id);
let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
Type::new(db, self.parent.module(db).id.krate.into(), var_id, ty) Type::new(db, self.parent.module(db).id.krate.into(), var_id, ty)
} }
@ -755,7 +761,7 @@ pub struct TypeParam {
impl TypeParam { impl TypeParam {
pub fn name(self, db: &impl HirDatabase) -> Name { pub fn name(self, db: &impl HirDatabase) -> Name {
let params = db.generic_params(self.id.parent); let params = db.generic_params(self.id.parent);
params.types[self.id.local_id].name.clone() params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
} }
pub fn module(self, db: &impl HirDatabase) -> Module { pub fn module(self, db: &impl HirDatabase) -> Module {
@ -789,8 +795,9 @@ impl ImplBlock {
pub fn target_ty(&self, db: &impl HirDatabase) -> Type { pub fn target_ty(&self, db: &impl HirDatabase) -> Type {
let impl_data = db.impl_data(self.id); let impl_data = db.impl_data(self.id);
let resolver = self.id.resolver(db); let resolver = self.id.resolver(db);
let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
let environment = TraitEnvironment::lower(db, &resolver); let environment = TraitEnvironment::lower(db, &resolver);
let ty = Ty::from_hir(db, &resolver, &impl_data.target_type); let ty = Ty::from_hir(&ctx, &impl_data.target_type);
Type { Type {
krate: self.id.lookup(db).container.module(db).krate, krate: self.id.lookup(db).container.module(db).krate,
ty: InEnvironment { value: ty, environment }, ty: InEnvironment { value: ty, environment },
@ -851,9 +858,10 @@ impl Type {
fn from_def( fn from_def(
db: &impl HirDatabase, db: &impl HirDatabase,
krate: CrateId, krate: CrateId,
def: impl HasResolver + Into<TyDefId>, def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
) -> Type { ) -> Type {
let ty = db.ty(def.into()); let substs = Substs::type_params(db, def);
let ty = db.ty(def.into()).subst(&substs);
Type::new(db, krate, def, ty) Type::new(db, krate, def, ty)
} }
@ -950,7 +958,7 @@ impl Type {
match a_ty.ctor { match a_ty.ctor {
TypeCtor::Tuple { .. } => { TypeCtor::Tuple { .. } => {
for ty in a_ty.parameters.iter() { for ty in a_ty.parameters.iter() {
let ty = ty.clone().subst(&a_ty.parameters); let ty = ty.clone();
res.push(self.derived(ty)); res.push(self.derived(ty));
} }
} }

View file

@ -178,6 +178,10 @@ impl SourceAnalyzer {
} }
} }
fn trait_env(&self, db: &impl HirDatabase) -> Arc<TraitEnvironment> {
TraitEnvironment::lower(db, &self.resolver)
}
pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> { pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> {
let expr_id = if let Some(expr) = self.expand_expr(db, InFile::new(self.file_id, expr)) { let expr_id = if let Some(expr) = self.expand_expr(db, InFile::new(self.file_id, expr)) {
self.body_source_map.as_ref()?.node_expr(expr.as_ref())? self.body_source_map.as_ref()?.node_expr(expr.as_ref())?
@ -186,14 +190,14 @@ impl SourceAnalyzer {
}; };
let ty = self.infer.as_ref()?[expr_id].clone(); let ty = self.infer.as_ref()?[expr_id].clone();
let environment = TraitEnvironment::lower(db, &self.resolver); let environment = self.trait_env(db);
Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
} }
pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> { pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> {
let pat_id = self.pat_id(pat)?; let pat_id = self.pat_id(pat)?;
let ty = self.infer.as_ref()?[pat_id].clone(); let ty = self.infer.as_ref()?[pat_id].clone();
let environment = TraitEnvironment::lower(db, &self.resolver); let environment = self.trait_env(db);
Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } })
} }

View file

@ -27,8 +27,16 @@ use crate::{
/// Data about a generic parameter (to a function, struct, impl, ...). /// Data about a generic parameter (to a function, struct, impl, ...).
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug)]
pub struct TypeParamData { pub struct TypeParamData {
pub name: Name, pub name: Option<Name>,
pub default: Option<TypeRef>, pub default: Option<TypeRef>,
pub provenance: TypeParamProvenance,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TypeParamProvenance {
TypeParamList,
TraitSelf,
ArgumentImplTrait,
} }
/// Data about the generic parameters of a function, struct, impl, etc. /// Data about the generic parameters of a function, struct, impl, etc.
@ -45,10 +53,17 @@ pub struct GenericParams {
/// associated type bindings like `Iterator<Item = u32>`. /// associated type bindings like `Iterator<Item = u32>`.
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug)]
pub struct WherePredicate { pub struct WherePredicate {
pub type_ref: TypeRef, pub target: WherePredicateTarget,
pub bound: TypeBound, pub bound: TypeBound,
} }
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum WherePredicateTarget {
TypeRef(TypeRef),
/// For desugared where predicates that can directly refer to a type param.
TypeParam(LocalTypeParamId),
}
type SourceMap = ArenaMap<LocalTypeParamId, Either<ast::TraitDef, ast::TypeParam>>; type SourceMap = ArenaMap<LocalTypeParamId, Either<ast::TraitDef, ast::TypeParam>>;
impl GenericParams { impl GenericParams {
@ -68,6 +83,11 @@ impl GenericParams {
GenericDefId::FunctionId(it) => { GenericDefId::FunctionId(it) => {
let src = it.lookup(db).source(db); let src = it.lookup(db).source(db);
generics.fill(&mut sm, &src.value); generics.fill(&mut sm, &src.value);
// lower `impl Trait` in arguments
let data = db.function_data(it);
for param in &data.params {
generics.fill_implicit_impl_trait_args(param);
}
src.file_id src.file_id
} }
GenericDefId::AdtId(AdtId::StructId(it)) => { GenericDefId::AdtId(AdtId::StructId(it)) => {
@ -89,8 +109,11 @@ impl GenericParams {
let src = it.lookup(db).source(db); let src = it.lookup(db).source(db);
// traits get the Self type as an implicit first type parameter // traits get the Self type as an implicit first type parameter
let self_param_id = let self_param_id = generics.types.alloc(TypeParamData {
generics.types.alloc(TypeParamData { name: name![Self], default: None }); name: Some(name![Self]),
default: None,
provenance: TypeParamProvenance::TraitSelf,
});
sm.insert(self_param_id, Either::Left(src.value.clone())); sm.insert(self_param_id, Either::Left(src.value.clone()));
// add super traits as bounds on Self // add super traits as bounds on Self
// i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
@ -142,7 +165,11 @@ impl GenericParams {
let name = type_param.name().map_or_else(Name::missing, |it| it.as_name()); let name = type_param.name().map_or_else(Name::missing, |it| it.as_name());
// FIXME: Use `Path::from_src` // FIXME: Use `Path::from_src`
let default = type_param.default_type().map(TypeRef::from_ast); let default = type_param.default_type().map(TypeRef::from_ast);
let param = TypeParamData { name: name.clone(), default }; let param = TypeParamData {
name: Some(name.clone()),
default,
provenance: TypeParamProvenance::TypeParamList,
};
let param_id = self.types.alloc(param); let param_id = self.types.alloc(param);
sm.insert(param_id, Either::Right(type_param.clone())); sm.insert(param_id, Either::Right(type_param.clone()));
@ -170,11 +197,43 @@ impl GenericParams {
return; return;
} }
let bound = TypeBound::from_ast(bound); let bound = TypeBound::from_ast(bound);
self.where_predicates.push(WherePredicate { type_ref, bound }); self.where_predicates
.push(WherePredicate { target: WherePredicateTarget::TypeRef(type_ref), bound });
}
fn fill_implicit_impl_trait_args(&mut self, type_ref: &TypeRef) {
type_ref.walk(&mut |type_ref| {
if let TypeRef::ImplTrait(bounds) = type_ref {
let param = TypeParamData {
name: None,
default: None,
provenance: TypeParamProvenance::ArgumentImplTrait,
};
let param_id = self.types.alloc(param);
for bound in bounds {
self.where_predicates.push(WherePredicate {
target: WherePredicateTarget::TypeParam(param_id),
bound: bound.clone(),
});
}
}
});
} }
pub fn find_by_name(&self, name: &Name) -> Option<LocalTypeParamId> { pub fn find_by_name(&self, name: &Name) -> Option<LocalTypeParamId> {
self.types.iter().find_map(|(id, p)| if &p.name == name { Some(id) } else { None }) self.types
.iter()
.find_map(|(id, p)| if p.name.as_ref() == Some(name) { Some(id) } else { None })
}
pub fn find_trait_self_param(&self) -> Option<LocalTypeParamId> {
self.types.iter().find_map(|(id, p)| {
if p.provenance == TypeParamProvenance::TraitSelf {
Some(id)
} else {
None
}
})
} }
} }

View file

@ -490,12 +490,14 @@ impl Scope {
} }
Scope::GenericParams { params, def } => { Scope::GenericParams { params, def } => {
for (local_id, param) in params.types.iter() { for (local_id, param) in params.types.iter() {
if let Some(name) = &param.name {
f( f(
param.name.clone(), name.clone(),
ScopeDef::GenericParam(TypeParamId { local_id, parent: *def }), ScopeDef::GenericParam(TypeParamId { local_id, parent: *def }),
) )
} }
} }
}
Scope::ImplBlockScope(i) => { Scope::ImplBlockScope(i) => {
f(name![Self], ScopeDef::ImplSelfType((*i).into())); f(name![Self], ScopeDef::ImplSelfType((*i).into()));
} }

View file

@ -124,6 +124,48 @@ impl TypeRef {
pub(crate) fn unit() -> TypeRef { pub(crate) fn unit() -> TypeRef {
TypeRef::Tuple(Vec::new()) TypeRef::Tuple(Vec::new())
} }
pub fn walk(&self, f: &mut impl FnMut(&TypeRef)) {
go(self, f);
fn go(type_ref: &TypeRef, f: &mut impl FnMut(&TypeRef)) {
f(type_ref);
match type_ref {
TypeRef::Fn(types) | TypeRef::Tuple(types) => types.iter().for_each(|t| go(t, f)),
TypeRef::RawPtr(type_ref, _)
| TypeRef::Reference(type_ref, _)
| TypeRef::Array(type_ref)
| TypeRef::Slice(type_ref) => go(&type_ref, f),
TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => {
for bound in bounds {
match bound {
TypeBound::Path(path) => go_path(path, f),
TypeBound::Error => (),
}
}
}
TypeRef::Path(path) => go_path(path, f),
TypeRef::Never | TypeRef::Placeholder | TypeRef::Error => {}
};
}
fn go_path(path: &Path, f: &mut impl FnMut(&TypeRef)) {
if let Some(type_ref) = path.type_anchor() {
go(type_ref, f);
}
for segment in path.segments().iter() {
if let Some(args_and_bindings) = segment.args_and_bindings {
for arg in &args_and_bindings.args {
let crate::path::GenericArg::Type(type_ref) = arg;
go(type_ref, f);
}
for (_, type_ref) in &args_and_bindings.bindings {
go(type_ref, f);
}
}
}
}
}
} }
pub(crate) fn type_bounds_from_ast(type_bounds_opt: Option<ast::TypeBoundList>) -> Vec<TypeBound> { pub(crate) fn type_bounds_from_ast(type_bounds_opt: Option<ast::TypeBoundList>) -> Vec<TypeBound> {

View file

@ -3,17 +3,18 @@
use std::sync::Arc; use std::sync::Arc;
use hir_def::{ use hir_def::{
db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId, db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, TypeParamId,
VariantId,
}; };
use ra_arena::map::ArenaMap; use ra_arena::map::ArenaMap;
use ra_db::{salsa, CrateId}; use ra_db::{impl_intern_key, salsa, CrateId};
use ra_prof::profile; use ra_prof::profile;
use crate::{ use crate::{
method_resolution::CrateImplBlocks, method_resolution::CrateImplBlocks,
traits::{chalk, AssocTyValue, Impl}, traits::{chalk, AssocTyValue, Impl},
CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, TraitRef, Ty, TyDefId, TypeCtor, Binders, CallableDef, GenericPredicate, InferenceResult, PolyFnSig, Substs, TraitRef, Ty,
ValueTyDefId, TyDefId, TypeCtor, ValueTyDefId,
}; };
#[salsa::query_group(HirDatabaseStorage)] #[salsa::query_group(HirDatabaseStorage)]
@ -27,34 +28,33 @@ pub trait HirDatabase: DefDatabase {
#[salsa::invoke(crate::lower::ty_query)] #[salsa::invoke(crate::lower::ty_query)]
#[salsa::cycle(crate::lower::ty_recover)] #[salsa::cycle(crate::lower::ty_recover)]
fn ty(&self, def: TyDefId) -> Ty; fn ty(&self, def: TyDefId) -> Binders<Ty>;
#[salsa::invoke(crate::lower::value_ty_query)] #[salsa::invoke(crate::lower::value_ty_query)]
fn value_ty(&self, def: ValueTyDefId) -> Ty; fn value_ty(&self, def: ValueTyDefId) -> Binders<Ty>;
#[salsa::invoke(crate::lower::impl_self_ty_query)] #[salsa::invoke(crate::lower::impl_self_ty_query)]
#[salsa::cycle(crate::lower::impl_self_ty_recover)] #[salsa::cycle(crate::lower::impl_self_ty_recover)]
fn impl_self_ty(&self, def: ImplId) -> Ty; fn impl_self_ty(&self, def: ImplId) -> Binders<Ty>;
#[salsa::invoke(crate::lower::impl_trait_query)] #[salsa::invoke(crate::lower::impl_trait_query)]
fn impl_trait(&self, def: ImplId) -> Option<TraitRef>; fn impl_trait(&self, def: ImplId) -> Option<Binders<TraitRef>>;
#[salsa::invoke(crate::lower::field_types_query)] #[salsa::invoke(crate::lower::field_types_query)]
fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>; fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Binders<Ty>>>;
#[salsa::invoke(crate::callable_item_sig)] #[salsa::invoke(crate::callable_item_sig)]
fn callable_item_signature(&self, def: CallableDef) -> FnSig; fn callable_item_signature(&self, def: CallableDef) -> PolyFnSig;
#[salsa::invoke(crate::lower::generic_predicates_for_param_query)] #[salsa::invoke(crate::lower::generic_predicates_for_param_query)]
#[salsa::cycle(crate::lower::generic_predicates_for_param_recover)] #[salsa::cycle(crate::lower::generic_predicates_for_param_recover)]
fn generic_predicates_for_param( fn generic_predicates_for_param(
&self, &self,
def: GenericDefId, param_id: TypeParamId,
param_idx: u32, ) -> Arc<[Binders<GenericPredicate>]>;
) -> Arc<[GenericPredicate]>;
#[salsa::invoke(crate::lower::generic_predicates_query)] #[salsa::invoke(crate::lower::generic_predicates_query)]
fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>; fn generic_predicates(&self, def: GenericDefId) -> Arc<[Binders<GenericPredicate>]>;
#[salsa::invoke(crate::lower::generic_defaults_query)] #[salsa::invoke(crate::lower::generic_defaults_query)]
fn generic_defaults(&self, def: GenericDefId) -> Substs; fn generic_defaults(&self, def: GenericDefId) -> Substs;
@ -77,6 +77,8 @@ pub trait HirDatabase: DefDatabase {
#[salsa::interned] #[salsa::interned]
fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId; fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
#[salsa::interned] #[salsa::interned]
fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId;
#[salsa::interned]
fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId; fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
#[salsa::interned] #[salsa::interned]
fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId; fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
@ -117,3 +119,7 @@ fn infer(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
fn hir_database_is_object_safe() { fn hir_database_is_object_safe() {
fn _assert_object_safe(_: &dyn HirDatabase) {} fn _assert_object_safe(_: &dyn HirDatabase) {}
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlobalTypeParamId(salsa::InternId);
impl_intern_key!(GlobalTypeParamId);

View file

@ -34,7 +34,6 @@ use hir_expand::{diagnostics::DiagnosticSink, name::name};
use ra_arena::map::ArenaMap; use ra_arena::map::ArenaMap;
use ra_prof::profile; use ra_prof::profile;
use ra_syntax::SmolStr; use ra_syntax::SmolStr;
use test_utils::tested_by;
use super::{ use super::{
primitive::{FloatTy, IntTy}, primitive::{FloatTy, IntTy},
@ -42,7 +41,9 @@ use super::{
ApplicationTy, GenericPredicate, InEnvironment, ProjectionTy, Substs, TraitEnvironment, ApplicationTy, GenericPredicate, InEnvironment, ProjectionTy, Substs, TraitEnvironment,
TraitRef, Ty, TypeCtor, TypeWalk, Uncertain, TraitRef, Ty, TypeCtor, TypeWalk, Uncertain,
}; };
use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic}; use crate::{
db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode,
};
pub(crate) use unify::unify; pub(crate) use unify::unify;
@ -271,38 +272,21 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.result.diagnostics.push(diagnostic); self.result.diagnostics.push(diagnostic);
} }
fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { fn make_ty_with_mode(
let ty = Ty::from_hir( &mut self,
self.db, type_ref: &TypeRef,
impl_trait_mode: ImplTraitLoweringMode,
) -> Ty {
// FIXME use right resolver for block // FIXME use right resolver for block
&self.resolver, let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
type_ref, .with_impl_trait_mode(impl_trait_mode);
); let ty = Ty::from_hir(&ctx, type_ref);
let ty = self.insert_type_vars(ty); let ty = self.insert_type_vars(ty);
self.normalize_associated_types_in(ty) self.normalize_associated_types_in(ty)
} }
/// Replaces `impl Trait` in `ty` by type variables and obligations for fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
/// those variables. This is done for function arguments when calling a self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
/// function, and for return types when inside the function body, i.e. in
/// the cases where the `impl Trait` is 'transparent'. In other cases, `impl
/// Trait` is represented by `Ty::Opaque`.
fn insert_vars_for_impl_trait(&mut self, ty: Ty) -> Ty {
ty.fold(&mut |ty| match ty {
Ty::Opaque(preds) => {
tested_by!(insert_vars_for_impl_trait);
let var = self.table.new_type_var();
let var_subst = Substs::builder(1).push(var.clone()).build();
self.obligations.extend(
preds
.iter()
.map(|pred| pred.clone().subst_bound_vars(&var_subst))
.filter_map(Obligation::from_predicate),
);
var
}
_ => ty,
})
} }
/// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it.
@ -446,19 +430,20 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
None => return (Ty::Unknown, None), None => return (Ty::Unknown, None),
}; };
let resolver = &self.resolver; let resolver = &self.resolver;
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
// FIXME: this should resolve assoc items as well, see this example: // FIXME: this should resolve assoc items as well, see this example:
// https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) { match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
Some(TypeNs::AdtId(AdtId::StructId(strukt))) => { Some(TypeNs::AdtId(AdtId::StructId(strukt))) => {
let substs = Ty::substs_from_path(self.db, resolver, path, strukt.into()); let substs = Ty::substs_from_path(&ctx, path, strukt.into());
let ty = self.db.ty(strukt.into()); let ty = self.db.ty(strukt.into());
let ty = self.insert_type_vars(ty.apply_substs(substs)); let ty = self.insert_type_vars(ty.subst(&substs));
(ty, Some(strukt.into())) (ty, Some(strukt.into()))
} }
Some(TypeNs::EnumVariantId(var)) => { Some(TypeNs::EnumVariantId(var)) => {
let substs = Ty::substs_from_path(self.db, resolver, path, var.into()); let substs = Ty::substs_from_path(&ctx, path, var.into());
let ty = self.db.ty(var.parent.into()); let ty = self.db.ty(var.parent.into());
let ty = self.insert_type_vars(ty.apply_substs(substs)); let ty = self.insert_type_vars(ty.subst(&substs));
(ty, Some(var.into())) (ty, Some(var.into()))
} }
Some(_) | None => (Ty::Unknown, None), Some(_) | None => (Ty::Unknown, None),
@ -471,13 +456,18 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
fn collect_fn(&mut self, data: &FunctionData) { fn collect_fn(&mut self, data: &FunctionData) {
let body = Arc::clone(&self.body); // avoid borrow checker problem let body = Arc::clone(&self.body); // avoid borrow checker problem
for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
let ty = self.make_ty(type_ref); .with_impl_trait_mode(ImplTraitLoweringMode::Param);
let param_tys =
data.params.iter().map(|type_ref| Ty::from_hir(&ctx, type_ref)).collect::<Vec<_>>();
for (ty, pat) in param_tys.into_iter().zip(body.params.iter()) {
let ty = self.insert_type_vars(ty);
let ty = self.normalize_associated_types_in(ty);
self.infer_pat(*pat, &ty, BindingMode::default()); self.infer_pat(*pat, &ty, BindingMode::default());
} }
let return_ty = self.make_ty(&data.ret_type); let return_ty = self.make_ty_with_mode(&data.ret_type, ImplTraitLoweringMode::Disallowed); // FIXME implement RPIT
self.return_ty = self.insert_vars_for_impl_trait(return_ty); self.return_ty = return_ty;
} }
fn infer_body(&mut self) { fn infer_body(&mut self) {

View file

@ -57,8 +57,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
let trait_ref = db.impl_trait(impl_id)?; let trait_ref = db.impl_trait(impl_id)?;
// `CoerseUnsized` has one generic parameter for the target type. // `CoerseUnsized` has one generic parameter for the target type.
let cur_from_ty = trait_ref.substs.0.get(0)?; let cur_from_ty = trait_ref.value.substs.0.get(0)?;
let cur_to_ty = trait_ref.substs.0.get(1)?; let cur_to_ty = trait_ref.value.substs.0.get(1)?;
match (&cur_from_ty, cur_to_ty) { match (&cur_from_ty, cur_to_ty) {
(ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => {
@ -66,9 +66,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
// This works for smart-pointer-like coercion, which covers all impls from std. // This works for smart-pointer-like coercion, which covers all impls from std.
st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| {
match (ty1, ty2) { match (ty1, ty2) {
(Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) (Ty::Bound(idx1), Ty::Bound(idx2)) if idx1 != idx2 => {
if p1 != p2 =>
{
Some(((*ctor1, *ctor2), i)) Some(((*ctor1, *ctor2), i))
} }
_ => None, _ => None,
@ -256,8 +254,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
let unsize_generic_index = { let unsize_generic_index = {
let mut index = None; let mut index = None;
let mut multiple_param = false; let mut multiple_param = false;
field_tys[last_field_id].walk(&mut |ty| match ty { field_tys[last_field_id].value.walk(&mut |ty| match ty {
&Ty::Param { idx, .. } => { &Ty::Bound(idx) => {
if index.is_none() { if index.is_none() {
index = Some(idx); index = Some(idx);
} else if Some(idx) != index { } else if Some(idx) != index {
@ -276,10 +274,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
// Check other fields do not involve it. // Check other fields do not involve it.
let mut multiple_used = false; let mut multiple_used = false;
fields.for_each(|(field_id, _data)| { fields.for_each(|(field_id, _data)| {
field_tys[field_id].walk(&mut |ty| match ty { field_tys[field_id].value.walk(&mut |ty| match ty {
&Ty::Param { idx, .. } if idx == unsize_generic_index => { &Ty::Bound(idx) if idx == unsize_generic_index => multiple_used = true,
multiple_used = true
}
_ => {} _ => {}
}) })
}); });

View file

@ -10,7 +10,7 @@ use hir_def::{
resolver::resolver_for_expr, resolver::resolver_for_expr,
AdtId, AssocContainerId, Lookup, StructFieldId, AdtId, AssocContainerId, Lookup, StructFieldId,
}; };
use hir_expand::name::{name, Name}; use hir_expand::name::Name;
use ra_syntax::ast::RangeOp; use ra_syntax::ast::RangeOp;
use crate::{ use crate::{
@ -19,8 +19,8 @@ use crate::{
method_resolution, op, method_resolution, op,
traits::InEnvironment, traits::InEnvironment,
utils::{generics, variant_data, Generics}, utils::{generics, variant_data, Generics},
ApplicationTy, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef, Ty, ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef,
TypeCtor, TypeWalk, Uncertain, Ty, TypeCtor, Uncertain,
}; };
use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
@ -236,8 +236,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.result.record_field_resolutions.insert(field.expr, field_def); self.result.record_field_resolutions.insert(field.expr, field_def);
} }
let field_ty = field_def let field_ty = field_def
.map_or(Ty::Unknown, |it| field_types[it.local_id].clone()) .map_or(Ty::Unknown, |it| field_types[it.local_id].clone().subst(&substs));
.subst(&substs);
self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
} }
if let Some(expr) = spread { if let Some(expr) = spread {
@ -588,10 +587,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
self.write_method_resolution(tgt_expr, func); self.write_method_resolution(tgt_expr, func);
(ty, self.db.value_ty(func.into()), Some(generics(self.db, func.into()))) (ty, self.db.value_ty(func.into()), Some(generics(self.db, func.into())))
} }
None => (receiver_ty, Ty::Unknown, None), None => (receiver_ty, Binders::new(0, Ty::Unknown), None),
}; };
let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); 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 = method_ty.subst(&substs);
let method_ty = self.insert_type_vars(method_ty); let method_ty = self.insert_type_vars(method_ty);
self.register_obligations_for_call(&method_ty); self.register_obligations_for_call(&method_ty);
let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
@ -635,7 +634,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
continue; continue;
} }
let param_ty = self.insert_vars_for_impl_trait(param_ty);
let param_ty = self.normalize_associated_types_in(param_ty); let param_ty = self.normalize_associated_types_in(param_ty);
self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone()));
} }
@ -648,13 +646,15 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
generic_args: Option<&GenericArgs>, generic_args: Option<&GenericArgs>,
receiver_ty: &Ty, receiver_ty: &Ty,
) -> Substs { ) -> Substs {
let (total_len, _parent_len, child_len) = let (parent_params, self_params, type_params, impl_trait_params) =
def_generics.as_ref().map_or((0, 0, 0), |g| g.len_split()); def_generics.as_ref().map_or((0, 0, 0, 0), |g| g.provenance_split());
assert_eq!(self_params, 0); // method shouldn't have another Self param
let total_len = parent_params + type_params + impl_trait_params;
let mut substs = Vec::with_capacity(total_len); let mut substs = Vec::with_capacity(total_len);
// Parent arguments are unknown, except for the receiver type // Parent arguments are unknown, except for the receiver type
if let Some(parent_generics) = def_generics.as_ref().map(|p| p.iter_parent()) { if let Some(parent_generics) = def_generics.as_ref().map(|p| p.iter_parent()) {
for (_id, param) in parent_generics { for (_id, param) in parent_generics {
if param.name == name![Self] { if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
substs.push(receiver_ty.clone()); substs.push(receiver_ty.clone());
} else { } else {
substs.push(Ty::Unknown); substs.push(Ty::Unknown);
@ -664,7 +664,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
// handle provided type arguments // handle provided type arguments
if let Some(generic_args) = generic_args { if let Some(generic_args) = generic_args {
// if args are provided, it should be all of them, but we can't rely on that // 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(child_len) { for arg in generic_args.args.iter().take(type_params) {
match arg { match arg {
GenericArg::Type(type_ref) => { GenericArg::Type(type_ref) => {
let ty = self.make_ty(type_ref); let ty = self.make_ty(type_ref);

View file

@ -12,7 +12,7 @@ use hir_expand::name::Name;
use test_utils::tested_by; use test_utils::tested_by;
use super::{BindingMode, InferenceContext}; use super::{BindingMode, InferenceContext};
use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk}; use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor};
impl<'a, D: HirDatabase> InferenceContext<'a, D> { impl<'a, D: HirDatabase> InferenceContext<'a, D> {
fn infer_tuple_struct_pat( fn infer_tuple_struct_pat(
@ -34,8 +34,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
let expected_ty = var_data let expected_ty = var_data
.as_ref() .as_ref()
.and_then(|d| d.field(&Name::new_tuple_field(i))) .and_then(|d| d.field(&Name::new_tuple_field(i)))
.map_or(Ty::Unknown, |field| field_tys[field].clone()) .map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs));
.subst(&substs);
let expected_ty = self.normalize_associated_types_in(expected_ty); let expected_ty = self.normalize_associated_types_in(expected_ty);
self.infer_pat(subpat, &expected_ty, default_bm); self.infer_pat(subpat, &expected_ty, default_bm);
} }
@ -65,7 +64,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
for subpat in subpats { for subpat in subpats {
let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name)); let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name));
let expected_ty = let expected_ty =
matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs); matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs));
let expected_ty = self.normalize_associated_types_in(expected_ty); let expected_ty = self.normalize_associated_types_in(expected_ty);
self.infer_pat(subpat.pat, &expected_ty, default_bm); self.infer_pat(subpat.pat, &expected_ty, default_bm);
} }

View file

@ -9,9 +9,9 @@ use hir_def::{
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use crate::{db::HirDatabase, method_resolution, Substs, Ty, TypeWalk, ValueTyDefId}; use crate::{db::HirDatabase, method_resolution, Substs, Ty, ValueTyDefId};
use super::{ExprOrPatId, InferenceContext, TraitEnvironment, TraitRef}; use super::{ExprOrPatId, InferenceContext, TraitRef};
impl<'a, D: HirDatabase> InferenceContext<'a, D> { impl<'a, D: HirDatabase> InferenceContext<'a, D> {
pub(super) fn infer_path( pub(super) fn infer_path(
@ -39,7 +39,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
} }
let ty = self.make_ty(type_ref); let ty = self.make_ty(type_ref);
let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1); let remaining_segments_for_ty = path.segments().take(path.segments().len() - 1);
let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); let ctx = crate::lower::TyLoweringContext::new(self.db, &resolver);
let ty = Ty::from_type_relative_path(&ctx, ty, remaining_segments_for_ty);
self.resolve_ty_assoc_item( self.resolve_ty_assoc_item(
ty, ty,
&path.segments().last().expect("path had at least one segment").name, &path.segments().last().expect("path had at least one segment").name,
@ -69,12 +70,16 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
ValueNs::EnumVariantId(it) => it.into(), ValueNs::EnumVariantId(it) => it.into(),
}; };
let mut ty = self.db.value_ty(typable); let ty = self.db.value_ty(typable);
if let Some(self_subst) = self_subst { // self_subst is just for the parent
ty = ty.subst(&self_subst); let parent_substs = self_subst.unwrap_or_else(Substs::empty);
} let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); let substs = Ty::substs_from_path(&ctx, path, typable);
let ty = ty.subst(&substs); let full_substs = Substs::builder(substs.len())
.use_parent_substs(&parent_substs)
.fill(substs.0[parent_substs.len()..].iter().cloned())
.build();
let ty = ty.subst(&full_substs);
Some(ty) Some(ty)
} }
@ -98,13 +103,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
(TypeNs::TraitId(trait_), true) => { (TypeNs::TraitId(trait_), true) => {
let segment = let segment =
remaining_segments.last().expect("there should be at least one segment here"); remaining_segments.last().expect("there should be at least one segment here");
let trait_ref = TraitRef::from_resolved_path( let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
self.db, let trait_ref =
&self.resolver, TraitRef::from_resolved_path(&ctx, trait_.into(), resolved_segment, None);
trait_.into(),
resolved_segment,
None,
);
self.resolve_trait_assoc_item(trait_ref, segment, id) self.resolve_trait_assoc_item(trait_ref, segment, id)
} }
(def, _) => { (def, _) => {
@ -114,9 +115,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
// as Iterator>::Item::default`) // as Iterator>::Item::default`)
let remaining_segments_for_ty = let remaining_segments_for_ty =
remaining_segments.take(remaining_segments.len() - 1); remaining_segments.take(remaining_segments.len() - 1);
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
let ty = Ty::from_partly_resolved_hir_path( let ty = Ty::from_partly_resolved_hir_path(
self.db, &ctx,
&self.resolver,
def, def,
resolved_segment, resolved_segment,
remaining_segments_for_ty, remaining_segments_for_ty,
@ -173,13 +174,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
AssocItemId::ConstId(c) => ValueNs::ConstId(c), AssocItemId::ConstId(c) => ValueNs::ConstId(c),
AssocItemId::TypeAliasId(_) => unreachable!(), 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); self.write_assoc_resolution(id, item);
Some((def, Some(substs))) Some((def, Some(trait_ref.substs)))
} }
fn resolve_ty_assoc_item( fn resolve_ty_assoc_item(
@ -193,14 +190,13 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
} }
let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone());
let env = TraitEnvironment::lower(self.db, &self.resolver);
let krate = self.resolver.krate()?; let krate = self.resolver.krate()?;
let traits_in_scope = self.resolver.traits_in_scope(self.db); let traits_in_scope = self.resolver.traits_in_scope(self.db);
method_resolution::iterate_method_candidates( method_resolution::iterate_method_candidates(
&canonical_ty.value, &canonical_ty.value,
self.db, self.db,
env, self.trait_env.clone(),
krate, krate,
&traits_in_scope, &traits_in_scope,
Some(name), Some(name),
@ -219,12 +215,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
.fill(iter::repeat_with(|| self.table.new_type_var())) .fill(iter::repeat_with(|| self.table.new_type_var()))
.build(); .build();
let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs); let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs);
let substs = Substs::build_for_def(self.db, item)
.use_parent_substs(&impl_substs)
.fill_with_params()
.build();
self.unify(&impl_self_ty, &ty); self.unify(&impl_self_ty, &ty);
Some(substs) Some(impl_substs)
} }
AssocContainerId::TraitId(trait_) => { AssocContainerId::TraitId(trait_) => {
// we're picking this method // we're picking this method
@ -232,15 +224,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
.push(ty.clone()) .push(ty.clone())
.fill(std::iter::repeat_with(|| self.table.new_type_var())) .fill(std::iter::repeat_with(|| self.table.new_type_var()))
.build(); .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 { self.obligations.push(super::Obligation::Trait(TraitRef {
trait_, trait_,
substs: trait_substs, substs: trait_substs.clone(),
})); }));
Some(substs) Some(trait_substs)
} }
AssocContainerId::ContainerId(_) => None, AssocContainerId::ContainerId(_) => None,
}; };

View file

@ -44,8 +44,8 @@ use std::sync::Arc;
use std::{fmt, iter, mem}; use std::{fmt, iter, mem};
use hir_def::{ use hir_def::{
expr::ExprId, type_ref::Mutability, AdtId, AssocContainerId, DefWithBodyId, GenericDefId, expr::ExprId, generics::TypeParamProvenance, type_ref::Mutability, AdtId, AssocContainerId,
HasModule, Lookup, TraitId, TypeAliasId, DefWithBodyId, GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, TypeParamId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use ra_db::{impl_intern_key, salsa, CrateId}; use ra_db::{impl_intern_key, salsa, CrateId};
@ -60,7 +60,9 @@ use display::{HirDisplay, HirFormatter};
pub use autoderef::autoderef; pub use autoderef::autoderef;
pub use infer::{do_infer_query, InferTy, InferenceResult}; pub use infer::{do_infer_query, InferTy, InferenceResult};
pub use lower::CallableDef; pub use lower::CallableDef;
pub use lower::{callable_item_sig, TyDefId, ValueTyDefId}; pub use lower::{
callable_item_sig, ImplTraitLoweringMode, TyDefId, TyLoweringContext, ValueTyDefId,
};
pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
/// A type constructor or type name: this might be something like the primitive /// A type constructor or type name: this might be something like the primitive
@ -285,22 +287,20 @@ pub enum Ty {
/// trait and all its parameters are fully known. /// trait and all its parameters are fully known.
Projection(ProjectionTy), Projection(ProjectionTy),
/// A type parameter; for example, `T` in `fn f<T>(x: T) {} /// A placeholder for a type parameter; for example, `T` in `fn f<T>(x: T)
Param { /// {}` when we're type-checking the body of that function. In this
/// The index of the parameter (starting with parameters from the /// situation, we know this stands for *some* type, but don't know the exact
/// surrounding impl, then the current function). /// type.
idx: u32, Param(TypeParamId),
/// 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 /// A bound type variable. This is used in various places: when representing
/// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. /// some polymorphic type like the type of function `fn f<T>`, the type
/// parameters get turned into variables; during trait resolution, inference
/// variables get turned into bound variables and back; and in `Dyn` the
/// `Self` type is represented with a bound variable as well.
Bound(u32), Bound(u32),
/// A type variable used during type checking. Not to be confused with a /// A type variable used during type checking.
/// type parameter.
Infer(InferTy), Infer(InferTy),
/// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust).
@ -364,15 +364,19 @@ impl Substs {
} }
/// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
pub(crate) fn identity(generic_params: &Generics) -> Substs { pub(crate) fn type_params_for_generics(generic_params: &Generics) -> Substs {
Substs( Substs(generic_params.iter().map(|(id, _)| Ty::Param(id)).collect())
generic_params.iter().map(|(idx, p)| Ty::Param { idx, name: p.name.clone() }).collect(), }
)
/// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
pub fn type_params(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> Substs {
let params = generics(db, def.into());
Substs::type_params_for_generics(&params)
} }
/// Return Substs that replace each parameter by a bound variable. /// Return Substs that replace each parameter by a bound variable.
pub(crate) fn bound_vars(generic_params: &Generics) -> Substs { pub(crate) fn bound_vars(generic_params: &Generics) -> Substs {
Substs(generic_params.iter().map(|(idx, _p)| Ty::Bound(idx)).collect()) Substs(generic_params.iter().enumerate().map(|(idx, _)| Ty::Bound(idx as u32)).collect())
} }
pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder { pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder {
@ -420,11 +424,6 @@ impl SubstsBuilder {
self.fill((starting_from..).map(Ty::Bound)) 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 { pub fn fill_with_unknown(self) -> Self {
self.fill(iter::repeat(Ty::Unknown)) self.fill(iter::repeat(Ty::Unknown))
} }
@ -451,6 +450,32 @@ impl Deref for Substs {
} }
} }
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Binders<T> {
pub num_binders: usize,
pub value: T,
}
impl<T> Binders<T> {
pub fn new(num_binders: usize, value: T) -> Self {
Self { num_binders, value }
}
}
impl<T: TypeWalk> Binders<T> {
/// Substitutes all variables.
pub fn subst(self, subst: &Substs) -> T {
assert_eq!(subst.len(), self.num_binders);
self.value.subst_bound_vars(subst)
}
/// Substitutes just a prefix of the variables (shifting the rest).
pub fn subst_prefix(self, subst: &Substs) -> Binders<T> {
assert!(subst.len() < self.num_binders);
Binders::new(self.num_binders - subst.len(), self.value.subst_bound_vars(subst))
}
}
/// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait.
/// Name to be bikeshedded: TraitBound? TraitImplements? /// Name to be bikeshedded: TraitBound? TraitImplements?
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug, Hash)]
@ -551,6 +576,9 @@ pub struct FnSig {
params_and_return: Arc<[Ty]>, params_and_return: Arc<[Ty]>,
} }
/// A polymorphic function signature.
pub type PolyFnSig = Binders<FnSig>;
impl FnSig { impl FnSig {
pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig { pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
params.push(ret); params.push(ret);
@ -730,22 +758,7 @@ pub trait TypeWalk {
self self
} }
/// Replaces type parameters in this type using the given `Substs`. (So e.g. /// Substitutes `Ty::Bound` vars with the given substitution.
/// 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 fn subst_bound_vars(mut self, substs: &Substs) -> Self
where where
Self: Sized, Self: Sized,
@ -755,6 +768,9 @@ pub trait TypeWalk {
&mut Ty::Bound(idx) => { &mut Ty::Bound(idx) => {
if idx as usize >= binders && (idx as usize - binders) < substs.len() { if idx as usize >= binders && (idx as usize - binders) < substs.len() {
*ty = substs.0[idx as usize - binders].clone(); *ty = substs.0[idx as usize - binders].clone();
} else if idx as usize >= binders + substs.len() {
// shift free binders
*ty = Ty::Bound(idx - substs.len() as u32);
} }
} }
_ => {} _ => {}
@ -880,7 +896,7 @@ impl HirDisplay for ApplicationTy {
write!(f, ") -> {}", sig.ret().display(f.db))?; write!(f, ") -> {}", sig.ret().display(f.db))?;
} }
TypeCtor::FnDef(def) => { TypeCtor::FnDef(def) => {
let sig = f.db.callable_item_signature(def); let sig = f.db.callable_item_signature(def).subst(&self.parameters);
let name = match def { let name = match def {
CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(),
CallableDef::StructId(s) => f.db.struct_data(s).name.clone(), CallableDef::StructId(s) => f.db.struct_data(s).name.clone(),
@ -896,10 +912,17 @@ impl HirDisplay for ApplicationTy {
} }
} }
if self.parameters.len() > 0 { if self.parameters.len() > 0 {
let generics = generics(f.db, def.into());
let (parent_params, self_param, type_params, _impl_trait_params) =
generics.provenance_split();
let total_len = parent_params + self_param + type_params;
// We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self?
if total_len > 0 {
write!(f, "<")?; write!(f, "<")?;
f.write_joined(&*self.parameters.0, ", ")?; f.write_joined(&self.parameters.0[..total_len], ", ")?;
write!(f, ">")?; write!(f, ">")?;
} }
}
write!(f, "(")?; write!(f, "(")?;
f.write_joined(sig.params(), ", ")?; f.write_joined(sig.params(), ", ")?;
write!(f, ") -> {}", sig.ret().display(f.db))?; write!(f, ") -> {}", sig.ret().display(f.db))?;
@ -1009,7 +1032,24 @@ impl HirDisplay for Ty {
match self { match self {
Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
Ty::Param { name, .. } => write!(f, "{}", name)?, Ty::Param(id) => {
let generics = generics(f.db, id.parent);
let param_data = &generics.params.types[id.local_id];
match param_data.provenance {
TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
write!(f, "{}", param_data.name.clone().unwrap_or_else(Name::missing))?
}
TypeParamProvenance::ArgumentImplTrait => {
write!(f, "impl ")?;
let bounds = f.db.generic_predicates_for_param(*id);
let substs = Substs::type_params_for_generics(&generics);
write_bounds_like_dyn_trait(
&bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(),
f,
)?;
}
}
}
Ty::Bound(idx) => write!(f, "?{}", idx)?, Ty::Bound(idx) => write!(f, "?{}", idx)?,
Ty::Dyn(predicates) | Ty::Opaque(predicates) => { Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
match self { match self {
@ -1017,6 +1057,19 @@ impl HirDisplay for Ty {
Ty::Opaque(_) => write!(f, "impl ")?, Ty::Opaque(_) => write!(f, "impl ")?,
_ => unreachable!(), _ => unreachable!(),
}; };
write_bounds_like_dyn_trait(&predicates, f)?;
}
Ty::Unknown => write!(f, "{{unknown}}")?,
Ty::Infer(..) => write!(f, "_")?,
}
Ok(())
}
}
fn write_bounds_like_dyn_trait(
predicates: &[GenericPredicate],
f: &mut HirFormatter<impl HirDatabase>,
) -> fmt::Result {
// Note: This code is written to produce nice results (i.e. // Note: This code is written to produce nice results (i.e.
// corresponding to surface Rust) for types that can occur in // corresponding to surface Rust) for types that can occur in
// actual Rust. It will have weird results if the predicates // actual Rust. It will have weird results if the predicates
@ -1055,9 +1108,7 @@ impl HirDisplay for Ty {
angle_open = true; angle_open = true;
} }
let name = let name =
f.db.type_alias_data(projection_pred.projection_ty.associated_ty) f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name.clone();
.name
.clone();
write!(f, "{} = ", name)?; write!(f, "{} = ", name)?;
projection_pred.ty.hir_fmt(f)?; projection_pred.ty.hir_fmt(f)?;
} }
@ -1077,13 +1128,8 @@ impl HirDisplay for Ty {
if angle_open { if angle_open {
write!(f, ">")?; write!(f, ">")?;
} }
}
Ty::Unknown => write!(f, "{{unknown}}")?,
Ty::Infer(..) => write!(f, "_")?,
}
Ok(()) Ok(())
} }
}
impl TraitRef { impl TraitRef {
fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {

View file

@ -10,12 +10,13 @@ use std::sync::Arc;
use hir_def::{ use hir_def::{
builtin_type::BuiltinType, builtin_type::BuiltinType,
generics::WherePredicate, generics::{TypeParamProvenance, WherePredicate, WherePredicateTarget},
path::{GenericArg, Path, PathSegment, PathSegments}, path::{GenericArg, Path, PathSegment, PathSegments},
resolver::{HasResolver, Resolver, TypeNs}, resolver::{HasResolver, Resolver, TypeNs},
type_ref::{TypeBound, TypeRef}, type_ref::{TypeBound, TypeRef},
AdtId, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, ImplId, AdtId, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, ImplId,
LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, LocalStructFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId,
VariantId,
}; };
use ra_arena::map::ArenaMap; use ra_arena::map::ArenaMap;
use ra_db::CrateId; use ra_db::CrateId;
@ -27,64 +28,159 @@ use crate::{
all_super_traits, associated_type_by_name_including_super_traits, generics, make_mut_slice, all_super_traits, associated_type_by_name_including_super_traits, generics, make_mut_slice,
variant_data, variant_data,
}, },
FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef, Binders, FnSig, GenericPredicate, PolyFnSig, ProjectionPredicate, ProjectionTy, Substs,
Ty, TypeCtor, TypeWalk, TraitEnvironment, TraitRef, Ty, TypeCtor,
}; };
#[derive(Debug)]
pub struct TyLoweringContext<'a, DB: HirDatabase> {
pub db: &'a DB,
pub resolver: &'a Resolver,
/// Note: Conceptually, it's thinkable that we could be in a location where
/// some type params should be represented as placeholders, and others
/// should be converted to variables. I think in practice, this isn't
/// possible currently, so this should be fine for now.
pub type_param_mode: TypeParamLoweringMode,
pub impl_trait_mode: ImplTraitLoweringMode,
pub impl_trait_counter: std::cell::Cell<u16>,
}
impl<'a, DB: HirDatabase> TyLoweringContext<'a, DB> {
pub fn new(db: &'a DB, resolver: &'a Resolver) -> Self {
let impl_trait_counter = std::cell::Cell::new(0);
let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
let type_param_mode = TypeParamLoweringMode::Placeholder;
Self { db, resolver, impl_trait_mode, impl_trait_counter, type_param_mode }
}
pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
Self { impl_trait_mode, ..self }
}
pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
Self { type_param_mode, ..self }
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ImplTraitLoweringMode {
/// `impl Trait` gets lowered into an opaque type that doesn't unify with
/// anything except itself. This is used in places where values flow 'out',
/// i.e. for arguments of the function we're currently checking, and return
/// types of functions we're calling.
Opaque,
/// `impl Trait` gets lowered into a type variable. Used for argument
/// position impl Trait when inside the respective function, since it allows
/// us to support that without Chalk.
Param,
/// `impl Trait` gets lowered into a variable that can unify with some
/// type. This is used in places where values flow 'in', i.e. for arguments
/// of functions we're calling, and the return type of the function we're
/// currently checking.
Variable,
/// `impl Trait` is disallowed and will be an error.
Disallowed,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TypeParamLoweringMode {
Placeholder,
Variable,
}
impl Ty { impl Ty {
pub fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { pub fn from_hir(ctx: &TyLoweringContext<'_, impl HirDatabase>, type_ref: &TypeRef) -> Self {
match type_ref { match type_ref {
TypeRef::Never => Ty::simple(TypeCtor::Never), TypeRef::Never => Ty::simple(TypeCtor::Never),
TypeRef::Tuple(inner) => { TypeRef::Tuple(inner) => {
let inner_tys: Arc<[Ty]> = let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| Ty::from_hir(ctx, tr)).collect();
inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect();
Ty::apply( Ty::apply(
TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, TypeCtor::Tuple { cardinality: inner_tys.len() as u16 },
Substs(inner_tys), Substs(inner_tys),
) )
} }
TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), TypeRef::Path(path) => Ty::from_hir_path(ctx, path),
TypeRef::RawPtr(inner, mutability) => { TypeRef::RawPtr(inner, mutability) => {
let inner_ty = Ty::from_hir(db, resolver, inner); let inner_ty = Ty::from_hir(ctx, inner);
Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty)
} }
TypeRef::Array(inner) => { TypeRef::Array(inner) => {
let inner_ty = Ty::from_hir(db, resolver, inner); let inner_ty = Ty::from_hir(ctx, inner);
Ty::apply_one(TypeCtor::Array, inner_ty) Ty::apply_one(TypeCtor::Array, inner_ty)
} }
TypeRef::Slice(inner) => { TypeRef::Slice(inner) => {
let inner_ty = Ty::from_hir(db, resolver, inner); let inner_ty = Ty::from_hir(ctx, inner);
Ty::apply_one(TypeCtor::Slice, inner_ty) Ty::apply_one(TypeCtor::Slice, inner_ty)
} }
TypeRef::Reference(inner, mutability) => { TypeRef::Reference(inner, mutability) => {
let inner_ty = Ty::from_hir(db, resolver, inner); let inner_ty = Ty::from_hir(ctx, inner);
Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty)
} }
TypeRef::Placeholder => Ty::Unknown, TypeRef::Placeholder => Ty::Unknown,
TypeRef::Fn(params) => { TypeRef::Fn(params) => {
let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); let sig = Substs(params.iter().map(|tr| Ty::from_hir(ctx, tr)).collect());
Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig)
} }
TypeRef::DynTrait(bounds) => { TypeRef::DynTrait(bounds) => {
let self_ty = Ty::Bound(0); let self_ty = Ty::Bound(0);
let predicates = bounds let predicates = bounds
.iter() .iter()
.flat_map(|b| { .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone())
})
.collect(); .collect();
Ty::Dyn(predicates) Ty::Dyn(predicates)
} }
TypeRef::ImplTrait(bounds) => { TypeRef::ImplTrait(bounds) => {
match ctx.impl_trait_mode {
ImplTraitLoweringMode::Opaque => {
let self_ty = Ty::Bound(0); let self_ty = Ty::Bound(0);
let predicates = bounds let predicates = bounds
.iter() .iter()
.flat_map(|b| { .flat_map(|b| {
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) GenericPredicate::from_type_bound(ctx, b, self_ty.clone())
}) })
.collect(); .collect();
Ty::Opaque(predicates) Ty::Opaque(predicates)
} }
ImplTraitLoweringMode::Param => {
let idx = ctx.impl_trait_counter.get();
ctx.impl_trait_counter.set(idx + 1);
if let Some(def) = ctx.resolver.generic_def() {
let generics = generics(ctx.db, def);
let param = generics
.iter()
.filter(|(_, data)| {
data.provenance == TypeParamProvenance::ArgumentImplTrait
})
.nth(idx as usize)
.map_or(Ty::Unknown, |(id, _)| Ty::Param(id));
param
} else {
Ty::Unknown
}
}
ImplTraitLoweringMode::Variable => {
let idx = ctx.impl_trait_counter.get();
ctx.impl_trait_counter.set(idx + 1);
let (parent_params, self_params, list_params, _impl_trait_params) =
if let Some(def) = ctx.resolver.generic_def() {
let generics = generics(ctx.db, def);
generics.provenance_split()
} else {
(0, 0, 0, 0)
};
Ty::Bound(
idx as u32
+ parent_params as u32
+ self_params as u32
+ list_params as u32,
)
}
ImplTraitLoweringMode::Disallowed => {
// FIXME: report error
Ty::Unknown
}
}
}
TypeRef::Error => Ty::Unknown, TypeRef::Error => Ty::Unknown,
} }
} }
@ -93,10 +189,9 @@ impl Ty {
/// lower the self types of the predicates since that could lead to cycles. /// 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. /// So we just check here if the `type_ref` resolves to a generic param, and which.
fn from_hir_only_param( fn from_hir_only_param(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
type_ref: &TypeRef, type_ref: &TypeRef,
) -> Option<u32> { ) -> Option<TypeParamId> {
let path = match type_ref { let path = match type_ref {
TypeRef::Path(path) => path, TypeRef::Path(path) => path,
_ => return None, _ => return None,
@ -107,29 +202,26 @@ impl Ty {
if path.segments().len() > 1 { if path.segments().len() > 1 {
return None; return None;
} }
let resolution = match resolver.resolve_path_in_type_ns(db, path.mod_path()) { let resolution = match ctx.resolver.resolve_path_in_type_ns(ctx.db, path.mod_path()) {
Some((it, None)) => it, Some((it, None)) => it,
_ => return None, _ => return None,
}; };
if let TypeNs::GenericParam(param_id) = resolution { if let TypeNs::GenericParam(param_id) = resolution {
let generics = generics(db, resolver.generic_def().expect("generics in scope")); Some(param_id)
let idx = generics.param_idx(param_id);
Some(idx)
} else { } else {
None None
} }
} }
pub(crate) fn from_type_relative_path( pub(crate) fn from_type_relative_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
ty: Ty, ty: Ty,
remaining_segments: PathSegments<'_>, remaining_segments: PathSegments<'_>,
) -> Ty { ) -> Ty {
if remaining_segments.len() == 1 { if remaining_segments.len() == 1 {
// resolve unselected assoc types // resolve unselected assoc types
let segment = remaining_segments.first().unwrap(); let segment = remaining_segments.first().unwrap();
Ty::select_associated_type(db, resolver, ty, segment) Ty::select_associated_type(ctx, ty, segment)
} else if remaining_segments.len() > 1 { } else if remaining_segments.len() > 1 {
// FIXME report error (ambiguous associated type) // FIXME report error (ambiguous associated type)
Ty::Unknown Ty::Unknown
@ -139,20 +231,18 @@ impl Ty {
} }
pub(crate) fn from_partly_resolved_hir_path( pub(crate) fn from_partly_resolved_hir_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
resolution: TypeNs, resolution: TypeNs,
resolved_segment: PathSegment<'_>, resolved_segment: PathSegment<'_>,
remaining_segments: PathSegments<'_>, remaining_segments: PathSegments<'_>,
) -> Ty { ) -> Ty {
let ty = match resolution { let ty = match resolution {
TypeNs::TraitId(trait_) => { TypeNs::TraitId(trait_) => {
let trait_ref = let trait_ref = TraitRef::from_resolved_path(ctx, trait_, resolved_segment, None);
TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None);
return if remaining_segments.len() == 1 { return if remaining_segments.len() == 1 {
let segment = remaining_segments.first().unwrap(); let segment = remaining_segments.first().unwrap();
let associated_ty = associated_type_by_name_including_super_traits( let associated_ty = associated_type_by_name_including_super_traits(
db, ctx.db,
trait_ref.trait_, trait_ref.trait_,
&segment.name, &segment.name,
); );
@ -177,37 +267,55 @@ impl Ty {
}; };
} }
TypeNs::GenericParam(param_id) => { TypeNs::GenericParam(param_id) => {
let generics = generics(db, resolver.generic_def().expect("generics in scope")); let generics =
let idx = generics.param_idx(param_id); generics(ctx.db, ctx.resolver.generic_def().expect("generics in scope"));
// FIXME: maybe return name in resolution? match ctx.type_param_mode {
let name = generics.param_name(param_id); TypeParamLoweringMode::Placeholder => Ty::Param(param_id),
Ty::Param { idx, name } TypeParamLoweringMode::Variable => {
let idx = generics.param_idx(param_id).expect("matching generics");
Ty::Bound(idx)
}
}
}
TypeNs::SelfType(impl_id) => {
let generics = generics(ctx.db, impl_id.into());
let substs = match ctx.type_param_mode {
TypeParamLoweringMode::Placeholder => {
Substs::type_params_for_generics(&generics)
}
TypeParamLoweringMode::Variable => Substs::bound_vars(&generics),
};
ctx.db.impl_self_ty(impl_id).subst(&substs)
}
TypeNs::AdtSelfType(adt) => {
let generics = generics(ctx.db, adt.into());
let substs = match ctx.type_param_mode {
TypeParamLoweringMode::Placeholder => {
Substs::type_params_for_generics(&generics)
}
TypeParamLoweringMode::Variable => Substs::bound_vars(&generics),
};
ctx.db.ty(adt.into()).subst(&substs)
} }
TypeNs::SelfType(impl_id) => db.impl_self_ty(impl_id).clone(),
TypeNs::AdtSelfType(adt) => db.ty(adt.into()),
TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), TypeNs::AdtId(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
TypeNs::BuiltinType(it) => { TypeNs::BuiltinType(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) TypeNs::TypeAliasId(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
}
TypeNs::TypeAliasId(it) => {
Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into())
}
// FIXME: report error // FIXME: report error
TypeNs::EnumVariantId(_) => return Ty::Unknown, TypeNs::EnumVariantId(_) => return Ty::Unknown,
}; };
Ty::from_type_relative_path(db, resolver, ty, remaining_segments) Ty::from_type_relative_path(ctx, ty, remaining_segments)
} }
pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { pub(crate) fn from_hir_path(ctx: &TyLoweringContext<'_, impl HirDatabase>, path: &Path) -> Ty {
// Resolve the path (in type namespace) // Resolve the path (in type namespace)
if let Some(type_ref) = path.type_anchor() { if let Some(type_ref) = path.type_anchor() {
let ty = Ty::from_hir(db, resolver, &type_ref); let ty = Ty::from_hir(ctx, &type_ref);
return Ty::from_type_relative_path(db, resolver, ty, path.segments()); return Ty::from_type_relative_path(ctx, ty, path.segments());
} }
let (resolution, remaining_index) = let (resolution, remaining_index) =
match resolver.resolve_path_in_type_ns(db, path.mod_path()) { match ctx.resolver.resolve_path_in_type_ns(ctx.db, path.mod_path()) {
Some(it) => it, Some(it) => it,
None => return Ty::Unknown, None => return Ty::Unknown,
}; };
@ -218,39 +326,44 @@ impl Ty {
), ),
Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)), Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
}; };
Ty::from_partly_resolved_hir_path( Ty::from_partly_resolved_hir_path(ctx, resolution, resolved_segment, remaining_segments)
db,
resolver,
resolution,
resolved_segment,
remaining_segments,
)
} }
fn select_associated_type( fn select_associated_type(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
self_ty: Ty, self_ty: Ty,
segment: PathSegment<'_>, segment: PathSegment<'_>,
) -> Ty { ) -> Ty {
let param_idx = match self_ty { let def = match ctx.resolver.generic_def() {
Ty::Param { idx, .. } => idx,
_ => return Ty::Unknown, // Error: Ambiguous associated type
};
let def = match resolver.generic_def() {
Some(def) => def, Some(def) => def,
None => return Ty::Unknown, // this can't actually happen None => return Ty::Unknown, // this can't actually happen
}; };
let predicates = db.generic_predicates_for_param(def.into(), param_idx); let param_id = match self_ty {
let traits_from_env = predicates.iter().filter_map(|pred| match pred { Ty::Param(id) if ctx.type_param_mode == TypeParamLoweringMode::Placeholder => id,
GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), Ty::Bound(idx) if ctx.type_param_mode == TypeParamLoweringMode::Variable => {
let generics = generics(ctx.db, def);
let param_id = if let Some((id, _)) = generics.iter().nth(idx as usize) {
id
} else {
return Ty::Unknown;
};
param_id
}
_ => return Ty::Unknown, // Error: Ambiguous associated type
};
let predicates = ctx.db.generic_predicates_for_param(param_id);
let traits_from_env = predicates.iter().filter_map(|pred| match &pred.value {
GenericPredicate::Implemented(tr) => Some(tr.trait_),
_ => None, _ => None,
}); });
let traits = traits_from_env.flat_map(|t| all_super_traits(db, t)); let traits = traits_from_env.flat_map(|t| all_super_traits(ctx.db, t));
for t in traits { for t in traits {
if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) { if let Some(associated_ty) = ctx.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(); let substs = Substs::build_for_def(ctx.db, t)
.push(self_ty.clone())
.fill_with_unknown()
.build();
// FIXME handle type parameters on the segment // FIXME handle type parameters on the segment
return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); return Ty::Projection(ProjectionTy { associated_ty, parameters: substs });
} }
@ -259,8 +372,7 @@ impl Ty {
} }
fn from_hir_path_inner( fn from_hir_path_inner(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
segment: PathSegment<'_>, segment: PathSegment<'_>,
typable: TyDefId, typable: TyDefId,
) -> Ty { ) -> Ty {
@ -269,15 +381,14 @@ impl Ty {
TyDefId::AdtId(it) => Some(it.into()), TyDefId::AdtId(it) => Some(it.into()),
TyDefId::TypeAliasId(it) => Some(it.into()), TyDefId::TypeAliasId(it) => Some(it.into()),
}; };
let substs = substs_from_path_segment(db, resolver, segment, generic_def, false); let substs = substs_from_path_segment(ctx, segment, generic_def, false);
db.ty(typable).subst(&substs) ctx.db.ty(typable).subst(&substs)
} }
/// Collect generic arguments from a path into a `Substs`. See also /// Collect generic arguments from a path into a `Substs`. See also
/// `create_substs_for_ast_path` and `def_to_ty` in rustc. /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
pub(super) fn substs_from_path( pub(super) fn substs_from_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
path: &Path, path: &Path,
// Note that we don't call `db.value_type(resolved)` here, // Note that we don't call `db.value_type(resolved)` here,
// `ValueTyDefId` is just a convenient way to pass generics and // `ValueTyDefId` is just a convenient way to pass generics and
@ -305,52 +416,49 @@ impl Ty {
(segment, Some(var.parent.into())) (segment, Some(var.parent.into()))
} }
}; };
substs_from_path_segment(db, resolver, segment, generic_def, false) substs_from_path_segment(ctx, segment, generic_def, false)
} }
} }
pub(super) fn substs_from_path_segment( pub(super) fn substs_from_path_segment(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
segment: PathSegment<'_>, segment: PathSegment<'_>,
def_generic: Option<GenericDefId>, def_generic: Option<GenericDefId>,
add_self_param: bool, _add_self_param: bool,
) -> Substs { ) -> Substs {
let mut substs = Vec::new(); let mut substs = Vec::new();
let def_generics = def_generic.map(|def| generics(db, def.into())); let def_generics = def_generic.map(|def| generics(ctx.db, def.into()));
let (total_len, parent_len, child_len) = def_generics.map_or((0, 0, 0), |g| g.len_split()); let (parent_params, self_params, type_params, impl_trait_params) =
substs.extend(iter::repeat(Ty::Unknown).take(parent_len)); def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
if add_self_param { substs.extend(iter::repeat(Ty::Unknown).take(parent_params));
// 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: `<Foo as Default>::default()`)
substs.push(Ty::Unknown);
}
if let Some(generic_args) = &segment.args_and_bindings { if let Some(generic_args) = &segment.args_and_bindings {
if !generic_args.has_self_type {
substs.extend(iter::repeat(Ty::Unknown).take(self_params));
}
let expected_num =
if generic_args.has_self_type { self_params + type_params } else { type_params };
let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
// if args are provided, it should be all of them, but we can't rely on that // 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 }; for arg in generic_args.args.iter().skip(skip).take(expected_num) {
let child_len = child_len - self_param_correction;
for arg in generic_args.args.iter().take(child_len) {
match arg { match arg {
GenericArg::Type(type_ref) => { GenericArg::Type(type_ref) => {
let ty = Ty::from_hir(db, resolver, type_ref); let ty = Ty::from_hir(ctx, type_ref);
substs.push(ty); substs.push(ty);
} }
} }
} }
} }
let total_len = parent_params + self_params + type_params + impl_trait_params;
// add placeholders for args that were not provided // add placeholders for args that were not provided
let supplied_params = substs.len(); for _ in substs.len()..total_len {
for _ in supplied_params..total_len {
substs.push(Ty::Unknown); substs.push(Ty::Unknown);
} }
assert_eq!(substs.len(), total_len); assert_eq!(substs.len(), total_len);
// handle defaults // handle defaults
if let Some(def_generic) = def_generic { if let Some(def_generic) = def_generic {
let default_substs = db.generic_defaults(def_generic.into()); let default_substs = ctx.db.generic_defaults(def_generic.into());
assert_eq!(substs.len(), default_substs.len()); assert_eq!(substs.len(), default_substs.len());
for (i, default_ty) in default_substs.iter().enumerate() { for (i, default_ty) in default_substs.iter().enumerate() {
@ -365,27 +473,25 @@ pub(super) fn substs_from_path_segment(
impl TraitRef { impl TraitRef {
fn from_path( fn from_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
path: &Path, path: &Path,
explicit_self_ty: Option<Ty>, explicit_self_ty: Option<Ty>,
) -> Option<Self> { ) -> Option<Self> {
let resolved = match resolver.resolve_path_in_type_ns_fully(db, path.mod_path())? { let resolved = match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db, path.mod_path())? {
TypeNs::TraitId(tr) => tr, TypeNs::TraitId(tr) => tr,
_ => return None, _ => return None,
}; };
let segment = path.segments().last().expect("path should have at least one segment"); 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)) Some(TraitRef::from_resolved_path(ctx, resolved.into(), segment, explicit_self_ty))
} }
pub(crate) fn from_resolved_path( pub(crate) fn from_resolved_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
resolved: TraitId, resolved: TraitId,
segment: PathSegment<'_>, segment: PathSegment<'_>,
explicit_self_ty: Option<Ty>, explicit_self_ty: Option<Ty>,
) -> Self { ) -> Self {
let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); let mut substs = TraitRef::substs_from_path(ctx, segment, resolved);
if let Some(self_ty) = explicit_self_ty { if let Some(self_ty) = explicit_self_ty {
make_mut_slice(&mut substs.0)[0] = self_ty; make_mut_slice(&mut substs.0)[0] = self_ty;
} }
@ -393,8 +499,7 @@ impl TraitRef {
} }
fn from_hir( fn from_hir(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
type_ref: &TypeRef, type_ref: &TypeRef,
explicit_self_ty: Option<Ty>, explicit_self_ty: Option<Ty>,
) -> Option<Self> { ) -> Option<Self> {
@ -402,28 +507,26 @@ impl TraitRef {
TypeRef::Path(path) => path, TypeRef::Path(path) => path,
_ => return None, _ => return None,
}; };
TraitRef::from_path(db, resolver, path, explicit_self_ty) TraitRef::from_path(ctx, path, explicit_self_ty)
} }
fn substs_from_path( fn substs_from_path(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
segment: PathSegment<'_>, segment: PathSegment<'_>,
resolved: TraitId, resolved: TraitId,
) -> Substs { ) -> Substs {
let has_self_param = let has_self_param =
segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); 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) substs_from_path_segment(ctx, segment, Some(resolved.into()), !has_self_param)
} }
pub(crate) fn from_type_bound( pub(crate) fn from_type_bound(
db: &impl HirDatabase, ctx: &TyLoweringContext<'_, impl HirDatabase>,
resolver: &Resolver,
bound: &TypeBound, bound: &TypeBound,
self_ty: Ty, self_ty: Ty,
) -> Option<TraitRef> { ) -> Option<TraitRef> {
match bound { match bound {
TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), TypeBound::Path(path) => TraitRef::from_path(ctx, path, Some(self_ty)),
TypeBound::Error => None, TypeBound::Error => None,
} }
} }
@ -431,33 +534,44 @@ impl TraitRef {
impl GenericPredicate { impl GenericPredicate {
pub(crate) fn from_where_predicate<'a>( pub(crate) fn from_where_predicate<'a>(
db: &'a impl HirDatabase, ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
resolver: &'a Resolver,
where_predicate: &'a WherePredicate, where_predicate: &'a WherePredicate,
) -> impl Iterator<Item = GenericPredicate> + 'a { ) -> impl Iterator<Item = GenericPredicate> + 'a {
let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); let self_ty = match &where_predicate.target {
GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) WherePredicateTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref),
WherePredicateTarget::TypeParam(param_id) => {
let generic_def = ctx.resolver.generic_def().expect("generics in scope");
let generics = generics(ctx.db, generic_def);
let param_id = hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
match ctx.type_param_mode {
TypeParamLoweringMode::Placeholder => Ty::Param(param_id),
TypeParamLoweringMode::Variable => {
let idx = generics.param_idx(param_id).expect("matching generics");
Ty::Bound(idx)
}
}
}
};
GenericPredicate::from_type_bound(ctx, &where_predicate.bound, self_ty)
} }
pub(crate) fn from_type_bound<'a>( pub(crate) fn from_type_bound<'a>(
db: &'a impl HirDatabase, ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
resolver: &'a Resolver,
bound: &'a TypeBound, bound: &'a TypeBound,
self_ty: Ty, self_ty: Ty,
) -> impl Iterator<Item = GenericPredicate> + 'a { ) -> impl Iterator<Item = GenericPredicate> + 'a {
let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); let trait_ref = TraitRef::from_type_bound(ctx, bound, self_ty);
iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented))
.chain( .chain(
trait_ref.into_iter().flat_map(move |tr| { trait_ref
assoc_type_bindings_from_type_bound(db, resolver, bound, tr) .into_iter()
}), .flat_map(move |tr| assoc_type_bindings_from_type_bound(ctx, bound, tr)),
) )
} }
} }
fn assoc_type_bindings_from_type_bound<'a>( fn assoc_type_bindings_from_type_bound<'a>(
db: &'a impl HirDatabase, ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
resolver: &'a Resolver,
bound: &'a TypeBound, bound: &'a TypeBound,
trait_ref: TraitRef, trait_ref: TraitRef,
) -> impl Iterator<Item = GenericPredicate> + 'a { ) -> impl Iterator<Item = GenericPredicate> + 'a {
@ -471,21 +585,21 @@ fn assoc_type_bindings_from_type_bound<'a>(
.flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
.map(move |(name, type_ref)| { .map(move |(name, type_ref)| {
let associated_ty = let associated_ty =
associated_type_by_name_including_super_traits(db, trait_ref.trait_, &name); associated_type_by_name_including_super_traits(ctx.db, trait_ref.trait_, &name);
let associated_ty = match associated_ty { let associated_ty = match associated_ty {
None => return GenericPredicate::Error, None => return GenericPredicate::Error,
Some(t) => t, Some(t) => t,
}; };
let projection_ty = let projection_ty =
ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() };
let ty = Ty::from_hir(db, resolver, type_ref); let ty = Ty::from_hir(ctx, type_ref);
let projection_predicate = ProjectionPredicate { projection_ty, ty }; let projection_predicate = ProjectionPredicate { projection_ty, ty };
GenericPredicate::Projection(projection_predicate) GenericPredicate::Projection(projection_predicate)
}) })
} }
/// Build the signature of a callable item (function, struct or enum variant). /// Build the signature of a callable item (function, struct or enum variant).
pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig {
match def { match def {
CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),
CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s),
@ -497,16 +611,19 @@ pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig {
pub(crate) fn field_types_query( pub(crate) fn field_types_query(
db: &impl HirDatabase, db: &impl HirDatabase,
variant_id: VariantId, variant_id: VariantId,
) -> Arc<ArenaMap<LocalStructFieldId, Ty>> { ) -> Arc<ArenaMap<LocalStructFieldId, Binders<Ty>>> {
let var_data = variant_data(db, variant_id); let var_data = variant_data(db, variant_id);
let resolver = match variant_id { let (resolver, def): (_, GenericDefId) = match variant_id {
VariantId::StructId(it) => it.resolver(db), VariantId::StructId(it) => (it.resolver(db), it.into()),
VariantId::UnionId(it) => it.resolver(db), VariantId::UnionId(it) => (it.resolver(db), it.into()),
VariantId::EnumVariantId(it) => it.parent.resolver(db), VariantId::EnumVariantId(it) => (it.parent.resolver(db), it.parent.into()),
}; };
let generics = generics(db, def);
let mut res = ArenaMap::default(); let mut res = ArenaMap::default();
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
for (field_id, field_data) in var_data.fields().iter() { for (field_id, field_data) in var_data.fields().iter() {
res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) res.insert(field_id, Binders::new(generics.len(), Ty::from_hir(&ctx, &field_data.type_ref)))
} }
Arc::new(res) Arc::new(res)
} }
@ -521,32 +638,43 @@ pub(crate) fn field_types_query(
/// these are fine: `T: Foo<U::Item>, U: Foo<()>`. /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
pub(crate) fn generic_predicates_for_param_query( pub(crate) fn generic_predicates_for_param_query(
db: &impl HirDatabase, db: &impl HirDatabase,
def: GenericDefId, param_id: TypeParamId,
param_idx: u32, ) -> Arc<[Binders<GenericPredicate>]> {
) -> Arc<[GenericPredicate]> { let resolver = param_id.parent.resolver(db);
let resolver = def.resolver(db); let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
let generics = generics(db, param_id.parent);
resolver resolver
.where_predicates_in_scope() .where_predicates_in_scope()
// we have to filter out all other predicates *first*, before attempting to lower them // 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)) .filter(|pred| match &pred.target {
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) WherePredicateTarget::TypeRef(type_ref) => {
Ty::from_hir_only_param(&ctx, type_ref) == Some(param_id)
}
WherePredicateTarget::TypeParam(local_id) => *local_id == param_id.local_id,
})
.flat_map(|pred| {
GenericPredicate::from_where_predicate(&ctx, pred)
.map(|p| Binders::new(generics.len(), p))
})
.collect() .collect()
} }
pub(crate) fn generic_predicates_for_param_recover( pub(crate) fn generic_predicates_for_param_recover(
_db: &impl HirDatabase, _db: &impl HirDatabase,
_cycle: &[String], _cycle: &[String],
_def: &GenericDefId, _param_id: &TypeParamId,
_param_idx: &u32, ) -> Arc<[Binders<GenericPredicate>]> {
) -> Arc<[GenericPredicate]> {
Arc::new([]) Arc::new([])
} }
impl TraitEnvironment { impl TraitEnvironment {
pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
let ctx = TyLoweringContext::new(db, &resolver)
.with_type_param_mode(TypeParamLoweringMode::Placeholder);
let predicates = resolver let predicates = resolver
.where_predicates_in_scope() .where_predicates_in_scope()
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) .flat_map(|pred| GenericPredicate::from_where_predicate(&ctx, pred))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Arc::new(TraitEnvironment { predicates }) Arc::new(TraitEnvironment { predicates })
@ -557,57 +685,74 @@ impl TraitEnvironment {
pub(crate) fn generic_predicates_query( pub(crate) fn generic_predicates_query(
db: &impl HirDatabase, db: &impl HirDatabase,
def: GenericDefId, def: GenericDefId,
) -> Arc<[GenericPredicate]> { ) -> Arc<[Binders<GenericPredicate>]> {
let resolver = def.resolver(db); let resolver = def.resolver(db);
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
let generics = generics(db, def);
resolver resolver
.where_predicates_in_scope() .where_predicates_in_scope()
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) .flat_map(|pred| {
GenericPredicate::from_where_predicate(&ctx, pred)
.map(|p| Binders::new(generics.len(), p))
})
.collect() .collect()
} }
/// Resolve the default type params from generics /// Resolve the default type params from generics
pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs { pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs {
let resolver = def.resolver(db); let resolver = def.resolver(db);
let ctx = TyLoweringContext::new(db, &resolver);
let generic_params = generics(db, def.into()); let generic_params = generics(db, def.into());
let defaults = generic_params let defaults = generic_params
.iter() .iter()
.map(|(_idx, p)| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) .map(|(_idx, p)| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(&ctx, t)))
.collect(); .collect();
Substs(defaults) Substs(defaults)
} }
fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> FnSig { fn fn_sig_for_fn(db: &impl HirDatabase, def: FunctionId) -> PolyFnSig {
let data = db.function_data(def); let data = db.function_data(def);
let resolver = def.resolver(db); let resolver = def.resolver(db);
let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>(); let ctx_params = TyLoweringContext::new(db, &resolver)
let ret = Ty::from_hir(db, &resolver, &data.ret_type); .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
FnSig::from_params_and_return(params, ret) .with_type_param_mode(TypeParamLoweringMode::Variable);
let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>();
let ctx_ret = ctx_params.with_impl_trait_mode(ImplTraitLoweringMode::Opaque);
let ret = Ty::from_hir(&ctx_ret, &data.ret_type);
let generics = generics(db, def.into());
let num_binders = generics.len();
Binders::new(num_binders, FnSig::from_params_and_return(params, ret))
} }
/// Build the declared type of a function. This should not need to look at the /// Build the declared type of a function. This should not need to look at the
/// function body. /// function body.
fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Ty { fn type_for_fn(db: &impl HirDatabase, def: FunctionId) -> Binders<Ty> {
let generics = generics(db, def.into()); let generics = generics(db, def.into());
let substs = Substs::identity(&generics); let substs = Substs::bound_vars(&generics);
Ty::apply(TypeCtor::FnDef(def.into()), substs) Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
} }
/// Build the declared type of a const. /// Build the declared type of a const.
fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Ty { fn type_for_const(db: &impl HirDatabase, def: ConstId) -> Binders<Ty> {
let data = db.const_data(def); let data = db.const_data(def);
let generics = generics(db, def.into());
let resolver = def.resolver(db); let resolver = def.resolver(db);
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
Ty::from_hir(db, &resolver, &data.type_ref) Binders::new(generics.len(), Ty::from_hir(&ctx, &data.type_ref))
} }
/// Build the declared type of a static. /// Build the declared type of a static.
fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Ty { fn type_for_static(db: &impl HirDatabase, def: StaticId) -> Binders<Ty> {
let data = db.static_data(def); let data = db.static_data(def);
let resolver = def.resolver(db); let resolver = def.resolver(db);
let ctx = TyLoweringContext::new(db, &resolver);
Ty::from_hir(db, &resolver, &data.type_ref) Binders::new(0, Ty::from_hir(&ctx, &data.type_ref))
} }
/// Build the declared type of a static. /// Build the declared type of a static.
@ -621,68 +766,69 @@ fn type_for_builtin(def: BuiltinType) -> Ty {
}) })
} }
fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> FnSig { fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> PolyFnSig {
let struct_data = db.struct_data(def.into()); let struct_data = db.struct_data(def.into());
let fields = struct_data.variant_data.fields(); let fields = struct_data.variant_data.fields();
let resolver = def.resolver(db); let resolver = def.resolver(db);
let params = fields let ctx =
.iter() TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
.map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) let params =
.collect::<Vec<_>>(); fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
let ret = type_for_adt(db, def.into()); let ret = type_for_adt(db, def.into());
FnSig::from_params_and_return(params, ret) Binders::new(ret.num_binders, FnSig::from_params_and_return(params, ret.value))
} }
/// Build the type of a tuple struct constructor. /// Build the type of a tuple struct constructor.
fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Ty { fn type_for_struct_constructor(db: &impl HirDatabase, def: StructId) -> Binders<Ty> {
let struct_data = db.struct_data(def.into()); let struct_data = db.struct_data(def.into());
if struct_data.variant_data.is_unit() { if struct_data.variant_data.is_unit() {
return type_for_adt(db, def.into()); // Unit struct return type_for_adt(db, def.into()); // Unit struct
} }
let generics = generics(db, def.into()); let generics = generics(db, def.into());
let substs = Substs::identity(&generics); let substs = Substs::bound_vars(&generics);
Ty::apply(TypeCtor::FnDef(def.into()), substs) Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
} }
fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> FnSig { fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> PolyFnSig {
let enum_data = db.enum_data(def.parent); let enum_data = db.enum_data(def.parent);
let var_data = &enum_data.variants[def.local_id]; let var_data = &enum_data.variants[def.local_id];
let fields = var_data.variant_data.fields(); let fields = var_data.variant_data.fields();
let resolver = def.parent.resolver(db); let resolver = def.parent.resolver(db);
let params = fields let ctx =
.iter() TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
.map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) let params =
.collect::<Vec<_>>(); fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
let generics = generics(db, def.parent.into()); let ret = type_for_adt(db, def.parent.into());
let substs = Substs::identity(&generics); Binders::new(ret.num_binders, FnSig::from_params_and_return(params, ret.value))
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. /// Build the type of a tuple enum variant constructor.
fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Ty { fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariantId) -> Binders<Ty> {
let enum_data = db.enum_data(def.parent); let enum_data = db.enum_data(def.parent);
let var_data = &enum_data.variants[def.local_id].variant_data; let var_data = &enum_data.variants[def.local_id].variant_data;
if var_data.is_unit() { if var_data.is_unit() {
return type_for_adt(db, def.parent.into()); // Unit variant return type_for_adt(db, def.parent.into()); // Unit variant
} }
let generics = generics(db, def.parent.into()); let generics = generics(db, def.parent.into());
let substs = Substs::identity(&generics); let substs = Substs::bound_vars(&generics);
Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs) Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs))
} }
fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Ty { fn type_for_adt(db: &impl HirDatabase, adt: AdtId) -> Binders<Ty> {
let generics = generics(db, adt.into()); let generics = generics(db, adt.into());
Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) let substs = Substs::bound_vars(&generics);
Binders::new(substs.len(), Ty::apply(TypeCtor::Adt(adt), substs))
} }
fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Ty { fn type_for_type_alias(db: &impl HirDatabase, t: TypeAliasId) -> Binders<Ty> {
let generics = generics(db, t.into()); let generics = generics(db, t.into());
let resolver = t.resolver(db); let resolver = t.resolver(db);
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
let type_ref = &db.type_alias_data(t).type_ref; let type_ref = &db.type_alias_data(t).type_ref;
let substs = Substs::identity(&generics); let substs = Substs::bound_vars(&generics);
let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error)); let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error));
inner.subst(&substs) Binders::new(substs.len(), inner)
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@ -736,19 +882,24 @@ impl_froms!(ValueTyDefId: FunctionId, StructId, EnumVariantId, ConstId, StaticId
/// `struct Foo(usize)`, we have two types: The type of the struct itself, and /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
/// the constructor function `(usize) -> Foo` which lives in the values /// the constructor function `(usize) -> Foo` which lives in the values
/// namespace. /// namespace.
pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Ty { pub(crate) fn ty_query(db: &impl HirDatabase, def: TyDefId) -> Binders<Ty> {
match def { match def {
TyDefId::BuiltinType(it) => type_for_builtin(it), TyDefId::BuiltinType(it) => Binders::new(0, type_for_builtin(it)),
TyDefId::AdtId(it) => type_for_adt(db, it), TyDefId::AdtId(it) => type_for_adt(db, it),
TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
} }
} }
pub(crate) fn ty_recover(_db: &impl HirDatabase, _cycle: &[String], _def: &TyDefId) -> Ty { pub(crate) fn ty_recover(db: &impl HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
Ty::Unknown let num_binders = match *def {
TyDefId::BuiltinType(_) => 0,
TyDefId::AdtId(it) => generics(db, it.into()).len(),
TyDefId::TypeAliasId(it) => generics(db, it.into()).len(),
};
Binders::new(num_binders, Ty::Unknown)
} }
pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty { pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
match def { match def {
ValueTyDefId::FunctionId(it) => type_for_fn(db, it), ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
@ -758,24 +909,36 @@ pub(crate) fn value_ty_query(db: &impl HirDatabase, def: ValueTyDefId) -> Ty {
} }
} }
pub(crate) fn impl_self_ty_query(db: &impl HirDatabase, impl_id: ImplId) -> Ty { pub(crate) fn impl_self_ty_query(db: &impl HirDatabase, impl_id: ImplId) -> Binders<Ty> {
let impl_data = db.impl_data(impl_id); let impl_data = db.impl_data(impl_id);
let resolver = impl_id.resolver(db); let resolver = impl_id.resolver(db);
Ty::from_hir(db, &resolver, &impl_data.target_type) let generics = generics(db, impl_id.into());
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type))
} }
pub(crate) fn impl_self_ty_recover( pub(crate) fn impl_self_ty_recover(
_db: &impl HirDatabase, db: &impl HirDatabase,
_cycle: &[String], _cycle: &[String],
_impl_id: &ImplId, impl_id: &ImplId,
) -> Ty { ) -> Binders<Ty> {
Ty::Unknown let generics = generics(db, (*impl_id).into());
Binders::new(generics.len(), Ty::Unknown)
} }
pub(crate) fn impl_trait_query(db: &impl HirDatabase, impl_id: ImplId) -> Option<TraitRef> { pub(crate) fn impl_trait_query(
db: &impl HirDatabase,
impl_id: ImplId,
) -> Option<Binders<TraitRef>> {
let impl_data = db.impl_data(impl_id); let impl_data = db.impl_data(impl_id);
let resolver = impl_id.resolver(db); let resolver = impl_id.resolver(db);
let ctx =
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
let self_ty = db.impl_self_ty(impl_id); let self_ty = db.impl_self_ty(impl_id);
let target_trait = impl_data.target_trait.as_ref()?; let target_trait = impl_data.target_trait.as_ref()?;
TraitRef::from_hir(db, &resolver, target_trait, Some(self_ty.clone())) Some(Binders::new(
self_ty.num_binders,
TraitRef::from_hir(&ctx, target_trait, Some(self_ty.value.clone()))?,
))
} }

View file

@ -6,5 +6,4 @@ test_utils::marks!(
type_var_resolves_to_int_var type_var_resolves_to_int_var
match_ergonomics_ref match_ergonomics_ref
coerce_merge_fail_fallback coerce_merge_fail_fallback
insert_vars_for_impl_trait
); );

View file

@ -61,11 +61,11 @@ impl CrateImplBlocks {
for impl_id in module_data.scope.impls() { for impl_id in module_data.scope.impls() {
match db.impl_trait(impl_id) { match db.impl_trait(impl_id) {
Some(tr) => { Some(tr) => {
res.impls_by_trait.entry(tr.trait_).or_default().push(impl_id); res.impls_by_trait.entry(tr.value.trait_).or_default().push(impl_id);
} }
None => { None => {
let self_ty = db.impl_self_ty(impl_id); let self_ty = db.impl_self_ty(impl_id);
if let Some(self_ty_fp) = TyFingerprint::for_impl(&self_ty) { if let Some(self_ty_fp) = TyFingerprint::for_impl(&self_ty.value) {
res.impls.entry(self_ty_fp).or_default().push(impl_id); res.impls.entry(self_ty_fp).or_default().push(impl_id);
} }
} }
@ -496,7 +496,7 @@ fn transform_receiver_ty(
AssocContainerId::ContainerId(_) => unreachable!(), AssocContainerId::ContainerId(_) => unreachable!(),
}; };
let sig = db.callable_item_signature(function_id.into()); let sig = db.callable_item_signature(function_id.into());
Some(sig.params()[0].clone().subst(&substs)) Some(sig.value.params()[0].clone().subst_bound_vars(&substs))
} }
pub fn implements_trait( pub fn implements_trait(

View file

@ -75,7 +75,7 @@ fn test2() {
[124; 131) 'loop {}': ! [124; 131) 'loop {}': !
[129; 131) '{}': () [129; 131) '{}': ()
[160; 173) '{ gen() }': *mut [U] [160; 173) '{ gen() }': *mut [U]
[166; 169) 'gen': fn gen<U>() -> *mut [T; _] [166; 169) 'gen': fn gen<U>() -> *mut [U; _]
[166; 171) 'gen()': *mut [U; _] [166; 171) 'gen()': *mut [U; _]
[186; 420) '{ ...rr); }': () [186; 420) '{ ...rr); }': ()
[196; 199) 'arr': &[u8; _] [196; 199) 'arr': &[u8; _]
@ -85,14 +85,14 @@ fn test2() {
[227; 228) 'a': &[u8] [227; 228) 'a': &[u8]
[237; 240) 'arr': &[u8; _] [237; 240) 'arr': &[u8; _]
[250; 251) 'b': u8 [250; 251) 'b': u8
[254; 255) 'f': fn f<u8>(&[T]) -> T [254; 255) 'f': fn f<u8>(&[u8]) -> u8
[254; 260) 'f(arr)': u8 [254; 260) 'f(arr)': u8
[256; 259) 'arr': &[u8; _] [256; 259) 'arr': &[u8; _]
[270; 271) 'c': &[u8] [270; 271) 'c': &[u8]
[280; 287) '{ arr }': &[u8] [280; 287) '{ arr }': &[u8]
[282; 285) 'arr': &[u8; _] [282; 285) 'arr': &[u8; _]
[297; 298) 'd': u8 [297; 298) 'd': u8
[301; 302) 'g': fn g<u8>(S<&[T]>) -> T [301; 302) 'g': fn g<u8>(S<&[u8]>) -> u8
[301; 316) 'g(S { a: arr })': u8 [301; 316) 'g(S { a: arr })': u8
[303; 315) 'S { a: arr }': S<&[u8]> [303; 315) 'S { a: arr }': S<&[u8]>
[310; 313) 'arr': &[u8; _] [310; 313) 'arr': &[u8; _]
@ -164,15 +164,15 @@ fn test(a: A<[u8; 2]>, b: B<[u8; 2]>, c: C<[u8; 2]>) {
[400; 401) 'c': C<[u8; _]> [400; 401) 'c': C<[u8; _]>
[415; 481) '{ ...(c); }': () [415; 481) '{ ...(c); }': ()
[425; 426) 'd': A<[{unknown}]> [425; 426) 'd': A<[{unknown}]>
[429; 433) 'foo1': fn foo1<{unknown}>(A<[T]>) -> A<[T]> [429; 433) 'foo1': fn foo1<{unknown}>(A<[{unknown}]>) -> A<[{unknown}]>
[429; 436) 'foo1(a)': A<[{unknown}]> [429; 436) 'foo1(a)': A<[{unknown}]>
[434; 435) 'a': A<[u8; _]> [434; 435) 'a': A<[u8; _]>
[446; 447) 'e': B<[u8]> [446; 447) 'e': B<[u8]>
[450; 454) 'foo2': fn foo2<u8>(B<[T]>) -> B<[T]> [450; 454) 'foo2': fn foo2<u8>(B<[u8]>) -> B<[u8]>
[450; 457) 'foo2(b)': B<[u8]> [450; 457) 'foo2(b)': B<[u8]>
[455; 456) 'b': B<[u8; _]> [455; 456) 'b': B<[u8; _]>
[467; 468) 'f': C<[u8]> [467; 468) 'f': C<[u8]>
[471; 475) 'foo3': fn foo3<u8>(C<[T]>) -> C<[T]> [471; 475) 'foo3': fn foo3<u8>(C<[u8]>) -> C<[u8]>
[471; 478) 'foo3(c)': C<[u8]> [471; 478) 'foo3(c)': C<[u8]>
[476; 477) 'c': C<[u8; _]> [476; 477) 'c': C<[u8; _]>
"### "###
@ -202,7 +202,7 @@ fn test() {
[64; 123) 'if tru... }': &[i32] [64; 123) 'if tru... }': &[i32]
[67; 71) 'true': bool [67; 71) 'true': bool
[72; 97) '{ ... }': &[i32] [72; 97) '{ ... }': &[i32]
[82; 85) 'foo': fn foo<i32>(&[T]) -> &[T] [82; 85) 'foo': fn foo<i32>(&[i32]) -> &[i32]
[82; 91) 'foo(&[1])': &[i32] [82; 91) 'foo(&[1])': &[i32]
[86; 90) '&[1]': &[i32; _] [86; 90) '&[1]': &[i32; _]
[87; 90) '[1]': [i32; _] [87; 90) '[1]': [i32; _]
@ -242,7 +242,7 @@ fn test() {
[83; 86) '[1]': [i32; _] [83; 86) '[1]': [i32; _]
[84; 85) '1': i32 [84; 85) '1': i32
[98; 123) '{ ... }': &[i32] [98; 123) '{ ... }': &[i32]
[108; 111) 'foo': fn foo<i32>(&[T]) -> &[T] [108; 111) 'foo': fn foo<i32>(&[i32]) -> &[i32]
[108; 117) 'foo(&[1])': &[i32] [108; 117) 'foo(&[1])': &[i32]
[112; 116) '&[1]': &[i32; _] [112; 116) '&[1]': &[i32; _]
[113; 116) '[1]': [i32; _] [113; 116) '[1]': [i32; _]
@ -275,7 +275,7 @@ fn test(i: i32) {
[70; 147) 'match ... }': &[i32] [70; 147) 'match ... }': &[i32]
[76; 77) 'i': i32 [76; 77) 'i': i32
[88; 89) '2': i32 [88; 89) '2': i32
[93; 96) 'foo': fn foo<i32>(&[T]) -> &[T] [93; 96) 'foo': fn foo<i32>(&[i32]) -> &[i32]
[93; 102) 'foo(&[2])': &[i32] [93; 102) 'foo(&[2])': &[i32]
[97; 101) '&[2]': &[i32; _] [97; 101) '&[2]': &[i32; _]
[98; 101) '[2]': [i32; _] [98; 101) '[2]': [i32; _]
@ -320,7 +320,7 @@ fn test(i: i32) {
[94; 97) '[1]': [i32; _] [94; 97) '[1]': [i32; _]
[95; 96) '1': i32 [95; 96) '1': i32
[107; 108) '2': i32 [107; 108) '2': i32
[112; 115) 'foo': fn foo<i32>(&[T]) -> &[T] [112; 115) 'foo': fn foo<i32>(&[i32]) -> &[i32]
[112; 121) 'foo(&[2])': &[i32] [112; 121) 'foo(&[2])': &[i32]
[116; 120) '&[2]': &[i32; _] [116; 120) '&[2]': &[i32; _]
[117; 120) '[2]': [i32; _] [117; 120) '[2]': [i32; _]
@ -438,16 +438,16 @@ fn test() {
[43; 45) '*x': T [43; 45) '*x': T
[44; 45) 'x': &T [44; 45) 'x': &T
[58; 127) '{ ...oo); }': () [58; 127) '{ ...oo); }': ()
[64; 73) 'takes_ref': fn takes_ref<Foo>(&T) -> T [64; 73) 'takes_ref': fn takes_ref<Foo>(&Foo) -> Foo
[64; 79) 'takes_ref(&Foo)': Foo [64; 79) 'takes_ref(&Foo)': Foo
[74; 78) '&Foo': &Foo [74; 78) '&Foo': &Foo
[75; 78) 'Foo': Foo [75; 78) 'Foo': Foo
[85; 94) 'takes_ref': fn takes_ref<&Foo>(&T) -> T [85; 94) 'takes_ref': fn takes_ref<&Foo>(&&Foo) -> &Foo
[85; 101) 'takes_...&&Foo)': &Foo [85; 101) 'takes_...&&Foo)': &Foo
[95; 100) '&&Foo': &&Foo [95; 100) '&&Foo': &&Foo
[96; 100) '&Foo': &Foo [96; 100) '&Foo': &Foo
[97; 100) 'Foo': Foo [97; 100) 'Foo': Foo
[107; 116) 'takes_ref': fn takes_ref<&&Foo>(&T) -> T [107; 116) 'takes_ref': fn takes_ref<&&Foo>(&&&Foo) -> &&Foo
[107; 124) 'takes_...&&Foo)': &&Foo [107; 124) 'takes_...&&Foo)': &&Foo
[117; 123) '&&&Foo': &&&Foo [117; 123) '&&&Foo': &&&Foo
[118; 123) '&&Foo': &&Foo [118; 123) '&&Foo': &&Foo

View file

@ -27,7 +27,7 @@ fn test() {
[66; 73) 'loop {}': ! [66; 73) 'loop {}': !
[71; 73) '{}': () [71; 73) '{}': ()
[133; 160) '{ ...o"); }': () [133; 160) '{ ...o"); }': ()
[139; 149) '<[_]>::foo': fn foo<u8>(&[T]) -> T [139; 149) '<[_]>::foo': fn foo<u8>(&[u8]) -> u8
[139; 157) '<[_]>:..."foo")': u8 [139; 157) '<[_]>:..."foo")': u8
[150; 156) 'b"foo"': &[u8] [150; 156) 'b"foo"': &[u8]
"### "###
@ -175,7 +175,7 @@ fn test() {
[98; 101) 'val': T [98; 101) 'val': T
[123; 155) '{ ...32); }': () [123; 155) '{ ...32); }': ()
[133; 134) 'a': Gen<u32> [133; 134) 'a': Gen<u32>
[137; 146) 'Gen::make': fn make<u32>(T) -> Gen<T> [137; 146) 'Gen::make': fn make<u32>(u32) -> Gen<u32>
[137; 152) 'Gen::make(0u32)': Gen<u32> [137; 152) 'Gen::make(0u32)': Gen<u32>
[147; 151) '0u32': u32 [147; 151) '0u32': u32
"### "###
@ -206,7 +206,7 @@ fn test() {
[95; 98) '{ }': () [95; 98) '{ }': ()
[118; 146) '{ ...e(); }': () [118; 146) '{ ...e(); }': ()
[128; 129) 'a': Gen<u32> [128; 129) 'a': Gen<u32>
[132; 141) 'Gen::make': fn make<u32>() -> Gen<T> [132; 141) 'Gen::make': fn make<u32>() -> Gen<u32>
[132; 143) 'Gen::make()': Gen<u32> [132; 143) 'Gen::make()': Gen<u32>
"### "###
); );
@ -260,7 +260,7 @@ fn test() {
[91; 94) '{ }': () [91; 94) '{ }': ()
[114; 149) '{ ...e(); }': () [114; 149) '{ ...e(); }': ()
[124; 125) 'a': Gen<u32> [124; 125) 'a': Gen<u32>
[128; 144) 'Gen::<...::make': fn make<u32>() -> Gen<T> [128; 144) 'Gen::<...::make': fn make<u32>() -> Gen<u32>
[128; 146) 'Gen::<...make()': Gen<u32> [128; 146) 'Gen::<...make()': Gen<u32>
"### "###
); );
@ -291,7 +291,7 @@ fn test() {
[117; 120) '{ }': () [117; 120) '{ }': ()
[140; 180) '{ ...e(); }': () [140; 180) '{ ...e(); }': ()
[150; 151) 'a': Gen<u32, u64> [150; 151) 'a': Gen<u32, u64>
[154; 175) 'Gen::<...::make': fn make<u64>() -> Gen<u32, T> [154; 175) 'Gen::<...::make': fn make<u64>() -> Gen<u32, u64>
[154; 177) 'Gen::<...make()': Gen<u32, u64> [154; 177) 'Gen::<...make()': Gen<u32, u64>
"### "###
); );
@ -475,7 +475,7 @@ fn test() {
@r###" @r###"
[33; 37) 'self': &Self [33; 37) 'self': &Self
[102; 127) '{ ...d(); }': () [102; 127) '{ ...d(); }': ()
[108; 109) 'S': S<u32>(T) -> S<T> [108; 109) 'S': S<u32>(u32) -> S<u32>
[108; 115) 'S(1u32)': S<u32> [108; 115) 'S(1u32)': S<u32>
[108; 124) 'S(1u32...thod()': u32 [108; 124) 'S(1u32...thod()': u32
[110; 114) '1u32': u32 [110; 114) '1u32': u32
@ -501,13 +501,13 @@ fn test() {
@r###" @r###"
[87; 193) '{ ...t(); }': () [87; 193) '{ ...t(); }': ()
[97; 99) 's1': S [97; 99) 's1': S
[105; 121) 'Defaul...efault': fn default<S>() -> Self [105; 121) 'Defaul...efault': fn default<S>() -> S
[105; 123) 'Defaul...ault()': S [105; 123) 'Defaul...ault()': S
[133; 135) 's2': S [133; 135) 's2': S
[138; 148) 'S::default': fn default<S>() -> Self [138; 148) 'S::default': fn default<S>() -> S
[138; 150) 'S::default()': S [138; 150) 'S::default()': S
[160; 162) 's3': S [160; 162) 's3': S
[165; 188) '<S as ...efault': fn default<S>() -> Self [165; 188) '<S as ...efault': fn default<S>() -> S
[165; 190) '<S as ...ault()': S [165; 190) '<S as ...ault()': S
"### "###
); );
@ -533,13 +533,13 @@ fn test() {
@r###" @r###"
[127; 211) '{ ...e(); }': () [127; 211) '{ ...e(); }': ()
[137; 138) 'a': u32 [137; 138) 'a': u32
[141; 148) 'S::make': fn make<S, u32>() -> T [141; 148) 'S::make': fn make<S, u32>() -> u32
[141; 150) 'S::make()': u32 [141; 150) 'S::make()': u32
[160; 161) 'b': u64 [160; 161) 'b': u64
[164; 178) 'G::<u64>::make': fn make<G<u64>, u64>() -> T [164; 178) 'G::<u64>::make': fn make<G<u64>, u64>() -> u64
[164; 180) 'G::<u6...make()': u64 [164; 180) 'G::<u6...make()': u64
[190; 191) 'c': f64 [190; 191) 'c': f64
[199; 206) 'G::make': fn make<G<f64>, f64>() -> T [199; 206) 'G::make': fn make<G<f64>, f64>() -> f64
[199; 208) 'G::make()': f64 [199; 208) 'G::make()': f64
"### "###
); );
@ -567,19 +567,19 @@ fn test() {
@r###" @r###"
[135; 313) '{ ...e(); }': () [135; 313) '{ ...e(); }': ()
[145; 146) 'a': (u32, i64) [145; 146) 'a': (u32, i64)
[149; 163) 'S::make::<i64>': fn make<S, u32, i64>() -> (T, U) [149; 163) 'S::make::<i64>': fn make<S, u32, i64>() -> (u32, i64)
[149; 165) 'S::mak...i64>()': (u32, i64) [149; 165) 'S::mak...i64>()': (u32, i64)
[175; 176) 'b': (u32, i64) [175; 176) 'b': (u32, i64)
[189; 196) 'S::make': fn make<S, u32, i64>() -> (T, U) [189; 196) 'S::make': fn make<S, u32, i64>() -> (u32, i64)
[189; 198) 'S::make()': (u32, i64) [189; 198) 'S::make()': (u32, i64)
[208; 209) 'c': (u32, i64) [208; 209) 'c': (u32, i64)
[212; 233) 'G::<u3...:<i64>': fn make<G<u32>, u32, i64>() -> (T, U) [212; 233) 'G::<u3...:<i64>': fn make<G<u32>, u32, i64>() -> (u32, i64)
[212; 235) 'G::<u3...i64>()': (u32, i64) [212; 235) 'G::<u3...i64>()': (u32, i64)
[245; 246) 'd': (u32, i64) [245; 246) 'd': (u32, i64)
[259; 273) 'G::make::<i64>': fn make<G<u32>, u32, i64>() -> (T, U) [259; 273) 'G::make::<i64>': fn make<G<u32>, u32, i64>() -> (u32, i64)
[259; 275) 'G::mak...i64>()': (u32, i64) [259; 275) 'G::mak...i64>()': (u32, i64)
[285; 286) 'e': (u32, i64) [285; 286) 'e': (u32, i64)
[301; 308) 'G::make': fn make<G<u32>, u32, i64>() -> (T, U) [301; 308) 'G::make': fn make<G<u32>, u32, i64>() -> (u32, i64)
[301; 310) 'G::make()': (u32, i64) [301; 310) 'G::make()': (u32, i64)
"### "###
); );
@ -601,7 +601,7 @@ fn test() {
@r###" @r###"
[101; 127) '{ ...e(); }': () [101; 127) '{ ...e(); }': ()
[111; 112) 'a': (S<i32>, i64) [111; 112) 'a': (S<i32>, i64)
[115; 122) 'S::make': fn make<S<i32>, i64>() -> (Self, T) [115; 122) 'S::make': fn make<S<i32>, i64>() -> (S<i32>, i64)
[115; 124) 'S::make()': (S<i32>, i64) [115; 124) 'S::make()': (S<i32>, i64)
"### "###
); );
@ -625,10 +625,10 @@ fn test() {
@r###" @r###"
[131; 203) '{ ...e(); }': () [131; 203) '{ ...e(); }': ()
[141; 142) 'a': (S<u64>, i64) [141; 142) 'a': (S<u64>, i64)
[158; 165) 'S::make': fn make<S<u64>, i64>() -> (Self, T) [158; 165) 'S::make': fn make<S<u64>, i64>() -> (S<u64>, i64)
[158; 167) 'S::make()': (S<u64>, i64) [158; 167) 'S::make()': (S<u64>, i64)
[177; 178) 'b': (S<u32>, i32) [177; 178) 'b': (S<u32>, i32)
[191; 198) 'S::make': fn make<S<u32>, i32>() -> (Self, T) [191; 198) 'S::make': fn make<S<u32>, i32>() -> (S<u32>, i32)
[191; 200) 'S::make()': (S<u32>, i32) [191; 200) 'S::make()': (S<u32>, i32)
"### "###
); );
@ -651,10 +651,10 @@ fn test() {
@r###" @r###"
[107; 211) '{ ...>(); }': () [107; 211) '{ ...>(); }': ()
[117; 118) 'a': (S<u64>, i64, u8) [117; 118) 'a': (S<u64>, i64, u8)
[121; 150) '<S as ...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U) [121; 150) '<S as ...::<u8>': fn make<S<u64>, i64, u8>() -> (S<u64>, i64, u8)
[121; 152) '<S as ...<u8>()': (S<u64>, i64, u8) [121; 152) '<S as ...<u8>()': (S<u64>, i64, u8)
[162; 163) 'b': (S<u64>, i64, u8) [162; 163) 'b': (S<u64>, i64, u8)
[182; 206) 'Trait:...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U) [182; 206) 'Trait:...::<u8>': fn make<S<u64>, i64, u8>() -> (S<u64>, i64, u8)
[182; 208) 'Trait:...<u8>()': (S<u64>, i64, u8) [182; 208) 'Trait:...<u8>()': (S<u64>, i64, u8)
"### "###
); );
@ -697,7 +697,7 @@ fn test<U, T: Trait<U>>(t: T) {
[71; 72) 't': T [71; 72) 't': T
[77; 96) '{ ...d(); }': () [77; 96) '{ ...d(); }': ()
[83; 84) 't': T [83; 84) 't': T
[83; 93) 't.method()': [missing name] [83; 93) 't.method()': U
"### "###
); );
} }
@ -728,7 +728,7 @@ fn test() {
[157; 158) 'S': S [157; 158) 'S': S
[157; 165) 'S.into()': u64 [157; 165) 'S.into()': u64
[175; 176) 'z': u64 [175; 176) 'z': u64
[179; 196) 'Into::...::into': fn into<S, u64>(Self) -> T [179; 196) 'Into::...::into': fn into<S, u64>(S) -> u64
[179; 199) 'Into::...nto(S)': u64 [179; 199) 'Into::...nto(S)': u64
[197; 198) 'S': S [197; 198) 'S': S
"### "###

View file

@ -96,13 +96,13 @@ fn test() {
[38; 42) 'A(n)': A<i32> [38; 42) 'A(n)': A<i32>
[40; 41) 'n': &i32 [40; 41) 'n': &i32
[45; 50) '&A(1)': &A<i32> [45; 50) '&A(1)': &A<i32>
[46; 47) 'A': A<i32>(T) -> A<T> [46; 47) 'A': A<i32>(i32) -> A<i32>
[46; 50) 'A(1)': A<i32> [46; 50) 'A(1)': A<i32>
[48; 49) '1': i32 [48; 49) '1': i32
[60; 64) 'A(n)': A<i32> [60; 64) 'A(n)': A<i32>
[62; 63) 'n': &mut i32 [62; 63) 'n': &mut i32
[67; 76) '&mut A(1)': &mut A<i32> [67; 76) '&mut A(1)': &mut A<i32>
[72; 73) 'A': A<i32>(T) -> A<T> [72; 73) 'A': A<i32>(i32) -> A<i32>
[72; 76) 'A(1)': A<i32> [72; 76) 'A(1)': A<i32>
[74; 75) '1': i32 [74; 75) '1': i32
"### "###

View file

@ -346,7 +346,7 @@ pub fn main_loop() {
@r###" @r###"
[144; 146) '{}': () [144; 146) '{}': ()
[169; 198) '{ ...t(); }': () [169; 198) '{ ...t(); }': ()
[175; 193) 'FxHash...efault': fn default<{unknown}, FxHasher>() -> HashSet<T, H> [175; 193) 'FxHash...efault': fn default<{unknown}, FxHasher>() -> HashSet<{unknown}, FxHasher>
[175; 195) 'FxHash...ault()': HashSet<{unknown}, FxHasher> [175; 195) 'FxHash...ault()': HashSet<{unknown}, FxHasher>
"### "###
); );

View file

@ -754,15 +754,15 @@ fn test() {
[289; 295) 'self.0': T [289; 295) 'self.0': T
[315; 353) '{ ...))); }': () [315; 353) '{ ...))); }': ()
[325; 326) 't': &i32 [325; 326) 't': &i32
[329; 335) 'A::foo': fn foo<i32>(&A<T>) -> &T [329; 335) 'A::foo': fn foo<i32>(&A<i32>) -> &i32
[329; 350) 'A::foo...42))))': &i32 [329; 350) 'A::foo...42))))': &i32
[336; 349) '&&B(B(A(42)))': &&B<B<A<i32>>> [336; 349) '&&B(B(A(42)))': &&B<B<A<i32>>>
[337; 349) '&B(B(A(42)))': &B<B<A<i32>>> [337; 349) '&B(B(A(42)))': &B<B<A<i32>>>
[338; 339) 'B': B<B<A<i32>>>(T) -> B<T> [338; 339) 'B': B<B<A<i32>>>(B<A<i32>>) -> B<B<A<i32>>>
[338; 349) 'B(B(A(42)))': B<B<A<i32>>> [338; 349) 'B(B(A(42)))': B<B<A<i32>>>
[340; 341) 'B': B<A<i32>>(T) -> B<T> [340; 341) 'B': B<A<i32>>(A<i32>) -> B<A<i32>>
[340; 348) 'B(A(42))': B<A<i32>> [340; 348) 'B(A(42))': B<A<i32>>
[342; 343) 'A': A<i32>(T) -> A<T> [342; 343) 'A': A<i32>(i32) -> A<i32>
[342; 347) 'A(42)': A<i32> [342; 347) 'A(42)': A<i32>
[344; 346) '42': i32 [344; 346) '42': i32
"### "###
@ -817,16 +817,16 @@ fn test(a: A<i32>) {
[326; 327) 'a': A<i32> [326; 327) 'a': A<i32>
[337; 383) '{ ...))); }': () [337; 383) '{ ...))); }': ()
[347; 348) 't': &i32 [347; 348) 't': &i32
[351; 352) 'A': A<i32>(*mut T) -> A<T> [351; 352) 'A': A<i32>(*mut i32) -> A<i32>
[351; 365) 'A(0 as *mut _)': A<i32> [351; 365) 'A(0 as *mut _)': A<i32>
[351; 380) 'A(0 as...B(a)))': &i32 [351; 380) 'A(0 as...B(a)))': &i32
[353; 354) '0': i32 [353; 354) '0': i32
[353; 364) '0 as *mut _': *mut i32 [353; 364) '0 as *mut _': *mut i32
[370; 379) '&&B(B(a))': &&B<B<A<i32>>> [370; 379) '&&B(B(a))': &&B<B<A<i32>>>
[371; 379) '&B(B(a))': &B<B<A<i32>>> [371; 379) '&B(B(a))': &B<B<A<i32>>>
[372; 373) 'B': B<B<A<i32>>>(T) -> B<T> [372; 373) 'B': B<B<A<i32>>>(B<A<i32>>) -> B<B<A<i32>>>
[372; 379) 'B(B(a))': B<B<A<i32>>> [372; 379) 'B(B(a))': B<B<A<i32>>>
[374; 375) 'B': B<A<i32>>(T) -> B<T> [374; 375) 'B': B<A<i32>>(A<i32>) -> B<A<i32>>
[374; 378) 'B(a)': B<A<i32>> [374; 378) 'B(a)': B<A<i32>>
[376; 377) 'a': A<i32> [376; 377) 'a': A<i32>
"### "###
@ -1169,16 +1169,16 @@ fn test() {
"#), "#),
@r###" @r###"
[76; 184) '{ ...one; }': () [76; 184) '{ ...one; }': ()
[82; 83) 'A': A<i32>(T) -> A<T> [82; 83) 'A': A<i32>(i32) -> A<i32>
[82; 87) 'A(42)': A<i32> [82; 87) 'A(42)': A<i32>
[84; 86) '42': i32 [84; 86) '42': i32
[93; 94) 'A': A<u128>(T) -> A<T> [93; 94) 'A': A<u128>(u128) -> A<u128>
[93; 102) 'A(42u128)': A<u128> [93; 102) 'A(42u128)': A<u128>
[95; 101) '42u128': u128 [95; 101) '42u128': u128
[108; 112) 'Some': Some<&str>(T) -> Option<T> [108; 112) 'Some': Some<&str>(&str) -> Option<&str>
[108; 117) 'Some("x")': Option<&str> [108; 117) 'Some("x")': Option<&str>
[113; 116) '"x"': &str [113; 116) '"x"': &str
[123; 135) 'Option::Some': Some<&str>(T) -> Option<T> [123; 135) 'Option::Some': Some<&str>(&str) -> Option<&str>
[123; 140) 'Option...e("x")': Option<&str> [123; 140) 'Option...e("x")': Option<&str>
[136; 139) '"x"': &str [136; 139) '"x"': &str
[146; 150) 'None': Option<{unknown}> [146; 150) 'None': Option<{unknown}>
@ -1205,14 +1205,14 @@ fn test() {
[21; 26) '{ t }': T [21; 26) '{ t }': T
[23; 24) 't': T [23; 24) 't': T
[38; 98) '{ ...(1); }': () [38; 98) '{ ...(1); }': ()
[44; 46) 'id': fn id<u32>(T) -> T [44; 46) 'id': fn id<u32>(u32) -> u32
[44; 52) 'id(1u32)': u32 [44; 52) 'id(1u32)': u32
[47; 51) '1u32': u32 [47; 51) '1u32': u32
[58; 68) 'id::<i128>': fn id<i128>(T) -> T [58; 68) 'id::<i128>': fn id<i128>(i128) -> i128
[58; 71) 'id::<i128>(1)': i128 [58; 71) 'id::<i128>(1)': i128
[69; 70) '1': i128 [69; 70) '1': i128
[81; 82) 'x': u64 [81; 82) 'x': u64
[90; 92) 'id': fn id<u64>(T) -> T [90; 92) 'id': fn id<u64>(u64) -> u64
[90; 95) 'id(1)': u64 [90; 95) 'id(1)': u64
[93; 94) '1': u64 [93; 94) '1': u64
"### "###
@ -1220,7 +1220,7 @@ fn test() {
} }
#[test] #[test]
fn infer_impl_generics() { fn infer_impl_generics_basic() {
assert_snapshot!( assert_snapshot!(
infer(r#" infer(r#"
struct A<T1, T2> { struct A<T1, T2> {
@ -1349,16 +1349,16 @@ fn test() -> i128 {
[146; 147) 'x': i128 [146; 147) 'x': i128
[150; 151) '1': i128 [150; 151) '1': i128
[162; 163) 'y': i128 [162; 163) 'y': i128
[166; 168) 'id': fn id<i128>(T) -> T [166; 168) 'id': fn id<i128>(i128) -> i128
[166; 171) 'id(x)': i128 [166; 171) 'id(x)': i128
[169; 170) 'x': i128 [169; 170) 'x': i128
[182; 183) 'a': A<i128> [182; 183) 'a': A<i128>
[186; 200) 'A { x: id(y) }': A<i128> [186; 200) 'A { x: id(y) }': A<i128>
[193; 195) 'id': fn id<i128>(T) -> T [193; 195) 'id': fn id<i128>(i128) -> i128
[193; 198) 'id(y)': i128 [193; 198) 'id(y)': i128
[196; 197) 'y': i128 [196; 197) 'y': i128
[211; 212) 'z': i128 [211; 212) 'z': i128
[215; 217) 'id': fn id<i128>(T) -> T [215; 217) 'id': fn id<i128>(i128) -> i128
[215; 222) 'id(a.x)': i128 [215; 222) 'id(a.x)': i128
[218; 219) 'a': A<i128> [218; 219) 'a': A<i128>
[218; 221) 'a.x': i128 [218; 221) 'a.x': i128
@ -1502,14 +1502,14 @@ fn test() {
[78; 158) '{ ...(1); }': () [78; 158) '{ ...(1); }': ()
[88; 89) 'y': u32 [88; 89) 'y': u32
[92; 97) '10u32': u32 [92; 97) '10u32': u32
[103; 105) 'id': fn id<u32>(T) -> T [103; 105) 'id': fn id<u32>(u32) -> u32
[103; 108) 'id(y)': u32 [103; 108) 'id(y)': u32
[106; 107) 'y': u32 [106; 107) 'y': u32
[118; 119) 'x': bool [118; 119) 'x': bool
[128; 133) 'clone': fn clone<bool>(&T) -> T [128; 133) 'clone': fn clone<bool>(&bool) -> bool
[128; 136) 'clone(z)': bool [128; 136) 'clone(z)': bool
[134; 135) 'z': &bool [134; 135) 'z': &bool
[142; 152) 'id::<i128>': fn id<i128>(T) -> T [142; 152) 'id::<i128>': fn id<i128>(i128) -> i128
[142; 155) 'id::<i128>(1)': i128 [142; 155) 'id::<i128>(1)': i128
[153; 154) '1': i128 [153; 154) '1': i128
"### "###

View file

@ -1,7 +1,6 @@
use insta::assert_snapshot; use insta::assert_snapshot;
use ra_db::fixture::WithFixture; use ra_db::fixture::WithFixture;
use test_utils::covers;
use super::{infer, infer_with_mismatches, type_at, type_at_pos}; use super::{infer, infer_with_mismatches, type_at, type_at_pos};
use crate::test_db::TestDB; use crate::test_db::TestDB;
@ -261,10 +260,10 @@ fn test() {
[92; 94) '{}': () [92; 94) '{}': ()
[105; 144) '{ ...(s); }': () [105; 144) '{ ...(s); }': ()
[115; 116) 's': S<u32> [115; 116) 's': S<u32>
[119; 120) 'S': S<u32>(T) -> S<T> [119; 120) 'S': S<u32>(u32) -> S<u32>
[119; 129) 'S(unknown)': S<u32> [119; 129) 'S(unknown)': S<u32>
[121; 128) 'unknown': u32 [121; 128) 'unknown': u32
[135; 138) 'foo': fn foo<S<u32>>(T) -> () [135; 138) 'foo': fn foo<S<u32>>(S<u32>) -> ()
[135; 141) 'foo(s)': () [135; 141) 'foo(s)': ()
[139; 140) 's': S<u32> [139; 140) 's': S<u32>
"### "###
@ -289,11 +288,11 @@ fn test() {
[98; 100) '{}': () [98; 100) '{}': ()
[111; 163) '{ ...(s); }': () [111; 163) '{ ...(s); }': ()
[121; 122) 's': S<u32> [121; 122) 's': S<u32>
[125; 126) 'S': S<u32>(T) -> S<T> [125; 126) 'S': S<u32>(u32) -> S<u32>
[125; 135) 'S(unknown)': S<u32> [125; 135) 'S(unknown)': S<u32>
[127; 134) 'unknown': u32 [127; 134) 'unknown': u32
[145; 146) 'x': u32 [145; 146) 'x': u32
[154; 157) 'foo': fn foo<u32, S<u32>>(T) -> U [154; 157) 'foo': fn foo<u32, S<u32>>(S<u32>) -> u32
[154; 160) 'foo(s)': u32 [154; 160) 'foo(s)': u32
[158; 159) 's': S<u32> [158; 159) 's': S<u32>
"### "###
@ -358,15 +357,15 @@ fn test() {
[221; 223) '{}': () [221; 223) '{}': ()
[234; 300) '{ ...(S); }': () [234; 300) '{ ...(S); }': ()
[244; 245) 'x': u32 [244; 245) 'x': u32
[248; 252) 'foo1': fn foo1<S>(T) -> <T as Iterable>::Item [248; 252) 'foo1': fn foo1<S>(S) -> <S as Iterable>::Item
[248; 255) 'foo1(S)': u32 [248; 255) 'foo1(S)': u32
[253; 254) 'S': S [253; 254) 'S': S
[265; 266) 'y': u32 [265; 266) 'y': u32
[269; 273) 'foo2': fn foo2<S>(T) -> <T as Iterable>::Item [269; 273) 'foo2': fn foo2<S>(S) -> <S as Iterable>::Item
[269; 276) 'foo2(S)': u32 [269; 276) 'foo2(S)': u32
[274; 275) 'S': S [274; 275) 'S': S
[286; 287) 'z': u32 [286; 287) 'z': u32
[290; 294) 'foo3': fn foo3<S>(T) -> <T as Iterable>::Item [290; 294) 'foo3': fn foo3<S>(S) -> <S as Iterable>::Item
[290; 297) 'foo3(S)': u32 [290; 297) 'foo3(S)': u32
[295; 296) 'S': S [295; 296) 'S': S
"### "###
@ -822,8 +821,7 @@ fn test<T: ApplyL>() {
"#, "#,
); );
// inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out<T>` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types]. // inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out<T>` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types].
// FIXME: fix type parameter names going missing when going through Chalk assert_eq!(t, "ApplyL::Out<T>");
assert_eq!(t, "ApplyL::Out<[missing name]>");
} }
#[test] #[test]
@ -849,6 +847,197 @@ fn test<T: ApplyL>(t: T) {
assert_eq!(t, "{unknown}"); assert_eq!(t, "{unknown}");
} }
#[test]
fn argument_impl_trait() {
assert_snapshot!(
infer_with_mismatches(r#"
trait Trait<T> {
fn foo(&self) -> T;
fn foo2(&self) -> i64;
}
fn bar(x: impl Trait<u16>) {}
struct S<T>(T);
impl<T> Trait<T> for S<T> {}
fn test(x: impl Trait<u64>, y: &impl Trait<u32>) {
x;
y;
let z = S(1);
bar(z);
x.foo();
y.foo();
z.foo();
x.foo2();
y.foo2();
z.foo2();
}
"#, true),
@r###"
[30; 34) 'self': &Self
[55; 59) 'self': &Self
[78; 79) 'x': impl Trait<u16>
[98; 100) '{}': ()
[155; 156) 'x': impl Trait<u64>
[175; 176) 'y': &impl Trait<u32>
[196; 324) '{ ...2(); }': ()
[202; 203) 'x': impl Trait<u64>
[209; 210) 'y': &impl Trait<u32>
[220; 221) 'z': S<u16>
[224; 225) 'S': S<u16>(u16) -> S<u16>
[224; 228) 'S(1)': S<u16>
[226; 227) '1': u16
[234; 237) 'bar': fn bar(S<u16>) -> ()
[234; 240) 'bar(z)': ()
[238; 239) 'z': S<u16>
[246; 247) 'x': impl Trait<u64>
[246; 253) 'x.foo()': u64
[259; 260) 'y': &impl Trait<u32>
[259; 266) 'y.foo()': u32
[272; 273) 'z': S<u16>
[272; 279) 'z.foo()': u16
[285; 286) 'x': impl Trait<u64>
[285; 293) 'x.foo2()': i64
[299; 300) 'y': &impl Trait<u32>
[299; 307) 'y.foo2()': i64
[313; 314) 'z': S<u16>
[313; 321) 'z.foo2()': i64
"###
);
}
#[test]
fn argument_impl_trait_type_args_1() {
assert_snapshot!(
infer_with_mismatches(r#"
trait Trait {}
trait Foo {
// this function has an implicit Self param, an explicit type param,
// and an implicit impl Trait param!
fn bar<T>(x: impl Trait) -> T { loop {} }
}
fn foo<T>(x: impl Trait) -> T { loop {} }
struct S;
impl Trait for S {}
struct F;
impl Foo for F {}
fn test() {
Foo::bar(S);
<F as Foo>::bar(S);
F::bar(S);
Foo::bar::<u32>(S);
<F as Foo>::bar::<u32>(S);
foo(S);
foo::<u32>(S);
foo::<u32, i32>(S); // we should ignore the extraneous i32
}
"#, true),
@r###"
[156; 157) 'x': impl Trait
[176; 187) '{ loop {} }': T
[178; 185) 'loop {}': !
[183; 185) '{}': ()
[200; 201) 'x': impl Trait
[220; 231) '{ loop {} }': T
[222; 229) 'loop {}': !
[227; 229) '{}': ()
[301; 510) '{ ... i32 }': ()
[307; 315) 'Foo::bar': fn bar<{unknown}, {unknown}>(S) -> {unknown}
[307; 318) 'Foo::bar(S)': {unknown}
[316; 317) 'S': S
[324; 339) '<F as Foo>::bar': fn bar<F, {unknown}>(S) -> {unknown}
[324; 342) '<F as ...bar(S)': {unknown}
[340; 341) 'S': S
[348; 354) 'F::bar': fn bar<F, {unknown}>(S) -> {unknown}
[348; 357) 'F::bar(S)': {unknown}
[355; 356) 'S': S
[363; 378) 'Foo::bar::<u32>': fn bar<{unknown}, u32>(S) -> u32
[363; 381) 'Foo::b...32>(S)': u32
[379; 380) 'S': S
[387; 409) '<F as ...:<u32>': fn bar<F, u32>(S) -> u32
[387; 412) '<F as ...32>(S)': u32
[410; 411) 'S': S
[419; 422) 'foo': fn foo<{unknown}>(S) -> {unknown}
[419; 425) 'foo(S)': {unknown}
[423; 424) 'S': S
[431; 441) 'foo::<u32>': fn foo<u32>(S) -> u32
[431; 444) 'foo::<u32>(S)': u32
[442; 443) 'S': S
[450; 465) 'foo::<u32, i32>': fn foo<u32>(S) -> u32
[450; 468) 'foo::<...32>(S)': u32
[466; 467) 'S': S
"###
);
}
#[test]
fn argument_impl_trait_type_args_2() {
assert_snapshot!(
infer_with_mismatches(r#"
trait Trait {}
struct S;
impl Trait for S {}
struct F<T>;
impl<T> F<T> {
fn foo<U>(self, x: impl Trait) -> (T, U) { loop {} }
}
fn test() {
F.foo(S);
F::<u32>.foo(S);
F::<u32>.foo::<i32>(S);
F::<u32>.foo::<i32, u32>(S); // extraneous argument should be ignored
}
"#, true),
@r###"
[88; 92) 'self': F<T>
[94; 95) 'x': impl Trait
[119; 130) '{ loop {} }': (T, U)
[121; 128) 'loop {}': !
[126; 128) '{}': ()
[144; 284) '{ ...ored }': ()
[150; 151) 'F': F<{unknown}>
[150; 158) 'F.foo(S)': ({unknown}, {unknown})
[156; 157) 'S': S
[164; 172) 'F::<u32>': F<u32>
[164; 179) 'F::<u32>.foo(S)': (u32, {unknown})
[177; 178) 'S': S
[185; 193) 'F::<u32>': F<u32>
[185; 207) 'F::<u3...32>(S)': (u32, i32)
[205; 206) 'S': S
[213; 221) 'F::<u32>': F<u32>
[213; 240) 'F::<u3...32>(S)': (u32, i32)
[238; 239) 'S': S
"###
);
}
#[test]
fn argument_impl_trait_to_fn_pointer() {
assert_snapshot!(
infer_with_mismatches(r#"
trait Trait {}
fn foo(x: impl Trait) { loop {} }
struct S;
impl Trait for S {}
fn test() {
let f: fn(S) -> () = foo;
}
"#, true),
@r###"
[23; 24) 'x': impl Trait
[38; 49) '{ loop {} }': ()
[40; 47) 'loop {}': !
[45; 47) '{}': ()
[91; 124) '{ ...foo; }': ()
[101; 102) 'f': fn(S) -> ()
[118; 121) 'foo': fn foo(S) -> ()
"###
);
}
#[test] #[test]
#[ignore] #[ignore]
fn impl_trait() { fn impl_trait() {
@ -994,29 +1183,17 @@ fn weird_bounds() {
assert_snapshot!( assert_snapshot!(
infer(r#" infer(r#"
trait Trait {} trait Trait {}
fn test() { fn test(a: impl Trait + 'lifetime, b: impl 'lifetime, c: impl (Trait), d: impl ('lifetime), e: impl ?Sized, f: impl Trait + ?Sized) {
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###" @r###"
[26; 237) '{ ...foo; }': () [24; 25) 'a': impl Trait + {error}
[36; 37) 'a': impl Trait + {error} [51; 52) 'b': impl {error}
[64; 67) 'foo': impl Trait + {error} [70; 71) 'c': impl Trait
[77; 78) 'b': impl {error} [87; 88) 'd': impl {error}
[97; 100) 'foo': impl {error} [108; 109) 'e': impl {error}
[110; 111) 'b': impl Trait [124; 125) 'f': impl Trait + {error}
[128; 131) 'foo': impl Trait [148; 151) '{ }': ()
[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}
"### "###
); );
} }
@ -1078,26 +1255,26 @@ fn test<T: Trait<Type = u32>>(x: T, y: impl Trait<Type = i64>) {
[296; 299) 'get': fn get<T>(T) -> <T as Trait>::Type [296; 299) 'get': fn get<T>(T) -> <T as Trait>::Type
[296; 302) 'get(x)': {unknown} [296; 302) 'get(x)': {unknown}
[300; 301) 'x': T [300; 301) 'x': T
[308; 312) 'get2': fn get2<{unknown}, T>(T) -> U [308; 312) 'get2': fn get2<{unknown}, T>(T) -> {unknown}
[308; 315) 'get2(x)': {unknown} [308; 315) 'get2(x)': {unknown}
[313; 314) 'x': T [313; 314) 'x': T
[321; 324) 'get': fn get<impl Trait<Type = i64>>(T) -> <T as Trait>::Type [321; 324) 'get': fn get<impl Trait<Type = i64>>(impl Trait<Type = i64>) -> <impl Trait<Type = i64> as Trait>::Type
[321; 327) 'get(y)': {unknown} [321; 327) 'get(y)': {unknown}
[325; 326) 'y': impl Trait<Type = i64> [325; 326) 'y': impl Trait<Type = i64>
[333; 337) 'get2': fn get2<{unknown}, impl Trait<Type = i64>>(T) -> U [333; 337) 'get2': fn get2<{unknown}, impl Trait<Type = i64>>(impl Trait<Type = i64>) -> {unknown}
[333; 340) 'get2(y)': {unknown} [333; 340) 'get2(y)': {unknown}
[338; 339) 'y': impl Trait<Type = i64> [338; 339) 'y': impl Trait<Type = i64>
[346; 349) 'get': fn get<S<u64>>(T) -> <T as Trait>::Type [346; 349) 'get': fn get<S<u64>>(S<u64>) -> <S<u64> as Trait>::Type
[346; 357) 'get(set(S))': u64 [346; 357) 'get(set(S))': u64
[350; 353) 'set': fn set<S<u64>>(T) -> T [350; 353) 'set': fn set<S<u64>>(S<u64>) -> S<u64>
[350; 356) 'set(S)': S<u64> [350; 356) 'set(S)': S<u64>
[354; 355) 'S': S<u64> [354; 355) 'S': S<u64>
[363; 367) 'get2': fn get2<u64, S<u64>>(T) -> U [363; 367) 'get2': fn get2<u64, S<u64>>(S<u64>) -> u64
[363; 375) 'get2(set(S))': u64 [363; 375) 'get2(set(S))': u64
[368; 371) 'set': fn set<S<u64>>(T) -> T [368; 371) 'set': fn set<S<u64>>(S<u64>) -> S<u64>
[368; 374) 'set(S)': S<u64> [368; 374) 'set(S)': S<u64>
[372; 373) 'S': S<u64> [372; 373) 'S': S<u64>
[381; 385) 'get2': fn get2<str, S<str>>(T) -> U [381; 385) 'get2': fn get2<str, S<str>>(S<str>) -> str
[381; 395) 'get2(S::<str>)': str [381; 395) 'get2(S::<str>)': str
[386; 394) 'S::<str>': S<str> [386; 394) 'S::<str>': S<str>
"### "###
@ -1224,6 +1401,32 @@ fn test<T: Trait1, U: Trait2>(x: T, y: U) {
); );
} }
#[test]
fn super_trait_impl_trait_method_resolution() {
assert_snapshot!(
infer(r#"
mod foo {
trait SuperTrait {
fn foo(&self) -> u32 {}
}
}
trait Trait1: foo::SuperTrait {}
fn test(x: &impl Trait1) {
x.foo();
}
"#),
@r###"
[50; 54) 'self': &Self
[63; 65) '{}': ()
[116; 117) 'x': &impl Trait1
[133; 149) '{ ...o(); }': ()
[139; 140) 'x': &impl Trait1
[139; 146) 'x.foo()': u32
"###
);
}
#[test] #[test]
fn super_trait_cycle() { fn super_trait_cycle() {
// This just needs to not crash // This just needs to not crash
@ -1270,9 +1473,9 @@ fn test() {
[157; 160) '{t}': T [157; 160) '{t}': T
[158; 159) 't': T [158; 159) 't': T
[259; 280) '{ ...S)); }': () [259; 280) '{ ...S)); }': ()
[265; 269) 'get2': fn get2<u64, S<u64>>(T) -> U [265; 269) 'get2': fn get2<u64, S<u64>>(S<u64>) -> u64
[265; 277) 'get2(set(S))': u64 [265; 277) 'get2(set(S))': u64
[270; 273) 'set': fn set<S<u64>>(T) -> T [270; 273) 'set': fn set<S<u64>>(S<u64>) -> S<u64>
[270; 276) 'set(S)': S<u64> [270; 276) 'set(S)': S<u64>
[274; 275) 'S': S<u64> [274; 275) 'S': S<u64>
"### "###
@ -1334,7 +1537,7 @@ fn test() {
[173; 175) '{}': () [173; 175) '{}': ()
[189; 308) '{ ... 1); }': () [189; 308) '{ ... 1); }': ()
[199; 200) 'x': Option<u32> [199; 200) 'x': Option<u32>
[203; 215) 'Option::Some': Some<u32>(T) -> Option<T> [203; 215) 'Option::Some': Some<u32>(u32) -> Option<u32>
[203; 221) 'Option...(1u32)': Option<u32> [203; 221) 'Option...(1u32)': Option<u32>
[216; 220) '1u32': u32 [216; 220) '1u32': u32
[227; 228) 'x': Option<u32> [227; 228) 'x': Option<u32>
@ -1444,7 +1647,7 @@ fn test() {
[340; 342) '{}': () [340; 342) '{}': ()
[356; 515) '{ ... S); }': () [356; 515) '{ ... S); }': ()
[366; 368) 'x1': u64 [366; 368) 'x1': u64
[371; 375) 'foo1': fn foo1<S, u64, |S| -> u64>(T, F) -> U [371; 375) 'foo1': fn foo1<S, u64, |S| -> u64>(S, |S| -> u64) -> u64
[371; 394) 'foo1(S...hod())': u64 [371; 394) 'foo1(S...hod())': u64
[376; 377) 'S': S [376; 377) 'S': S
[379; 393) '|s| s.method()': |S| -> u64 [379; 393) '|s| s.method()': |S| -> u64
@ -1452,7 +1655,7 @@ fn test() {
[383; 384) 's': S [383; 384) 's': S
[383; 393) 's.method()': u64 [383; 393) 's.method()': u64
[404; 406) 'x2': u64 [404; 406) 'x2': u64
[409; 413) 'foo2': fn foo2<S, u64, |S| -> u64>(F, T) -> U [409; 413) 'foo2': fn foo2<S, u64, |S| -> u64>(|S| -> u64, S) -> u64
[409; 432) 'foo2(|...(), S)': u64 [409; 432) 'foo2(|...(), S)': u64
[414; 428) '|s| s.method()': |S| -> u64 [414; 428) '|s| s.method()': |S| -> u64
[415; 416) 's': S [415; 416) 's': S
@ -1605,7 +1808,6 @@ fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> {
#[test] #[test]
fn unify_impl_trait() { fn unify_impl_trait() {
covers!(insert_vars_for_impl_trait);
assert_snapshot!( assert_snapshot!(
infer_with_mismatches(r#" infer_with_mismatches(r#"
trait Trait<T> {} trait Trait<T> {}
@ -1637,26 +1839,26 @@ fn test() -> impl Trait<i32> {
[172; 183) '{ loop {} }': T [172; 183) '{ loop {} }': T
[174; 181) 'loop {}': ! [174; 181) 'loop {}': !
[179; 181) '{}': () [179; 181) '{}': ()
[214; 310) '{ ...t()) }': S<i32> [214; 310) '{ ...t()) }': S<{unknown}>
[224; 226) 's1': S<u32> [224; 226) 's1': S<u32>
[229; 230) 'S': S<u32>(T) -> S<T> [229; 230) 'S': S<u32>(u32) -> S<u32>
[229; 241) 'S(default())': S<u32> [229; 241) 'S(default())': S<u32>
[231; 238) 'default': fn default<u32>() -> T [231; 238) 'default': fn default<u32>() -> u32
[231; 240) 'default()': u32 [231; 240) 'default()': u32
[247; 250) 'foo': fn foo(impl Trait<u32>) -> () [247; 250) 'foo': fn foo(S<u32>) -> ()
[247; 254) 'foo(s1)': () [247; 254) 'foo(s1)': ()
[251; 253) 's1': S<u32> [251; 253) 's1': S<u32>
[264; 265) 'x': i32 [264; 265) 'x': i32
[273; 276) 'bar': fn bar<i32>(impl Trait<T>) -> T [273; 276) 'bar': fn bar<i32>(S<i32>) -> i32
[273; 290) 'bar(S(...lt()))': i32 [273; 290) 'bar(S(...lt()))': i32
[277; 278) 'S': S<i32>(T) -> S<T> [277; 278) 'S': S<i32>(i32) -> S<i32>
[277; 289) 'S(default())': S<i32> [277; 289) 'S(default())': S<i32>
[279; 286) 'default': fn default<i32>() -> T [279; 286) 'default': fn default<i32>() -> i32
[279; 288) 'default()': i32 [279; 288) 'default()': i32
[296; 297) 'S': S<i32>(T) -> S<T> [296; 297) 'S': S<{unknown}>({unknown}) -> S<{unknown}>
[296; 308) 'S(default())': S<i32> [296; 308) 'S(default())': S<{unknown}>
[298; 305) 'default': fn default<i32>() -> T [298; 305) 'default': fn default<{unknown}>() -> {unknown}
[298; 307) 'default()': i32 [298; 307) 'default()': {unknown}
"### "###
); );
} }

View file

@ -14,7 +14,7 @@ use ra_db::{
use super::{builtin, AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; use super::{builtin, AssocTyValue, Canonical, ChalkContext, Impl, Obligation};
use crate::{ use crate::{
db::HirDatabase, display::HirDisplay, utils::generics, ApplicationTy, GenericPredicate, db::HirDatabase, display::HirDisplay, utils::generics, ApplicationTy, GenericPredicate,
ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, ProjectionTy, Substs, TraitRef, Ty, TypeCtor,
}; };
#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] #[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
@ -142,8 +142,12 @@ impl ToChalk for Ty {
let substitution = proj_ty.parameters.to_chalk(db); let substitution = proj_ty.parameters.to_chalk(db);
chalk_ir::AliasTy { associated_ty_id, substitution }.cast().intern() chalk_ir::AliasTy { associated_ty_id, substitution }.cast().intern()
} }
Ty::Param { idx, .. } => { Ty::Param(id) => {
PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize } let interned_id = db.intern_type_param_id(id);
PlaceholderIndex {
ui: UniverseIndex::ROOT,
idx: interned_id.as_intern_id().as_usize(),
}
.to_ty::<TypeFamily>() .to_ty::<TypeFamily>()
} }
Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(),
@ -177,7 +181,10 @@ impl ToChalk for Ty {
}, },
chalk_ir::TyData::Placeholder(idx) => { chalk_ir::TyData::Placeholder(idx) => {
assert_eq!(idx.ui, UniverseIndex::ROOT); assert_eq!(idx.ui, UniverseIndex::ROOT);
Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } let interned_id = crate::db::GlobalTypeParamId::from_intern_id(
crate::salsa::InternId::from(idx.idx),
);
Ty::Param(db.lookup_intern_type_param_id(interned_id))
} }
chalk_ir::TyData::Alias(proj) => { chalk_ir::TyData::Alias(proj) => {
let associated_ty = from_chalk(db, proj.associated_ty_id); let associated_ty = from_chalk(db, proj.associated_ty_id);
@ -520,7 +527,7 @@ fn convert_where_clauses(
let generic_predicates = db.generic_predicates(def); let generic_predicates = db.generic_predicates(def);
let mut result = Vec::with_capacity(generic_predicates.len()); let mut result = Vec::with_capacity(generic_predicates.len());
for pred in generic_predicates.iter() { for pred in generic_predicates.iter() {
if pred.is_error() { if pred.value.is_error() {
// skip errored predicates completely // skip errored predicates completely
continue; continue;
} }
@ -709,12 +716,12 @@ fn impl_block_datum(
let trait_ref = db let trait_ref = db
.impl_trait(impl_id) .impl_trait(impl_id)
// ImplIds for impls where the trait ref can't be resolved should never reach Chalk // ImplIds for impls where the trait ref can't be resolved should never reach Chalk
.expect("invalid impl passed to Chalk"); .expect("invalid impl passed to Chalk")
.value;
let impl_data = db.impl_data(impl_id); let impl_data = db.impl_data(impl_id);
let generic_params = generics(db, impl_id.into()); let generic_params = generics(db, impl_id.into());
let bound_vars = Substs::bound_vars(&generic_params); let bound_vars = Substs::bound_vars(&generic_params);
let trait_ref = trait_ref.subst(&bound_vars);
let trait_ = trait_ref.trait_; let trait_ = trait_ref.trait_;
let impl_type = if impl_id.lookup(db).container.module(db).krate == krate { let impl_type = if impl_id.lookup(db).container.module(db).krate == krate {
chalk_rust_ir::ImplType::Local chalk_rust_ir::ImplType::Local
@ -789,20 +796,18 @@ fn type_alias_associated_ty_value(
_ => panic!("assoc ty value should be in impl"), _ => panic!("assoc ty value should be in impl"),
}; };
let trait_ref = db.impl_trait(impl_id).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 = db.impl_trait(impl_id).expect("assoc ty value should not exist").value; // we don't return any assoc ty values if the impl'd trait can't be resolved
let assoc_ty = db let assoc_ty = db
.trait_data(trait_ref.trait_) .trait_data(trait_ref.trait_)
.associated_type_by_name(&type_alias_data.name) .associated_type_by_name(&type_alias_data.name)
.expect("assoc ty value should not exist"); // validated when building the impl data as well .expect("assoc ty value should not exist"); // validated when building the impl data as well
let generic_params = generics(db, impl_id.into()); let ty = db.ty(type_alias.into());
let bound_vars = Substs::bound_vars(&generic_params); let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
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 { let value = chalk_rust_ir::AssociatedTyValue {
impl_id: Impl::ImplBlock(impl_id.into()).to_chalk(db), impl_id: Impl::ImplBlock(impl_id.into()).to_chalk(db),
associated_ty_id: assoc_ty.to_chalk(db), associated_ty_id: assoc_ty.to_chalk(db),
value: make_binders(value_bound, bound_vars.len()), value: make_binders(value_bound, ty.num_binders),
}; };
Arc::new(value) Arc::new(value)
} }

View file

@ -2,10 +2,11 @@
//! query, but can't be computed directly from `*Data` (ie, which need a `db`). //! query, but can't be computed directly from `*Data` (ie, which need a `db`).
use std::sync::Arc; use std::sync::Arc;
use hir_def::generics::WherePredicateTarget;
use hir_def::{ use hir_def::{
adt::VariantData, adt::VariantData,
db::DefDatabase, db::DefDatabase,
generics::{GenericParams, TypeParamData}, generics::{GenericParams, TypeParamData, TypeParamProvenance},
path::Path, path::Path,
resolver::{HasResolver, TypeNs}, resolver::{HasResolver, TypeNs},
type_ref::TypeRef, type_ref::TypeRef,
@ -19,11 +20,18 @@ fn direct_super_traits(db: &impl DefDatabase, trait_: TraitId) -> Vec<TraitId> {
// lifetime problems, but since there usually shouldn't be more than a // 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 // few direct traits this should be fine (we could even use some kind of
// SmallVec if performance is a concern) // SmallVec if performance is a concern)
db.generic_params(trait_.into()) let generic_params = db.generic_params(trait_.into());
let trait_self = generic_params.find_trait_self_param();
generic_params
.where_predicates .where_predicates
.iter() .iter()
.filter_map(|pred| match &pred.type_ref { .filter_map(|pred| match &pred.target {
TypeRef::Path(p) if p == &Path::from(name![Self]) => pred.bound.as_path(), WherePredicateTarget::TypeRef(TypeRef::Path(p)) if p == &Path::from(name![Self]) => {
pred.bound.as_path()
}
WherePredicateTarget::TypeParam(local_id) if Some(*local_id) == trait_self => {
pred.bound.as_path()
}
_ => None, _ => None,
}) })
.filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) { .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path.mod_path()) {
@ -95,41 +103,77 @@ pub(crate) struct Generics {
} }
impl Generics { impl Generics {
pub(crate) fn iter<'a>(&'a self) -> impl Iterator<Item = (u32, &'a TypeParamData)> + 'a { pub(crate) fn iter<'a>(
&'a self,
) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
self.parent_generics self.parent_generics
.as_ref() .as_ref()
.into_iter() .into_iter()
.flat_map(|it| it.params.types.iter()) .flat_map(|it| {
.chain(self.params.types.iter()) it.params
.enumerate() .types
.map(|(i, (_local_id, p))| (i as u32, p)) .iter()
.map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
})
.chain(
self.params
.types
.iter()
.map(move |(local_id, p)| (TypeParamId { parent: self.def, local_id }, p)),
)
} }
pub(crate) fn iter_parent<'a>(&'a self) -> impl Iterator<Item = (u32, &'a TypeParamData)> + 'a { pub(crate) fn iter_parent<'a>(
self.parent_generics &'a self,
.as_ref() ) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
.into_iter() self.parent_generics.as_ref().into_iter().flat_map(|it| {
.flat_map(|it| it.params.types.iter()) it.params
.enumerate() .types
.map(|(i, (_local_id, p))| (i as u32, p)) .iter()
.map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
})
} }
pub(crate) fn len(&self) -> usize { pub(crate) fn len(&self) -> usize {
self.len_split().0 self.len_split().0
} }
/// (total, parents, child) /// (total, parents, child)
pub(crate) fn len_split(&self) -> (usize, usize, usize) { pub(crate) fn len_split(&self) -> (usize, usize, usize) {
let parent = self.parent_generics.as_ref().map_or(0, |p| p.len()); let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
let child = self.params.types.len(); let child = self.params.types.len();
(parent + child, parent, child) (parent + child, parent, child)
} }
pub(crate) fn param_idx(&self, param: TypeParamId) -> u32 {
self.find_param(param).0 /// (parent total, self param, type param list, impl trait)
pub(crate) fn provenance_split(&self) -> (usize, usize, usize, usize) {
let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
let self_params = self
.params
.types
.iter()
.filter(|(_, p)| p.provenance == TypeParamProvenance::TraitSelf)
.count();
let list_params = self
.params
.types
.iter()
.filter(|(_, p)| p.provenance == TypeParamProvenance::TypeParamList)
.count();
let impl_trait_params = self
.params
.types
.iter()
.filter(|(_, p)| p.provenance == TypeParamProvenance::ArgumentImplTrait)
.count();
(parent, self_params, list_params, impl_trait_params)
} }
pub(crate) fn param_name(&self, param: TypeParamId) -> Name {
self.find_param(param).1.name.clone() pub(crate) fn param_idx(&self, param: TypeParamId) -> Option<u32> {
Some(self.find_param(param)?.0)
} }
fn find_param(&self, param: TypeParamId) -> (u32, &TypeParamData) {
fn find_param(&self, param: TypeParamId) -> Option<(u32, &TypeParamData)> {
if param.parent == self.def { if param.parent == self.def {
let (idx, (_local_id, data)) = self let (idx, (_local_id, data)) = self
.params .params
@ -139,9 +183,10 @@ impl Generics {
.find(|(_, (idx, _))| *idx == param.local_id) .find(|(_, (idx, _))| *idx == param.local_id)
.unwrap(); .unwrap();
let (_total, parent_len, _child) = self.len_split(); let (_total, parent_len, _child) = self.len_split();
return ((parent_len + idx) as u32, data); Some(((parent_len + idx) as u32, data))
} else {
self.parent_generics.as_ref().and_then(|g| g.find_param(param))
} }
self.parent_generics.as_ref().unwrap().find_param(param)
} }
} }