rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Session-local IDs survive unambiguous declaration edits, not deletion.
use crate::{DefId, ImplId, SourceId, Span, ast::Program};
use std::{collections::HashMap, sync::Arc};
mod declarations;
use declarations::Key;

pub(crate) const PERSISTENT_ID_BIT: u32 = 1 << 31;

#[derive(Clone, Debug, Default)]
pub(crate) struct DeclarationIdentities(Arc<Snapshot>);

#[derive(Clone, Debug, Default)]
struct Snapshot {
    definitions: HashMap<Span, DefId>,
    implementations: HashMap<Span, ImplId>,
    revisions: HashMap<SourceId, u64>,
}

impl DeclarationIdentities {
    pub(crate) fn same_bindings(&self, other: &Self) -> bool {
        self.0.definitions == other.0.definitions
            && self.0.implementations == other.0.implementations
    }
    pub(crate) fn definition(&self, span: Span) -> Option<DefId> {
        self.0.definitions.get(&span).copied()
    }
    pub(crate) fn implementation(&self, span: Span) -> Option<ImplId> {
        self.0.implementations.get(&span).copied()
    }
    pub(crate) fn revisions(&self) -> &HashMap<SourceId, u64> {
        &self.0.revisions
    }
    pub(crate) fn extend(&mut self, other: Self) {
        let target = Arc::make_mut(&mut self.0);
        target
            .definitions
            .extend(other.0.definitions.iter().map(|(k, v)| (*k, *v)));
        target
            .implementations
            .extend(other.0.implementations.iter().map(|(k, v)| (*k, *v)));
        target
            .revisions
            .extend(other.0.revisions.iter().map(|(k, v)| (*k, *v)));
    }
}

#[derive(Clone, Debug, Default)]
pub(super) struct DeclarationRegistry {
    next: u32,
    active: HashMap<Key, u32>,
    current: HashMap<(Key, Span), u32>,
    revision: u64,
}

impl DeclarationRegistry {
    pub(super) fn update(&mut self, program: &Program, revision: u64) {
        let entries = declarations::collect(program);
        let mut counts = HashMap::<&Key, usize>::new();
        for entry in &entries {
            *counts.entry(&entry.key).or_default() += 1;
        }
        let mut active = HashMap::new();
        self.current.clear();
        for entry in &entries {
            let unambiguous = (1..=entry.key.0.len()).all(|length| {
                counts
                    .get(&Key(entry.key.0[..length].to_vec()))
                    .is_none_or(|count| *count == 1)
            });
            let id = unambiguous
                .then(|| self.active.get(&entry.key).copied())
                .flatten()
                .unwrap_or_else(|| {
                    self.next = self.next.checked_add(1).expect("declaration ID overflow");
                    assert!(self.next < PERSISTENT_ID_BIT, "declaration ID overflow");
                    self.next | PERSISTENT_ID_BIT
                });
            if unambiguous {
                active.insert(entry.key.clone(), id);
            }
            self.current.insert((entry.key.clone(), entry.span), id);
        }
        self.active = active;
        self.revision = revision;
    }

    pub(super) fn snapshot(&self, program: &Program) -> DeclarationIdentities {
        let mut snapshot = Snapshot::default();
        for entry in declarations::collect(program) {
            let Some(local) = self.current.get(&(entry.key, entry.span)).copied() else {
                continue;
            };
            let source = entry.span.source;
            snapshot.revisions.insert(source, self.revision);
            if entry.implementation {
                snapshot
                    .implementations
                    .insert(entry.span, ImplId { source, local });
            } else {
                // The source declaration precedes its expansions. A generated
                // method can reuse the type's name as its diagnostic anchor.
                snapshot
                    .definitions
                    .entry(entry.span)
                    .or_insert(DefId { source, local });
            }
        }
        DeclarationIdentities(Arc::new(snapshot))
    }
}