1use serde::{Deserialize, Serialize};
9
10use crate::symbol::SymbolKind;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Semantics {
14 pub import_scopes_names: bool,
19 pub addressable: &'static [SymbolKind],
23 pub visibility: &'static [VisibilityRule],
25 pub default_visibility: ReachKind,
27}
28
29impl Semantics {
30 pub fn is_addressable(&self, kind: SymbolKind) -> bool {
31 self.addressable.contains(&kind)
32 }
33
34 pub fn reach_kind(&self, modifier: Option<&str>) -> ReachKind {
36 let Some(text) = modifier else {
37 return self.default_visibility;
38 };
39 self.visibility
40 .iter()
41 .find(|rule| rule.matches(text))
42 .map_or(self.default_visibility, |rule| rule.reach)
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct VisibilityRule {
49 pub text: &'static str,
50 pub reach: ReachKind,
51 pub prefix: bool,
53}
54
55impl VisibilityRule {
56 pub const fn exact(text: &'static str, reach: ReachKind) -> Self {
57 Self {
58 text,
59 reach,
60 prefix: false,
61 }
62 }
63
64 pub const fn prefix(text: &'static str, reach: ReachKind) -> Self {
65 Self {
66 text,
67 reach,
68 prefix: true,
69 }
70 }
71
72 fn matches(&self, modifier: &str) -> bool {
73 if self.prefix {
74 modifier.starts_with(self.text)
75 } else {
76 modifier == self.text
77 }
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum ReachKind {
85 Declaring,
87 Parent,
89 Package,
91 Everyone,
93 Path,
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 const RUST: Semantics = Semantics {
102 import_scopes_names: false,
103 addressable: &[SymbolKind::Struct],
104 visibility: &[
105 VisibilityRule::exact("pub", ReachKind::Everyone),
106 VisibilityRule::exact("pub(crate)", ReachKind::Package),
107 VisibilityRule::exact("pub(super)", ReachKind::Parent),
108 VisibilityRule::exact("pub(self)", ReachKind::Declaring),
109 VisibilityRule::prefix("pub(in", ReachKind::Path),
110 ],
111 default_visibility: ReachKind::Declaring,
112 };
113
114 #[test]
115 fn modifiers_map_to_reach_kinds() {
116 assert_eq!(RUST.reach_kind(None), ReachKind::Declaring);
117 assert_eq!(RUST.reach_kind(Some("pub")), ReachKind::Everyone);
118 assert_eq!(RUST.reach_kind(Some("pub(super)")), ReachKind::Parent);
119 assert_eq!(RUST.reach_kind(Some("pub(in crate::a)")), ReachKind::Path);
120 assert_eq!(
121 RUST.reach_kind(Some("pub(weird)")),
122 ReachKind::Declaring,
123 "unknown: narrowest"
124 );
125 }
126}