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

1602 lines
50 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2019-01-08 12:19:37 +00:00
use std::sync::Arc;
2020-03-11 02:58:17 +00:00
use arrayvec::ArrayVec;
use either::Either;
2019-10-30 14:19:30 +00:00
use hir_def::{
adt::StructKind,
2019-10-31 13:40:36 +00:00
adt::VariantData,
2019-10-31 07:51:54 +00:00
builtin_type::BuiltinType,
2019-11-23 11:43:38 +00:00
docs::Documentation,
2019-11-27 14:46:02 +00:00
expr::{BindingAnnotation, Pat, PatId},
import_map,
2019-11-23 13:53:16 +00:00
per_ns::PerNs,
2020-03-23 00:01:07 +00:00
resolver::{HasResolver, Resolver},
type_ref::{Mutability, TypeRef},
2020-02-12 14:31:44 +00:00
AdtId, AssocContainerId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule,
2020-04-25 12:23:34 +00:00
ImplId, LocalEnumVariantId, LocalFieldId, LocalModuleId, Lookup, ModuleId, StaticId, StructId,
TraitId, TypeAliasId, TypeParamId, UnionId,
2019-10-30 14:19:30 +00:00
};
2019-11-02 20:42:38 +00:00
use hir_expand::{
diagnostics::DiagnosticSink,
2019-12-13 21:01:06 +00:00
name::{name, AsName},
2020-05-02 19:24:27 +00:00
MacroDefId, MacroDefKind,
2019-11-02 20:42:38 +00:00
};
2019-12-08 11:44:14 +00:00
use hir_ty::{
autoderef,
display::{HirDisplayError, HirFormatter},
expr::ExprValidator,
2020-06-11 20:06:58 +00:00
method_resolution, ApplicationTy, Canonical, GenericPredicate, InEnvironment, Substs,
TraitEnvironment, Ty, TyDefId, TypeCtor,
2019-12-08 11:44:14 +00:00
};
2020-04-14 12:32:32 +00:00
use ra_db::{CrateId, CrateName, Edition, FileId};
use ra_prof::profile;
2020-02-12 14:31:44 +00:00
use ra_syntax::{
2020-03-03 17:22:52 +00:00
ast::{self, AttrsOwner, NameOwner},
2020-02-12 14:31:44 +00:00
AstNode,
};
use rustc_hash::FxHashSet;
2019-01-04 21:02:05 +00:00
2020-03-23 07:59:14 +00:00
use crate::{
db::{DefDatabase, HirDatabase},
has_source::HasSource,
CallableDef, HirDisplay, InFile, Name,
};
2019-01-04 21:02:05 +00:00
/// hir::Crate describes a single crate. It's the main interface with which
/// a crate's dependencies interact. Mostly, it should be just a proxy for the
2019-01-04 21:02:05 +00:00
/// root module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-04 21:02:05 +00:00
pub struct Crate {
2019-12-08 11:01:45 +00:00
pub(crate) id: CrateId,
2019-01-04 21:02:05 +00:00
}
#[derive(Debug)]
pub struct CrateDependency {
pub krate: Crate,
pub name: Name,
}
impl Crate {
pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
2020-03-09 10:11:59 +00:00
db.crate_graph()[self.id]
2020-03-09 09:26:46 +00:00
.dependencies
.iter()
2019-05-23 17:30:09 +00:00
.map(|dep| {
2020-03-09 10:18:41 +00:00
let krate = Crate { id: dep.crate_id };
2019-05-23 17:30:09 +00:00
let name = dep.as_name();
CrateDependency { krate, name }
})
.collect()
2019-01-04 21:02:05 +00:00
}
2019-02-11 22:11:12 +00:00
2019-12-08 11:01:45 +00:00
// FIXME: add `transitive_reverse_dependencies`.
pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
2019-12-08 11:01:45 +00:00
let crate_graph = db.crate_graph();
crate_graph
.iter()
2020-03-09 09:26:46 +00:00
.filter(|&krate| {
2020-03-09 10:11:59 +00:00
crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
2020-03-09 09:26:46 +00:00
})
2019-12-08 11:01:45 +00:00
.map(|id| Crate { id })
.collect()
}
pub fn root_module(self, db: &dyn HirDatabase) -> Option<Module> {
2019-12-08 11:01:45 +00:00
let module_id = db.crate_def_map(self.id).root;
2019-10-30 09:27:54 +00:00
Some(Module::new(self, module_id))
2019-01-04 21:02:05 +00:00
}
pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
2020-03-09 10:11:59 +00:00
db.crate_graph()[self.id].root_file_id
2019-12-08 11:01:45 +00:00
}
pub fn edition(self, db: &dyn HirDatabase) -> Edition {
2020-03-09 10:11:59 +00:00
db.crate_graph()[self.id].edition
2019-02-11 22:11:12 +00:00
}
2020-04-14 12:32:32 +00:00
pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateName> {
db.crate_graph()[self.id].display_name.as_ref().cloned()
}
pub fn query_external_importables(
self,
db: &dyn DefDatabase,
query: &str,
) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
2020-06-10 10:30:33 +00:00
import_map::search_dependencies(
db,
self.into(),
import_map::Query::new(query).anchor_end().case_sensitive().limit(40),
2020-06-10 10:30:33 +00:00
)
.into_iter()
.map(|item| match item {
ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
})
}
pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
2019-12-08 11:01:45 +00:00
db.crate_graph().iter().map(|id| Crate { id }).collect()
}
2019-01-04 21:02:05 +00:00
}
2019-01-04 22:37:40 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-04 22:37:40 +00:00
pub struct Module {
2019-10-30 09:27:54 +00:00
pub(crate) id: ModuleId,
}
/// The defs which can be visible in the module.
2019-03-14 08:25:51 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModuleDef {
Module(Module),
2019-01-24 12:28:50 +00:00
Function(Function),
2019-09-12 21:34:52 +00:00
Adt(Adt),
2019-01-24 22:32:47 +00:00
// Can't be directly declared, but can be imported.
2019-01-24 20:32:41 +00:00
EnumVariant(EnumVariant),
2019-01-24 21:50:08 +00:00
Const(Const),
Static(Static),
2019-01-24 22:31:32 +00:00
Trait(Trait),
2019-02-24 20:36:49 +00:00
TypeAlias(TypeAlias),
2019-05-30 11:05:35 +00:00
BuiltinType(BuiltinType),
2019-02-24 20:36:49 +00:00
}
impl_froms!(
ModuleDef: Module,
Function,
2019-09-12 21:34:52 +00:00
Adt(Struct, Enum, Union),
2019-02-24 20:36:49 +00:00
EnumVariant,
Const,
Static,
Trait,
2019-05-30 11:05:35 +00:00
TypeAlias,
BuiltinType
2019-02-24 20:36:49 +00:00
);
2019-01-24 14:54:18 +00:00
impl ModuleDef {
pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
match self {
ModuleDef::Module(it) => it.parent(db),
ModuleDef::Function(it) => Some(it.module(db)),
ModuleDef::Adt(it) => Some(it.module(db)),
ModuleDef::EnumVariant(it) => Some(it.module(db)),
ModuleDef::Const(it) => Some(it.module(db)),
ModuleDef::Static(it) => Some(it.module(db)),
ModuleDef::Trait(it) => Some(it.module(db)),
ModuleDef::TypeAlias(it) => Some(it.module(db)),
ModuleDef::BuiltinType(_) => None,
}
}
2020-05-11 11:28:14 +00:00
pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
let module = match self {
ModuleDef::Module(it) => it.parent(db)?,
ModuleDef::Function(it) => return Some(it.visibility(db)),
ModuleDef::Adt(it) => it.module(db),
ModuleDef::EnumVariant(it) => {
let parent = it.parent_enum(db);
let module = it.module(db);
return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
}
ModuleDef::Const(it) => return Some(it.visibility(db)),
ModuleDef::Static(it) => it.module(db),
ModuleDef::Trait(it) => it.module(db),
ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
ModuleDef::BuiltinType(_) => return None,
};
module.visibility_of(db, self)
}
2020-06-11 11:41:42 +00:00
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
match self {
ModuleDef::Adt(it) => Some(it.name(db)),
ModuleDef::Trait(it) => Some(it.name(db)),
ModuleDef::Function(it) => Some(it.name(db)),
ModuleDef::EnumVariant(it) => Some(it.name(db)),
ModuleDef::TypeAlias(it) => Some(it.name(db)),
ModuleDef::Module(it) => it.name(db),
ModuleDef::Const(it) => it.name(db),
ModuleDef::Static(it) => it.name(db),
ModuleDef::BuiltinType(it) => Some(it.as_name()),
}
}
}
2020-02-12 14:31:44 +00:00
pub use hir_def::{
2020-02-12 15:18:29 +00:00
attr::Attrs, item_scope::ItemInNs, visibility::Visibility, AssocItemId, AssocItemLoc,
2020-02-12 14:31:44 +00:00
};
2019-05-23 18:01:08 +00:00
2019-01-04 22:37:40 +00:00
impl Module {
2019-11-23 13:49:53 +00:00
pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
2019-12-08 11:01:45 +00:00
Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } }
2019-10-30 09:27:54 +00:00
}
2019-01-06 13:10:25 +00:00
/// Name of this module.
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2019-10-31 15:45:10 +00:00
let def_map = db.crate_def_map(self.id.krate);
2019-11-27 18:31:51 +00:00
let parent = def_map[self.id.local_id].parent?;
2019-05-23 18:01:08 +00:00
def_map[parent].children.iter().find_map(|(name, module_id)| {
2019-11-27 18:31:51 +00:00
if *module_id == self.id.local_id {
2019-05-23 18:01:08 +00:00
Some(name.clone())
} else {
None
}
})
2019-01-06 12:58:45 +00:00
}
2019-01-04 22:37:40 +00:00
/// Returns the crate this module is part of.
2019-10-30 09:27:54 +00:00
pub fn krate(self) -> Crate {
2019-12-08 11:01:45 +00:00
Crate { id: self.id.krate }
2019-01-04 22:37:40 +00:00
}
2019-01-06 13:10:25 +00:00
/// Topmost parent of this module. Every module has a `crate_root`, but some
/// might be missing `krate`. This can happen if a module's file is not included
2019-02-11 16:18:27 +00:00
/// in the module tree of any target in `Cargo.toml`.
pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
2019-10-31 15:45:10 +00:00
let def_map = db.crate_def_map(self.id.krate);
2019-11-24 15:05:12 +00:00
self.with_module_id(def_map.root)
2019-01-04 22:37:40 +00:00
}
/// Iterates over all child modules.
pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
2019-10-31 15:45:10 +00:00
let def_map = db.crate_def_map(self.id.krate);
2019-11-27 18:31:51 +00:00
let children = def_map[self.id.local_id]
2019-05-23 18:01:08 +00:00
.children
.iter()
.map(|(_, module_id)| self.with_module_id(*module_id))
.collect::<Vec<_>>();
children.into_iter()
}
2019-01-06 11:05:03 +00:00
/// Finds a parent module.
pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
2019-10-31 15:45:10 +00:00
let def_map = db.crate_def_map(self.id.krate);
2019-11-27 18:31:51 +00:00
let parent_id = def_map[self.id.local_id].parent?;
2019-05-23 18:01:08 +00:00
Some(self.with_module_id(parent_id))
2019-01-06 11:05:03 +00:00
}
pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
2019-07-05 02:59:28 +00:00
let mut res = vec![self];
let mut curr = self;
while let Some(next) = curr.parent(db) {
2019-07-05 02:59:28 +00:00
res.push(next);
2019-01-06 12:58:45 +00:00
curr = next
}
res
2019-01-06 12:58:45 +00:00
}
2019-01-06 12:16:21 +00:00
/// Returns a `ModuleScope`: a set of items, visible in this module.
pub fn scope(
self,
db: &dyn HirDatabase,
visible_from: Option<Module>,
) -> Vec<(Name, ScopeDef)> {
2019-11-27 18:31:51 +00:00
db.crate_def_map(self.id.krate)[self.id.local_id]
2019-10-31 15:45:10 +00:00
.scope
.entries()
.filter_map(|(name, def)| {
if let Some(m) = visible_from {
let filtered =
def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
if filtered.is_none() && !def.is_none() {
None
} else {
Some((name, filtered))
}
} else {
Some((name, def))
}
})
2020-03-13 11:28:13 +00:00
.flat_map(|(name, def)| {
ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
})
2019-10-31 15:45:10 +00:00
.collect()
2019-01-06 12:16:21 +00:00
}
2020-03-24 20:45:42 +00:00
pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
2020-03-25 16:11:38 +00:00
db.crate_def_map(self.id.krate)[self.id.local_id].scope.visibility_of(def.clone().into())
2020-03-24 20:45:42 +00:00
}
pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
let _p = profile("Module::diagnostics");
let crate_def_map = db.crate_def_map(self.id.krate);
crate_def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
2019-03-24 07:21:36 +00:00
for decl in self.declarations(db) {
match decl {
crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
crate::ModuleDef::Module(m) => {
// Only add diagnostics from inline modules
if crate_def_map[m.id.local_id].origin.is_inline() {
m.diagnostics(db, sink)
}
}
2019-03-24 07:21:36 +00:00
_ => (),
}
}
2020-02-29 20:24:40 +00:00
for impl_def in self.impl_defs(db) {
for item in impl_def.items(db) {
if let AssocItem::Function(f) = item {
2019-06-03 14:01:10 +00:00
f.diagnostics(db, sink);
2019-03-24 07:21:36 +00:00
}
}
}
2019-01-06 12:58:45 +00:00
}
2019-01-19 20:23:26 +00:00
pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
2019-10-31 15:45:10 +00:00
let def_map = db.crate_def_map(self.id.krate);
2019-11-27 18:31:51 +00:00
def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
}
pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<ImplDef> {
2019-11-15 18:28:00 +00:00
let def_map = db.crate_def_map(self.id.krate);
2020-02-29 20:24:40 +00:00
def_map[self.id.local_id].scope.impls().map(ImplDef::from).collect()
}
2019-05-23 18:01:08 +00:00
2019-12-08 11:20:59 +00:00
pub(crate) fn with_module_id(self, module_id: LocalModuleId) -> Module {
2019-10-30 09:27:54 +00:00
Module::new(self.krate(), module_id)
2019-05-23 18:01:08 +00:00
}
2020-01-10 17:40:45 +00:00
/// Finds a path that can be used to refer to the given item from within
/// this module, if possible.
pub fn find_use_path(
self,
2020-03-23 07:59:14 +00:00
db: &dyn DefDatabase,
2020-03-23 11:34:56 +00:00
item: impl Into<ItemInNs>,
) -> Option<hir_def::path::ModPath> {
2020-03-23 11:34:56 +00:00
hir_def::find_path::find_path(db, item.into(), self.into())
}
2019-01-04 22:37:40 +00:00
}
2019-01-08 12:19:37 +00:00
2019-01-25 11:21:14 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2020-04-25 12:23:34 +00:00
pub struct Field {
2019-01-25 17:32:34 +00:00
pub(crate) parent: VariantDef,
2020-04-25 12:23:34 +00:00
pub(crate) id: LocalFieldId,
2019-01-08 12:27:00 +00:00
}
2019-09-16 10:48:54 +00:00
#[derive(Debug, PartialEq, Eq)]
2019-01-25 17:32:34 +00:00
pub enum FieldSource {
2019-08-23 12:55:21 +00:00
Named(ast::RecordFieldDef),
Pos(ast::TupleFieldDef),
2019-01-25 17:32:34 +00:00
}
2020-04-25 12:23:34 +00:00
impl Field {
pub fn name(&self, db: &dyn HirDatabase) -> Name {
2019-11-24 19:44:24 +00:00
self.parent.variant_data(db).fields()[self.id].name.clone()
2019-01-08 12:27:00 +00:00
}
/// Returns the type as in the signature of the struct (i.e., with
/// placeholder types for type parameters). This is good for showing
/// signature help, but not so good to actually get the type of the field
/// when you actually have a variable of the struct.
pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
2019-12-08 11:16:57 +00:00
let var_id = self.parent.into();
2020-02-04 20:33:03 +00:00
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, var_id, ty)
2019-01-25 11:21:14 +00:00
}
pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
2019-01-25 11:21:14 +00:00
self.parent
2019-01-08 12:32:27 +00:00
}
}
2020-04-25 12:23:34 +00:00
impl HasVisibility for Field {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let variant_data = self.parent.variant_data(db);
let visibility = &variant_data.fields()[self.id].visibility;
let parent_id: hir_def::VariantId = self.parent.into();
visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
}
}
2019-01-24 14:54:18 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-08 12:19:37 +00:00
pub struct Struct {
2019-01-24 14:54:18 +00:00
pub(crate) id: StructId,
2019-01-08 12:19:37 +00:00
}
impl Struct {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
2019-01-08 12:19:37 +00:00
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
db.struct_data(self.id).name.clone()
2019-01-08 12:22:57 +00:00
}
2019-01-08 12:23:56 +00:00
2020-04-25 12:23:34 +00:00
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
db.struct_data(self.id)
2019-01-09 15:46:02 +00:00
.variant_data
.fields()
2019-11-24 19:44:24 +00:00
.iter()
2020-04-25 12:23:34 +00:00
.map(|(id, _)| Field { parent: self.into(), id })
2019-01-15 15:43:25 +00:00
.collect()
2019-01-08 12:23:56 +00:00
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
}
fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
db.struct_data(self.id).variant_data.clone()
2019-11-20 18:08:39 +00:00
}
2019-01-08 12:22:57 +00:00
}
2019-05-23 17:18:47 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Union {
2019-10-31 15:45:10 +00:00
pub(crate) id: UnionId,
2019-05-23 17:18:47 +00:00
}
impl Union {
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-11-25 14:30:50 +00:00
db.union_data(self.id).name.clone()
2019-05-23 17:18:47 +00:00
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
2019-05-23 17:18:47 +00:00
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
}
2019-11-26 11:29:12 +00:00
2020-04-25 12:23:34 +00:00
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
2019-11-26 11:29:12 +00:00
db.union_data(self.id)
.variant_data
.fields()
.iter()
2020-04-25 12:23:34 +00:00
.map(|(id, _)| Field { parent: self.into(), id })
2019-11-26 11:29:12 +00:00
.collect()
}
fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
2019-11-26 11:29:12 +00:00
db.union_data(self.id).variant_data.clone()
}
2019-05-23 17:18:47 +00:00
}
2019-01-24 15:56:38 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-08 12:22:57 +00:00
pub struct Enum {
2019-01-24 15:56:38 +00:00
pub(crate) id: EnumId,
2019-01-08 12:22:57 +00:00
}
impl Enum {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
2019-01-08 12:22:57 +00:00
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-10-31 13:40:36 +00:00
db.enum_data(self.id).name.clone()
2019-01-08 12:22:57 +00:00
}
pub fn variants(self, db: &dyn HirDatabase) -> Vec<EnumVariant> {
2019-10-31 13:40:36 +00:00
db.enum_data(self.id)
.variants
.iter()
.map(|(id, _)| EnumVariant { parent: self, id })
.collect()
2019-01-25 09:41:23 +00:00
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
}
2019-01-08 12:19:37 +00:00
}
2019-01-08 17:11:13 +00:00
2019-01-24 20:32:41 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EnumVariant {
2019-01-25 08:35:38 +00:00
pub(crate) parent: Enum,
2019-10-31 08:23:30 +00:00
pub(crate) id: LocalEnumVariantId,
}
impl EnumVariant {
pub fn module(self, db: &dyn HirDatabase) -> Module {
2019-01-25 08:35:38 +00:00
self.parent.module(db)
}
pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
2019-01-25 08:35:38 +00:00
self.parent
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-10-31 13:40:36 +00:00
db.enum_data(self.parent.id).variants[self.id].name.clone()
}
2020-04-25 12:23:34 +00:00
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
self.variant_data(db)
.fields()
2019-11-24 19:44:24 +00:00
.iter()
2020-04-25 12:23:34 +00:00
.map(|(id, _)| Field { parent: self.into(), id })
.collect()
}
2019-01-25 11:21:14 +00:00
pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
self.variant_data(db).kind()
}
pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
2019-10-31 13:40:36 +00:00
db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
}
}
2019-09-12 21:34:52 +00:00
/// A Data Type
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2019-09-12 21:34:52 +00:00
pub enum Adt {
Struct(Struct),
Union(Union),
Enum(Enum),
}
2019-09-12 21:34:52 +00:00
impl_froms!(Adt: Struct, Union, Enum);
2019-09-12 21:34:52 +00:00
impl Adt {
pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
let subst = db.generic_defaults(self.into());
subst.iter().any(|ty| ty == &Ty::Unknown)
}
/// Turns this ADT into a type. Any type parameters of the ADT will be
/// turned into unknown types, which is good for e.g. finding the most
/// general set of completions, but will not look very nice when printed.
pub fn ty(self, db: &dyn HirDatabase) -> Type {
2019-11-26 19:56:07 +00:00
let id = AdtId::from(self);
Type::from_def(db, id.module(db.upcast()).krate, id)
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
2019-11-20 19:00:57 +00:00
match self {
Adt::Struct(s) => s.module(db),
Adt::Union(s) => s.module(db),
Adt::Enum(e) => e.module(db),
}
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-11-20 19:00:57 +00:00
Some(self.module(db).krate())
}
2020-03-05 23:02:14 +00:00
2020-05-26 18:12:13 +00:00
pub fn name(self, db: &dyn HirDatabase) -> Name {
2020-03-05 23:02:14 +00:00
match self {
Adt::Struct(s) => s.name(db),
Adt::Union(u) => u.name(db),
Adt::Enum(e) => e.name(db),
}
}
}
2019-11-20 18:08:39 +00:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VariantDef {
Struct(Struct),
2019-11-26 11:29:12 +00:00
Union(Union),
2019-11-20 18:08:39 +00:00
EnumVariant(EnumVariant),
}
2019-11-26 11:29:12 +00:00
impl_froms!(VariantDef: Struct, Union, EnumVariant);
2019-11-20 18:08:39 +00:00
impl VariantDef {
2020-04-25 12:23:34 +00:00
pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
2019-11-20 18:08:39 +00:00
match self {
VariantDef::Struct(it) => it.fields(db),
2019-11-26 11:29:12 +00:00
VariantDef::Union(it) => it.fields(db),
2019-11-20 18:08:39 +00:00
VariantDef::EnumVariant(it) => it.fields(db),
}
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
2019-11-20 18:08:39 +00:00
match self {
VariantDef::Struct(it) => it.module(db),
2019-11-26 11:29:12 +00:00
VariantDef::Union(it) => it.module(db),
2019-11-20 18:08:39 +00:00
VariantDef::EnumVariant(it) => it.module(db),
}
}
pub fn name(&self, db: &dyn HirDatabase) -> Name {
2020-03-05 23:02:14 +00:00
match self {
VariantDef::Struct(s) => s.name(db),
VariantDef::Union(u) => u.name(db),
VariantDef::EnumVariant(e) => e.name(db),
}
}
pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
2019-11-20 18:08:39 +00:00
match self {
VariantDef::Struct(it) => it.variant_data(db),
2019-11-26 11:29:12 +00:00
VariantDef::Union(it) => it.variant_data(db),
2019-11-20 18:08:39 +00:00
VariantDef::EnumVariant(it) => it.variant_data(db),
}
}
}
2019-03-30 10:50:00 +00:00
/// The defs which have a body.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DefWithBody {
Function(Function),
2019-03-30 10:50:00 +00:00
Static(Static),
2019-04-10 21:00:56 +00:00
Const(Const),
2019-03-30 10:50:00 +00:00
}
impl_froms!(DefWithBody: Function, Const, Static);
2019-03-30 10:50:00 +00:00
impl DefWithBody {
pub fn module(self, db: &dyn HirDatabase) -> Module {
2019-10-09 11:59:47 +00:00
match self {
DefWithBody::Const(c) => c.module(db),
DefWithBody::Function(f) => f.module(db),
DefWithBody::Static(s) => s.module(db),
}
}
2020-03-05 23:02:14 +00:00
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2020-03-05 23:02:14 +00:00
match self {
DefWithBody::Function(f) => Some(f.name(db)),
DefWithBody::Static(s) => s.name(db),
DefWithBody::Const(c) => c.name(db),
}
}
2019-03-30 10:50:00 +00:00
}
2019-01-24 12:28:50 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-08 17:11:13 +00:00
pub struct Function {
2019-01-24 12:28:50 +00:00
pub(crate) id: FunctionId,
2019-01-08 17:11:13 +00:00
}
impl Function {
pub fn module(self, db: &dyn HirDatabase) -> Module {
self.id.lookup(db.upcast()).module(db.upcast()).into()
2019-01-08 17:11:13 +00:00
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
2019-09-07 19:03:03 +00:00
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-11-22 14:10:51 +00:00
db.function_data(self.id).name.clone()
}
pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
2019-11-22 14:10:51 +00:00
db.function_data(self.id).has_self_param
}
pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeRef> {
2019-11-22 14:10:51 +00:00
db.function_data(self.id).params.clone()
}
pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
db.function_data(self.id).is_unsafe
}
pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
let _p = profile("Function::diagnostics");
2019-12-08 11:26:53 +00:00
let infer = db.infer(self.id.into());
2019-11-27 12:56:20 +00:00
infer.add_diagnostics(db, self.id, sink);
2019-11-27 14:46:02 +00:00
let mut validator = ExprValidator::new(self.id, infer, sink);
2019-04-10 21:00:56 +00:00
validator.validate_body(db);
2019-03-21 19:13:11 +00:00
}
}
2019-01-22 13:55:05 +00:00
impl HasVisibility for Function {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let function_data = db.function_data(self.id);
let visibility = &function_data.visibility;
visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
2019-01-24 21:50:08 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-11 17:28:10 +00:00
pub struct Const {
2019-01-24 21:50:08 +00:00
pub(crate) id: ConstId,
2019-01-11 17:28:10 +00:00
}
2019-01-11 18:02:12 +00:00
impl Const {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
2019-02-16 21:06:23 +00:00
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
2019-09-07 19:03:03 +00:00
}
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2019-11-22 15:51:53 +00:00
db.const_data(self.id).name.clone()
}
2019-01-11 18:02:12 +00:00
}
impl HasVisibility for Const {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let function_data = db.const_data(self.id);
let visibility = &function_data.visibility;
visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
2019-01-24 21:50:08 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-11 17:28:10 +00:00
pub struct Static {
2019-01-24 21:50:08 +00:00
pub(crate) id: StaticId,
2019-01-11 17:28:10 +00:00
}
2019-01-11 18:02:12 +00:00
impl Static {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
2019-02-16 21:06:23 +00:00
}
2019-02-25 08:21:01 +00:00
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
2019-09-07 19:03:03 +00:00
}
2020-03-03 17:22:52 +00:00
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2020-03-03 17:22:52 +00:00
db.static_data(self.id).name.clone()
}
2020-05-10 15:08:28 +00:00
pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
db.static_data(self.id).mutable
}
2019-01-11 18:02:12 +00:00
}
2019-01-24 22:31:32 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-01-11 17:28:10 +00:00
pub struct Trait {
2019-01-24 22:31:32 +00:00
pub(crate) id: TraitId,
2019-01-11 17:28:10 +00:00
}
2019-01-11 18:02:12 +00:00
impl Trait {
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
2019-02-16 21:06:23 +00:00
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-11-22 15:53:39 +00:00
db.trait_data(self.id).name.clone()
2019-03-24 16:36:15 +00:00
}
pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2019-11-26 14:12:16 +00:00
db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
2019-03-24 16:36:15 +00:00
}
pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
2019-11-22 15:53:39 +00:00
db.trait_data(self.id).auto
}
2019-01-11 18:02:12 +00:00
}
2019-01-24 22:31:32 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2019-02-24 20:36:49 +00:00
pub struct TypeAlias {
2019-03-26 16:15:39 +00:00
pub(crate) id: TypeAliasId,
2019-01-11 17:28:10 +00:00
}
2019-01-11 18:02:12 +00:00
2019-02-24 20:36:49 +00:00
impl TypeAlias {
pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
let subst = db.generic_defaults(self.id.into());
subst.iter().any(|ty| ty == &Ty::Unknown)
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
2019-02-16 21:06:23 +00:00
}
pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
2019-10-30 09:27:54 +00:00
Some(self.module(db).krate())
}
pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
2019-11-22 09:57:40 +00:00
db.type_alias_data(self.id).type_ref.clone()
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate, self.id)
2019-07-02 18:08:39 +00:00
}
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-11-22 09:57:40 +00:00
db.type_alias_data(self.id).name.clone()
2019-02-24 16:25:41 +00:00
}
2019-01-11 18:02:12 +00:00
}
impl HasVisibility for TypeAlias {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
let function_data = db.type_alias_data(self.id);
let visibility = &function_data.visibility;
visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
}
}
2019-05-26 12:10:56 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MacroDef {
pub(crate) id: MacroDefId,
}
impl MacroDef {
/// FIXME: right now, this just returns the root module of the crate that
/// defines this macro. The reasons for this is that macros are expanded
/// early, in `ra_hir_expand`, where modules simply do not exist yet.
pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
let krate = self.id.krate?;
let module_id = db.crate_def_map(krate).root;
Some(Module::new(Crate { id: krate }, module_id))
}
2020-03-03 17:22:52 +00:00
/// XXX: this parses the file
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2020-03-03 17:22:52 +00:00
self.source(db).value.name().map(|it| it.as_name())
}
2020-04-18 11:26:35 +00:00
/// Indicate it is a proc-macro
pub fn is_proc_macro(&self) -> bool {
2020-05-02 19:24:27 +00:00
matches!(self.id.kind, MacroDefKind::CustomDerive(_))
}
/// Indicate it is a derive macro
pub fn is_derive_macro(&self) -> bool {
matches!(self.id.kind, MacroDefKind::CustomDerive(_) | MacroDefKind::BuiltInDerive(_))
2020-04-18 11:26:35 +00:00
}
}
2020-02-12 14:31:44 +00:00
/// Invariant: `inner.as_assoc_item(db).is_some()`
/// We do not actively enforce this invariant.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum AssocItem {
Function(Function),
Const(Const),
TypeAlias(TypeAlias),
}
2020-02-12 14:31:44 +00:00
pub enum AssocItemContainer {
Trait(Trait),
2020-02-29 20:24:40 +00:00
ImplDef(ImplDef),
2020-02-12 14:31:44 +00:00
}
pub trait AsAssocItem {
fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
2020-02-12 14:31:44 +00:00
}
impl AsAssocItem for Function {
fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2020-02-12 14:31:44 +00:00
as_assoc_item(db, AssocItem::Function, self.id)
}
}
impl AsAssocItem for Const {
fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2020-02-12 14:31:44 +00:00
as_assoc_item(db, AssocItem::Const, self.id)
}
}
impl AsAssocItem for TypeAlias {
fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2020-02-12 14:31:44 +00:00
as_assoc_item(db, AssocItem::TypeAlias, self.id)
}
}
fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
2020-02-12 14:31:44 +00:00
where
ID: Lookup<Data = AssocItemLoc<AST>>,
DEF: From<ID>,
CTOR: FnOnce(DEF) -> AssocItem,
AST: AstNode,
{
match id.lookup(db.upcast()).container {
2020-02-12 14:31:44 +00:00
AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
AssocContainerId::ContainerId(_) => None,
}
}
2019-10-09 11:59:47 +00:00
impl AssocItem {
pub fn module(self, db: &dyn HirDatabase) -> Module {
2019-10-09 11:59:47 +00:00
match self {
AssocItem::Function(f) => f.module(db),
AssocItem::Const(c) => c.module(db),
AssocItem::TypeAlias(t) => t.module(db),
}
}
pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
2020-02-12 15:18:29 +00:00
let container = match self {
AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
2020-02-12 15:18:29 +00:00
};
match container {
AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
2020-02-29 20:24:40 +00:00
AssocContainerId::ImplId(id) => AssocItemContainer::ImplDef(id.into()),
2020-02-12 15:18:29 +00:00
AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"),
2020-02-12 14:31:44 +00:00
}
}
2019-10-09 11:59:47 +00:00
}
2019-11-09 21:32:00 +00:00
impl HasVisibility for AssocItem {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
match self {
AssocItem::Function(f) => f.visibility(db),
AssocItem::Const(c) => c.visibility(db),
AssocItem::TypeAlias(t) => t.visibility(db),
}
}
}
2019-11-21 13:23:02 +00:00
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum GenericDef {
Function(Function),
Adt(Adt),
Trait(Trait),
TypeAlias(TypeAlias),
2020-02-29 20:24:40 +00:00
ImplDef(ImplDef),
2019-11-21 13:23:02 +00:00
// enum variants cannot have generics themselves, but their parent enums
// can, and this makes some code easier to write
EnumVariant(EnumVariant),
// consts can have type parameters from their parents (i.e. associated consts of traits)
Const(Const),
}
impl_froms!(
GenericDef: Function,
Adt(Struct, Enum, Union),
Trait,
TypeAlias,
2020-02-29 20:24:40 +00:00
ImplDef,
2019-11-21 13:23:02 +00:00
EnumVariant,
Const
);
impl GenericDef {
pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into());
generics
.types
.iter()
.map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
.collect()
}
}
2019-11-09 21:32:00 +00:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Local {
2020-02-29 17:34:34 +00:00
pub(crate) parent: DefWithBodyId,
2019-11-09 21:32:00 +00:00
pub(crate) pat_id: PatId,
}
impl Local {
2020-03-03 17:22:52 +00:00
// FIXME: why is this an option? It shouldn't be?
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2019-11-24 17:53:42 +00:00
let body = db.body(self.parent.into());
2019-11-09 21:32:00 +00:00
match &body[self.pat_id] {
Pat::Bind { name, .. } => Some(name.clone()),
_ => None,
}
}
pub fn is_self(self, db: &dyn HirDatabase) -> bool {
2019-12-13 21:01:06 +00:00
self.name(db) == Some(name![self])
2019-11-09 21:32:00 +00:00
}
pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2019-11-24 17:53:42 +00:00
let body = db.body(self.parent.into());
2019-11-09 21:32:00 +00:00
match &body[self.pat_id] {
Pat::Bind { mode, .. } => match mode {
BindingAnnotation::Mutable | BindingAnnotation::RefMut => true,
_ => false,
},
_ => false,
}
}
pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
2020-02-29 17:34:34 +00:00
self.parent.into()
2019-11-09 21:32:00 +00:00
}
pub fn module(self, db: &dyn HirDatabase) -> Module {
2020-02-29 17:34:34 +00:00
self.parent(db).module(db)
2019-11-09 21:32:00 +00:00
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
let def = DefWithBodyId::from(self.parent);
2019-11-27 13:02:33 +00:00
let infer = db.infer(def);
let ty = infer[self.pat_id].clone();
let krate = def.module(db.upcast()).krate;
2020-03-23 00:01:07 +00:00
Type::new(db, krate, def, ty)
2019-11-09 21:32:00 +00:00
}
pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::BindPat, ast::SelfParam>> {
2019-11-24 17:53:42 +00:00
let (_body, source_map) = db.body_with_source_map(self.parent.into());
2019-11-09 21:32:00 +00:00
let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
let root = src.file_syntax(db.upcast());
src.map(|ast| {
ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
})
2019-11-09 21:32:00 +00:00
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TypeParam {
pub(crate) id: TypeParamId,
}
2019-11-15 18:28:00 +00:00
impl TypeParam {
pub fn name(self, db: &dyn HirDatabase) -> Name {
2019-12-07 17:48:35 +00:00
let params = db.generic_params(self.id.parent);
2020-01-24 18:35:09 +00:00
params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
2019-12-07 17:48:35 +00:00
}
2019-12-07 18:52:09 +00:00
pub fn module(self, db: &dyn HirDatabase) -> Module {
self.id.parent.module(db.upcast()).into()
2019-12-07 18:52:09 +00:00
}
pub fn ty(self, db: &dyn HirDatabase) -> Type {
let resolver = self.id.parent.resolver(db.upcast());
let environment = TraitEnvironment::lower(db, &resolver);
let ty = Ty::Placeholder(self.id);
Type {
krate: self.id.parent.module(db.upcast()).krate,
ty: InEnvironment { value: ty, environment },
}
}
2020-05-13 13:06:42 +00:00
2020-05-14 10:53:45 +00:00
pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
let params = db.generic_defaults(self.id.parent);
2020-05-14 10:47:36 +00:00
let local_idx = hir_ty::param_idx(db, self.id)?;
2020-05-14 10:53:45 +00:00
let resolver = self.id.parent.resolver(db.upcast());
let environment = TraitEnvironment::lower(db, &resolver);
params.get(local_idx).cloned().map(|ty| Type {
krate: self.id.parent.module(db.upcast()).krate,
ty: InEnvironment { value: ty, environment },
})
2020-05-13 13:06:42 +00:00
}
2019-12-07 17:48:35 +00:00
}
2020-02-29 20:24:40 +00:00
// FIXME: rename from `ImplDef` to `Impl`
2019-11-15 18:28:00 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2020-02-29 20:24:40 +00:00
pub struct ImplDef {
2019-11-15 18:28:00 +00:00
pub(crate) id: ImplId,
}
2019-11-21 11:21:26 +00:00
2020-02-29 20:24:40 +00:00
impl ImplDef {
pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<ImplDef> {
2019-12-08 11:01:45 +00:00
let impls = db.impls_in_crate(krate.id);
2019-11-26 12:27:33 +00:00
impls.all_impls().map(Self::from).collect()
}
pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplDef> {
2019-12-08 11:01:45 +00:00
let impls = db.impls_in_crate(krate.id);
2020-02-29 20:24:40 +00:00
impls.lookup_impl_defs_for_trait(trait_.id).map(Self::from).collect()
2019-11-26 12:27:33 +00:00
}
2020-05-26 18:12:13 +00:00
pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
2019-11-24 18:03:24 +00:00
db.impl_data(self.id).target_trait.clone()
}
2020-05-26 18:12:13 +00:00
pub fn target_type(self, db: &dyn HirDatabase) -> TypeRef {
2019-11-24 18:03:24 +00:00
db.impl_data(self.id).target_type.clone()
}
2020-05-26 18:12:13 +00:00
pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
2019-11-27 14:46:02 +00:00
let impl_data = db.impl_data(self.id);
let resolver = self.id.resolver(db.upcast());
2020-02-04 20:33:03 +00:00
let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
2020-01-24 14:22:00 +00:00
let environment = TraitEnvironment::lower(db, &resolver);
2020-01-24 13:32:47 +00:00
let ty = Ty::from_hir(&ctx, &impl_data.target_type);
2019-12-12 13:09:13 +00:00
Type {
krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate,
2019-12-12 13:09:13 +00:00
ty: InEnvironment { value: ty, environment },
}
2019-11-24 18:03:24 +00:00
}
2020-05-26 18:12:13 +00:00
pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2019-11-24 18:03:24 +00:00
db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
}
2020-05-26 18:12:13 +00:00
pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
2019-11-24 18:03:24 +00:00
db.impl_data(self.id).is_negative
}
2020-05-26 18:12:13 +00:00
pub fn module(self, db: &dyn HirDatabase) -> Module {
self.id.lookup(db.upcast()).container.module(db.upcast()).into()
2019-11-24 18:03:24 +00:00
}
2020-05-26 18:12:13 +00:00
pub fn krate(self, db: &dyn HirDatabase) -> Crate {
2019-12-08 11:01:45 +00:00
Crate { id: self.module(db).id.krate }
2019-11-24 18:03:24 +00:00
}
2020-05-26 18:12:13 +00:00
pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
let src = self.source(db);
let item = src.file_id.is_builtin_derive(db.upcast())?;
let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
let attr = item
.value
.attrs()
.filter_map(|it| {
let path = hir_def::path::ModPath::from_src(it.path()?, &hygenic)?;
if path.as_ident()?.to_string() == "derive" {
Some(it)
} else {
None
}
})
.last()?;
Some(item.with_value(attr))
}
2019-11-24 18:03:24 +00:00
}
2019-11-26 18:18:26 +00:00
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Type {
2020-03-23 00:01:07 +00:00
krate: CrateId,
ty: InEnvironment<Ty>,
}
impl Type {
2020-03-23 00:01:07 +00:00
pub(crate) fn new_with_resolver(
db: &dyn HirDatabase,
resolver: &Resolver,
ty: Ty,
) -> Option<Type> {
let krate = resolver.krate()?;
Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
}
pub(crate) fn new_with_resolver_inner(
db: &dyn HirDatabase,
krate: CrateId,
resolver: &Resolver,
ty: Ty,
) -> Type {
2020-03-23 00:01:07 +00:00
let environment = TraitEnvironment::lower(db, &resolver);
Type { krate, ty: InEnvironment { value: ty, environment } }
2020-03-23 00:01:07 +00:00
}
fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
let resolver = lexical_env.resolver(db.upcast());
2020-01-24 14:22:00 +00:00
let environment = TraitEnvironment::lower(db, &resolver);
2019-12-08 11:16:57 +00:00
Type { krate, ty: InEnvironment { value: ty, environment } }
}
2019-11-26 19:56:07 +00:00
fn from_def(
db: &dyn HirDatabase,
2019-11-26 19:56:07 +00:00
krate: CrateId,
2020-02-04 20:33:03 +00:00
def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
2019-11-26 19:56:07 +00:00
) -> Type {
let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
2020-02-04 20:33:03 +00:00
let ty = db.ty(def.into()).subst(&substs);
2019-12-08 11:16:57 +00:00
Type::new(db, krate, def, ty)
2019-11-26 19:56:07 +00:00
}
pub fn is_bool(&self) -> bool {
matches!(self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. }))
}
pub fn is_mutable_reference(&self) -> bool {
matches!(
self.ty.value,
Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(Mutability::Mut), .. })
)
}
pub fn is_unknown(&self) -> bool {
matches!(self.ty.value, Ty::Unknown)
}
/// Checks that particular type `ty` implements `std::future::Future`.
/// This function is used in `.await` syntax completion.
pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
let krate = self.krate;
let std_future_trait =
db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
let std_future_trait = match std_future_trait {
Some(it) => it,
None => return false,
};
let canonical_ty = Canonical { value: self.ty.value.clone(), num_vars: 0 };
2020-01-14 13:42:52 +00:00
method_resolution::implements_trait(
&canonical_ty,
db,
self.ty.environment.clone(),
krate,
std_future_trait,
)
}
pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
let trait_ref = hir_ty::TraitRef {
trait_: trait_.id,
substs: Substs::build_for_def(db, trait_.id)
.push(self.ty.value.clone())
.fill(args.iter().map(|t| t.ty.value.clone()))
.build(),
};
let goal = Canonical {
value: hir_ty::InEnvironment::new(
self.ty.environment.clone(),
hir_ty::Obligation::Trait(trait_ref),
),
num_vars: 0,
};
db.trait_solve(self.krate, goal).is_some()
}
// FIXME: this method is broken, as it doesn't take closures into account.
pub fn as_callable(&self) -> Option<CallableDef> {
Some(self.ty.value.as_callable()?.0)
}
pub fn is_closure(&self) -> bool {
matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. }))
}
pub fn is_fn(&self) -> bool {
matches!(&self.ty.value,
Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(..), .. }) |
Ty::Apply(ApplicationTy { ctor: TypeCtor::FnPtr { .. }, .. })
)
}
pub fn is_raw_ptr(&self) -> bool {
matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(..), .. }))
}
pub fn contains_unknown(&self) -> bool {
return go(&self.ty.value);
fn go(ty: &Ty) -> bool {
match ty {
Ty::Unknown => true,
Ty::Apply(a_ty) => a_ty.parameters.iter().any(go),
_ => false,
}
}
}
2020-04-25 12:23:34 +00:00
pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
if let Ty::Apply(a_ty) = &self.ty.value {
2020-04-28 20:45:46 +00:00
let variant_id = match a_ty.ctor {
TypeCtor::Adt(AdtId::StructId(s)) => s.into(),
TypeCtor::Adt(AdtId::UnionId(u)) => u.into(),
_ => return Vec::new(),
};
return db
.field_types(variant_id)
.iter()
.map(|(local_id, ty)| {
let def = Field { parent: variant_id.into(), id: local_id };
let ty = ty.clone().subst(&a_ty.parameters);
(def, self.derived(ty))
})
.collect();
};
2019-11-26 11:29:12 +00:00
Vec::new()
}
pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
let mut res = Vec::new();
if let Ty::Apply(a_ty) = &self.ty.value {
2020-02-18 13:32:19 +00:00
if let TypeCtor::Tuple { .. } = a_ty.ctor {
for ty in a_ty.parameters.iter() {
let ty = ty.clone();
res.push(self.derived(ty));
}
}
};
res
}
pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
// There should be no inference vars in types passed here
// FIXME check that?
2019-12-08 11:44:14 +00:00
let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
let environment = self.ty.environment.clone();
let ty = InEnvironment { value: canonical, environment };
2019-12-08 11:44:14 +00:00
autoderef(db, Some(self.krate), ty)
.map(|canonical| canonical.value)
.map(move |ty| self.derived(ty))
}
2019-11-26 19:56:07 +00:00
// This would be nicer if it just returned an iterator, but that runs into
2020-02-29 20:24:40 +00:00
// lifetime problems, because we need to borrow temp `CrateImplDefs`.
2020-05-05 15:56:10 +00:00
pub fn iterate_assoc_items<T>(
2019-11-26 19:56:07 +00:00
self,
db: &dyn HirDatabase,
2019-11-26 19:56:07 +00:00
krate: Crate,
mut callback: impl FnMut(AssocItem) -> Option<T>,
) -> Option<T> {
2019-12-08 11:01:45 +00:00
for krate in self.ty.value.def_crates(db, krate.id)? {
2019-11-26 19:56:07 +00:00
let impls = db.impls_in_crate(krate);
2020-02-29 20:24:40 +00:00
for impl_def in impls.lookup_impl_defs(&self.ty.value) {
for &item in db.impl_data(impl_def).items.iter() {
2019-11-26 19:56:07 +00:00
if let Some(result) = callback(item.into()) {
return Some(result);
}
}
}
}
None
}
2020-01-14 13:42:52 +00:00
pub fn iterate_method_candidates<T>(
&self,
db: &dyn HirDatabase,
2020-01-14 13:42:52 +00:00
krate: Crate,
traits_in_scope: &FxHashSet<TraitId>,
name: Option<&Name>,
mut callback: impl FnMut(&Ty, Function) -> Option<T>,
) -> Option<T> {
// There should be no inference vars in types passed here
// FIXME check that?
// FIXME replace Unknown by bound vars here
let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
let env = self.ty.environment.clone();
let krate = krate.id;
method_resolution::iterate_method_candidates(
&canonical,
db,
env,
krate,
traits_in_scope,
name,
method_resolution::LookupMode::MethodCall,
|ty, it| match it {
AssocItemId::FunctionId(f) => callback(ty, f.into()),
_ => None,
},
)
}
pub fn iterate_path_candidates<T>(
&self,
db: &dyn HirDatabase,
2020-01-14 13:42:52 +00:00
krate: Crate,
traits_in_scope: &FxHashSet<TraitId>,
name: Option<&Name>,
mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
) -> Option<T> {
// There should be no inference vars in types passed here
// FIXME check that?
// FIXME replace Unknown by bound vars here
let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
let env = self.ty.environment.clone();
let krate = krate.id;
method_resolution::iterate_method_candidates(
&canonical,
db,
env,
krate,
traits_in_scope,
name,
method_resolution::LookupMode::Path,
|ty, it| callback(ty, it.into()),
)
}
pub fn as_adt(&self) -> Option<Adt> {
let (adt, _subst) = self.ty.value.as_adt()?;
2019-11-26 18:25:17 +00:00
Some(adt.into())
}
2020-06-11 17:17:32 +00:00
pub fn as_dyn_trait(&self) -> Option<Trait> {
self.ty.value.dyn_trait().map(Into::into)
}
2020-06-11 20:06:58 +00:00
pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
self.ty.value.impl_trait_bounds(db).map(|it| {
it.into_iter()
.filter_map(|pred| match pred {
hir_ty::GenericPredicate::Implemented(trait_ref) => {
Some(Trait::from(trait_ref.trait_))
}
_ => None,
})
.collect()
})
2020-06-11 17:17:32 +00:00
}
pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
self.ty.value.associated_type_parent_trait(db).map(Into::into)
}
2019-11-27 14:46:02 +00:00
// FIXME: provide required accessors such that it becomes implementable from outside.
pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
match (&self.ty.value, &other.ty.value) {
2019-12-08 11:44:14 +00:00
(Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor
{
TypeCtor::Ref(..) => match parameters.as_single() {
Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
_ => false,
},
_ => a_original_ty.ctor == *ctor,
},
2019-11-27 14:46:02 +00:00
_ => false,
}
}
fn derived(&self, ty: Ty) -> Type {
Type {
krate: self.krate,
ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
}
}
2020-06-11 17:17:32 +00:00
pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2020-06-11 20:06:58 +00:00
// TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
// We need a different order here.
fn walk_substs(
db: &dyn HirDatabase,
type_: &Type,
substs: &Substs,
cb: &mut impl FnMut(Type),
) {
2020-06-11 17:17:32 +00:00
for ty in substs.iter() {
2020-06-11 20:06:58 +00:00
walk_type(db, &type_.derived(ty.clone()), cb);
}
}
2020-06-11 20:06:58 +00:00
fn walk_bounds(
db: &dyn HirDatabase,
2020-06-11 20:06:58 +00:00
type_: &Type,
bounds: &[GenericPredicate],
2020-06-11 17:17:32 +00:00
cb: &mut impl FnMut(Type),
) {
2020-06-11 20:06:58 +00:00
for pred in bounds {
match pred {
GenericPredicate::Implemented(trait_ref) => {
cb(type_.clone());
walk_substs(db, type_, &trait_ref.substs, cb);
}
_ => (),
}
}
}
2020-06-11 20:06:58 +00:00
fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
let ty = type_.ty.value.strip_references();
2020-06-11 17:17:32 +00:00
match ty {
Ty::Apply(ApplicationTy { ctor, parameters }) => {
match ctor {
2020-06-11 20:06:58 +00:00
TypeCtor::Adt(_) => {
cb(type_.derived(ty.clone()));
2020-06-11 17:17:32 +00:00
}
TypeCtor::AssociatedType(_) => {
2020-06-11 20:06:58 +00:00
if let Some(_) = ty.associated_type_parent_trait(db) {
cb(type_.derived(ty.clone()));
2020-06-11 17:17:32 +00:00
}
2020-06-10 19:56:49 +00:00
}
_ => (),
}
2020-06-11 17:17:32 +00:00
// adt params, tuples, etc...
2020-06-11 20:06:58 +00:00
walk_substs(db, type_, parameters, cb);
}
2020-06-11 17:17:32 +00:00
Ty::Opaque(opaque_ty) => {
2020-06-11 20:06:58 +00:00
if let Some(bounds) = ty.impl_trait_bounds(db) {
walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2020-06-11 17:17:32 +00:00
}
2020-06-11 20:06:58 +00:00
walk_substs(db, type_, &opaque_ty.parameters, cb);
}
2020-06-11 17:17:32 +00:00
Ty::Placeholder(_) => {
2020-06-11 20:06:58 +00:00
if let Some(bounds) = ty.impl_trait_bounds(db) {
walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
}
}
2020-06-11 20:06:58 +00:00
Ty::Dyn(bounds) => {
walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
}
2020-06-11 17:17:32 +00:00
_ => (),
}
}
2020-06-11 20:06:58 +00:00
walk_type(db, self, &mut cb);
}
}
impl HirDisplay for Type {
fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
self.ty.value.hir_fmt(f)
}
}
2019-11-21 11:21:26 +00:00
/// For IDE only
#[derive(Debug)]
2019-11-21 11:21:26 +00:00
pub enum ScopeDef {
ModuleDef(ModuleDef),
MacroDef(MacroDef),
GenericParam(TypeParam),
2020-02-29 20:24:40 +00:00
ImplSelfType(ImplDef),
2019-11-21 11:21:26 +00:00
AdtSelfType(Adt),
Local(Local),
Unknown,
}
2020-03-11 02:58:17 +00:00
impl ScopeDef {
pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
let mut items = ArrayVec::new();
match (def.take_types(), def.take_values()) {
2020-03-13 11:28:13 +00:00
(Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
(None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2020-03-11 02:58:17 +00:00
(Some(m1), Some(m2)) => {
// Some items, like unit structs and enum variants, are
// returned as both a type and a value. Here we want
// to de-duplicate them.
if m1 != m2 {
items.push(ScopeDef::ModuleDef(m1.into()));
items.push(ScopeDef::ModuleDef(m2.into()));
} else {
items.push(ScopeDef::ModuleDef(m1.into()));
}
2020-03-13 11:28:13 +00:00
}
(None, None) => {}
2020-03-11 02:58:17 +00:00
};
if let Some(macro_def_id) = def.take_macros() {
items.push(ScopeDef::MacroDef(macro_def_id.into()));
}
if items.is_empty() {
items.push(ScopeDef::Unknown);
}
items
2019-11-21 11:21:26 +00:00
}
}
2019-11-23 08:14:10 +00:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AttrDef {
Module(Module),
2020-04-25 12:23:34 +00:00
Field(Field),
2019-11-23 08:14:10 +00:00
Adt(Adt),
Function(Function),
EnumVariant(EnumVariant),
Static(Static),
Const(Const),
Trait(Trait),
TypeAlias(TypeAlias),
MacroDef(MacroDef),
}
impl_froms!(
AttrDef: Module,
2020-04-25 12:23:34 +00:00
Field,
2019-11-23 08:14:10 +00:00
Adt(Struct, Enum, Union),
EnumVariant,
Static,
Const,
Function,
Trait,
TypeAlias,
MacroDef
);
pub trait HasAttrs {
fn attrs(self, db: &dyn HirDatabase) -> Attrs;
2019-11-23 08:14:10 +00:00
}
impl<T: Into<AttrDef>> HasAttrs for T {
fn attrs(self, db: &dyn HirDatabase) -> Attrs {
2019-11-23 11:43:38 +00:00
let def: AttrDef = self.into();
db.attrs(def.into())
}
}
pub trait Docs {
fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation>;
2019-11-23 11:43:38 +00:00
}
impl<T: Into<AttrDef> + Copy> Docs for T {
fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation> {
2019-11-23 11:43:38 +00:00
let def: AttrDef = (*self).into();
db.documentation(def.into())
2019-11-23 08:14:10 +00:00
}
}
pub trait HasVisibility {
fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
let vis = self.visibility(db);
vis.is_visible_from(db.upcast(), module.id)
}
}