use serde::{Deserialize, Serialize};
use crate::symbol::SymbolKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Semantics {
pub import_scopes_names: bool,
pub addressable: &'static [SymbolKind],
pub visibility: &'static [VisibilityRule],
pub default_visibility: ReachKind,
}
impl Semantics {
pub fn is_addressable(&self, kind: SymbolKind) -> bool {
self.addressable.contains(&kind)
}
pub fn reach_kind(&self, modifier: Option<&str>) -> ReachKind {
let Some(text) = modifier else {
return self.default_visibility;
};
self.visibility
.iter()
.find(|rule| rule.matches(text))
.map_or(self.default_visibility, |rule| rule.reach)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VisibilityRule {
pub text: &'static str,
pub reach: ReachKind,
pub prefix: bool,
}
impl VisibilityRule {
pub const fn exact(text: &'static str, reach: ReachKind) -> Self {
Self {
text,
reach,
prefix: false,
}
}
pub const fn prefix(text: &'static str, reach: ReachKind) -> Self {
Self {
text,
reach,
prefix: true,
}
}
fn matches(&self, modifier: &str) -> bool {
if self.prefix {
modifier.starts_with(self.text)
} else {
modifier == self.text
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum ReachKind {
Declaring,
Parent,
Package,
Everyone,
Path,
}
#[cfg(test)]
mod tests {
use super::*;
const RUST: Semantics = Semantics {
import_scopes_names: false,
addressable: &[SymbolKind::Struct],
visibility: &[
VisibilityRule::exact("pub", ReachKind::Everyone),
VisibilityRule::exact("pub(crate)", ReachKind::Package),
VisibilityRule::exact("pub(super)", ReachKind::Parent),
VisibilityRule::exact("pub(self)", ReachKind::Declaring),
VisibilityRule::prefix("pub(in", ReachKind::Path),
],
default_visibility: ReachKind::Declaring,
};
#[test]
fn modifiers_map_to_reach_kinds() {
assert_eq!(RUST.reach_kind(None), ReachKind::Declaring);
assert_eq!(RUST.reach_kind(Some("pub")), ReachKind::Everyone);
assert_eq!(RUST.reach_kind(Some("pub(super)")), ReachKind::Parent);
assert_eq!(RUST.reach_kind(Some("pub(in crate::a)")), ReachKind::Path);
assert_eq!(
RUST.reach_kind(Some("pub(weird)")),
ReachKind::Declaring,
"unknown: narrowest"
);
}
}