rust/crates/ra_hir_def/src/generics.rs

258 lines
9.4 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;
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,
};
use ra_arena::{map::ArenaMap, Arena};
use ra_db::FileId;
2019-11-20 03:25:02 -06:00
use ra_syntax::ast::{self, NameOwner, TypeBoundsOwner, TypeParamsOwner};
use crate::{
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,
2019-12-07 11:24:52 -06:00
src::HasChildSource,
src::HasSource,
2019-11-20 03:25:02 -06:00
type_ref::{TypeBound, TypeRef},
2019-12-12 08:11:57 -06:00
AdtId, GenericDefId, 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,
}
#[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.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct GenericParams {
pub types: Arena<LocalTypeParamId, TypeParamData>,
// lifetimes: Arena<LocalLifetimeParamId, 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)]
pub struct WherePredicate {
pub target: WherePredicateTarget,
2019-11-20 03:25:02 -06:00
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>>;
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(
2019-11-23 05:44:43 -06:00
db: &impl DefDatabase,
2019-11-20 11:33:18 -06:00
def: GenericDefId,
) -> Arc<GenericParams> {
2019-12-07 11:24:52 -06:00
let (params, _source_map) = GenericParams::new(db, def.into());
Arc::new(params)
2019-11-20 11:33:18 -06:00
}
2019-12-07 11:24:52 -06:00
fn new(db: &impl DefDatabase, def: GenericDefId) -> (GenericParams, InFile<SourceMap>) {
let mut generics = GenericParams { types: Arena::default(), where_predicates: Vec::new() };
2019-12-07 11:24:52 -06:00
let mut sm = ArenaMap::default();
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);
generics.fill(&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);
2019-12-07 11:24:52 -06:00
generics.fill(&mut sm, &src.value);
src.file_id
}
GenericDefId::AdtId(AdtId::UnionId(it)) => {
2019-12-12 08:11:57 -06:00
let src = it.lookup(db).source(db);
2019-12-07 11:24:52 -06:00
generics.fill(&mut sm, &src.value);
src.file_id
}
GenericDefId::AdtId(AdtId::EnumId(it)) => {
2019-12-12 08:11:57 -06:00
let src = it.lookup(db).source(db);
2019-12-07 11:24:52 -06:00
generics.fill(&mut sm, &src.value);
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);
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,
});
2019-12-07 11:24:52 -06:00
sm.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());
2019-12-07 11:24:52 -06:00
generics.fill_bounds(&src.value, self_param);
2019-12-07 10:34:28 -06:00
2019-12-07 11:24:52 -06:00
generics.fill(&mut sm, &src.value);
src.file_id
}
GenericDefId::TypeAliasId(it) => {
let src = it.lookup(db).source(db);
generics.fill(&mut sm, &src.value);
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);
2019-12-07 11:24:52 -06:00
generics.fill(&mut sm, &src.value);
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
}
2019-12-07 11:24:52 -06:00
fn fill(&mut self, sm: &mut SourceMap, node: &dyn TypeParamsOwner) {
2019-11-20 03:25:02 -06:00
if let Some(params) = node.type_param_list() {
2019-12-07 11:24:52 -06:00
self.fill_params(sm, params)
2019-11-20 03:25:02 -06:00
}
if let Some(where_clause) = node.where_clause() {
self.fill_where_predicates(where_clause);
}
}
2019-12-07 10:34:28 -06:00
fn fill_bounds(&mut self, node: &dyn ast::TypeBoundsOwner, type_ref: TypeRef) {
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(bound, type_ref.clone());
}
}
2019-12-07 11:24:52 -06:00
fn fill_params(&mut self, sm: &mut SourceMap, params: ast::TypeParamList) {
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`
let default = type_param.default_type().map(TypeRef::from_ast);
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);
2019-12-07 11:24:52 -06:00
sm.insert(param_id, Either::Right(type_param.clone()));
2019-11-20 03:25:02 -06:00
let type_ref = TypeRef::Path(name.into());
self.fill_bounds(&type_param, type_ref);
}
}
fn fill_where_predicates(&mut self, where_clause: ast::WhereClause) {
for pred in where_clause.predicates() {
let type_ref = match pred.type_ref() {
Some(type_ref) => type_ref,
None => continue,
};
let type_ref = TypeRef::from_ast(type_ref);
for bound in pred.type_bound_list().iter().flat_map(|l| l.bounds()) {
self.add_where_predicate_from_bound(bound, type_ref.clone());
}
}
}
fn add_where_predicate_from_bound(&mut self, bound: ast::TypeBound, type_ref: TypeRef) {
if bound.has_question_mark() {
// FIXME: remove this bound
return;
}
let bound = TypeBound::from_ast(bound);
self.where_predicates.push(WherePredicate { target: WherePredicateTarget::TypeRef(type_ref), bound });
2019-11-20 03:25:02 -06:00
}
2020-01-24 12:35:09 -06:00
fn fill_implicit_impl_trait_args(&mut self, type_ref: &TypeRef) {
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 {
self.where_predicates.push(WherePredicate {
target: WherePredicateTarget::TypeParam(param_id),
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> {
self.types
.iter()
.find_map(|(id, p)| if p.provenance == TypeParamProvenance::TraitSelf { Some(id) } else { None })
}
2019-11-20 11:33:18 -06:00
}
2019-12-07 11:24:52 -06:00
impl HasChildSource for GenericDefId {
type ChildId = LocalTypeParamId;
2019-12-07 11:24:52 -06:00
type Value = Either<ast::TraitDef, ast::TypeParam>;
fn child_source(&self, db: &impl DefDatabase) -> InFile<SourceMap> {
let (_, sm) = GenericParams::new(db, *self);
sm
}
}
2019-12-07 12:52:09 -06:00
impl ChildBySource for GenericDefId {
fn child_by_source(&self, db: &impl DefDatabase) -> DynMap {
let mut res = DynMap::default();
let arena_map = self.child_source(db);
let arena_map = arena_map.as_ref();
for (local_id, src) in arena_map.value.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(arena_map.with_value(type_param.clone()), id)
}
}
res
}
}