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#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
84#[serde(rename_all = "snake_case")]
85pub enum ReachKind {
86 Declaring,
88 Parent,
90 Package,
92 Everyone,
94 Path,
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 const RUST: Semantics = Semantics {
103 import_scopes_names: false,
104 addressable: &[SymbolKind::Struct],
105 visibility: &[
106 VisibilityRule::exact("pub", ReachKind::Everyone),
107 VisibilityRule::exact("pub(crate)", ReachKind::Package),
108 VisibilityRule::exact("pub(super)", ReachKind::Parent),
109 VisibilityRule::exact("pub(self)", ReachKind::Declaring),
110 VisibilityRule::prefix("pub(in", ReachKind::Path),
111 ],
112 default_visibility: ReachKind::Declaring,
113 };
114
115 #[test]
116 fn modifiers_map_to_reach_kinds() {
117 assert_eq!(RUST.reach_kind(None), ReachKind::Declaring);
118 assert_eq!(RUST.reach_kind(Some("pub")), ReachKind::Everyone);
119 assert_eq!(RUST.reach_kind(Some("pub(super)")), ReachKind::Parent);
120 assert_eq!(RUST.reach_kind(Some("pub(in crate::a)")), ReachKind::Path);
121 assert_eq!(
122 RUST.reach_kind(Some("pub(weird)")),
123 ReachKind::Declaring,
124 "unknown: narrowest"
125 );
126 }
127}