rune/compile/
visibility.rs

1use core::fmt;
2use core::mem::take;
3
4use crate::Item;
5
6/// Information on the visibility of an item.
7#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum Visibility {
10    /// Inherited, or private visibility.
11    #[default]
12    Inherited,
13    /// Something that is publicly visible `pub`.
14    Public,
15    /// Something that is only visible in the current crate `pub(crate)`.
16    Crate,
17    /// Visible in the parent crate.
18    Super,
19    /// Only visible in the same crate.
20    SelfValue,
21}
22
23impl Visibility {
24    /// Take the current visilibity.
25    pub(crate) fn take(&mut self) -> Self {
26        take(self)
27    }
28
29    /// Test if visibility is public.
30    pub(crate) fn is_public(self) -> bool {
31        matches!(self, Self::Public)
32    }
33
34    /// Check if `from` can access `to` with the current visibility.
35    pub(crate) fn is_visible(self, from: &Item, to: &Item) -> bool {
36        match self {
37            Visibility::Inherited | Visibility::SelfValue => from.is_super_of(to, 1),
38            Visibility::Super => from.is_super_of(to, 2),
39            Visibility::Public => true,
40            Visibility::Crate => true,
41        }
42    }
43
44    /// Check if `from` can access `to` with the current visibility.
45    pub(crate) fn is_visible_inside(self, from: &Item, to: &Item) -> bool {
46        match self {
47            Visibility::Inherited | Visibility::SelfValue => from == to,
48            Visibility::Super => from.is_super_of(to, 1),
49            Visibility::Public => true,
50            Visibility::Crate => true,
51        }
52    }
53}
54
55impl fmt::Display for Visibility {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Visibility::Inherited => write!(f, "private")?,
59            Visibility::Public => write!(f, "pub")?,
60            Visibility::Crate => write!(f, "pub(crate)")?,
61            Visibility::Super => write!(f, "pub(super)")?,
62            Visibility::SelfValue => write!(f, "pub(self)")?,
63        }
64
65        Ok(())
66    }
67}