rust/crates/hir_def/src/generics.rs

412 lines
15 KiB
Rust
Raw Normal View History

2019-11-20 03:25:02 -06:00
//! Many kinds of items or constructs can have generic parameters: functions,
//! structs, impls, traits, etc. This module provides a common HIR for these
//! generic parameters. See also the `Generics` type and the `generics_of` query
//! in rustc.
use std::sync::Arc;
2020-08-12 09:22:05 -05:00
use arena::{map::ArenaMap, Arena};
2020-08-13 09:25:38 -05:00
use base_db::FileId;
2019-12-07 11:24:52 -06:00
use either::Either;
use hir_expand::{
2019-12-13 15:01:06 -06:00
name::{name, AsName, Name},
2019-12-07 11:24:52 -06:00
InFile,
};
2020-08-12 11:26:51 -05:00
use syntax::ast::{self, GenericParamsOwner, NameOwner, TypeBoundsOwner};
2019-11-20 03:25:02 -06:00
use crate::{
2020-04-30 05:20:13 -05:00
body::LowerCtx,
2019-12-07 12:52:09 -06:00
child_by_source::ChildBySource,
2019-11-23 05:44:43 -06:00
db::DefDatabase,
2019-12-07 12:52:09 -06:00
dyn_map::DynMap,
keys,
src::{HasChildSource, HasSource},
2020-12-11 06:49:32 -06:00
type_ref::{LifetimeRef, TypeBound, TypeRef},
AdtId, GenericDefId, LifetimeParamId, LocalLifetimeParamId, LocalTypeParamId, Lookup,
TypeParamId,
2019-11-20 03:25:02 -06:00
};
/// Data about a generic parameter (to a function, struct, impl, ...).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TypeParamData {
2020-01-24 12:35:09 -06:00
pub name: Option<Name>,
2019-11-20 03:25:02 -06:00
pub default: Option<TypeRef>,
2020-01-24 12:35:09 -06:00
pub provenance: TypeParamProvenance,
}
2020-12-11 06:49:32 -06:00
/// Data about a generic parameter (to a function, struct, impl, ...).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LifetimeParamData {
pub name: Name,
}
2020-01-24 12:35:09 -06:00
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TypeParamProvenance {
TypeParamList,
TraitSelf,
ArgumentImplTrait,
2019-11-20 03:25:02 -06:00
}
/// Data about the generic parameters of a function, struct, impl, etc.
2020-06-17 05:24:05 -05:00
#[derive(Clone, PartialEq, Eq, Debug, Default)]
2019-11-20 03:25:02 -06:00
pub struct GenericParams {
2020-03-19 10:00:11 -05:00
pub types: Arena<TypeParamData>,
2020-12-11 06:49:32 -06:00
pub lifetimes: Arena<LifetimeParamData>,
2019-11-20 03:25:02 -06:00
pub where_predicates: Vec<WherePredicate>,
}
/// A single predicate from a where clause, i.e. `where Type: Trait`. Combined
/// where clauses like `where T: Foo + Bar` are turned into multiple of these.
/// It might still result in multiple actual predicates though, because of
/// associated type bindings like `Iterator<Item = u32>`.
#[derive(Clone, PartialEq, Eq, Debug)]
2020-12-11 06:49:32 -06:00
pub enum WherePredicate {
TypeBound { target: WherePredicateTypeTarget, bound: TypeBound },
Lifetime { target: LifetimeRef, bound: LifetimeRef },
ForLifetime { lifetimes: Box<[Name]>, target: WherePredicateTypeTarget, bound: TypeBound },
2019-11-20 03:25:02 -06:00
}
#[derive(Clone, PartialEq, Eq, Debug)]
2020-12-11 06:49:32 -06:00
pub enum WherePredicateTypeTarget {
TypeRef(TypeRef),
/// For desugared where predicates that can directly refer to a type param.
2020-02-07 08:13:15 -06:00
TypeParam(LocalTypeParamId),
}
#[derive(Default)]
pub(crate) struct SourceMap {
pub(crate) type_params: ArenaMap<LocalTypeParamId, Either<ast::Trait, ast::TypeParam>>,
lifetime_params: ArenaMap<LocalLifetimeParamId, ast::LifetimeParam>,
}
2019-12-07 11:24:52 -06:00
2019-11-20 03:25:02 -06:00
impl GenericParams {
2019-11-20 11:33:18 -06:00
pub(crate) fn generic_params_query(
db: &dyn DefDatabase,
2019-11-20 11:33:18 -06:00
def: GenericDefId,
) -> Arc<GenericParams> {
2020-08-12 09:32:36 -05:00
let _p = profile::span("generic_params_query");
let generics = match def {
GenericDefId::FunctionId(id) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::AdtId(AdtId::StructId(id)) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::AdtId(AdtId::EnumId(id)) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::AdtId(AdtId::UnionId(id)) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::TraitId(id) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::TypeAliasId(id) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::ImplId(id) => {
let id = id.lookup(db).id;
let tree = db.item_tree(id.file_id);
let item = &tree[id.value];
2020-06-24 08:54:35 -05:00
tree[item.generic_params].clone()
}
GenericDefId::EnumVariantId(_) | GenericDefId::ConstId(_) => GenericParams::default(),
};
Arc::new(generics)
2019-11-20 11:33:18 -06:00
}
fn new(db: &dyn DefDatabase, def: GenericDefId) -> (GenericParams, InFile<SourceMap>) {
2020-12-11 06:49:32 -06:00
let mut generics = GenericParams::default();
let mut sm = SourceMap::default();
2020-04-30 05:20:13 -05:00
2019-11-20 03:25:02 -06:00
// FIXME: add `: Sized` bound for everything except for `Self` in traits
2019-12-07 11:24:52 -06:00
let file_id = match def {
GenericDefId::FunctionId(it) => {
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2020-01-24 12:35:09 -06:00
// lower `impl Trait` in arguments
let data = db.function_data(it);
for param in &data.params {
generics.fill_implicit_impl_trait_args(param);
}
2019-12-07 11:24:52 -06:00
src.file_id
}
GenericDefId::AdtId(AdtId::StructId(it)) => {
2019-12-12 07:58:04 -06:00
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
}
GenericDefId::AdtId(AdtId::UnionId(it)) => {
2019-12-12 08:11:57 -06:00
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
}
GenericDefId::AdtId(AdtId::EnumId(it)) => {
2019-12-12 08:11:57 -06:00
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
}
2019-11-20 03:25:02 -06:00
GenericDefId::TraitId(it) => {
2019-12-12 07:34:03 -06:00
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
2019-12-07 11:24:52 -06:00
2019-11-20 03:25:02 -06:00
// traits get the Self type as an implicit first type parameter
2020-01-24 12:35:09 -06:00
let self_param_id = generics.types.alloc(TypeParamData {
name: Some(name![Self]),
default: None,
provenance: TypeParamProvenance::TraitSelf,
});
sm.type_params.insert(self_param_id, Either::Left(src.value.clone()));
2019-11-20 03:25:02 -06:00
// add super traits as bounds on Self
// i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
2019-12-13 15:01:06 -06:00
let self_param = TypeRef::Path(name![Self].into());
2020-12-11 06:49:32 -06:00
generics.fill_bounds(&lower_ctx, &src.value, Either::Left(self_param));
2019-12-07 10:34:28 -06:00
2020-04-30 05:20:13 -05:00
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
}
GenericDefId::TypeAliasId(it) => {
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
2019-11-20 03:25:02 -06:00
}
// Note that we don't add `Self` here: in `impl`s, `Self` is not a
// type-parameter, but rather is a type-alias for impl's target
// type, so this is handled by the resolver.
2019-12-07 11:24:52 -06:00
GenericDefId::ImplId(it) => {
2019-12-12 07:09:13 -06:00
let src = it.lookup(db).source(db);
2020-04-30 05:20:13 -05:00
let lower_ctx = LowerCtx::new(db, src.file_id);
generics.fill(&lower_ctx, &mut sm, &src.value);
2019-12-07 11:24:52 -06:00
src.file_id
}
// We won't be using this ID anyway
GenericDefId::EnumVariantId(_) | GenericDefId::ConstId(_) => FileId(!0).into(),
};
2019-11-20 03:25:02 -06:00
2019-12-07 11:24:52 -06:00
(generics, InFile::new(file_id, sm))
2019-11-20 03:25:02 -06:00
}
2020-06-17 05:24:05 -05:00
pub(crate) fn fill(
&mut self,
lower_ctx: &LowerCtx,
sm: &mut SourceMap,
node: &dyn GenericParamsOwner,
2020-06-17 05:24:05 -05:00
) {
if let Some(params) = node.generic_param_list() {
2020-04-30 05:20:13 -05:00
self.fill_params(lower_ctx, sm, params)
2019-11-20 03:25:02 -06:00
}
if let Some(where_clause) = node.where_clause() {
2020-04-30 05:20:13 -05:00
self.fill_where_predicates(lower_ctx, where_clause);
2019-11-20 03:25:02 -06:00
}
}
2020-06-17 05:24:05 -05:00
pub(crate) fn fill_bounds(
2020-04-30 05:20:13 -05:00
&mut self,
lower_ctx: &LowerCtx,
node: &dyn ast::TypeBoundsOwner,
2020-12-11 06:49:32 -06:00
target: Either<TypeRef, LifetimeRef>,
2020-04-30 05:20:13 -05:00
) {
2019-11-20 03:25:02 -06:00
for bound in
node.type_bound_list().iter().flat_map(|type_bound_list| type_bound_list.bounds())
{
self.add_where_predicate_from_bound(lower_ctx, bound, None, target.clone());
2019-11-20 03:25:02 -06:00
}
}
2020-04-30 05:20:13 -05:00
fn fill_params(
&mut self,
lower_ctx: &LowerCtx,
sm: &mut SourceMap,
params: ast::GenericParamList,
2020-04-30 05:20:13 -05:00
) {
for type_param in params.type_params() {
2019-11-20 03:25:02 -06:00
let name = type_param.name().map_or_else(Name::missing, |it| it.as_name());
// FIXME: Use `Path::from_src`
2020-04-30 05:20:13 -05:00
let default = type_param.default_type().map(|it| TypeRef::from_ast(lower_ctx, it));
2020-01-24 12:35:09 -06:00
let param = TypeParamData {
name: Some(name.clone()),
default,
provenance: TypeParamProvenance::TypeParamList,
};
let param_id = self.types.alloc(param);
sm.type_params.insert(param_id, Either::Right(type_param.clone()));
2019-11-20 03:25:02 -06:00
let type_ref = TypeRef::Path(name.into());
2020-12-11 06:49:32 -06:00
self.fill_bounds(&lower_ctx, &type_param, Either::Left(type_ref));
}
for lifetime_param in params.lifetime_params() {
2020-12-15 12:23:51 -06:00
let name =
lifetime_param.lifetime().map_or_else(Name::missing, |lt| Name::new_lifetime(&lt));
2020-12-11 06:49:32 -06:00
let param = LifetimeParamData { name: name.clone() };
let param_id = self.lifetimes.alloc(param);
sm.lifetime_params.insert(param_id, lifetime_param.clone());
2020-12-11 06:49:32 -06:00
let lifetime_ref = LifetimeRef::new_name(name);
self.fill_bounds(&lower_ctx, &lifetime_param, Either::Right(lifetime_ref));
2019-11-20 03:25:02 -06:00
}
}
2020-04-30 05:20:13 -05:00
fn fill_where_predicates(&mut self, lower_ctx: &LowerCtx, where_clause: ast::WhereClause) {
2019-11-20 03:25:02 -06:00
for pred in where_clause.predicates() {
2020-12-11 06:49:32 -06:00
let target = if let Some(type_ref) = pred.ty() {
Either::Left(TypeRef::from_ast(lower_ctx, type_ref))
2020-12-15 12:23:51 -06:00
} else if let Some(lifetime) = pred.lifetime() {
Either::Right(LifetimeRef::new(&lifetime))
2020-12-11 06:49:32 -06:00
} else {
continue;
2019-11-20 03:25:02 -06:00
};
let lifetimes: Option<Box<_>> = pred.generic_param_list().map(|param_list| {
// Higher-Ranked Trait Bounds
param_list
.lifetime_params()
.map(|lifetime_param| {
lifetime_param
.lifetime()
.map_or_else(Name::missing, |lt| Name::new_lifetime(&lt))
})
.collect()
});
2019-11-20 03:25:02 -06:00
for bound in pred.type_bound_list().iter().flat_map(|l| l.bounds()) {
self.add_where_predicate_from_bound(
lower_ctx,
bound,
lifetimes.as_ref(),
target.clone(),
);
2019-11-20 03:25:02 -06:00
}
}
}
2020-04-30 05:20:13 -05:00
fn add_where_predicate_from_bound(
&mut self,
lower_ctx: &LowerCtx,
bound: ast::TypeBound,
hrtb_lifetimes: Option<&Box<[Name]>>,
2020-12-11 06:49:32 -06:00
target: Either<TypeRef, LifetimeRef>,
2020-04-30 05:20:13 -05:00
) {
2020-07-31 08:01:18 -05:00
if bound.question_mark_token().is_some() {
2019-11-20 03:25:02 -06:00
// FIXME: remove this bound
return;
}
2020-04-30 05:20:13 -05:00
let bound = TypeBound::from_ast(lower_ctx, bound);
2020-12-11 06:49:32 -06:00
let predicate = match (target, bound) {
(Either::Left(type_ref), bound) => match hrtb_lifetimes {
Some(hrtb_lifetimes) => WherePredicate::ForLifetime {
lifetimes: hrtb_lifetimes.clone(),
target: WherePredicateTypeTarget::TypeRef(type_ref),
bound,
},
None => WherePredicate::TypeBound {
target: WherePredicateTypeTarget::TypeRef(type_ref),
bound,
},
2020-12-11 06:49:32 -06:00
},
(Either::Right(lifetime), TypeBound::Lifetime(bound)) => {
WherePredicate::Lifetime { target: lifetime, bound }
}
_ => return,
};
self.where_predicates.push(predicate);
2019-11-20 03:25:02 -06:00
}
2020-06-17 05:24:05 -05:00
pub(crate) fn fill_implicit_impl_trait_args(&mut self, type_ref: &TypeRef) {
2020-01-24 12:35:09 -06:00
type_ref.walk(&mut |type_ref| {
if let TypeRef::ImplTrait(bounds) = type_ref {
2020-01-24 12:35:09 -06:00
let param = TypeParamData {
name: None,
default: None,
provenance: TypeParamProvenance::ArgumentImplTrait,
};
let param_id = self.types.alloc(param);
for bound in bounds {
2020-12-11 06:49:32 -06:00
self.where_predicates.push(WherePredicate::TypeBound {
target: WherePredicateTypeTarget::TypeParam(param_id),
2020-02-07 08:13:15 -06:00
bound: bound.clone(),
});
}
2020-01-24 12:35:09 -06:00
}
});
}
pub fn find_by_name(&self, name: &Name) -> Option<LocalTypeParamId> {
2020-01-24 12:35:09 -06:00
self.types
.iter()
.find_map(|(id, p)| if p.name.as_ref() == Some(name) { Some(id) } else { None })
2019-11-20 11:33:18 -06:00
}
pub fn find_trait_self_param(&self) -> Option<LocalTypeParamId> {
2020-02-07 08:13:15 -06:00
self.types.iter().find_map(|(id, p)| {
if p.provenance == TypeParamProvenance::TraitSelf {
Some(id)
} else {
None
}
})
}
2019-11-20 11:33:18 -06:00
}
impl HasChildSource<LocalTypeParamId> for GenericDefId {
type Value = Either<ast::Trait, ast::TypeParam>;
fn child_source(
&self,
db: &dyn DefDatabase,
) -> InFile<ArenaMap<LocalTypeParamId, Self::Value>> {
GenericParams::new(db, *self).1.map(|source_maps| source_maps.type_params)
}
}
impl HasChildSource<LocalLifetimeParamId> for GenericDefId {
type Value = ast::LifetimeParam;
fn child_source(
&self,
db: &dyn DefDatabase,
) -> InFile<ArenaMap<LocalLifetimeParamId, Self::Value>> {
GenericParams::new(db, *self).1.map(|source_maps| source_maps.lifetime_params)
2019-12-07 11:24:52 -06:00
}
}
2019-12-07 12:52:09 -06:00
impl ChildBySource for GenericDefId {
fn child_by_source(&self, db: &dyn DefDatabase) -> DynMap {
2019-12-07 12:52:09 -06:00
let mut res = DynMap::default();
let (_, sm) = GenericParams::new(db, *self);
let sm = sm.as_ref();
for (local_id, src) in sm.value.type_params.iter() {
let id = TypeParamId { parent: *self, local_id };
2019-12-07 12:52:09 -06:00
if let Either::Right(type_param) = src {
res[keys::TYPE_PARAM].insert(sm.with_value(type_param.clone()), id)
2019-12-07 12:52:09 -06:00
}
}
for (local_id, src) in sm.value.lifetime_params.iter() {
let id = LifetimeParamId { parent: *self, local_id };
res[keys::LIFETIME_PARAM].insert(sm.with_value(src.clone()), id);
}
2019-12-07 12:52:09 -06:00
res
}
}