mirror of
https://github.com/rust-lang/rust.git
synced 2025-01-19 03:03:21 +00:00
Merge #3050
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:
commit
01836a0f35
@ -1,5 +1,5 @@
|
||||
use format_buf::format;
|
||||
use hir::InFile;
|
||||
use hir::{Adt, InFile};
|
||||
use join_to_string::join;
|
||||
use ra_syntax::{
|
||||
ast::{
|
||||
@ -135,16 +135,22 @@ fn find_struct_impl(ctx: &AssistCtx, strukt: &ast::StructDef) -> Option<Option<a
|
||||
})?;
|
||||
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() };
|
||||
sb.to_def(src)?.ty(db)
|
||||
sb.to_def(src)?
|
||||
};
|
||||
|
||||
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 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();
|
||||
|
||||
if !(same_ty && not_trait_impl) {
|
||||
|
@ -10,9 +10,9 @@ use hir_def::{
|
||||
per_ns::PerNs,
|
||||
resolver::HasResolver,
|
||||
type_ref::{Mutability, TypeRef},
|
||||
AdtId, ConstId, DefWithBodyId, EnumId, FunctionId, HasModule, ImplId, LocalEnumVariantId,
|
||||
LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
|
||||
TypeParamId, UnionId,
|
||||
AdtId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId,
|
||||
LocalEnumVariantId, LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId,
|
||||
TraitId, TypeAliasId, TypeParamId, UnionId,
|
||||
};
|
||||
use hir_expand::{
|
||||
diagnostics::DiagnosticSink,
|
||||
@ -21,7 +21,7 @@ use hir_expand::{
|
||||
};
|
||||
use hir_ty::{
|
||||
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_prof::profile;
|
||||
@ -270,7 +270,13 @@ impl StructField {
|
||||
|
||||
pub fn ty(&self, db: &impl HirDatabase) -> Type {
|
||||
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)
|
||||
}
|
||||
|
||||
@ -755,7 +761,7 @@ pub struct TypeParam {
|
||||
impl TypeParam {
|
||||
pub fn name(self, db: &impl HirDatabase) -> Name {
|
||||
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 {
|
||||
@ -789,8 +795,9 @@ impl ImplBlock {
|
||||
pub fn target_ty(&self, db: &impl HirDatabase) -> Type {
|
||||
let impl_data = db.impl_data(self.id);
|
||||
let resolver = self.id.resolver(db);
|
||||
let ctx = hir_ty::TyLoweringContext::new(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 {
|
||||
krate: self.id.lookup(db).container.module(db).krate,
|
||||
ty: InEnvironment { value: ty, environment },
|
||||
@ -851,9 +858,10 @@ impl Type {
|
||||
fn from_def(
|
||||
db: &impl HirDatabase,
|
||||
krate: CrateId,
|
||||
def: impl HasResolver + Into<TyDefId>,
|
||||
def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
|
||||
) -> 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)
|
||||
}
|
||||
|
||||
@ -950,7 +958,7 @@ impl Type {
|
||||
match a_ty.ctor {
|
||||
TypeCtor::Tuple { .. } => {
|
||||
for ty in a_ty.parameters.iter() {
|
||||
let ty = ty.clone().subst(&a_ty.parameters);
|
||||
let ty = ty.clone();
|
||||
res.push(self.derived(ty));
|
||||
}
|
||||
}
|
||||
|
@ -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> {
|
||||
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())?
|
||||
@ -186,14 +190,14 @@ impl SourceAnalyzer {
|
||||
};
|
||||
|
||||
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 } })
|
||||
}
|
||||
|
||||
pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> {
|
||||
let pat_id = self.pat_id(pat)?;
|
||||
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 } })
|
||||
}
|
||||
|
||||
|
@ -27,8 +27,16 @@ use crate::{
|
||||
/// Data about a generic parameter (to a function, struct, impl, ...).
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct TypeParamData {
|
||||
pub name: Name,
|
||||
pub name: Option<Name>,
|
||||
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.
|
||||
@ -45,10 +53,17 @@ pub struct GenericParams {
|
||||
/// associated type bindings like `Iterator<Item = u32>`.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct WherePredicate {
|
||||
pub type_ref: TypeRef,
|
||||
pub target: WherePredicateTarget,
|
||||
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>>;
|
||||
|
||||
impl GenericParams {
|
||||
@ -68,6 +83,11 @@ impl GenericParams {
|
||||
GenericDefId::FunctionId(it) => {
|
||||
let src = it.lookup(db).source(db);
|
||||
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
|
||||
}
|
||||
GenericDefId::AdtId(AdtId::StructId(it)) => {
|
||||
@ -89,8 +109,11 @@ impl GenericParams {
|
||||
let src = it.lookup(db).source(db);
|
||||
|
||||
// traits get the Self type as an implicit first type parameter
|
||||
let self_param_id =
|
||||
generics.types.alloc(TypeParamData { name: name![Self], default: None });
|
||||
let self_param_id = generics.types.alloc(TypeParamData {
|
||||
name: Some(name![Self]),
|
||||
default: None,
|
||||
provenance: TypeParamProvenance::TraitSelf,
|
||||
});
|
||||
sm.insert(self_param_id, Either::Left(src.value.clone()));
|
||||
// add super traits as bounds on Self
|
||||
// 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());
|
||||
// FIXME: Use `Path::from_src`
|
||||
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);
|
||||
sm.insert(param_id, Either::Right(type_param.clone()));
|
||||
|
||||
@ -170,11 +197,43 @@ impl GenericParams {
|
||||
return;
|
||||
}
|
||||
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> {
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -490,10 +490,12 @@ impl Scope {
|
||||
}
|
||||
Scope::GenericParams { params, def } => {
|
||||
for (local_id, param) in params.types.iter() {
|
||||
f(
|
||||
param.name.clone(),
|
||||
ScopeDef::GenericParam(TypeParamId { local_id, parent: *def }),
|
||||
)
|
||||
if let Some(name) = ¶m.name {
|
||||
f(
|
||||
name.clone(),
|
||||
ScopeDef::GenericParam(TypeParamId { local_id, parent: *def }),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Scope::ImplBlockScope(i) => {
|
||||
|
@ -124,6 +124,48 @@ impl TypeRef {
|
||||
pub(crate) fn unit() -> TypeRef {
|
||||
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> {
|
||||
|
@ -3,17 +3,18 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
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_db::{salsa, CrateId};
|
||||
use ra_db::{impl_intern_key, salsa, CrateId};
|
||||
use ra_prof::profile;
|
||||
|
||||
use crate::{
|
||||
method_resolution::CrateImplBlocks,
|
||||
traits::{chalk, AssocTyValue, Impl},
|
||||
CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, TraitRef, Ty, TyDefId, TypeCtor,
|
||||
ValueTyDefId,
|
||||
Binders, CallableDef, GenericPredicate, InferenceResult, PolyFnSig, Substs, TraitRef, Ty,
|
||||
TyDefId, TypeCtor, ValueTyDefId,
|
||||
};
|
||||
|
||||
#[salsa::query_group(HirDatabaseStorage)]
|
||||
@ -27,34 +28,33 @@ pub trait HirDatabase: DefDatabase {
|
||||
|
||||
#[salsa::invoke(crate::lower::ty_query)]
|
||||
#[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)]
|
||||
fn value_ty(&self, def: ValueTyDefId) -> Ty;
|
||||
fn value_ty(&self, def: ValueTyDefId) -> Binders<Ty>;
|
||||
|
||||
#[salsa::invoke(crate::lower::impl_self_ty_query)]
|
||||
#[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)]
|
||||
fn impl_trait(&self, def: ImplId) -> Option<TraitRef>;
|
||||
fn impl_trait(&self, def: ImplId) -> Option<Binders<TraitRef>>;
|
||||
|
||||
#[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)]
|
||||
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::cycle(crate::lower::generic_predicates_for_param_recover)]
|
||||
fn generic_predicates_for_param(
|
||||
&self,
|
||||
def: GenericDefId,
|
||||
param_idx: u32,
|
||||
) -> Arc<[GenericPredicate]>;
|
||||
param_id: TypeParamId,
|
||||
) -> Arc<[Binders<GenericPredicate>]>;
|
||||
|
||||
#[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)]
|
||||
fn generic_defaults(&self, def: GenericDefId) -> Substs;
|
||||
@ -77,6 +77,8 @@ pub trait HirDatabase: DefDatabase {
|
||||
#[salsa::interned]
|
||||
fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
|
||||
#[salsa::interned]
|
||||
fn intern_type_param_id(&self, param_id: TypeParamId) -> GlobalTypeParamId;
|
||||
#[salsa::interned]
|
||||
fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
|
||||
#[salsa::interned]
|
||||
fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
|
||||
@ -117,3 +119,7 @@ fn infer(db: &impl HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> {
|
||||
fn hir_database_is_object_safe() {
|
||||
fn _assert_object_safe(_: &dyn HirDatabase) {}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct GlobalTypeParamId(salsa::InternId);
|
||||
impl_intern_key!(GlobalTypeParamId);
|
||||
|
@ -34,7 +34,6 @@ use hir_expand::{diagnostics::DiagnosticSink, name::name};
|
||||
use ra_arena::map::ArenaMap;
|
||||
use ra_prof::profile;
|
||||
use ra_syntax::SmolStr;
|
||||
use test_utils::tested_by;
|
||||
|
||||
use super::{
|
||||
primitive::{FloatTy, IntTy},
|
||||
@ -42,7 +41,9 @@ use super::{
|
||||
ApplicationTy, GenericPredicate, InEnvironment, ProjectionTy, Substs, TraitEnvironment,
|
||||
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;
|
||||
|
||||
@ -271,38 +272,21 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
self.result.diagnostics.push(diagnostic);
|
||||
}
|
||||
|
||||
fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
|
||||
let ty = Ty::from_hir(
|
||||
self.db,
|
||||
// FIXME use right resolver for block
|
||||
&self.resolver,
|
||||
type_ref,
|
||||
);
|
||||
fn make_ty_with_mode(
|
||||
&mut self,
|
||||
type_ref: &TypeRef,
|
||||
impl_trait_mode: ImplTraitLoweringMode,
|
||||
) -> Ty {
|
||||
// FIXME use right resolver for block
|
||||
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
|
||||
.with_impl_trait_mode(impl_trait_mode);
|
||||
let ty = Ty::from_hir(&ctx, type_ref);
|
||||
let ty = self.insert_type_vars(ty);
|
||||
self.normalize_associated_types_in(ty)
|
||||
}
|
||||
|
||||
/// Replaces `impl Trait` in `ty` by type variables and obligations for
|
||||
/// those variables. This is done for function arguments when calling a
|
||||
/// 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,
|
||||
})
|
||||
fn make_ty(&mut self, type_ref: &TypeRef) -> Ty {
|
||||
self.make_ty_with_mode(type_ref, ImplTraitLoweringMode::Disallowed)
|
||||
}
|
||||
|
||||
/// 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),
|
||||
};
|
||||
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:
|
||||
// https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521
|
||||
match resolver.resolve_path_in_type_ns_fully(self.db, path.mod_path()) {
|
||||
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.insert_type_vars(ty.apply_substs(substs));
|
||||
let ty = self.insert_type_vars(ty.subst(&substs));
|
||||
(ty, Some(strukt.into()))
|
||||
}
|
||||
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.insert_type_vars(ty.apply_substs(substs));
|
||||
let ty = self.insert_type_vars(ty.subst(&substs));
|
||||
(ty, Some(var.into()))
|
||||
}
|
||||
Some(_) | None => (Ty::Unknown, None),
|
||||
@ -471,13 +456,18 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
|
||||
fn collect_fn(&mut self, data: &FunctionData) {
|
||||
let body = Arc::clone(&self.body); // avoid borrow checker problem
|
||||
for (type_ref, pat) in data.params.iter().zip(body.params.iter()) {
|
||||
let ty = self.make_ty(type_ref);
|
||||
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
|
||||
.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());
|
||||
}
|
||||
let return_ty = self.make_ty(&data.ret_type);
|
||||
self.return_ty = self.insert_vars_for_impl_trait(return_ty);
|
||||
let return_ty = self.make_ty_with_mode(&data.ret_type, ImplTraitLoweringMode::Disallowed); // FIXME implement RPIT
|
||||
self.return_ty = return_ty;
|
||||
}
|
||||
|
||||
fn infer_body(&mut self) {
|
||||
|
@ -57,8 +57,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
let trait_ref = db.impl_trait(impl_id)?;
|
||||
|
||||
// `CoerseUnsized` has one generic parameter for the target type.
|
||||
let cur_from_ty = trait_ref.substs.0.get(0)?;
|
||||
let cur_to_ty = trait_ref.substs.0.get(1)?;
|
||||
let cur_from_ty = trait_ref.value.substs.0.get(0)?;
|
||||
let cur_to_ty = trait_ref.value.substs.0.get(1)?;
|
||||
|
||||
match (&cur_from_ty, cur_to_ty) {
|
||||
(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.
|
||||
st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| {
|
||||
match (ty1, ty2) {
|
||||
(Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. })
|
||||
if p1 != p2 =>
|
||||
{
|
||||
(Ty::Bound(idx1), Ty::Bound(idx2)) if idx1 != idx2 => {
|
||||
Some(((*ctor1, *ctor2), i))
|
||||
}
|
||||
_ => None,
|
||||
@ -256,8 +254,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
let unsize_generic_index = {
|
||||
let mut index = None;
|
||||
let mut multiple_param = false;
|
||||
field_tys[last_field_id].walk(&mut |ty| match ty {
|
||||
&Ty::Param { idx, .. } => {
|
||||
field_tys[last_field_id].value.walk(&mut |ty| match ty {
|
||||
&Ty::Bound(idx) => {
|
||||
if index.is_none() {
|
||||
index = Some(idx);
|
||||
} else if Some(idx) != index {
|
||||
@ -276,10 +274,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
// Check other fields do not involve it.
|
||||
let mut multiple_used = false;
|
||||
fields.for_each(|(field_id, _data)| {
|
||||
field_tys[field_id].walk(&mut |ty| match ty {
|
||||
&Ty::Param { idx, .. } if idx == unsize_generic_index => {
|
||||
multiple_used = true
|
||||
}
|
||||
field_tys[field_id].value.walk(&mut |ty| match ty {
|
||||
&Ty::Bound(idx) if idx == unsize_generic_index => multiple_used = true,
|
||||
_ => {}
|
||||
})
|
||||
});
|
||||
|
@ -10,7 +10,7 @@ use hir_def::{
|
||||
resolver::resolver_for_expr,
|
||||
AdtId, AssocContainerId, Lookup, StructFieldId,
|
||||
};
|
||||
use hir_expand::name::{name, Name};
|
||||
use hir_expand::name::Name;
|
||||
use ra_syntax::ast::RangeOp;
|
||||
|
||||
use crate::{
|
||||
@ -19,8 +19,8 @@ use crate::{
|
||||
method_resolution, op,
|
||||
traits::InEnvironment,
|
||||
utils::{generics, variant_data, Generics},
|
||||
ApplicationTy, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef, Ty,
|
||||
TypeCtor, TypeWalk, Uncertain,
|
||||
ApplicationTy, Binders, CallableDef, InferTy, IntTy, Mutability, Obligation, Substs, TraitRef,
|
||||
Ty, TypeCtor, Uncertain,
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
let field_ty = field_def
|
||||
.map_or(Ty::Unknown, |it| field_types[it.local_id].clone())
|
||||
.subst(&substs);
|
||||
.map_or(Ty::Unknown, |it| field_types[it.local_id].clone().subst(&substs));
|
||||
self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty));
|
||||
}
|
||||
if let Some(expr) = spread {
|
||||
@ -588,10 +587,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
self.write_method_resolution(tgt_expr, func);
|
||||
(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 method_ty = method_ty.apply_substs(substs);
|
||||
let method_ty = method_ty.subst(&substs);
|
||||
let method_ty = self.insert_type_vars(method_ty);
|
||||
self.register_obligations_for_call(&method_ty);
|
||||
let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) {
|
||||
@ -635,7 +634,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let param_ty = self.insert_vars_for_impl_trait(param_ty);
|
||||
let param_ty = self.normalize_associated_types_in(param_ty);
|
||||
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>,
|
||||
receiver_ty: &Ty,
|
||||
) -> Substs {
|
||||
let (total_len, _parent_len, child_len) =
|
||||
def_generics.as_ref().map_or((0, 0, 0), |g| g.len_split());
|
||||
let (parent_params, self_params, type_params, impl_trait_params) =
|
||||
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);
|
||||
// Parent arguments are unknown, except for the receiver type
|
||||
if let Some(parent_generics) = def_generics.as_ref().map(|p| p.iter_parent()) {
|
||||
for (_id, param) in parent_generics {
|
||||
if param.name == name![Self] {
|
||||
if param.provenance == hir_def::generics::TypeParamProvenance::TraitSelf {
|
||||
substs.push(receiver_ty.clone());
|
||||
} else {
|
||||
substs.push(Ty::Unknown);
|
||||
@ -664,7 +664,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
// handle provided type arguments
|
||||
if let Some(generic_args) = generic_args {
|
||||
// if args are provided, it should be all of them, but we can't rely on that
|
||||
for arg in generic_args.args.iter().take(child_len) {
|
||||
for arg in generic_args.args.iter().take(type_params) {
|
||||
match arg {
|
||||
GenericArg::Type(type_ref) => {
|
||||
let ty = self.make_ty(type_ref);
|
||||
|
@ -12,7 +12,7 @@ use hir_expand::name::Name;
|
||||
use test_utils::tested_by;
|
||||
|
||||
use super::{BindingMode, InferenceContext};
|
||||
use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk};
|
||||
use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor};
|
||||
|
||||
impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
fn infer_tuple_struct_pat(
|
||||
@ -34,8 +34,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
let expected_ty = var_data
|
||||
.as_ref()
|
||||
.and_then(|d| d.field(&Name::new_tuple_field(i)))
|
||||
.map_or(Ty::Unknown, |field| field_tys[field].clone())
|
||||
.subst(&substs);
|
||||
.map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs));
|
||||
let expected_ty = self.normalize_associated_types_in(expected_ty);
|
||||
self.infer_pat(subpat, &expected_ty, default_bm);
|
||||
}
|
||||
@ -65,7 +64,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
for subpat in subpats {
|
||||
let matching_field = var_data.as_ref().and_then(|it| it.field(&subpat.name));
|
||||
let expected_ty =
|
||||
matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone()).subst(&substs);
|
||||
matching_field.map_or(Ty::Unknown, |field| field_tys[field].clone().subst(&substs));
|
||||
let expected_ty = self.normalize_associated_types_in(expected_ty);
|
||||
self.infer_pat(subpat.pat, &expected_ty, default_bm);
|
||||
}
|
||||
|
@ -9,9 +9,9 @@ use hir_def::{
|
||||
};
|
||||
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> {
|
||||
pub(super) fn infer_path(
|
||||
@ -39,7 +39,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
}
|
||||
let ty = self.make_ty(type_ref);
|
||||
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(
|
||||
ty,
|
||||
&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(),
|
||||
};
|
||||
|
||||
let mut ty = self.db.value_ty(typable);
|
||||
if let Some(self_subst) = self_subst {
|
||||
ty = ty.subst(&self_subst);
|
||||
}
|
||||
let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable);
|
||||
let ty = ty.subst(&substs);
|
||||
let ty = self.db.value_ty(typable);
|
||||
// self_subst is just for the parent
|
||||
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(&ctx, path, typable);
|
||||
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)
|
||||
}
|
||||
|
||||
@ -98,13 +103,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
(TypeNs::TraitId(trait_), true) => {
|
||||
let segment =
|
||||
remaining_segments.last().expect("there should be at least one segment here");
|
||||
let trait_ref = TraitRef::from_resolved_path(
|
||||
self.db,
|
||||
&self.resolver,
|
||||
trait_.into(),
|
||||
resolved_segment,
|
||||
None,
|
||||
);
|
||||
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
|
||||
let trait_ref =
|
||||
TraitRef::from_resolved_path(&ctx, trait_.into(), resolved_segment, None);
|
||||
self.resolve_trait_assoc_item(trait_ref, segment, id)
|
||||
}
|
||||
(def, _) => {
|
||||
@ -114,9 +115,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
// as Iterator>::Item::default`)
|
||||
let remaining_segments_for_ty =
|
||||
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(
|
||||
self.db,
|
||||
&self.resolver,
|
||||
&ctx,
|
||||
def,
|
||||
resolved_segment,
|
||||
remaining_segments_for_ty,
|
||||
@ -173,13 +174,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
AssocItemId::ConstId(c) => ValueNs::ConstId(c),
|
||||
AssocItemId::TypeAliasId(_) => unreachable!(),
|
||||
};
|
||||
let substs = Substs::build_for_def(self.db, item)
|
||||
.use_parent_substs(&trait_ref.substs)
|
||||
.fill_with_params()
|
||||
.build();
|
||||
|
||||
self.write_assoc_resolution(id, item);
|
||||
Some((def, Some(substs)))
|
||||
Some((def, Some(trait_ref.substs)))
|
||||
}
|
||||
|
||||
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 env = TraitEnvironment::lower(self.db, &self.resolver);
|
||||
let krate = self.resolver.krate()?;
|
||||
let traits_in_scope = self.resolver.traits_in_scope(self.db);
|
||||
|
||||
method_resolution::iterate_method_candidates(
|
||||
&canonical_ty.value,
|
||||
self.db,
|
||||
env,
|
||||
self.trait_env.clone(),
|
||||
krate,
|
||||
&traits_in_scope,
|
||||
Some(name),
|
||||
@ -219,12 +215,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
.fill(iter::repeat_with(|| self.table.new_type_var()))
|
||||
.build();
|
||||
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);
|
||||
Some(substs)
|
||||
Some(impl_substs)
|
||||
}
|
||||
AssocContainerId::TraitId(trait_) => {
|
||||
// we're picking this method
|
||||
@ -232,15 +224,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
|
||||
.push(ty.clone())
|
||||
.fill(std::iter::repeat_with(|| self.table.new_type_var()))
|
||||
.build();
|
||||
let substs = Substs::build_for_def(self.db, item)
|
||||
.use_parent_substs(&trait_substs)
|
||||
.fill_with_params()
|
||||
.build();
|
||||
self.obligations.push(super::Obligation::Trait(TraitRef {
|
||||
trait_,
|
||||
substs: trait_substs,
|
||||
substs: trait_substs.clone(),
|
||||
}));
|
||||
Some(substs)
|
||||
Some(trait_substs)
|
||||
}
|
||||
AssocContainerId::ContainerId(_) => None,
|
||||
};
|
||||
|
@ -44,8 +44,8 @@ use std::sync::Arc;
|
||||
use std::{fmt, iter, mem};
|
||||
|
||||
use hir_def::{
|
||||
expr::ExprId, type_ref::Mutability, AdtId, AssocContainerId, DefWithBodyId, GenericDefId,
|
||||
HasModule, Lookup, TraitId, TypeAliasId,
|
||||
expr::ExprId, generics::TypeParamProvenance, type_ref::Mutability, AdtId, AssocContainerId,
|
||||
DefWithBodyId, GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, TypeParamId,
|
||||
};
|
||||
use hir_expand::name::Name;
|
||||
use ra_db::{impl_intern_key, salsa, CrateId};
|
||||
@ -60,7 +60,9 @@ use display::{HirDisplay, HirFormatter};
|
||||
pub use autoderef::autoderef;
|
||||
pub use infer::{do_infer_query, InferTy, InferenceResult};
|
||||
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};
|
||||
|
||||
/// 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.
|
||||
Projection(ProjectionTy),
|
||||
|
||||
/// A type parameter; for example, `T` in `fn f<T>(x: T) {}
|
||||
Param {
|
||||
/// The index of the parameter (starting with parameters from the
|
||||
/// surrounding impl, then the current function).
|
||||
idx: u32,
|
||||
/// The name of the parameter, for displaying.
|
||||
// FIXME get rid of this
|
||||
name: Name,
|
||||
},
|
||||
/// A placeholder for a type parameter; for example, `T` in `fn f<T>(x: T)
|
||||
/// {}` when we're type-checking the body of that function. In this
|
||||
/// situation, we know this stands for *some* type, but don't know the exact
|
||||
/// type.
|
||||
Param(TypeParamId),
|
||||
|
||||
/// A bound type variable. Used during trait resolution to represent Chalk
|
||||
/// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type.
|
||||
/// A bound type variable. This is used in various places: when representing
|
||||
/// 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),
|
||||
|
||||
/// A type variable used during type checking. Not to be confused with a
|
||||
/// type parameter.
|
||||
/// A type variable used during type checking.
|
||||
Infer(InferTy),
|
||||
|
||||
/// 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`).
|
||||
pub(crate) fn identity(generic_params: &Generics) -> Substs {
|
||||
Substs(
|
||||
generic_params.iter().map(|(idx, p)| Ty::Param { idx, name: p.name.clone() }).collect(),
|
||||
)
|
||||
pub(crate) fn type_params_for_generics(generic_params: &Generics) -> Substs {
|
||||
Substs(generic_params.iter().map(|(id, _)| Ty::Param(id)).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(¶ms)
|
||||
}
|
||||
|
||||
/// Return Substs that replace each parameter by a bound variable.
|
||||
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 {
|
||||
@ -420,11 +424,6 @@ impl SubstsBuilder {
|
||||
self.fill((starting_from..).map(Ty::Bound))
|
||||
}
|
||||
|
||||
pub fn fill_with_params(self) -> Self {
|
||||
let start = self.vec.len() as u32;
|
||||
self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() }))
|
||||
}
|
||||
|
||||
pub fn fill_with_unknown(self) -> Self {
|
||||
self.fill(iter::repeat(Ty::Unknown))
|
||||
}
|
||||
@ -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.
|
||||
/// Name to be bikeshedded: TraitBound? TraitImplements?
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
|
||||
@ -551,6 +576,9 @@ pub struct FnSig {
|
||||
params_and_return: Arc<[Ty]>,
|
||||
}
|
||||
|
||||
/// A polymorphic function signature.
|
||||
pub type PolyFnSig = Binders<FnSig>;
|
||||
|
||||
impl FnSig {
|
||||
pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
|
||||
params.push(ret);
|
||||
@ -730,22 +758,7 @@ pub trait TypeWalk {
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaces type parameters in this type using the given `Substs`. (So e.g.
|
||||
/// if `self` is `&[T]`, where type parameter T has index 0, and the
|
||||
/// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.)
|
||||
fn subst(self, substs: &Substs) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.fold(&mut |ty| match ty {
|
||||
Ty::Param { idx, name } => {
|
||||
substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name })
|
||||
}
|
||||
ty => ty,
|
||||
})
|
||||
}
|
||||
|
||||
/// Substitutes `Ty::Bound` vars (as opposed to type parameters).
|
||||
/// Substitutes `Ty::Bound` vars with the given substitution.
|
||||
fn subst_bound_vars(mut self, substs: &Substs) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
@ -755,6 +768,9 @@ pub trait TypeWalk {
|
||||
&mut Ty::Bound(idx) => {
|
||||
if idx as usize >= binders && (idx as usize - binders) < substs.len() {
|
||||
*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))?;
|
||||
}
|
||||
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 {
|
||||
CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(),
|
||||
CallableDef::StructId(s) => f.db.struct_data(s).name.clone(),
|
||||
@ -896,9 +912,16 @@ impl HirDisplay for ApplicationTy {
|
||||
}
|
||||
}
|
||||
if self.parameters.len() > 0 {
|
||||
write!(f, "<")?;
|
||||
f.write_joined(&*self.parameters.0, ", ")?;
|
||||
write!(f, ">")?;
|
||||
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, "<")?;
|
||||
f.write_joined(&self.parameters.0[..total_len], ", ")?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
}
|
||||
write!(f, "(")?;
|
||||
f.write_joined(sig.params(), ", ")?;
|
||||
@ -1009,7 +1032,24 @@ impl HirDisplay for Ty {
|
||||
match self {
|
||||
Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
|
||||
Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
|
||||
Ty::Param { name, .. } => write!(f, "{}", name)?,
|
||||
Ty::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::Dyn(predicates) | Ty::Opaque(predicates) => {
|
||||
match self {
|
||||
@ -1017,66 +1057,7 @@ impl HirDisplay for Ty {
|
||||
Ty::Opaque(_) => write!(f, "impl ")?,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
// Note: This code is written to produce nice results (i.e.
|
||||
// corresponding to surface Rust) for types that can occur in
|
||||
// actual Rust. It will have weird results if the predicates
|
||||
// aren't as expected (i.e. self types = $0, projection
|
||||
// predicates for a certain trait come after the Implemented
|
||||
// predicate for that trait).
|
||||
let mut first = true;
|
||||
let mut angle_open = false;
|
||||
for p in predicates.iter() {
|
||||
match p {
|
||||
GenericPredicate::Implemented(trait_ref) => {
|
||||
if angle_open {
|
||||
write!(f, ">")?;
|
||||
}
|
||||
if !first {
|
||||
write!(f, " + ")?;
|
||||
}
|
||||
// We assume that the self type is $0 (i.e. the
|
||||
// existential) here, which is the only thing that's
|
||||
// possible in actual Rust, and hence don't print it
|
||||
write!(f, "{}", f.db.trait_data(trait_ref.trait_).name.clone())?;
|
||||
if trait_ref.substs.len() > 1 {
|
||||
write!(f, "<")?;
|
||||
f.write_joined(&trait_ref.substs[1..], ", ")?;
|
||||
// there might be assoc type bindings, so we leave the angle brackets open
|
||||
angle_open = true;
|
||||
}
|
||||
}
|
||||
GenericPredicate::Projection(projection_pred) => {
|
||||
// in types in actual Rust, these will always come
|
||||
// after the corresponding Implemented predicate
|
||||
if angle_open {
|
||||
write!(f, ", ")?;
|
||||
} else {
|
||||
write!(f, "<")?;
|
||||
angle_open = true;
|
||||
}
|
||||
let name =
|
||||
f.db.type_alias_data(projection_pred.projection_ty.associated_ty)
|
||||
.name
|
||||
.clone();
|
||||
write!(f, "{} = ", name)?;
|
||||
projection_pred.ty.hir_fmt(f)?;
|
||||
}
|
||||
GenericPredicate::Error => {
|
||||
if angle_open {
|
||||
// impl Trait<X, {error}>
|
||||
write!(f, ", ")?;
|
||||
} else if !first {
|
||||
// impl Trait + {error}
|
||||
write!(f, " + ")?;
|
||||
}
|
||||
p.hir_fmt(f)?;
|
||||
}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
if angle_open {
|
||||
write!(f, ">")?;
|
||||
}
|
||||
write_bounds_like_dyn_trait(&predicates, f)?;
|
||||
}
|
||||
Ty::Unknown => write!(f, "{{unknown}}")?,
|
||||
Ty::Infer(..) => write!(f, "_")?,
|
||||
@ -1085,6 +1066,71 @@ impl HirDisplay for Ty {
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
// corresponding to surface Rust) for types that can occur in
|
||||
// actual Rust. It will have weird results if the predicates
|
||||
// aren't as expected (i.e. self types = $0, projection
|
||||
// predicates for a certain trait come after the Implemented
|
||||
// predicate for that trait).
|
||||
let mut first = true;
|
||||
let mut angle_open = false;
|
||||
for p in predicates.iter() {
|
||||
match p {
|
||||
GenericPredicate::Implemented(trait_ref) => {
|
||||
if angle_open {
|
||||
write!(f, ">")?;
|
||||
}
|
||||
if !first {
|
||||
write!(f, " + ")?;
|
||||
}
|
||||
// We assume that the self type is $0 (i.e. the
|
||||
// existential) here, which is the only thing that's
|
||||
// possible in actual Rust, and hence don't print it
|
||||
write!(f, "{}", f.db.trait_data(trait_ref.trait_).name.clone())?;
|
||||
if trait_ref.substs.len() > 1 {
|
||||
write!(f, "<")?;
|
||||
f.write_joined(&trait_ref.substs[1..], ", ")?;
|
||||
// there might be assoc type bindings, so we leave the angle brackets open
|
||||
angle_open = true;
|
||||
}
|
||||
}
|
||||
GenericPredicate::Projection(projection_pred) => {
|
||||
// in types in actual Rust, these will always come
|
||||
// after the corresponding Implemented predicate
|
||||
if angle_open {
|
||||
write!(f, ", ")?;
|
||||
} else {
|
||||
write!(f, "<")?;
|
||||
angle_open = true;
|
||||
}
|
||||
let name =
|
||||
f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name.clone();
|
||||
write!(f, "{} = ", name)?;
|
||||
projection_pred.ty.hir_fmt(f)?;
|
||||
}
|
||||
GenericPredicate::Error => {
|
||||
if angle_open {
|
||||
// impl Trait<X, {error}>
|
||||
write!(f, ", ")?;
|
||||
} else if !first {
|
||||
// impl Trait + {error}
|
||||
write!(f, " + ")?;
|
||||
}
|
||||
p.hir_fmt(f)?;
|
||||
}
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
if angle_open {
|
||||
write!(f, ">")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl TraitRef {
|
||||
fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {
|
||||
if f.should_truncate() {
|
||||
|
@ -10,12 +10,13 @@ use std::sync::Arc;
|
||||
|
||||
use hir_def::{
|
||||
builtin_type::BuiltinType,
|
||||
generics::WherePredicate,
|
||||
generics::{TypeParamProvenance, WherePredicate, WherePredicateTarget},
|
||||
path::{GenericArg, Path, PathSegment, PathSegments},
|
||||
resolver::{HasResolver, Resolver, TypeNs},
|
||||
type_ref::{TypeBound, TypeRef},
|
||||
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_db::CrateId;
|
||||
@ -27,63 +28,158 @@ use crate::{
|
||||
all_super_traits, associated_type_by_name_including_super_traits, generics, make_mut_slice,
|
||||
variant_data,
|
||||
},
|
||||
FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, TraitRef,
|
||||
Ty, TypeCtor, TypeWalk,
|
||||
Binders, FnSig, GenericPredicate, PolyFnSig, ProjectionPredicate, ProjectionTy, Substs,
|
||||
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 {
|
||||
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 {
|
||||
TypeRef::Never => Ty::simple(TypeCtor::Never),
|
||||
TypeRef::Tuple(inner) => {
|
||||
let inner_tys: Arc<[Ty]> =
|
||||
inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect();
|
||||
let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| Ty::from_hir(ctx, tr)).collect();
|
||||
Ty::apply(
|
||||
TypeCtor::Tuple { cardinality: inner_tys.len() as u16 },
|
||||
Substs(inner_tys),
|
||||
)
|
||||
}
|
||||
TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path),
|
||||
TypeRef::Path(path) => Ty::from_hir_path(ctx, path),
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
TypeRef::Placeholder => Ty::Unknown,
|
||||
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)
|
||||
}
|
||||
TypeRef::DynTrait(bounds) => {
|
||||
let self_ty = Ty::Bound(0);
|
||||
let predicates = bounds
|
||||
.iter()
|
||||
.flat_map(|b| {
|
||||
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone())
|
||||
})
|
||||
.flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
|
||||
.collect();
|
||||
Ty::Dyn(predicates)
|
||||
}
|
||||
TypeRef::ImplTrait(bounds) => {
|
||||
let self_ty = Ty::Bound(0);
|
||||
let predicates = bounds
|
||||
.iter()
|
||||
.flat_map(|b| {
|
||||
GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone())
|
||||
})
|
||||
.collect();
|
||||
Ty::Opaque(predicates)
|
||||
match ctx.impl_trait_mode {
|
||||
ImplTraitLoweringMode::Opaque => {
|
||||
let self_ty = Ty::Bound(0);
|
||||
let predicates = bounds
|
||||
.iter()
|
||||
.flat_map(|b| {
|
||||
GenericPredicate::from_type_bound(ctx, b, self_ty.clone())
|
||||
})
|
||||
.collect();
|
||||
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,
|
||||
}
|
||||
@ -93,10 +189,9 @@ impl Ty {
|
||||
/// lower the self types of the predicates since that could lead to cycles.
|
||||
/// So we just check here if the `type_ref` resolves to a generic param, and which.
|
||||
fn from_hir_only_param(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
type_ref: &TypeRef,
|
||||
) -> Option<u32> {
|
||||
) -> Option<TypeParamId> {
|
||||
let path = match type_ref {
|
||||
TypeRef::Path(path) => path,
|
||||
_ => return None,
|
||||
@ -107,29 +202,26 @@ impl Ty {
|
||||
if path.segments().len() > 1 {
|
||||
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,
|
||||
_ => return None,
|
||||
};
|
||||
if let TypeNs::GenericParam(param_id) = resolution {
|
||||
let generics = generics(db, resolver.generic_def().expect("generics in scope"));
|
||||
let idx = generics.param_idx(param_id);
|
||||
Some(idx)
|
||||
Some(param_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_type_relative_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
ty: Ty,
|
||||
remaining_segments: PathSegments<'_>,
|
||||
) -> Ty {
|
||||
if remaining_segments.len() == 1 {
|
||||
// resolve unselected assoc types
|
||||
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 {
|
||||
// FIXME report error (ambiguous associated type)
|
||||
Ty::Unknown
|
||||
@ -139,20 +231,18 @@ impl Ty {
|
||||
}
|
||||
|
||||
pub(crate) fn from_partly_resolved_hir_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
resolution: TypeNs,
|
||||
resolved_segment: PathSegment<'_>,
|
||||
remaining_segments: PathSegments<'_>,
|
||||
) -> Ty {
|
||||
let ty = match resolution {
|
||||
TypeNs::TraitId(trait_) => {
|
||||
let trait_ref =
|
||||
TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None);
|
||||
let trait_ref = TraitRef::from_resolved_path(ctx, trait_, resolved_segment, None);
|
||||
return if remaining_segments.len() == 1 {
|
||||
let segment = remaining_segments.first().unwrap();
|
||||
let associated_ty = associated_type_by_name_including_super_traits(
|
||||
db,
|
||||
ctx.db,
|
||||
trait_ref.trait_,
|
||||
&segment.name,
|
||||
);
|
||||
@ -177,37 +267,55 @@ impl Ty {
|
||||
};
|
||||
}
|
||||
TypeNs::GenericParam(param_id) => {
|
||||
let generics = generics(db, resolver.generic_def().expect("generics in scope"));
|
||||
let idx = generics.param_idx(param_id);
|
||||
// FIXME: maybe return name in resolution?
|
||||
let name = generics.param_name(param_id);
|
||||
Ty::Param { idx, name }
|
||||
let generics =
|
||||
generics(ctx.db, ctx.resolver.generic_def().expect("generics in scope"));
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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::BuiltinType(it) => {
|
||||
Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into())
|
||||
}
|
||||
TypeNs::TypeAliasId(it) => {
|
||||
Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into())
|
||||
}
|
||||
TypeNs::AdtId(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
|
||||
TypeNs::BuiltinType(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
|
||||
TypeNs::TypeAliasId(it) => Ty::from_hir_path_inner(ctx, resolved_segment, it.into()),
|
||||
// FIXME: report error
|
||||
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)
|
||||
if let Some(type_ref) = path.type_anchor() {
|
||||
let ty = Ty::from_hir(db, resolver, &type_ref);
|
||||
return Ty::from_type_relative_path(db, resolver, ty, path.segments());
|
||||
let ty = Ty::from_hir(ctx, &type_ref);
|
||||
return Ty::from_type_relative_path(ctx, ty, path.segments());
|
||||
}
|
||||
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,
|
||||
None => return Ty::Unknown,
|
||||
};
|
||||
@ -218,39 +326,44 @@ impl Ty {
|
||||
),
|
||||
Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
|
||||
};
|
||||
Ty::from_partly_resolved_hir_path(
|
||||
db,
|
||||
resolver,
|
||||
resolution,
|
||||
resolved_segment,
|
||||
remaining_segments,
|
||||
)
|
||||
Ty::from_partly_resolved_hir_path(ctx, resolution, resolved_segment, remaining_segments)
|
||||
}
|
||||
|
||||
fn select_associated_type(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
self_ty: Ty,
|
||||
segment: PathSegment<'_>,
|
||||
) -> Ty {
|
||||
let param_idx = match self_ty {
|
||||
Ty::Param { idx, .. } => idx,
|
||||
_ => return Ty::Unknown, // Error: Ambiguous associated type
|
||||
};
|
||||
let def = match resolver.generic_def() {
|
||||
let def = match ctx.resolver.generic_def() {
|
||||
Some(def) => def,
|
||||
None => return Ty::Unknown, // this can't actually happen
|
||||
};
|
||||
let predicates = db.generic_predicates_for_param(def.into(), param_idx);
|
||||
let traits_from_env = predicates.iter().filter_map(|pred| match pred {
|
||||
GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_),
|
||||
let param_id = match self_ty {
|
||||
Ty::Param(id) if ctx.type_param_mode == TypeParamLoweringMode::Placeholder => id,
|
||||
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,
|
||||
});
|
||||
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 {
|
||||
if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) {
|
||||
let substs =
|
||||
Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build();
|
||||
if let Some(associated_ty) = ctx.db.trait_data(t).associated_type_by_name(&segment.name)
|
||||
{
|
||||
let substs = Substs::build_for_def(ctx.db, t)
|
||||
.push(self_ty.clone())
|
||||
.fill_with_unknown()
|
||||
.build();
|
||||
// FIXME handle type parameters on the segment
|
||||
return Ty::Projection(ProjectionTy { associated_ty, parameters: substs });
|
||||
}
|
||||
@ -259,8 +372,7 @@ impl Ty {
|
||||
}
|
||||
|
||||
fn from_hir_path_inner(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
segment: PathSegment<'_>,
|
||||
typable: TyDefId,
|
||||
) -> Ty {
|
||||
@ -269,15 +381,14 @@ impl Ty {
|
||||
TyDefId::AdtId(it) => Some(it.into()),
|
||||
TyDefId::TypeAliasId(it) => Some(it.into()),
|
||||
};
|
||||
let substs = substs_from_path_segment(db, resolver, segment, generic_def, false);
|
||||
db.ty(typable).subst(&substs)
|
||||
let substs = substs_from_path_segment(ctx, segment, generic_def, false);
|
||||
ctx.db.ty(typable).subst(&substs)
|
||||
}
|
||||
|
||||
/// Collect generic arguments from a path into a `Substs`. See also
|
||||
/// `create_substs_for_ast_path` and `def_to_ty` in rustc.
|
||||
pub(super) fn substs_from_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
path: &Path,
|
||||
// Note that we don't call `db.value_type(resolved)` here,
|
||||
// `ValueTyDefId` is just a convenient way to pass generics and
|
||||
@ -305,52 +416,49 @@ impl Ty {
|
||||
(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(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
segment: PathSegment<'_>,
|
||||
def_generic: Option<GenericDefId>,
|
||||
add_self_param: bool,
|
||||
_add_self_param: bool,
|
||||
) -> Substs {
|
||||
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());
|
||||
substs.extend(iter::repeat(Ty::Unknown).take(parent_len));
|
||||
if add_self_param {
|
||||
// FIXME this add_self_param argument is kind of a hack: Traits have the
|
||||
// Self type as an implicit first type parameter, but it can't be
|
||||
// actually provided in the type arguments
|
||||
// (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`)
|
||||
substs.push(Ty::Unknown);
|
||||
}
|
||||
let (parent_params, self_params, type_params, impl_trait_params) =
|
||||
def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
|
||||
substs.extend(iter::repeat(Ty::Unknown).take(parent_params));
|
||||
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
|
||||
let self_param_correction = if add_self_param { 1 } else { 0 };
|
||||
let child_len = child_len - self_param_correction;
|
||||
for arg in generic_args.args.iter().take(child_len) {
|
||||
for arg in generic_args.args.iter().skip(skip).take(expected_num) {
|
||||
match arg {
|
||||
GenericArg::Type(type_ref) => {
|
||||
let ty = Ty::from_hir(db, resolver, type_ref);
|
||||
let ty = Ty::from_hir(ctx, type_ref);
|
||||
substs.push(ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let total_len = parent_params + self_params + type_params + impl_trait_params;
|
||||
// add placeholders for args that were not provided
|
||||
let supplied_params = substs.len();
|
||||
for _ in supplied_params..total_len {
|
||||
for _ in substs.len()..total_len {
|
||||
substs.push(Ty::Unknown);
|
||||
}
|
||||
assert_eq!(substs.len(), total_len);
|
||||
|
||||
// handle defaults
|
||||
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());
|
||||
|
||||
for (i, default_ty) in default_substs.iter().enumerate() {
|
||||
@ -365,27 +473,25 @@ pub(super) fn substs_from_path_segment(
|
||||
|
||||
impl TraitRef {
|
||||
fn from_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
path: &Path,
|
||||
explicit_self_ty: Option<Ty>,
|
||||
) -> 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,
|
||||
_ => return None,
|
||||
};
|
||||
let segment = path.segments().last().expect("path should have at least one segment");
|
||||
Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty))
|
||||
Some(TraitRef::from_resolved_path(ctx, resolved.into(), segment, explicit_self_ty))
|
||||
}
|
||||
|
||||
pub(crate) fn from_resolved_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
resolved: TraitId,
|
||||
segment: PathSegment<'_>,
|
||||
explicit_self_ty: Option<Ty>,
|
||||
) -> 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 {
|
||||
make_mut_slice(&mut substs.0)[0] = self_ty;
|
||||
}
|
||||
@ -393,8 +499,7 @@ impl TraitRef {
|
||||
}
|
||||
|
||||
fn from_hir(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
type_ref: &TypeRef,
|
||||
explicit_self_ty: Option<Ty>,
|
||||
) -> Option<Self> {
|
||||
@ -402,28 +507,26 @@ impl TraitRef {
|
||||
TypeRef::Path(path) => path,
|
||||
_ => return None,
|
||||
};
|
||||
TraitRef::from_path(db, resolver, path, explicit_self_ty)
|
||||
TraitRef::from_path(ctx, path, explicit_self_ty)
|
||||
}
|
||||
|
||||
fn substs_from_path(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
segment: PathSegment<'_>,
|
||||
resolved: TraitId,
|
||||
) -> Substs {
|
||||
let has_self_param =
|
||||
segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false);
|
||||
substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param)
|
||||
substs_from_path_segment(ctx, segment, Some(resolved.into()), !has_self_param)
|
||||
}
|
||||
|
||||
pub(crate) fn from_type_bound(
|
||||
db: &impl HirDatabase,
|
||||
resolver: &Resolver,
|
||||
ctx: &TyLoweringContext<'_, impl HirDatabase>,
|
||||
bound: &TypeBound,
|
||||
self_ty: Ty,
|
||||
) -> Option<TraitRef> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@ -431,33 +534,44 @@ impl TraitRef {
|
||||
|
||||
impl GenericPredicate {
|
||||
pub(crate) fn from_where_predicate<'a>(
|
||||
db: &'a impl HirDatabase,
|
||||
resolver: &'a Resolver,
|
||||
ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
|
||||
where_predicate: &'a WherePredicate,
|
||||
) -> impl Iterator<Item = GenericPredicate> + 'a {
|
||||
let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref);
|
||||
GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty)
|
||||
let self_ty = match &where_predicate.target {
|
||||
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>(
|
||||
db: &'a impl HirDatabase,
|
||||
resolver: &'a Resolver,
|
||||
ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
|
||||
bound: &'a TypeBound,
|
||||
self_ty: Ty,
|
||||
) -> 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))
|
||||
.chain(
|
||||
trait_ref.into_iter().flat_map(move |tr| {
|
||||
assoc_type_bindings_from_type_bound(db, resolver, bound, tr)
|
||||
}),
|
||||
trait_ref
|
||||
.into_iter()
|
||||
.flat_map(move |tr| assoc_type_bindings_from_type_bound(ctx, bound, tr)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn assoc_type_bindings_from_type_bound<'a>(
|
||||
db: &'a impl HirDatabase,
|
||||
resolver: &'a Resolver,
|
||||
ctx: &'a TyLoweringContext<'a, impl HirDatabase>,
|
||||
bound: &'a TypeBound,
|
||||
trait_ref: TraitRef,
|
||||
) -> 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())
|
||||
.map(move |(name, type_ref)| {
|
||||
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 {
|
||||
None => return GenericPredicate::Error,
|
||||
Some(t) => t,
|
||||
};
|
||||
let projection_ty =
|
||||
ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() };
|
||||
let ty = Ty::from_hir(db, resolver, type_ref);
|
||||
let ty = Ty::from_hir(ctx, type_ref);
|
||||
let projection_predicate = ProjectionPredicate { projection_ty, ty };
|
||||
GenericPredicate::Projection(projection_predicate)
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the signature of a callable item (function, struct or enum variant).
|
||||
pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig {
|
||||
pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig {
|
||||
match def {
|
||||
CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),
|
||||
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(
|
||||
db: &impl HirDatabase,
|
||||
variant_id: VariantId,
|
||||
) -> Arc<ArenaMap<LocalStructFieldId, Ty>> {
|
||||
) -> Arc<ArenaMap<LocalStructFieldId, Binders<Ty>>> {
|
||||
let var_data = variant_data(db, variant_id);
|
||||
let resolver = match variant_id {
|
||||
VariantId::StructId(it) => it.resolver(db),
|
||||
VariantId::UnionId(it) => it.resolver(db),
|
||||
VariantId::EnumVariantId(it) => it.parent.resolver(db),
|
||||
let (resolver, def): (_, GenericDefId) = match variant_id {
|
||||
VariantId::StructId(it) => (it.resolver(db), it.into()),
|
||||
VariantId::UnionId(it) => (it.resolver(db), it.into()),
|
||||
VariantId::EnumVariantId(it) => (it.parent.resolver(db), it.parent.into()),
|
||||
};
|
||||
let generics = generics(db, def);
|
||||
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() {
|
||||
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)
|
||||
}
|
||||
@ -521,32 +638,43 @@ pub(crate) fn field_types_query(
|
||||
/// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
|
||||
pub(crate) fn generic_predicates_for_param_query(
|
||||
db: &impl HirDatabase,
|
||||
def: GenericDefId,
|
||||
param_idx: u32,
|
||||
) -> Arc<[GenericPredicate]> {
|
||||
let resolver = def.resolver(db);
|
||||
param_id: TypeParamId,
|
||||
) -> Arc<[Binders<GenericPredicate>]> {
|
||||
let resolver = param_id.parent.resolver(db);
|
||||
let ctx =
|
||||
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
|
||||
let generics = generics(db, param_id.parent);
|
||||
resolver
|
||||
.where_predicates_in_scope()
|
||||
// we have to filter out all other predicates *first*, before attempting to lower them
|
||||
.filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx))
|
||||
.flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
|
||||
.filter(|pred| match &pred.target {
|
||||
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()
|
||||
}
|
||||
|
||||
pub(crate) fn generic_predicates_for_param_recover(
|
||||
_db: &impl HirDatabase,
|
||||
_cycle: &[String],
|
||||
_def: &GenericDefId,
|
||||
_param_idx: &u32,
|
||||
) -> Arc<[GenericPredicate]> {
|
||||
_param_id: &TypeParamId,
|
||||
) -> Arc<[Binders<GenericPredicate>]> {
|
||||
Arc::new([])
|
||||
}
|
||||
|
||||
impl 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
|
||||
.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<_>>();
|
||||
|
||||
Arc::new(TraitEnvironment { predicates })
|
||||
@ -557,57 +685,74 @@ impl TraitEnvironment {
|
||||
pub(crate) fn generic_predicates_query(
|
||||
db: &impl HirDatabase,
|
||||
def: GenericDefId,
|
||||
) -> Arc<[GenericPredicate]> {
|
||||
) -> Arc<[Binders<GenericPredicate>]> {
|
||||
let resolver = def.resolver(db);
|
||||
let ctx =
|
||||
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
|
||||
let generics = generics(db, def);
|
||||
resolver
|
||||
.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()
|
||||
}
|
||||
|
||||
/// Resolve the default type params from generics
|
||||
pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDefId) -> Substs {
|
||||
let resolver = def.resolver(db);
|
||||
let ctx = TyLoweringContext::new(db, &resolver);
|
||||
let generic_params = generics(db, def.into());
|
||||
|
||||
let defaults = generic_params
|
||||
.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();
|
||||
|
||||
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 resolver = def.resolver(db);
|
||||
let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>();
|
||||
let ret = Ty::from_hir(db, &resolver, &data.ret_type);
|
||||
FnSig::from_params_and_return(params, ret)
|
||||
let ctx_params = TyLoweringContext::new(db, &resolver)
|
||||
.with_impl_trait_mode(ImplTraitLoweringMode::Variable)
|
||||
.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
|
||||
/// 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 substs = Substs::identity(&generics);
|
||||
Ty::apply(TypeCtor::FnDef(def.into()), substs)
|
||||
let substs = Substs::bound_vars(&generics);
|
||||
Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
|
||||
}
|
||||
|
||||
/// 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 generics = generics(db, def.into());
|
||||
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.
|
||||
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 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.
|
||||
@ -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 fields = struct_data.variant_data.fields();
|
||||
let resolver = def.resolver(db);
|
||||
let params = fields
|
||||
.iter()
|
||||
.map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref))
|
||||
.collect::<Vec<_>>();
|
||||
let ctx =
|
||||
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
|
||||
let params =
|
||||
fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
|
||||
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.
|
||||
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());
|
||||
if struct_data.variant_data.is_unit() {
|
||||
return type_for_adt(db, def.into()); // Unit struct
|
||||
}
|
||||
let generics = generics(db, def.into());
|
||||
let substs = Substs::identity(&generics);
|
||||
Ty::apply(TypeCtor::FnDef(def.into()), substs)
|
||||
let substs = Substs::bound_vars(&generics);
|
||||
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 var_data = &enum_data.variants[def.local_id];
|
||||
let fields = var_data.variant_data.fields();
|
||||
let resolver = def.parent.resolver(db);
|
||||
let params = fields
|
||||
.iter()
|
||||
.map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref))
|
||||
.collect::<Vec<_>>();
|
||||
let generics = generics(db, def.parent.into());
|
||||
let substs = Substs::identity(&generics);
|
||||
let ret = type_for_adt(db, def.parent.into()).subst(&substs);
|
||||
FnSig::from_params_and_return(params, ret)
|
||||
let ctx =
|
||||
TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
|
||||
let params =
|
||||
fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
|
||||
let ret = type_for_adt(db, def.parent.into());
|
||||
Binders::new(ret.num_binders, FnSig::from_params_and_return(params, ret.value))
|
||||
}
|
||||
|
||||
/// 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 var_data = &enum_data.variants[def.local_id].variant_data;
|
||||
if var_data.is_unit() {
|
||||
return type_for_adt(db, def.parent.into()); // Unit variant
|
||||
}
|
||||
let generics = generics(db, def.parent.into());
|
||||
let substs = Substs::identity(&generics);
|
||||
Ty::apply(TypeCtor::FnDef(EnumVariantId::from(def).into()), substs)
|
||||
let substs = Substs::bound_vars(&generics);
|
||||
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());
|
||||
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 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 substs = Substs::identity(&generics);
|
||||
let inner = Ty::from_hir(db, &resolver, type_ref.as_ref().unwrap_or(&TypeRef::Error));
|
||||
inner.subst(&substs)
|
||||
let substs = Substs::bound_vars(&generics);
|
||||
let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error));
|
||||
Binders::new(substs.len(), inner)
|
||||
}
|
||||
|
||||
#[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
|
||||
/// the constructor function `(usize) -> Foo` which lives in the values
|
||||
/// 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 {
|
||||
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::TypeAliasId(it) => type_for_type_alias(db, it),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ty_recover(_db: &impl HirDatabase, _cycle: &[String], _def: &TyDefId) -> Ty {
|
||||
Ty::Unknown
|
||||
pub(crate) fn ty_recover(db: &impl HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
|
||||
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 {
|
||||
ValueTyDefId::FunctionId(it) => type_for_fn(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 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(
|
||||
_db: &impl HirDatabase,
|
||||
db: &impl HirDatabase,
|
||||
_cycle: &[String],
|
||||
_impl_id: &ImplId,
|
||||
) -> Ty {
|
||||
Ty::Unknown
|
||||
impl_id: &ImplId,
|
||||
) -> Binders<Ty> {
|
||||
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 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 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()))?,
|
||||
))
|
||||
}
|
||||
|
@ -6,5 +6,4 @@ test_utils::marks!(
|
||||
type_var_resolves_to_int_var
|
||||
match_ergonomics_ref
|
||||
coerce_merge_fail_fallback
|
||||
insert_vars_for_impl_trait
|
||||
);
|
||||
|
@ -61,11 +61,11 @@ impl CrateImplBlocks {
|
||||
for impl_id in module_data.scope.impls() {
|
||||
match db.impl_trait(impl_id) {
|
||||
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 => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -496,7 +496,7 @@ fn transform_receiver_ty(
|
||||
AssocContainerId::ContainerId(_) => unreachable!(),
|
||||
};
|
||||
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(
|
||||
|
@ -75,7 +75,7 @@ fn test2() {
|
||||
[124; 131) 'loop {}': !
|
||||
[129; 131) '{}': ()
|
||||
[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; _]
|
||||
[186; 420) '{ ...rr); }': ()
|
||||
[196; 199) 'arr': &[u8; _]
|
||||
@ -85,14 +85,14 @@ fn test2() {
|
||||
[227; 228) 'a': &[u8]
|
||||
[237; 240) 'arr': &[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
|
||||
[256; 259) 'arr': &[u8; _]
|
||||
[270; 271) 'c': &[u8]
|
||||
[280; 287) '{ arr }': &[u8]
|
||||
[282; 285) 'arr': &[u8; _]
|
||||
[297; 298) 'd': u8
|
||||
[301; 302) 'g': fn g<u8>(S<&[T]>) -> T
|
||||
[301; 302) 'g': fn g<u8>(S<&[u8]>) -> u8
|
||||
[301; 316) 'g(S { a: arr })': u8
|
||||
[303; 315) 'S { a: arr }': S<&[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; _]>
|
||||
[415; 481) '{ ...(c); }': ()
|
||||
[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}]>
|
||||
[434; 435) 'a': A<[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]>
|
||||
[455; 456) 'b': B<[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]>
|
||||
[476; 477) 'c': C<[u8; _]>
|
||||
"###
|
||||
@ -202,7 +202,7 @@ fn test() {
|
||||
[64; 123) 'if tru... }': &[i32]
|
||||
[67; 71) 'true': bool
|
||||
[72; 97) '{ ... }': &[i32]
|
||||
[82; 85) 'foo': fn foo<i32>(&[T]) -> &[T]
|
||||
[82; 85) 'foo': fn foo<i32>(&[i32]) -> &[i32]
|
||||
[82; 91) 'foo(&[1])': &[i32]
|
||||
[86; 90) '&[1]': &[i32; _]
|
||||
[87; 90) '[1]': [i32; _]
|
||||
@ -242,7 +242,7 @@ fn test() {
|
||||
[83; 86) '[1]': [i32; _]
|
||||
[84; 85) '1': 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]
|
||||
[112; 116) '&[1]': &[i32; _]
|
||||
[113; 116) '[1]': [i32; _]
|
||||
@ -275,7 +275,7 @@ fn test(i: i32) {
|
||||
[70; 147) 'match ... }': &[i32]
|
||||
[76; 77) 'i': 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]
|
||||
[97; 101) '&[2]': &[i32; _]
|
||||
[98; 101) '[2]': [i32; _]
|
||||
@ -320,7 +320,7 @@ fn test(i: i32) {
|
||||
[94; 97) '[1]': [i32; _]
|
||||
[95; 96) '1': 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]
|
||||
[116; 120) '&[2]': &[i32; _]
|
||||
[117; 120) '[2]': [i32; _]
|
||||
@ -438,16 +438,16 @@ fn test() {
|
||||
[43; 45) '*x': T
|
||||
[44; 45) 'x': &T
|
||||
[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
|
||||
[74; 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
|
||||
[95; 100) '&&Foo': &&Foo
|
||||
[96; 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
|
||||
[117; 123) '&&&Foo': &&&Foo
|
||||
[118; 123) '&&Foo': &&Foo
|
||||
|
@ -27,7 +27,7 @@ fn test() {
|
||||
[66; 73) 'loop {}': !
|
||||
[71; 73) '{}': ()
|
||||
[133; 160) '{ ...o"); }': ()
|
||||
[139; 149) '<[_]>::foo': fn foo<u8>(&[T]) -> T
|
||||
[139; 149) '<[_]>::foo': fn foo<u8>(&[u8]) -> u8
|
||||
[139; 157) '<[_]>:..."foo")': u8
|
||||
[150; 156) 'b"foo"': &[u8]
|
||||
"###
|
||||
@ -175,7 +175,7 @@ fn test() {
|
||||
[98; 101) 'val': T
|
||||
[123; 155) '{ ...32); }': ()
|
||||
[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>
|
||||
[147; 151) '0u32': u32
|
||||
"###
|
||||
@ -206,7 +206,7 @@ fn test() {
|
||||
[95; 98) '{ }': ()
|
||||
[118; 146) '{ ...e(); }': ()
|
||||
[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>
|
||||
"###
|
||||
);
|
||||
@ -260,7 +260,7 @@ fn test() {
|
||||
[91; 94) '{ }': ()
|
||||
[114; 149) '{ ...e(); }': ()
|
||||
[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>
|
||||
"###
|
||||
);
|
||||
@ -291,7 +291,7 @@ fn test() {
|
||||
[117; 120) '{ }': ()
|
||||
[140; 180) '{ ...e(); }': ()
|
||||
[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>
|
||||
"###
|
||||
);
|
||||
@ -475,7 +475,7 @@ fn test() {
|
||||
@r###"
|
||||
[33; 37) 'self': &Self
|
||||
[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; 124) 'S(1u32...thod()': u32
|
||||
[110; 114) '1u32': u32
|
||||
@ -501,13 +501,13 @@ fn test() {
|
||||
@r###"
|
||||
[87; 193) '{ ...t(); }': ()
|
||||
[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
|
||||
[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
|
||||
[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
|
||||
"###
|
||||
);
|
||||
@ -533,13 +533,13 @@ fn test() {
|
||||
@r###"
|
||||
[127; 211) '{ ...e(); }': ()
|
||||
[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
|
||||
[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
|
||||
[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
|
||||
"###
|
||||
);
|
||||
@ -567,19 +567,19 @@ fn test() {
|
||||
@r###"
|
||||
[135; 313) '{ ...e(); }': ()
|
||||
[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)
|
||||
[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)
|
||||
[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)
|
||||
[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)
|
||||
[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)
|
||||
"###
|
||||
);
|
||||
@ -601,7 +601,7 @@ fn test() {
|
||||
@r###"
|
||||
[101; 127) '{ ...e(); }': ()
|
||||
[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)
|
||||
"###
|
||||
);
|
||||
@ -625,10 +625,10 @@ fn test() {
|
||||
@r###"
|
||||
[131; 203) '{ ...e(); }': ()
|
||||
[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)
|
||||
[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)
|
||||
"###
|
||||
);
|
||||
@ -651,10 +651,10 @@ fn test() {
|
||||
@r###"
|
||||
[107; 211) '{ ...>(); }': ()
|
||||
[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)
|
||||
[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)
|
||||
"###
|
||||
);
|
||||
@ -697,7 +697,7 @@ fn test<U, T: Trait<U>>(t: T) {
|
||||
[71; 72) 't': T
|
||||
[77; 96) '{ ...d(); }': ()
|
||||
[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; 165) 'S.into()': 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
|
||||
[197; 198) 'S': S
|
||||
"###
|
||||
|
@ -96,13 +96,13 @@ fn test() {
|
||||
[38; 42) 'A(n)': A<i32>
|
||||
[40; 41) 'n': &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>
|
||||
[48; 49) '1': i32
|
||||
[60; 64) 'A(n)': A<i32>
|
||||
[62; 63) 'n': &mut 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>
|
||||
[74; 75) '1': i32
|
||||
"###
|
||||
|
@ -346,7 +346,7 @@ pub fn main_loop() {
|
||||
@r###"
|
||||
[144; 146) '{}': ()
|
||||
[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>
|
||||
"###
|
||||
);
|
||||
|
@ -754,15 +754,15 @@ fn test() {
|
||||
[289; 295) 'self.0': T
|
||||
[315; 353) '{ ...))); }': ()
|
||||
[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
|
||||
[336; 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>>>
|
||||
[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>>
|
||||
[342; 343) 'A': A<i32>(T) -> A<T>
|
||||
[342; 343) 'A': A<i32>(i32) -> A<i32>
|
||||
[342; 347) 'A(42)': A<i32>
|
||||
[344; 346) '42': i32
|
||||
"###
|
||||
@ -817,16 +817,16 @@ fn test(a: A<i32>) {
|
||||
[326; 327) 'a': A<i32>
|
||||
[337; 383) '{ ...))); }': ()
|
||||
[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; 380) 'A(0 as...B(a)))': &i32
|
||||
[353; 354) '0': i32
|
||||
[353; 364) '0 as *mut _': *mut i32
|
||||
[370; 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>>>
|
||||
[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>>
|
||||
[376; 377) 'a': A<i32>
|
||||
"###
|
||||
@ -1169,16 +1169,16 @@ fn test() {
|
||||
"#),
|
||||
@r###"
|
||||
[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>
|
||||
[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>
|
||||
[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>
|
||||
[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>
|
||||
[136; 139) '"x"': &str
|
||||
[146; 150) 'None': Option<{unknown}>
|
||||
@ -1205,14 +1205,14 @@ fn test() {
|
||||
[21; 26) '{ t }': T
|
||||
[23; 24) 't': T
|
||||
[38; 98) '{ ...(1); }': ()
|
||||
[44; 46) 'id': fn id<u32>(T) -> T
|
||||
[44; 46) 'id': fn id<u32>(u32) -> u32
|
||||
[44; 52) 'id(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
|
||||
[69; 70) '1': i128
|
||||
[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
|
||||
[93; 94) '1': u64
|
||||
"###
|
||||
@ -1220,7 +1220,7 @@ fn test() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn infer_impl_generics() {
|
||||
fn infer_impl_generics_basic() {
|
||||
assert_snapshot!(
|
||||
infer(r#"
|
||||
struct A<T1, T2> {
|
||||
@ -1349,16 +1349,16 @@ fn test() -> i128 {
|
||||
[146; 147) 'x': i128
|
||||
[150; 151) '1': 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
|
||||
[169; 170) 'x': i128
|
||||
[182; 183) 'a': 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
|
||||
[196; 197) 'y': 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
|
||||
[218; 219) 'a': A<i128>
|
||||
[218; 221) 'a.x': i128
|
||||
@ -1502,14 +1502,14 @@ fn test() {
|
||||
[78; 158) '{ ...(1); }': ()
|
||||
[88; 89) 'y': 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
|
||||
[106; 107) 'y': u32
|
||||
[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
|
||||
[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
|
||||
[153; 154) '1': i128
|
||||
"###
|
||||
|
@ -1,7 +1,6 @@
|
||||
use insta::assert_snapshot;
|
||||
|
||||
use ra_db::fixture::WithFixture;
|
||||
use test_utils::covers;
|
||||
|
||||
use super::{infer, infer_with_mismatches, type_at, type_at_pos};
|
||||
use crate::test_db::TestDB;
|
||||
@ -261,10 +260,10 @@ fn test() {
|
||||
[92; 94) '{}': ()
|
||||
[105; 144) '{ ...(s); }': ()
|
||||
[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>
|
||||
[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)': ()
|
||||
[139; 140) 's': S<u32>
|
||||
"###
|
||||
@ -289,11 +288,11 @@ fn test() {
|
||||
[98; 100) '{}': ()
|
||||
[111; 163) '{ ...(s); }': ()
|
||||
[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>
|
||||
[127; 134) 'unknown': 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
|
||||
[158; 159) 's': S<u32>
|
||||
"###
|
||||
@ -358,15 +357,15 @@ fn test() {
|
||||
[221; 223) '{}': ()
|
||||
[234; 300) '{ ...(S); }': ()
|
||||
[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
|
||||
[253; 254) 'S': S
|
||||
[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
|
||||
[274; 275) 'S': S
|
||||
[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
|
||||
[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].
|
||||
// FIXME: fix type parameter names going missing when going through Chalk
|
||||
assert_eq!(t, "ApplyL::Out<[missing name]>");
|
||||
assert_eq!(t, "ApplyL::Out<T>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -849,6 +847,197 @@ fn test<T: ApplyL>(t: T) {
|
||||
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]
|
||||
#[ignore]
|
||||
fn impl_trait() {
|
||||
@ -994,29 +1183,17 @@ fn weird_bounds() {
|
||||
assert_snapshot!(
|
||||
infer(r#"
|
||||
trait Trait {}
|
||||
fn test() {
|
||||
let a: impl Trait + 'lifetime = foo;
|
||||
let b: impl 'lifetime = foo;
|
||||
let b: impl (Trait) = foo;
|
||||
let b: impl ('lifetime) = foo;
|
||||
let d: impl ?Sized = foo;
|
||||
let e: impl Trait + ?Sized = foo;
|
||||
fn test(a: impl Trait + 'lifetime, b: impl 'lifetime, c: impl (Trait), d: impl ('lifetime), e: impl ?Sized, f: impl Trait + ?Sized) {
|
||||
}
|
||||
"#),
|
||||
@r###"
|
||||
[26; 237) '{ ...foo; }': ()
|
||||
[36; 37) 'a': impl Trait + {error}
|
||||
[64; 67) 'foo': impl Trait + {error}
|
||||
[77; 78) 'b': impl {error}
|
||||
[97; 100) 'foo': impl {error}
|
||||
[110; 111) 'b': impl Trait
|
||||
[128; 131) 'foo': impl Trait
|
||||
[141; 142) 'b': impl {error}
|
||||
[163; 166) 'foo': impl {error}
|
||||
[176; 177) 'd': impl {error}
|
||||
[193; 196) 'foo': impl {error}
|
||||
[206; 207) 'e': impl Trait + {error}
|
||||
[231; 234) 'foo': impl Trait + {error}
|
||||
[24; 25) 'a': impl Trait + {error}
|
||||
[51; 52) 'b': impl {error}
|
||||
[70; 71) 'c': impl Trait
|
||||
[87; 88) 'd': impl {error}
|
||||
[108; 109) 'e': impl {error}
|
||||
[124; 125) 'f': impl Trait + {error}
|
||||
[148; 151) '{ }': ()
|
||||
"###
|
||||
);
|
||||
}
|
||||
@ -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; 302) 'get(x)': {unknown}
|
||||
[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}
|
||||
[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}
|
||||
[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}
|
||||
[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
|
||||
[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>
|
||||
[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
|
||||
[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>
|
||||
[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
|
||||
[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]
|
||||
fn super_trait_cycle() {
|
||||
// This just needs to not crash
|
||||
@ -1270,9 +1473,9 @@ fn test() {
|
||||
[157; 160) '{t}': T
|
||||
[158; 159) 't': T
|
||||
[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
|
||||
[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>
|
||||
[274; 275) 'S': S<u64>
|
||||
"###
|
||||
@ -1334,7 +1537,7 @@ fn test() {
|
||||
[173; 175) '{}': ()
|
||||
[189; 308) '{ ... 1); }': ()
|
||||
[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>
|
||||
[216; 220) '1u32': u32
|
||||
[227; 228) 'x': Option<u32>
|
||||
@ -1444,7 +1647,7 @@ fn test() {
|
||||
[340; 342) '{}': ()
|
||||
[356; 515) '{ ... S); }': ()
|
||||
[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
|
||||
[376; 377) 'S': S
|
||||
[379; 393) '|s| s.method()': |S| -> u64
|
||||
@ -1452,7 +1655,7 @@ fn test() {
|
||||
[383; 384) 's': S
|
||||
[383; 393) 's.method()': 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
|
||||
[414; 428) '|s| s.method()': |S| -> u64
|
||||
[415; 416) 's': S
|
||||
@ -1605,7 +1808,6 @@ fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> {
|
||||
|
||||
#[test]
|
||||
fn unify_impl_trait() {
|
||||
covers!(insert_vars_for_impl_trait);
|
||||
assert_snapshot!(
|
||||
infer_with_mismatches(r#"
|
||||
trait Trait<T> {}
|
||||
@ -1637,26 +1839,26 @@ fn test() -> impl Trait<i32> {
|
||||
[172; 183) '{ loop {} }': T
|
||||
[174; 181) 'loop {}': !
|
||||
[179; 181) '{}': ()
|
||||
[214; 310) '{ ...t()) }': S<i32>
|
||||
[214; 310) '{ ...t()) }': S<{unknown}>
|
||||
[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>
|
||||
[231; 238) 'default': fn default<u32>() -> T
|
||||
[231; 238) 'default': fn default<u32>() -> u32
|
||||
[231; 240) 'default()': u32
|
||||
[247; 250) 'foo': fn foo(impl Trait<u32>) -> ()
|
||||
[247; 250) 'foo': fn foo(S<u32>) -> ()
|
||||
[247; 254) 'foo(s1)': ()
|
||||
[251; 253) 's1': S<u32>
|
||||
[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
|
||||
[277; 278) 'S': S<i32>(T) -> S<T>
|
||||
[277; 278) 'S': S<i32>(i32) -> 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
|
||||
[296; 297) 'S': S<i32>(T) -> S<T>
|
||||
[296; 308) 'S(default())': S<i32>
|
||||
[298; 305) 'default': fn default<i32>() -> T
|
||||
[298; 307) 'default()': i32
|
||||
[296; 297) 'S': S<{unknown}>({unknown}) -> S<{unknown}>
|
||||
[296; 308) 'S(default())': S<{unknown}>
|
||||
[298; 305) 'default': fn default<{unknown}>() -> {unknown}
|
||||
[298; 307) 'default()': {unknown}
|
||||
"###
|
||||
);
|
||||
}
|
||||
|
@ -14,7 +14,7 @@ use ra_db::{
|
||||
use super::{builtin, AssocTyValue, Canonical, ChalkContext, Impl, Obligation};
|
||||
use crate::{
|
||||
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)]
|
||||
@ -142,9 +142,13 @@ impl ToChalk for Ty {
|
||||
let substitution = proj_ty.parameters.to_chalk(db);
|
||||
chalk_ir::AliasTy { associated_ty_id, substitution }.cast().intern()
|
||||
}
|
||||
Ty::Param { idx, .. } => {
|
||||
PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }
|
||||
.to_ty::<TypeFamily>()
|
||||
Ty::Param(id) => {
|
||||
let interned_id = db.intern_type_param_id(id);
|
||||
PlaceholderIndex {
|
||||
ui: UniverseIndex::ROOT,
|
||||
idx: interned_id.as_intern_id().as_usize(),
|
||||
}
|
||||
.to_ty::<TypeFamily>()
|
||||
}
|
||||
Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(),
|
||||
Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"),
|
||||
@ -177,7 +181,10 @@ impl ToChalk for Ty {
|
||||
},
|
||||
chalk_ir::TyData::Placeholder(idx) => {
|
||||
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) => {
|
||||
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 mut result = Vec::with_capacity(generic_predicates.len());
|
||||
for pred in generic_predicates.iter() {
|
||||
if pred.is_error() {
|
||||
if pred.value.is_error() {
|
||||
// skip errored predicates completely
|
||||
continue;
|
||||
}
|
||||
@ -709,12 +716,12 @@ fn impl_block_datum(
|
||||
let trait_ref = db
|
||||
.impl_trait(impl_id)
|
||||
// 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 generic_params = generics(db, impl_id.into());
|
||||
let bound_vars = Substs::bound_vars(&generic_params);
|
||||
let trait_ref = trait_ref.subst(&bound_vars);
|
||||
let trait_ = trait_ref.trait_;
|
||||
let impl_type = if impl_id.lookup(db).container.module(db).krate == krate {
|
||||
chalk_rust_ir::ImplType::Local
|
||||
@ -789,20 +796,18 @@ fn type_alias_associated_ty_value(
|
||||
_ => 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
|
||||
.trait_data(trait_ref.trait_)
|
||||
.associated_type_by_name(&type_alias_data.name)
|
||||
.expect("assoc ty value should not exist"); // validated when building the impl data as well
|
||||
let generic_params = generics(db, impl_id.into());
|
||||
let bound_vars = Substs::bound_vars(&generic_params);
|
||||
let ty = db.ty(type_alias.into()).subst(&bound_vars);
|
||||
let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) };
|
||||
let ty = db.ty(type_alias.into());
|
||||
let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
|
||||
let value = chalk_rust_ir::AssociatedTyValue {
|
||||
impl_id: Impl::ImplBlock(impl_id.into()).to_chalk(db),
|
||||
associated_ty_id: assoc_ty.to_chalk(db),
|
||||
value: make_binders(value_bound, bound_vars.len()),
|
||||
value: make_binders(value_bound, ty.num_binders),
|
||||
};
|
||||
Arc::new(value)
|
||||
}
|
||||
|
@ -2,10 +2,11 @@
|
||||
//! query, but can't be computed directly from `*Data` (ie, which need a `db`).
|
||||
use std::sync::Arc;
|
||||
|
||||
use hir_def::generics::WherePredicateTarget;
|
||||
use hir_def::{
|
||||
adt::VariantData,
|
||||
db::DefDatabase,
|
||||
generics::{GenericParams, TypeParamData},
|
||||
generics::{GenericParams, TypeParamData, TypeParamProvenance},
|
||||
path::Path,
|
||||
resolver::{HasResolver, TypeNs},
|
||||
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
|
||||
// few direct traits this should be fine (we could even use some kind of
|
||||
// SmallVec if performance is a concern)
|
||||
db.generic_params(trait_.into())
|
||||
let generic_params = db.generic_params(trait_.into());
|
||||
let trait_self = generic_params.find_trait_self_param();
|
||||
generic_params
|
||||
.where_predicates
|
||||
.iter()
|
||||
.filter_map(|pred| match &pred.type_ref {
|
||||
TypeRef::Path(p) if p == &Path::from(name![Self]) => pred.bound.as_path(),
|
||||
.filter_map(|pred| match &pred.target {
|
||||
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,
|
||||
})
|
||||
.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 {
|
||||
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
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|it| it.params.types.iter())
|
||||
.chain(self.params.types.iter())
|
||||
.enumerate()
|
||||
.map(|(i, (_local_id, p))| (i as u32, p))
|
||||
.flat_map(|it| {
|
||||
it.params
|
||||
.types
|
||||
.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 {
|
||||
self.parent_generics
|
||||
.as_ref()
|
||||
.into_iter()
|
||||
.flat_map(|it| it.params.types.iter())
|
||||
.enumerate()
|
||||
.map(|(i, (_local_id, p))| (i as u32, p))
|
||||
pub(crate) fn iter_parent<'a>(
|
||||
&'a self,
|
||||
) -> impl Iterator<Item = (TypeParamId, &'a TypeParamData)> + 'a {
|
||||
self.parent_generics.as_ref().into_iter().flat_map(|it| {
|
||||
it.params
|
||||
.types
|
||||
.iter()
|
||||
.map(move |(local_id, p)| (TypeParamId { parent: it.def, local_id }, p))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.len_split().0
|
||||
}
|
||||
|
||||
/// (total, parents, child)
|
||||
pub(crate) fn len_split(&self) -> (usize, usize, usize) {
|
||||
let parent = self.parent_generics.as_ref().map_or(0, |p| p.len());
|
||||
let child = self.params.types.len();
|
||||
(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 {
|
||||
let (idx, (_local_id, data)) = self
|
||||
.params
|
||||
@ -139,9 +183,10 @@ impl Generics {
|
||||
.find(|(_, (idx, _))| *idx == param.local_id)
|
||||
.unwrap();
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user