]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/middle/privacy.rs
Rollup merge of #92707 - JohnScience:patch-1, r=GuillaumeGomez
[rust.git] / compiler / rustc_middle / src / middle / privacy.rs
1 //! A pass that checks to make sure private fields and methods aren't used
2 //! outside their scopes. This pass will also generate a set of exported items
3 //! which are available for use externally when compiled as a library.
4
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
7 use rustc_macros::HashStable;
8 use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
9 use rustc_span::def_id::LocalDefId;
10 use std::hash::Hash;
11
12 /// Represents the levels of accessibility an item can have.
13 ///
14 /// The variants are sorted in ascending order of accessibility.
15 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, HashStable)]
16 pub enum AccessLevel {
17     /// Superset of `AccessLevel::Reachable` used to mark impl Trait items.
18     ReachableFromImplTrait,
19     /// Exported items + items participating in various kinds of public interfaces,
20     /// but not directly nameable. For example, if function `fn f() -> T {...}` is
21     /// public, then type `T` is reachable. Its values can be obtained by other crates
22     /// even if the type itself is not nameable.
23     Reachable,
24     /// Public items + items accessible to other crates with the help of `pub use` re-exports.
25     Exported,
26     /// Items accessible to other crates directly, without the help of re-exports.
27     Public,
28 }
29
30 /// Holds a map of accessibility levels for reachable HIR nodes.
31 #[derive(Debug, Clone)]
32 pub struct AccessLevels<Id = LocalDefId> {
33     pub map: FxHashMap<Id, AccessLevel>,
34 }
35
36 impl<Id: Hash + Eq> AccessLevels<Id> {
37     /// See `AccessLevel::Reachable`.
38     pub fn is_reachable(&self, id: Id) -> bool {
39         self.map.get(&id) >= Some(&AccessLevel::Reachable)
40     }
41
42     /// See `AccessLevel::Exported`.
43     pub fn is_exported(&self, id: Id) -> bool {
44         self.map.get(&id) >= Some(&AccessLevel::Exported)
45     }
46
47     /// See `AccessLevel::Public`.
48     pub fn is_public(&self, id: Id) -> bool {
49         self.map.get(&id) >= Some(&AccessLevel::Public)
50     }
51 }
52
53 impl<Id> Default for AccessLevels<Id> {
54     fn default() -> Self {
55         AccessLevels { map: Default::default() }
56     }
57 }
58
59 impl<'a> HashStable<StableHashingContext<'a>> for AccessLevels {
60     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
61         hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
62             let AccessLevels { ref map } = *self;
63             map.hash_stable(hcx, hasher);
64         });
65     }
66 }