rust/crates/hir-def/src/visibility.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

245 lines
8.5 KiB
Rust
Raw Normal View History

2019-12-24 15:11:50 -06:00
//! Defines hir-level representation of visibility (e.g. `pub` and `pub(crate)`).
2023-05-02 09:12:22 -05:00
use std::iter;
2023-12-18 06:30:41 -06:00
use hir_expand::{span_map::SpanMapRef, InFile};
use la_arena::ArenaMap;
2020-08-12 11:26:51 -05:00
use syntax::ast;
2023-05-02 09:12:22 -05:00
use triomphe::Arc;
use crate::{
db::DefDatabase,
2021-01-18 13:18:05 -06:00
nameres::DefMap,
path::{ModPath, PathKind},
resolver::HasResolver,
ConstId, FunctionId, HasModule, LocalFieldId, LocalModuleId, ModuleId, VariantId,
};
/// Visibility of an item, not yet resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
2019-12-26 08:57:14 -06:00
pub enum RawVisibility {
/// `pub(in module)`, `pub(crate)` or `pub(super)`. Also private, which is
/// equivalent to `pub(self)`.
Module(ModPath, VisibilityExplicity),
/// `pub`.
Public,
}
2019-12-26 08:57:14 -06:00
impl RawVisibility {
2022-02-23 08:55:06 -06:00
pub(crate) const fn private() -> RawVisibility {
RawVisibility::Module(ModPath::from_kind(PathKind::Super(0)), VisibilityExplicity::Implicit)
}
pub(crate) fn from_ast(
db: &dyn DefDatabase,
node: InFile<Option<ast::Visibility>>,
) -> RawVisibility {
Self::from_ast_with_span_map(db, node.value, db.span_map(node.file_id).as_ref())
}
pub(crate) fn from_ast_with_span_map(
db: &dyn DefDatabase,
node: Option<ast::Visibility>,
span_map: SpanMapRef<'_>,
2019-12-26 08:57:14 -06:00
) -> RawVisibility {
let node = match node {
None => return RawVisibility::private(),
Some(node) => node,
};
match node.kind() {
ast::VisibilityKind::In(path) => {
let path = ModPath::from_src(db.upcast(), path, span_map);
let path = match path {
2019-12-26 08:57:14 -06:00
None => return RawVisibility::private(),
Some(path) => path,
};
RawVisibility::Module(path, VisibilityExplicity::Explicit)
}
ast::VisibilityKind::PubCrate => {
let path = ModPath::from_kind(PathKind::Crate);
RawVisibility::Module(path, VisibilityExplicity::Explicit)
}
ast::VisibilityKind::PubSuper => {
let path = ModPath::from_kind(PathKind::Super(1));
RawVisibility::Module(path, VisibilityExplicity::Explicit)
}
ast::VisibilityKind::PubSelf => {
let path = ModPath::from_kind(PathKind::Super(0));
RawVisibility::Module(path, VisibilityExplicity::Explicit)
}
2019-12-26 08:57:14 -06:00
ast::VisibilityKind::Pub => RawVisibility::Public,
}
}
pub fn resolve(
&self,
db: &dyn DefDatabase,
resolver: &crate::resolver::Resolver,
) -> Visibility {
// we fall back to public visibility (i.e. fail open) if the path can't be resolved
resolver.resolve_visibility(db, self).unwrap_or(Visibility::Public)
}
}
/// Visibility of an item, with the path resolved.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Visibility {
/// Visibility is restricted to a certain module.
Module(ModuleId, VisibilityExplicity),
/// Visibility is unrestricted.
Public,
}
impl Visibility {
pub fn is_visible_from(self, db: &dyn DefDatabase, from_module: ModuleId) -> bool {
let to_module = match self {
Visibility::Module(m, _) => m,
Visibility::Public => return true,
};
// if they're not in the same crate, it can't be visible
if from_module.krate != to_module.krate {
return false;
}
let def_map = from_module.def_map(db);
self.is_visible_from_def_map(db, &def_map, from_module.local_id)
}
2019-12-27 04:24:31 -06:00
pub(crate) fn is_visible_from_other_crate(self) -> bool {
2022-02-23 08:55:06 -06:00
matches!(self, Visibility::Public)
2019-12-26 09:31:38 -06:00
}
2019-12-27 04:24:31 -06:00
pub(crate) fn is_visible_from_def_map(
self,
db: &dyn DefDatabase,
2021-01-18 13:18:05 -06:00
def_map: &DefMap,
mut from_module: LocalModuleId,
) -> bool {
let mut to_module = match self {
Visibility::Module(m, _) => m,
Visibility::Public => return true,
};
// `to_module` might be the root module of a block expression. Those have the same
// visibility as the containing module (even though no items are directly nameable from
// there, getting this right is important for method resolution).
// In that case, we adjust the visibility of `to_module` to point to the containing module.
// Additional complication: `to_module` might be in `from_module`'s `DefMap`, which we're
// currently computing, so we must not call the `def_map` query for it.
let mut arc;
loop {
let to_module_def_map =
if to_module.krate == def_map.krate() && to_module.block == def_map.block_id() {
cov_mark::hit!(is_visible_from_same_block_def_map);
def_map
} else {
arc = to_module.def_map(db);
&arc
};
match to_module_def_map.parent() {
Some(parent) => to_module = parent,
None => break,
}
}
// from_module needs to be a descendant of to_module
let mut def_map = def_map;
let mut parent_arc;
loop {
if def_map.module_id(from_module) == to_module {
return true;
}
match def_map[from_module].parent {
2022-02-23 08:55:06 -06:00
Some(parent) => from_module = parent,
None => {
match def_map.parent() {
Some(module) => {
parent_arc = module.def_map(db);
def_map = &*parent_arc;
from_module = module.local_id;
}
2022-02-23 08:55:06 -06:00
// Reached the root module, nothing left to check.
None => return false,
}
}
}
}
}
2020-07-21 10:52:43 -05:00
/// Returns the most permissive visibility of `self` and `other`.
///
/// If there is no subset relation between `self` and `other`, returns `None` (ie. they're only
/// visible in unrelated modules).
2021-01-18 13:18:05 -06:00
pub(crate) fn max(self, other: Visibility, def_map: &DefMap) -> Option<Visibility> {
2020-07-21 10:52:43 -05:00
match (self, other) {
(Visibility::Module(_, _) | Visibility::Public, Visibility::Public)
| (Visibility::Public, Visibility::Module(_, _)) => Some(Visibility::Public),
(Visibility::Module(mod_a, vis_a), Visibility::Module(mod_b, vis_b)) => {
2020-07-21 10:52:43 -05:00
if mod_a.krate != mod_b.krate {
return None;
}
2022-02-23 08:55:06 -06:00
let mut a_ancestors = iter::successors(Some(mod_a.local_id), |&m| {
let parent_id = def_map[m].parent?;
2020-07-21 10:52:43 -05:00
Some(parent_id)
});
2022-02-23 08:55:06 -06:00
let mut b_ancestors = iter::successors(Some(mod_b.local_id), |&m| {
let parent_id = def_map[m].parent?;
2020-07-21 10:52:43 -05:00
Some(parent_id)
});
if a_ancestors.any(|m| m == mod_b.local_id) {
// B is above A
return Some(Visibility::Module(mod_b, vis_b));
2020-07-21 10:52:43 -05:00
}
if b_ancestors.any(|m| m == mod_a.local_id) {
// A is above B
return Some(Visibility::Module(mod_a, vis_a));
2020-07-21 10:52:43 -05:00
}
None
}
}
}
}
/// Whether the item was imported through `pub(crate) use` or just `use`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum VisibilityExplicity {
Explicit,
Implicit,
}
impl VisibilityExplicity {
pub fn is_explicit(&self) -> bool {
matches!(self, Self::Explicit)
}
}
/// Resolve visibility of all specific fields of a struct or union variant.
pub(crate) fn field_visibilities_query(
db: &dyn DefDatabase,
variant_id: VariantId,
) -> Arc<ArenaMap<LocalFieldId, Visibility>> {
2024-01-15 05:03:31 -06:00
let var_data = variant_id.variant_data(db);
let resolver = variant_id.module(db).resolver(db);
let mut res = ArenaMap::default();
for (field_id, field_data) in var_data.fields().iter() {
res.insert(field_id, field_data.visibility.resolve(db, &resolver));
}
Arc::new(res)
}
/// Resolve visibility of a function.
pub(crate) fn function_visibility_query(db: &dyn DefDatabase, def: FunctionId) -> Visibility {
2021-04-04 21:27:57 -05:00
let resolver = def.resolver(db);
db.function_data(def).visibility.resolve(db, &resolver)
}
2022-03-17 11:02:58 -05:00
/// Resolve visibility of a const.
pub(crate) fn const_visibility_query(db: &dyn DefDatabase, def: ConstId) -> Visibility {
let resolver = def.resolver(db);
db.const_data(def).visibility.resolve(db, &resolver)
}