rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
use crate::exports::{collect_package_exports, resolve_package_reexports};
use std::collections::{HashMap, HashSet};
mod module_cache;
mod snapshot;
pub(crate) use module_cache::ModuleCache;
use module_cache::Pass;
pub use snapshot::ProjectSemanticSnapshot;

use crate::{
    ModuleGraph, ProjectSyntax, SourceId,
    analysis::{
        DocumentAnalysis, ExternalModuleExport,
        analyze_program_in_module_with_external_exports_and_host_types,
    },
    types::FunctionSignature,
};

struct ProjectHost<'a> {
    functions: &'a HashMap<String, FunctionSignature>,
    types: &'a HashSet<String>,
    contract: Option<&'a rils_host::HostContract>,
}

pub fn analyze_project_with_host_declarations(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host_functions: &HashMap<String, FunctionSignature>,
    host_types: &HashSet<String>,
) -> DocumentAnalysis {
    analyze_project_with_host_declarations_and_contract(
        syntax,
        modules,
        host_functions,
        host_types,
        None,
    )
}

pub(crate) fn analyze_project_with_host_declarations_and_contract(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host_functions: &HashMap<String, FunctionSignature>,
    host_types: &HashSet<String>,
    host_contract: Option<&rils_host::HostContract>,
) -> DocumentAnalysis {
    analyze_project_snapshot(
        syntax,
        modules,
        ProjectHost {
            functions: host_functions,
            types: host_types,
            contract: host_contract,
        },
        &HashMap::new(),
        None,
        None,
    )
    .analysis
}

fn analyze_project_snapshot(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host: ProjectHost<'_>,
    inherited_exports: &HashMap<String, Vec<ExternalModuleExport>>,
    entry_source: Option<SourceId>,
    mut cache: Option<&mut ModuleCache>,
) -> ProjectSemanticSnapshot {
    let ProjectHost {
        functions: host_functions,
        types: host_types,
        contract: host_contract,
    } = host;
    let root = syntax.root_program();
    let mut units =
        Vec::with_capacity(syntax.modules().len() + usize::from(!root.statements.is_empty()));
    if syntax.roots().len() != 0 {
        units.push((entry_source.unwrap_or(SourceId::UNKNOWN), Vec::new(), root));
    }
    units.extend(syntax.modules().filter_map(|(id, program)| {
        let module = modules.module(id)?;
        Some((
            module.source.unwrap_or(SourceId::UNKNOWN),
            module_path_segments(&module.path),
            program.clone(),
        ))
    }));
    if let Some(cache) = cache.as_deref_mut() {
        cache.prepare(
            &units,
            syntax,
            modules,
            host_contract
                .expect("session host contract")
                .contract_hash(),
        );
    }

    let mut declaration_types = crate::semantic::DeclarationTypeResolver::from_project_programs(
        units
            .iter()
            .map(|(_, path, program)| (path.as_slice(), program)),
        modules,
    );
    declaration_types.identities = syntax.identities.clone();
    if let Some(host) = host_contract {
        declaration_types.extend_host_contract(host);
    }

    if !syntax.scripts.is_empty() {
        declaration_types.file_modules = std::sync::Arc::new(crate::source_file::FileModules::new(
            modules,
            &syntax.scripts,
        ));
    }
    let mut exports = inherited_exports.clone();
    for (_, path, program) in &units {
        collect_package_exports(
            program,
            path,
            None,
            &mut exports,
            &declaration_types.packages,
        );
    }
    crate::exports::extend_external_declarations(&mut exports, host_functions, host_types);
    resolve_package_reexports(
        &mut exports,
        units
            .iter()
            .map(|(_, path, program)| (path.as_slice(), program)),
        &declaration_types.packages,
    );

    let analyze_unit = |(source, path, program): &module_cache::Unit, exports: &_| {
        analyze_program_in_module_with_external_exports_and_host_types(
            program,
            *source,
            host_functions,
            host_types,
            exports,
            path,
            crate::analysis::ModuleAnalysisContext {
                host_contract,
                declaration_types: Some(&declaration_types),
            },
        )
    };
    let mut first_pass = cache
        .as_deref_mut()
        .map(|cache| cache.first.for_exports(&exports));
    let mut resolved_exports = inherited_exports.clone();
    for (index, unit @ (_, path, program)) in units.iter().enumerate() {
        let analysis = Pass::analyze(first_pass.as_deref_mut(), index, || {
            analyze_unit(unit, &exports).into_export_context()
        });
        collect_package_exports(
            program,
            path,
            Some(&analysis),
            &mut resolved_exports,
            &declaration_types.packages,
        );
    }

    crate::exports::extend_external_declarations(&mut resolved_exports, host_functions, host_types);
    let mut result = DocumentAnalysis::default();
    result
        .diagnostics
        .extend_from_slice(&syntax.file_diagnostics);
    result.diagnostics.extend(resolve_package_reexports(
        &mut resolved_exports,
        units
            .iter()
            .map(|(_, path, program)| (path.as_slice(), program)),
        &declaration_types.packages,
    ));
    let mut documents = HashMap::new();
    let mut second_pass = cache
        .as_deref_mut()
        .map(|cache| cache.second.for_exports(&resolved_exports));
    for (index, unit @ (source, _, program)) in units.iter().enumerate() {
        let analysis = Pass::analyze(second_pass.as_deref_mut(), index, || {
            analyze_unit(unit, &resolved_exports)
        });
        for source in program
            .statements
            .iter()
            .map(|statement| statement.span().source)
            .chain([*source])
        {
            documents
                .entry(source)
                .or_insert_with(|| analysis.document_context());
        }
        result.extend(analysis.into_owned());
    }
    // Reused units carry their old revision map. Bind the assembled result
    // to the current input revisions even when all declaration IDs survived.
    result
        .source_revisions
        .clone_from(syntax.identities.revisions());
    let resolution_units = units
        .iter()
        .map(|(source, path, program)| (*source, path.as_slice(), program))
        .collect::<Vec<_>>();
    result.def_map.link_project_symbols(&mut result.symbols);
    let definitions = result.def_map.clone();
    let pattern_errors = crate::semantic::resolve_project_calls(
        &resolution_units,
        &definitions,
        host_functions,
        &mut result.typeck_results,
        (&result.host_type_resolutions, host_contract),
        &declaration_types,
    );
    result.diagnostics.extend(pattern_errors.iter().cloned());
    result.pattern_diagnostics.extend(pattern_errors);
    let trait_units = units
        .iter()
        .map(|(_, path, program)| (path.as_slice(), program))
        .collect::<Vec<_>>();
    crate::callable_analysis::refresh(&resolution_units, &declaration_types, &mut result);
    let trait_check =
        crate::trait_check::analyze_project(&trait_units, &result.def_map, host_types);
    result
        .impl_coherence_diagnostics
        .extend(trait_check.coherence_diagnostics);
    result.diagnostics.extend(trait_check.diagnostics);
    result.verified_trait_impls = trait_check
        .verified_impls
        .into_iter()
        .filter_map(|span| result.def_map.impl_at(span))
        .collect();
    result.sort_diagnostics();
    let snapshot = ProjectSemanticSnapshot::new(
        result,
        documents,
        declaration_types,
        &units,
        host_functions,
        host_types,
        inherited_exports,
    );
    if let Some(cache) = cache {
        cache.units = units.into();
    }
    snapshot
}

pub fn analyze_project_with_host(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host: &rils_host::HostContract,
) -> DocumentAnalysis {
    let host_functions = host.signatures();
    let host_types = host
        .types()
        .map(|declaration| declaration.name.clone())
        .collect();
    analyze_project_with_host_declarations_and_contract(
        syntax,
        modules,
        &host_functions,
        &host_types,
        Some(host),
    )
}

pub fn analyze_project_with_host_and_external_exports(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host: &rils_host::HostContract,
    external_exports: &HashMap<String, Vec<ExternalModuleExport>>,
) -> DocumentAnalysis {
    project_snapshot_with_host(syntax, modules, host, external_exports, None, None).analysis
}

pub(crate) fn project_snapshot_with_host(
    syntax: &ProjectSyntax,
    modules: &ModuleGraph,
    host: &rils_host::HostContract,
    external_exports: &crate::exports::ExportTable,
    entry_source: Option<SourceId>,
    cache: Option<&mut ModuleCache>,
) -> ProjectSemanticSnapshot {
    let host_functions = host.signatures();
    let host_types = host
        .types()
        .map(|declaration| declaration.name.clone())
        .collect();
    analyze_project_snapshot(
        syntax,
        modules,
        ProjectHost {
            functions: &host_functions,
            types: &host_types,
            contract: Some(host),
        },
        external_exports,
        entry_source,
        cache,
    )
}

fn module_path_segments(path: &str) -> Vec<String> {
    path.split("::")
        .filter(|segment| !segment.is_empty())
        .map(str::to_owned)
        .collect()
}

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