rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Resolve source visibility once against its declaring module and package.
use crate::SourceId;
use crate::ast::{Visibility, VisibilityScope};
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

#[derive(Clone, Debug, Default)]
pub struct PackageScopes {
    pub(crate) sources: Arc<HashMap<SourceId, String>>,
    dependencies: Arc<HashSet<String>>,
}

impl PackageScopes {
    pub(crate) fn for_graph(graph: &crate::ModuleGraph) -> Self {
        Self {
            dependencies: Arc::new(graph.source_packages.values().cloned().collect()),
            sources: graph.source_packages.clone(),
        }
    }

    pub(crate) fn scope(
        &self,
        visibility: &Visibility,
        module: &[String],
        source: SourceId,
    ) -> Result<ExportVisibility, &'static str> {
        let package = self.sources.get(&source);
        // A dependency is mounted below its package name in the shared module graph.
        let root = usize::from(package.is_some_and(|name| module.first() == Some(name)));
        let local = &module[root..];
        let length = match visibility {
            Visibility::Public => return Ok(ExportVisibility::Public),
            Visibility::Private | Visibility::Restricted(VisibilityScope::SelfModule) => {
                local.len()
            }
            Visibility::Restricted(VisibilityScope::Crate) => 0,
            Visibility::Restricted(VisibilityScope::ParentModule) => local
                .len()
                .checked_sub(1)
                .ok_or("visibility scope goes above the package root")?,
            Visibility::Restricted(VisibilityScope::In(path)) => {
                let mut target = if path.first().is_some_and(|s| s == "crate") {
                    Vec::new()
                } else {
                    local.to_vec()
                };
                for part in path {
                    match part.as_str() {
                        "crate" | "self" => {}
                        "super" => {
                            target
                                .pop()
                                .ok_or("visibility scope goes above the package root")?;
                        }
                        _ => target.push(part.clone()),
                    }
                }
                if !local.starts_with(&target) {
                    return Err(
                        "visibility scope must name the declaring module or one of its ancestors",
                    );
                }
                target.len()
            }
        };
        if !visibility.is_explicit() && self.dependencies.is_empty() {
            return Ok(ExportVisibility::Module(module.to_vec()));
        }
        Ok(ExportVisibility::Scoped {
            path: module[..root + length].to_vec(),
            package: package.cloned(),
            dependencies: self.dependencies.clone(),
            explicit: visibility.is_explicit(),
        })
    }

    pub(crate) fn binding(
        &self,
        visibility: &Visibility,
        module: &[String],
        source: SourceId,
    ) -> ExportVisibility {
        self.scope(visibility, module, source)
            .unwrap_or(ExportVisibility::Invalid)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExportVisibility {
    Public,
    Module(Vec<String>),
    Scoped {
        path: Vec<String>,
        package: Option<String>,
        dependencies: Arc<HashSet<String>>,
        explicit: bool,
    },
    Invalid,
}

impl ExportVisibility {
    pub fn from_declaration(visibility: Visibility, module: &[String]) -> Self {
        PackageScopes::default().binding(&visibility, module, SourceId::UNKNOWN)
    }

    fn boundary(&self) -> Option<(&[String], Option<&String>)> {
        match self {
            Self::Module(path) => Some((path, None)),
            Self::Scoped { path, package, .. } => Some((path, package.as_ref())),
            _ => None,
        }
    }

    pub(crate) fn contains_module(&self, module: &[String]) -> bool {
        match self {
            Self::Public => true,
            Self::Module(path) | Self::Scoped { path, .. } => module.starts_with(path),
            Self::Invalid => false,
        }
    }

    pub fn visible_from(&self, module: &[String]) -> bool {
        match self {
            Self::Public => true,
            Self::Module(path) => module.starts_with(path),
            Self::Scoped {
                path,
                package,
                dependencies,
                ..
            } => {
                module.starts_with(path)
                    && module.first().filter(|name| dependencies.contains(*name))
                        == package.as_ref()
            }
            Self::Invalid => false,
        }
    }

    pub fn glob_visible_from(&self, module: &[String]) -> bool {
        matches!(self, Self::Public | Self::Scoped { explicit: true, .. })
            && self.visible_from(module)
    }

    pub(crate) fn permits(&self, exported: &Self) -> bool {
        matches!(self, Self::Public)
            || self.boundary().zip(exported.boundary()).is_some_and(
                |((path, package), (other, other_package))| {
                    package == other_package && other.starts_with(path)
                },
            )
    }
}