rust-analyzer/crates/ra_hir/src/generics.rs

73 lines
2.4 KiB
Rust
Raw Normal View History

//! 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-01-24 22:31:32 +00:00
use ra_syntax::ast::{self, NameOwner, TypeParamsOwner};
2019-02-16 20:19:24 +00:00
use crate::{db::PersistentHirDatabase, Name, AsName, Function, Struct, Enum, Trait, Type, ImplBlock};
/// Data about a generic parameter (to a function, struct, impl, ...).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct GenericParam {
// TODO: give generic params proper IDs
pub(crate) idx: u32,
pub(crate) name: Name,
}
/// Data about the generic parameters of a function, struct, impl, etc.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
2019-01-19 17:58:04 +00:00
pub struct GenericParams {
pub(crate) params: Vec<GenericParam>,
}
2019-01-24 12:28:50 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum GenericDef {
Function(Function),
2019-01-24 14:54:18 +00:00
Struct(Struct),
2019-01-24 15:56:38 +00:00
Enum(Enum),
2019-01-24 22:31:32 +00:00
Trait(Trait),
Type(Type),
2019-02-16 20:19:24 +00:00
ImplBlock(ImplBlock),
2019-01-24 12:28:50 +00:00
}
2019-02-16 20:19:24 +00:00
impl_froms!(GenericDef: Function, Struct, Enum, Trait, Type, ImplBlock);
2019-01-24 12:28:50 +00:00
2019-01-19 17:58:04 +00:00
impl GenericParams {
2019-01-24 12:28:50 +00:00
pub(crate) fn generic_params_query(
2019-02-01 10:33:41 +00:00
db: &impl PersistentHirDatabase,
2019-01-24 12:28:50 +00:00
def: GenericDef,
) -> Arc<GenericParams> {
2019-01-19 17:58:04 +00:00
let mut generics = GenericParams::default();
2019-01-24 12:28:50 +00:00
match def {
2019-01-24 15:56:38 +00:00
GenericDef::Function(it) => generics.fill(&*it.source(db).1),
GenericDef::Struct(it) => generics.fill(&*it.source(db).1),
GenericDef::Enum(it) => generics.fill(&*it.source(db).1),
2019-01-24 22:31:32 +00:00
GenericDef::Trait(it) => generics.fill(&*it.source(db).1),
GenericDef::Type(it) => generics.fill(&*it.source(db).1),
2019-02-16 20:19:24 +00:00
GenericDef::ImplBlock(it) => generics.fill(&*it.source(db).1),
}
2019-01-24 12:28:50 +00:00
Arc::new(generics)
}
2019-01-24 15:56:38 +00:00
fn fill(&mut self, node: &impl TypeParamsOwner) {
if let Some(params) = node.type_param_list() {
self.fill_params(params)
}
}
fn fill_params(&mut self, params: &ast::TypeParamList) {
2019-01-24 12:28:50 +00:00
for (idx, type_param) in params.type_params().enumerate() {
2019-02-08 11:49:43 +00:00
let name = type_param.name().map(AsName::as_name).unwrap_or_else(Name::missing);
let param = GenericParam { idx: idx as u32, name };
2019-01-24 12:28:50 +00:00
self.params.push(param);
}
}
pub(crate) fn find_by_name(&self, name: &Name) -> Option<&GenericParam> {
self.params.iter().find(|p| &p.name == name)
}
}