rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
use std::collections::{BTreeMap, HashMap};

use crate::parser::ParseCapabilities;
use crate::{
    DefId, DefMap, DefinitionData, FrontendError, ModuleId, SourceFile, SourceId,
    analysis::DocumentAnalysis, ast::Program,
};

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProjectId(u32);

/// A module identity qualified by its owning project in this session.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct ProjectModuleId {
    pub project: ProjectId,
    pub module: ModuleId,
}

impl ProjectId {
    pub const fn new(value: u32) -> Self {
        Self(value)
    }
}

#[derive(Clone, Debug, Default)]
pub struct CompilationSession {
    sources: SourceDatabase,
    next_project_id: u32,
    projects_by_name: HashMap<String, ProjectId>,
    projects: BTreeMap<ProjectId, ProjectSemanticIndex>,
    project_syntax: BTreeMap<ProjectId, ProjectSyntax>,
    project_analyses: BTreeMap<ProjectId, ProjectAnalysisState>,
    module_analyses: BTreeMap<ProjectId, crate::project_analysis::ModuleCache>,
    module_histories: HashMap<ProjectId, modules::ModuleHistory>,
    next_analysis_generation: u64,
}

impl CompilationSession {
    pub fn sources(&self) -> &SourceDatabase {
        &self.sources
    }

    pub fn sources_mut(&mut self) -> &mut SourceDatabase {
        self.project_analyses.clear();
        &mut self.sources
    }

    /// Update one source, invalidating its owning projects and their dependents.
    /// Unlike unrestricted source access, this preserves unrelated project analyses.
    pub fn update_source(
        &mut self,
        id: SourceId,
        name: impl Into<String>,
        text: impl Into<String>,
        capabilities: ParseCapabilities,
    ) {
        let previous = self.sources.generation(id);
        self.sources
            .set_source_with_id_and_capabilities(id, name, text, capabilities);
        if previous == self.sources.generation(id) {
            return;
        }
        self.invalidate_source_projects(id);
    }

    /// For editors that install the last successful parse as project syntax.
    /// A parse error with identical retained syntax changes the document revision,
    /// but leaves the installed declarations, tokens for trait defaults and all
    /// dependent project inputs intact. The caller must show the returned error
    /// in place of this source's old document view.
    pub fn update_editor_source(
        &mut self,
        id: SourceId,
        name: String,
        text: String,
        capabilities: ParseCapabilities,
    ) -> Option<FrontendError> {
        let previous = self.sources.generation(id);
        self.sources
            .set_source_with_id_and_capabilities(id, name, text, capabilities);
        if let Some(error) = self.sources.retained_syntax_error(id) {
            self.advance_retained_source(id, previous);
            return Some(error);
        }
        if previous != self.sources.generation(id) {
            self.invalidate_source_projects(id);
        }
        None
    }

    fn invalidate_source_projects(&mut self, id: SourceId) {
        let affected = self
            .projects
            .iter()
            .filter_map(|(project, index)| {
                (index.module(id).is_some()
                    || index.entry_source() == Some(id)
                    || self.project_syntax.get(project).is_some_and(|syntax| {
                        syntax
                            .roots()
                            .chain(syntax.modules().map(|(_, program)| program))
                            .any(|program| {
                                program
                                    .statements
                                    .iter()
                                    .any(|statement| statement.span().source == id)
                            })
                    }))
                .then_some(*project)
            })
            .collect::<std::collections::HashSet<_>>();
        self.invalidate_projects(affected);
    }

    pub fn register_project(&mut self, name: impl Into<String>) -> ProjectId {
        let name = name.into();
        if let Some(id) = self.projects_by_name.get(&name) {
            self.projects.entry(*id).or_default();
            self.project_syntax.entry(*id).or_default();
            return *id;
        }
        self.next_project_id = self
            .next_project_id
            .checked_add(1)
            .expect("project ID overflow");
        let id = ProjectId::new(self.next_project_id);
        self.projects_by_name.insert(name, id);
        self.projects.insert(id, ProjectSemanticIndex::default());
        self.project_syntax.insert(id, ProjectSyntax::default());
        id
    }

    pub fn project_id(&self, name: &str) -> Option<ProjectId> {
        self.projects_by_name
            .get(name)
            .copied()
            .filter(|id| self.projects.contains_key(id))
    }

    pub fn project(&self, id: ProjectId) -> Option<&ProjectSemanticIndex> {
        self.projects.get(&id)
    }

    pub fn project_mut(&mut self, id: ProjectId) -> Option<&mut ProjectSemanticIndex> {
        self.invalidate_projects(std::collections::HashSet::from([id]));
        if let Some(syntax) = self.project_syntax.get_mut(&id) {
            syntax.defaults_prepared = false;
        }
        self.projects.get_mut(&id)
    }

    /// Replace a discovered topology and return old-to-session module IDs so
    /// callers can insert the corresponding syntax under the reconciled IDs.
    pub fn replace_project(
        &mut self,
        id: ProjectId,
        mut semantics: ProjectSemanticIndex,
    ) -> HashMap<ModuleId, ModuleId> {
        self.invalidate_projects(std::collections::HashSet::from([id]));
        let slot = self
            .projects
            .get_mut(&id)
            .expect("project must be registered before replacing its semantics");
        let history = self.module_histories.entry(id).or_default();
        // Initial discovery can register modules directly through project_mut.
        // An empty placeholder after clear_projects must not erase that history.
        if slot.modules().len() != 0 {
            history.remember(slot.module_graph());
        }
        let mapping = semantics.reconcile_modules(history);
        *slot = semantics;
        if let Some(syntax) = self.project_syntax.get_mut(&id) {
            syntax.defaults_prepared = false;
        }
        mapping
    }

    pub fn project_syntax(&self, id: ProjectId) -> Option<&ProjectSyntax> {
        self.project_syntax.get(&id)
    }

    pub fn project_syntax_mut(&mut self, id: ProjectId) -> Option<&mut ProjectSyntax> {
        self.invalidate_projects(std::collections::HashSet::from([id]));
        self.project_syntax.get_mut(&id)
    }

    /// Resolve copied trait defaults after all syntax units have been registered.
    pub fn prepare_project(&mut self, id: ProjectId) {
        let Some(syntax) = self.project_syntax.get_mut(&id) else {
            return;
        };
        if syntax.defaults_prepared {
            return;
        }
        let Some(project) = self.projects.get(&id) else {
            return;
        };
        crate::trait_defaults::expand_project(syntax, project.module_graph(), &self.sources);
        syntax.identities = DeclarationIdentities::default();
        for program in syntax.roots.iter().chain(syntax.modules.values()) {
            syntax
                .identities
                .extend(self.sources.declaration_identities(program));
        }
        syntax.defaults_prepared = true;
        self.invalidate_projects(std::collections::HashSet::from([id]));
    }

    pub fn clear_projects(&mut self) {
        // Retain the name-to-ID interner across rebuilds. Only live project
        // state and cached analyses are invalidated.
        for (id, project) in &self.projects {
            if project.modules().len() != 0 {
                self.module_histories
                    .entry(*id)
                    .or_default()
                    .remember(project.module_graph());
            }
        }
        self.projects.clear();
        self.project_syntax.clear();
        self.project_analyses.clear();
        self.module_analyses.clear();
    }

    pub fn projects(&self) -> impl Iterator<Item = &ProjectSemanticIndex> {
        self.projects.values()
    }

    pub fn resolve_module(
        &self,
        project: ProjectId,
        source: SourceId,
        path: &str,
    ) -> Option<ProjectModuleId> {
        let module = self.project(project)?.resolve(source, path)?;
        Some(ProjectModuleId {
            project,
            module: module.id,
        })
    }

    pub fn module(&self, id: ProjectModuleId) -> Option<&ModuleData> {
        self.project(id.project)?.module_graph().module(id.module)
    }
}

/// Parsed syntax units belonging to one project.
///
/// Module programs retain their file and module identities. The inline-module
/// compatibility view exists only for the reference AST interpreter while it
/// migrates to project semantic identities.
#[derive(Clone, Debug, Default)]
pub struct ProjectSyntax {
    pub(crate) identities: DeclarationIdentities,
    pub(crate) scripts: BTreeMap<String, String>,
    pub(crate) file_diagnostics: Vec<crate::analysis::AnalysisDiagnostic>,
    defaults_prepared: bool,
    roots: Vec<Program>,
    modules: BTreeMap<ModuleId, Program>,
}

impl ProjectSyntax {
    pub fn insert_script_file(
        &mut self,
        module: ModuleId,
        path: &str,
        file: String,
        source: SourceId,
        mut program: Program,
    ) {
        self.mark_script(path, file);
        if let Err(error) = crate::source_file::prepare_entry(&mut program, source, false) {
            self.file_diagnostics.push(error);
        }
        self.insert_module(module, program);
    }

    pub fn mark_script(&mut self, module: &str, file: String) {
        self.scripts.insert(module.to_owned(), file);
    }

    pub fn push_root(&mut self, program: Program) {
        self.defaults_prepared = false;
        self.roots.push(program);
    }

    pub fn insert_module(&mut self, module: ModuleId, program: Program) {
        self.defaults_prepared = false;
        self.modules.insert(module, program);
    }

    pub fn roots(&self) -> impl ExactSizeIterator<Item = &Program> {
        self.roots.iter()
    }

    pub fn roots_mut(&mut self) -> impl ExactSizeIterator<Item = &mut Program> {
        self.defaults_prepared = false;
        self.roots.iter_mut()
    }

    pub fn module(&self, module: ModuleId) -> Option<&Program> {
        self.modules.get(&module)
    }

    pub fn modules(&self) -> impl ExactSizeIterator<Item = (ModuleId, &Program)> {
        self.modules.iter().map(|(id, program)| (*id, program))
    }

    pub fn modules_mut(&mut self) -> impl ExactSizeIterator<Item = (ModuleId, &mut Program)> {
        self.defaults_prepared = false;
        self.modules.iter_mut().map(|(id, program)| (*id, program))
    }

    pub fn root_program(&self) -> Program {
        let mut program = Program {
            language_declaration_spans: Vec::new(),
            statements: Vec::new(),
            type_references: Vec::new(),
            macros: Vec::new(),
            generated_sources: Vec::new(),
        };
        for root in &self.roots {
            program
                .language_declaration_spans
                .extend(root.language_declaration_spans.clone());
            program.statements.extend(root.statements.clone());
            program.type_references.extend(root.type_references.clone());
            program.macros.extend(root.macros.clone());
            program
                .generated_sources
                .extend(root.generated_sources.clone());
        }
        program
    }
}

mod cache;
pub(crate) mod identities;
use cache::ProjectAnalysisState;
pub use cache::ProjectCacheError;
mod modules;
mod sources;
pub(crate) use identities::DeclarationIdentities;
pub use modules::{ModuleData, ModuleGraph, ProjectSemanticIndex};
pub use sources::SourceDatabase;

#[cfg(test)]
#[path = "../tests/unit/database.rs"]
mod tests;