rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Project-scoped cache validity. Stable declaration IDs are never cache keys.
use super::*;
use crate::{ProjectSemanticSnapshot, exports::ExportTable};
use std::{collections::HashSet, sync::Arc};

#[derive(Clone, Debug, PartialEq, Eq)]
struct CacheKey {
    host: String,
    sources: Vec<(SourceId, Option<u64>)>,
    dependencies: Vec<(ProjectId, u64)>,
}

#[derive(Clone, Debug)]
pub(super) struct ProjectAnalysisState {
    key: CacheKey,
    generation: u64,
    result: CachedAnalysis,
}

#[derive(Clone, Debug)]
enum CachedAnalysis {
    Analysis(Arc<DocumentAnalysis>),
    Snapshot(Arc<ProjectSemanticSnapshot>),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProjectCacheError {
    UnknownProject(ProjectId),
    UnavailableDependency(ProjectId),
}

impl std::fmt::Display for ProjectCacheError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownProject(id) => write!(f, "project {id:?} is not registered"),
            Self::UnavailableDependency(id) => {
                write!(f, "dependency {id:?} requires a current semantic snapshot")
            }
        }
    }
}
impl std::error::Error for ProjectCacheError {}

impl CompilationSession {
    pub(super) fn advance_retained_source(&mut self, source: SourceId, previous: Option<u64>) {
        let generation = self.sources.generation(source);
        for state in self.project_analyses.values_mut() {
            // Only a project snapshot describes the installed syntax. A caller
            // may have supplied an arbitrary standalone analysis.
            if matches!(state.result, CachedAnalysis::Snapshot(_))
                && let Ok(slot) = state
                    .key
                    .sources
                    .binary_search_by_key(&source, |(id, _)| *id)
                && state.key.sources[slot].1 == previous
            {
                state.key.sources[slot].1 = generation;
            }
        }
    }

    pub(super) fn invalidate_projects(&mut self, mut affected: HashSet<ProjectId>) {
        loop {
            let before = affected.len();
            for (project, index) in &self.projects {
                if index
                    .dependencies()
                    .any(|dependency| affected.contains(&dependency))
                {
                    affected.insert(*project);
                }
            }
            if before == affected.len() {
                break;
            }
        }
        self.project_analyses
            .retain(|project, _| !affected.contains(project));
    }

    fn cache_key(&self, id: ProjectId, host: String) -> Option<CacheKey> {
        let index = self.projects.get(&id)?;
        let mut sources = index
            .modules()
            .filter_map(|module| module.source)
            .collect::<Vec<_>>();
        sources.extend(index.entry_source());
        if let Some(syntax) = self.project_syntax.get(&id) {
            for program in syntax
                .roots()
                .chain(syntax.modules().map(|(_, program)| program))
            {
                sources.extend(
                    program
                        .statements
                        .iter()
                        .map(|statement| statement.span().source),
                );
            }
        }
        sources.sort_unstable();
        sources.dedup();
        let sources = sources
            .into_iter()
            .map(|source| (source, self.sources.generation(source)))
            .collect();
        let dependencies = index
            .dependencies()
            .map(|dependency| {
                (
                    dependency,
                    self.project_analyses
                        .get(&dependency)
                        .map_or(0, |state| state.generation),
                )
            })
            .collect();
        Some(CacheKey {
            host,
            sources,
            dependencies,
        })
    }

    fn current_state(
        &self,
        id: ProjectId,
        host: &rils_host::HostContract,
    ) -> Option<&ProjectAnalysisState> {
        let state = self.project_analyses.get(&id)?;
        (state.key == self.cache_key(id, host.contract_hash())?).then_some(state)
    }

    /// A read-only query never builds or replaces a snapshot.
    pub fn project_snapshot(
        &self,
        id: ProjectId,
        host: &rils_host::HostContract,
    ) -> Option<&Arc<ProjectSemanticSnapshot>> {
        match &self.current_state(id, host)?.result {
            CachedAnalysis::Snapshot(snapshot) => Some(snapshot),
            CachedAnalysis::Analysis(_) => None,
        }
    }

    pub fn project_analysis(
        &self,
        id: ProjectId,
        host: &rils_host::HostContract,
    ) -> Option<&DocumentAnalysis> {
        let state = self.current_state(id, host)?;
        Some(match &state.result {
            CachedAnalysis::Analysis(analysis) => analysis,
            CachedAnalysis::Snapshot(snapshot) => snapshot.analysis(),
        })
    }

    pub fn set_project_analysis(
        &mut self,
        id: ProjectId,
        host: &rils_host::HostContract,
        analysis: DocumentAnalysis,
    ) {
        self.store_analysis(id, host, CachedAnalysis::Analysis(Arc::new(analysis)));
    }

    fn store_analysis(
        &mut self,
        id: ProjectId,
        host: &rils_host::HostContract,
        result: CachedAnalysis,
    ) {
        self.invalidate_projects(HashSet::from([id]));
        let key = self
            .cache_key(id, host.contract_hash())
            .expect("registered project");
        self.next_analysis_generation = self
            .next_analysis_generation
            .checked_add(1)
            .expect("analysis generation overflow");
        self.project_analyses.insert(
            id,
            ProjectAnalysisState {
                key,
                generation: self.next_analysis_generation,
                result,
            },
        );
    }

    /// Dependencies must be prepared first using their own host contracts.
    /// Topology/syntax mutation invalidates this project and its transitive consumers.
    pub fn analyze_project_cached(
        &mut self,
        id: ProjectId,
        host: &rils_host::HostContract,
    ) -> Result<Arc<ProjectSemanticSnapshot>, ProjectCacheError> {
        if let Some(snapshot) = self.project_snapshot(id, host) {
            return Ok(snapshot.clone());
        }
        let index = self
            .projects
            .get(&id)
            .ok_or(ProjectCacheError::UnknownProject(id))?;
        let mut inherited = ExportTable::new();
        for dependency in index.dependencies() {
            let state = self
                .project_analyses
                .get(&dependency)
                .filter(|state| {
                    self.cache_key(dependency, state.key.host.clone()).as_ref() == Some(&state.key)
                })
                .and_then(|state| match &state.result {
                    CachedAnalysis::Snapshot(snapshot) => Some(snapshot),
                    CachedAnalysis::Analysis(_) => None,
                })
                .ok_or(ProjectCacheError::UnavailableDependency(dependency))?;
            for (path, items) in state.public_exports().as_ref() {
                inherited
                    .entry(path.clone())
                    .or_default()
                    .extend(items.iter().cloned());
            }
        }
        self.prepare_project(id);
        let snapshot = Arc::new(crate::project_analysis::project_snapshot_with_host(
            &self.project_syntax[&id],
            self.projects[&id].module_graph(),
            host,
            &inherited,
            self.projects[&id].entry_source(),
            Some(self.module_analyses.entry(id).or_default()),
        ));
        self.projects
            .get_mut(&id)
            .expect("registered project")
            .replace_def_map(&snapshot.analysis().def_map);
        self.store_analysis(id, host, CachedAnalysis::Snapshot(snapshot.clone()));
        Ok(snapshot)
    }
}