rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Shared project export collection and re-export queries.
use crate::{
    Type,
    analysis::{DocumentAnalysis, ExternalModuleExport, ExternalTypeField, SymbolKind},
    ast::{Program, Stmt},
};
use std::collections::HashMap;
mod external;
mod resolution;
mod surface;
mod types;
mod variants;
pub(crate) use types::extend_builtin_types;
mod visibility;
pub use external::extend_external_declarations;
pub(crate) use resolution::resolve_package_reexports;
pub use resolution::{
    import_declarations, module_candidates, resolve_export, resolve_module_path, resolve_reexports,
};
pub use surface::{is_public_module_path, public_exports};
pub use visibility::ExportVisibility;
pub(crate) use visibility::PackageScopes;
pub type ExportTable = HashMap<String, Vec<ExternalModuleExport>>;

pub fn join_path(parent: &str, name: &str) -> String {
    if parent.is_empty() {
        name.into()
    } else {
        format!("{parent}::{name}")
    }
}

pub fn collect_exports(
    program: &Program,
    module_path: &[String],
    analysis: Option<&DocumentAnalysis>,
    output: &mut ExportTable,
) {
    collect_package_exports(program, module_path, analysis, output, &Default::default());
}

pub(crate) fn collect_package_exports(
    program: &Program,
    module_path: &[String],
    analysis: Option<&DocumentAnalysis>,
    output: &mut HashMap<String, Vec<ExternalModuleExport>>,
    packages: &PackageScopes,
) {
    let source = program
        .statements
        .iter()
        .find_map(|statement| declaration_export(statement, "", None, packages))
        .and_then(|export| export.span.map(|span| span.source))
        .unwrap_or(crate::SourceId::UNKNOWN);
    let mut parent = String::new();
    for (index, name) in module_path.iter().enumerate() {
        let target = join_path(&parent, name);
        let siblings = output.entry(parent.clone()).or_default();
        if !siblings.iter().any(|export| export.name == *name) {
            siblings.push(ExternalModuleExport {
                canonical_path: target.clone(),
                visibility: ExportVisibility::Public,
                declaration_visibility: ExportVisibility::Public,
                name: name.clone(),
                target_module: Some(target.clone()),
                span: Some(crate::Span::in_source(
                    if index + 1 == module_path.len() {
                        source
                    } else {
                        crate::SourceId::UNKNOWN
                    },
                    0,
                    0,
                )),
                external_function: None,
                definition_id: None,
                kind: SymbolKind::Module,
                inferred_type: None,
                detail: Some(format!("module {target}")),
                module_path: parent.clone(),
                fields: Vec::new(),
            });
        }
        parent = target;
    }
    collect_package_statements(&program.statements, module_path, analysis, output, packages);
    mark_language_functions(output, program);
}

pub(crate) fn mark_language_functions(exports: &mut ExportTable, program: &Program) {
    for (module, members) in exports {
        for export in members {
            if export.kind == SymbolKind::Function
                && export.span.is_some_and(|span| {
                    program.language_declaration_spans.iter().any(|region| {
                        region.source == span.source
                            && region.start <= span.start
                            && span.end <= region.end
                    })
                })
                && let Some(declaration) =
                    rils_builtins::builtin_function(&join_path(module, &export.name))
            {
                export.external_function = Some(crate::analysis::ExternalFunction::Builtin(
                    declaration.path.into(),
                ));
            }
        }
    }
}

pub fn collect_statements(
    statements: &[Stmt],
    module_path: &[String],
    analysis: Option<&DocumentAnalysis>,
    output: &mut ExportTable,
) {
    collect_package_statements(
        statements,
        module_path,
        analysis,
        output,
        &Default::default(),
    );
}

pub(crate) fn collect_package_statements(
    statements: &[Stmt],
    module_path: &[String],
    analysis: Option<&DocumentAnalysis>,
    output: &mut HashMap<String, Vec<ExternalModuleExport>>,
    packages: &PackageScopes,
) {
    let path = module_path.join("::");
    let exports = output.entry(path.clone()).or_default();
    for statement in statements {
        if let Some(export) = declaration_export(statement, &path, analysis, packages) {
            if export.kind == SymbolKind::Module {
                // A child file may be indexed before the parent's explicit mod.
                // Its synthetic entry must not override the declared visibility.
                exports.retain(|previous| {
                    !(previous.kind == SymbolKind::Module
                        && previous.name == export.name
                        && previous.span.is_some_and(|span| span.start == span.end))
                });
            }
            exports.push(export);
        }
    }
    for statement in statements {
        if let Stmt::Enum {
            name,
            generic_parameters,
            variants,
            visibility,
            ..
        } = statement
        {
            let owner = crate::semantic::source_type_path(module_path, name);
            let arguments = generic_parameters
                .iter()
                .map(|parameter| Type::Variable(parameter.name.clone()))
                .collect::<Vec<_>>();
            let result = Type::Named {
                name: crate::semantic::source_type_path(module_path, name),
                arguments,
            };
            let members = output.entry(join_path(&path, name)).or_default();
            for variant in variants {
                let (name, span, ty) = match variant {
                    crate::ast::EnumVariant::Unit { name, span, .. } => {
                        (name, *span, Some(result.clone()))
                    }
                    crate::ast::EnumVariant::Tuple {
                        name, span, fields, ..
                    } => (
                        name,
                        *span,
                        Some(Type::function(fields.clone(), result.clone())),
                    ),
                    crate::ast::EnumVariant::Record { name, span, .. } => {
                        (name, *span, Some(result.clone()))
                    }
                };
                let span = if span.start == span.end {
                    span
                } else {
                    crate::Span::in_source(span.source, span.start, span.start + name.len())
                };
                members.push(ExternalModuleExport {
                    canonical_path: join_path(&owner, name),
                    visibility: packages.binding(visibility, module_path, span.source),
                    declaration_visibility: packages.binding(visibility, module_path, span.source),
                    name: name.clone(),
                    target_module: None,
                    span: Some(span),
                    external_function: None,
                    definition_id: analysis.and_then(|analysis| analysis.def_map.resolution(span)),
                    kind: SymbolKind::Variant,
                    inferred_type: ty,
                    detail: Some(crate::analysis::enum_variant_declaration(&owner, variant)),
                    module_path: owner.clone(),
                    fields: match variant {
                        crate::ast::EnumVariant::Record { fields, .. } => fields
                            .iter()
                            .map(|field| ExternalTypeField {
                                visibility: None,
                                name: field.name.clone(),
                                span: field.span,
                                ty: field.type_annotation.clone(),
                            })
                            .collect(),
                        _ => Vec::new(),
                    },
                });
            }
        }
        if let Stmt::Module {
            name,
            statements: Some(children),
            ..
        } = statement
        {
            let mut child_path = module_path.to_vec();
            child_path.push(name.clone());
            collect_package_statements(children, &child_path, analysis, output, packages);
        }
    }
}

fn declaration_export(
    statement: &Stmt,
    module_path: &str,
    analysis: Option<&DocumentAnalysis>,
    packages: &PackageScopes,
) -> Option<ExternalModuleExport> {
    let (name, span, kind, inferred_type, fields) = match statement {
        Stmt::Let {
            kind: crate::ast::BindingKind::Const(_) | crate::ast::BindingKind::Static(_),
            name,
            name_span,
            type_annotation,
            ..
        } => (
            name,
            *name_span,
            SymbolKind::Variable,
            type_annotation.clone(),
            Vec::new(),
        ),
        Stmt::Function {
            name,
            name_span,
            parameters,
            return_type,
            ..
        } => (
            name,
            *name_span,
            SymbolKind::Function,
            Some(Type::function(
                parameters
                    .iter()
                    .map(|parameter| parameter.type_annotation.clone().unwrap_or(Type::Unknown))
                    .collect(),
                return_type.clone().unwrap_or(Type::Unknown),
            )),
            Vec::new(),
        ),
        Stmt::Struct {
            name,
            name_span,
            fields,
            ..
        } => (
            name,
            *name_span,
            SymbolKind::Type,
            None,
            fields
                .iter()
                .map(|field| ExternalTypeField {
                    visibility: Some(field.visibility.clone()),
                    name: field.name.clone(),
                    span: field.span,
                    ty: field.type_annotation.clone(),
                })
                .collect(),
        ),
        Stmt::Enum {
            name, name_span, ..
        }
        | Stmt::TypeAlias {
            name, name_span, ..
        } => (name, *name_span, SymbolKind::Type, None, Vec::new()),
        Stmt::Trait {
            name, name_span, ..
        } => (name, *name_span, SymbolKind::Trait, None, Vec::new()),
        Stmt::Module {
            name, name_span, ..
        } => (name, *name_span, SymbolKind::Module, None, Vec::new()),
        _ => return None,
    };
    let symbol = analysis.and_then(|analysis| {
        analysis
            .symbols
            .iter()
            .find(|symbol| symbol.is_definition && symbol.span == span)
    });
    let module = module_path
        .split("::")
        .filter(|part| !part.is_empty())
        .map(str::to_owned)
        .collect::<Vec<_>>();
    let visibility = packages.binding(&statement.visibility().unwrap(), &module, span.source);
    Some(ExternalModuleExport {
        canonical_path: if matches!(kind, SymbolKind::Type | SymbolKind::Trait) {
            crate::semantic::source_type_path(&module, name)
        } else {
            join_path(module_path, name)
        },
        visibility: visibility.clone(),
        declaration_visibility: visibility,
        name: name.clone(),
        target_module: (kind == SymbolKind::Module || matches!(statement, Stmt::Enum { .. }))
            .then(|| join_path(module_path, name)),
        span: Some(span),
        external_function: None,
        definition_id: analysis.and_then(|analysis| analysis.def_map.resolution(span)),
        kind,
        inferred_type: symbol
            .and_then(|symbol| symbol.inferred_type.clone())
            .or(inferred_type),
        detail: symbol.and_then(|symbol| symbol.detail.clone()),
        module_path: module_path.to_owned(),
        fields,
    })
}