rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Lexical name queries for editor completion. Uses the resolver's actual scopes.
use super::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VisibleName {
    module_data: bool,
    pub name: String,
    pub canonical_path: Option<String>,
    pub kind: SymbolKind,
    pub definition_span: Option<Span>,
    pub definition_id: Option<SymbolId>,
    pub inferred_type: Option<Type>,
    pub detail: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct LexicalScope {
    pub(super) span: Span,
    depth: usize,
    module: Vec<String>,
    names: Vec<VisibleName>,
}

impl Analyzer {
    pub(super) fn record_scope(&mut self, span: Span) {
        if !self.inside_derive {
            self.record_scope_at(span, self.scopes.len() - 1);
        }
    }

    pub(super) fn record_root_scopes(&mut self, span: Span) {
        for depth in 0..self.scopes.len() {
            self.record_scope_at(span, depth);
        }
    }

    fn record_scope_at(&mut self, span: Span, depth: usize) {
        let names = self
            .scopes
            .get(depth)
            .into_iter()
            .flatten()
            .map(|(name, definition)| {
                let export = self.module_exports.values().flatten().find(|export| {
                    (definition.span.is_some() && export.span == definition.span)
                        || (definition.external_function.is_some()
                            && export.external_function == definition.external_function)
                });
                VisibleName {
                    module_data: export.is_some_and(|e| e.kind == SymbolKind::Variable),
                    name: name.clone(),
                    canonical_path: definition.canonical_path.clone(),
                    kind: definition.kind,
                    definition_span: definition.span,
                    definition_id: definition.id,
                    inferred_type: export
                        .and_then(|export| export.inferred_type.clone())
                        .or_else(|| definition.native_trait_type()),
                    detail: export.and_then(|export| export.detail.clone()),
                }
            })
            .collect();
        self.result.lexical_scopes.push(LexicalScope {
            span,
            depth: depth + 1,
            module: self.module_path.clone(),
            names,
        });
    }
}

impl DocumentAnalysis {
    /// Module owning the innermost scope at the query site, including inline modules.
    pub fn lexical_module(&self, source: SourceId, offset: usize) -> Option<&[String]> {
        self.lexical_scopes
            .iter()
            .filter(|scope| {
                scope.span.source == source && scope.span.start <= offset && offset < scope.span.end
            })
            .max_by_key(|scope| scope.depth)
            .map(|scope| scope.module.as_slice())
    }

    /// Visible bindings, with inner scopes taking precedence and later locals excluded.
    /// Definition identities are retained through aliases and glob imports.
    pub fn visible_names(&self, source: SourceId, offset: usize) -> Vec<VisibleName> {
        let mut scopes = self
            .lexical_scopes
            .iter()
            .filter(|scope| {
                scope.span.source == source && scope.span.start <= offset && offset < scope.span.end
            })
            .collect::<Vec<_>>();
        scopes.sort_by_key(|scope| std::cmp::Reverse(scope.depth));
        let module = scopes.first().map(|scope| &scope.module);
        let mut seen = HashSet::new();
        let mut result = Vec::new();
        for scope in scopes {
            for name in &scope.names {
                if !name.module_data
                    && matches!(name.kind, SymbolKind::Variable | SymbolKind::Parameter)
                    && (Some(&scope.module) != module
                        || name
                            .definition_span
                            .is_some_and(|span| span.source == source && span.end > offset))
                {
                    continue;
                }
                if !seen.insert(&name.name) {
                    continue;
                }
                let mut name = name.clone();
                if let Some(symbol) = self.symbols.iter().find(|symbol| {
                    symbol.is_definition
                        && (name.definition_id.is_some() && symbol.symbol_id == name.definition_id
                            || name.definition_span.is_some()
                                && Some(symbol.span) == name.definition_span)
                }) {
                    name.inferred_type = symbol.inferred_type.clone().or(name.inferred_type);
                    name.detail = symbol.detail.clone().or(name.detail);
                }
                result.push(name);
            }
        }
        result.sort_by(|a, b| a.name.cmp(&b.name));
        result
    }
}