rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Parsed source revisions and their retained declaration identities.
use super::*;

#[derive(Clone, Debug)]
struct SourceEntry {
    identities: super::identities::DeclarationRegistry,
    file: SourceFile,
    text: String,
    initialized: bool,
    revision: u64,
    generation: u64,
    parsed: Result<Program, FrontendError>,
    capabilities: ParseCapabilities,
    /// The last syntax tree that parsed successfully before the current edit.
    ///
    /// Editor clients frequently produce temporarily invalid source while a
    /// user is typing. Keeping this snapshot separate from `parsed` lets
    /// tooling continue to answer semantic requests without making the
    /// compiler accept the invalid revision.
    last_valid: Option<Program>,
    /// Tokens from the same revision as the current or last valid syntax.
    syntax_tokens: Vec<crate::token::Token>,
}

/// In-memory source storage shared by compilers and editor tooling.
///
/// A source keeps its identity when its text changes. Parsing happens once per
/// revision and later consumers clone the cached syntax tree instead of
/// invoking the lexer and parser independently.
#[derive(Clone, Debug, Default)]
pub struct SourceDatabase {
    next_id: u32,
    by_name: HashMap<String, SourceId>,
    sources: BTreeMap<SourceId, SourceEntry>,
}

impl SourceDatabase {
    pub(crate) fn declaration_identities(&self, program: &Program) -> DeclarationIdentities {
        let sources = program
            .statements
            .iter()
            .map(|statement| statement.span().source)
            .collect::<std::collections::HashSet<_>>();
        let mut result = DeclarationIdentities::default();
        for source in sources {
            if let Some(entry) = self.sources.get(&source) {
                result.extend(entry.identities.snapshot(program));
            }
        }
        result
    }

    pub fn reserve(&mut self, name: impl Into<String>) -> SourceId {
        let name = name.into();
        if let Some(id) = self.by_name.get(&name) {
            return *id;
        }
        let id = self.allocate_id();
        self.insert(id, name, String::new(), false, ParseCapabilities::USER);
        id
    }

    pub fn set_source(&mut self, name: impl Into<String>, text: impl Into<String>) -> SourceId {
        self.set_source_with_capabilities(name, text, ParseCapabilities::USER)
    }

    pub fn set_source_with_capabilities(
        &mut self,
        name: impl Into<String>,
        text: impl Into<String>,
        capabilities: ParseCapabilities,
    ) -> SourceId {
        let name = name.into();
        let text = text.into();
        if let Some(id) = self.by_name.get(&name).copied() {
            self.update(id, text, capabilities);
            return id;
        }
        let id = self.allocate_id();
        self.insert(id, name, text, true, capabilities);
        id
    }

    pub fn set_source_with_id(
        &mut self,
        id: SourceId,
        name: impl Into<String>,
        text: impl Into<String>,
    ) {
        self.set_source_with_id_and_capabilities(id, name, text, ParseCapabilities::USER);
    }

    pub fn set_source_with_id_and_capabilities(
        &mut self,
        id: SourceId,
        name: impl Into<String>,
        text: impl Into<String>,
        capabilities: ParseCapabilities,
    ) {
        assert!(id != SourceId::UNKNOWN, "source database IDs must be known");
        let name = name.into();
        let text = text.into();
        self.next_id = self.next_id.max(id.0);
        if let Some(existing) = self.sources.get(&id) {
            assert_eq!(
                existing.file.name, name,
                "source ID reused for another name"
            );
            self.update(id, text, capabilities);
            return;
        }
        assert!(
            !self.by_name.contains_key(&name),
            "source name reused with another ID"
        );
        self.insert(id, name, text, true, capabilities);
    }

    pub fn source_id(&self, name: &str) -> Option<SourceId> {
        self.by_name.get(name).copied()
    }

    pub fn source_file(&self, id: SourceId) -> Option<&SourceFile> {
        self.sources.get(&id).map(|entry| &entry.file)
    }

    pub fn source_text(&self, id: SourceId) -> Option<&str> {
        self.sources.get(&id).map(|entry| entry.text.as_str())
    }

    pub fn revision(&self, id: SourceId) -> Option<u64> {
        self.sources.get(&id).map(|entry| entry.revision)
    }

    /// Changes for every parsed input, including initial text and parser capabilities.
    pub(super) fn generation(&self, id: SourceId) -> Option<u64> {
        self.sources.get(&id).map(|entry| entry.generation)
    }

    pub fn parse_capabilities(&self, id: SourceId) -> Option<ParseCapabilities> {
        self.sources.get(&id).map(|entry| entry.capabilities)
    }

    pub fn parse(&self, id: SourceId) -> Result<Program, FrontendError> {
        self.try_parse(id)
            .expect("source must be registered before parsing")
    }

    pub fn try_parse(&self, id: SourceId) -> Option<Result<Program, FrontendError>> {
        self.sources.get(&id).map(|entry| entry.parsed.clone())
    }

    /// Borrow the cached parse, including a current-revision error, without
    /// cloning syntax when a caller only needs to validate or inspect it.
    pub fn parse_result(&self, id: SourceId) -> Option<Result<&Program, &FrontendError>> {
        self.sources.get(&id).map(|entry| entry.parsed.as_ref())
    }

    /// Returns the most recent successfully parsed revision when the current
    /// source revision is invalid. This is intended for editor tooling only;
    /// compilers must continue to use [`Self::parse`] and report the current
    /// syntax error.
    pub fn last_valid_parse(&self, id: SourceId) -> Option<Program> {
        self.sources
            .get(&id)
            .filter(|entry| entry.parsed.is_err())
            .and_then(|entry| entry.last_valid.clone())
    }

    pub(super) fn retained_syntax_error(&self, id: SourceId) -> Option<FrontendError> {
        let entry = self.sources.get(&id)?;
        entry.last_valid.as_ref()?;
        entry.parsed.as_ref().err().cloned()
    }

    pub fn source_files(&self) -> Vec<SourceFile> {
        self.sources
            .values()
            .map(|entry| entry.file.clone())
            .collect()
    }

    pub(crate) fn syntax_tokens(&self) -> impl Iterator<Item = &crate::token::Token> {
        self.sources.values().flat_map(|entry| &entry.syntax_tokens)
    }

    fn allocate_id(&mut self) -> SourceId {
        self.next_id = self.next_id.checked_add(1).expect("source ID overflow");
        SourceId::new(self.next_id)
    }

    fn insert(
        &mut self,
        id: SourceId,
        name: String,
        text: String,
        initialized: bool,
        capabilities: ParseCapabilities,
    ) {
        let (parsed, syntax_tokens) = parse_source(&text, id, capabilities);
        let mut identities = super::identities::DeclarationRegistry::default();
        if let Ok(program) = &parsed {
            identities.update(program, 0);
        }
        self.by_name.insert(name.clone(), id);
        self.sources.insert(
            id,
            SourceEntry {
                identities,
                file: SourceFile { id, name },
                text,
                initialized,
                revision: 0,
                generation: 0,
                parsed,
                capabilities,
                last_valid: None,
                syntax_tokens,
            },
        );
    }

    fn update(&mut self, id: SourceId, text: String, capabilities: ParseCapabilities) {
        let entry = self.sources.get_mut(&id).expect("registered source");
        let text_changed = entry.text != text;
        let capabilities_changed = entry.capabilities != capabilities;
        if entry.initialized && !text_changed && !capabilities_changed {
            return;
        }
        entry.generation = entry
            .generation
            .checked_add(1)
            .expect("source generation overflow");
        entry.text = text;
        if entry.initialized && text_changed {
            entry.revision = entry
                .revision
                .checked_add(1)
                .expect("source revision overflow");
        }
        entry.initialized = true;
        let (parsed, syntax_tokens) = parse_source(&entry.text, id, capabilities);
        if let Ok(program) = &parsed {
            entry.identities.update(program, entry.revision);
        }
        if parsed.is_ok() || capabilities_changed {
            entry.last_valid = None;
            entry.syntax_tokens = syntax_tokens;
        } else if let Ok(program) = &entry.parsed {
            entry.last_valid = Some(program.clone());
        } else if entry.last_valid.is_none() {
            entry.syntax_tokens = syntax_tokens;
        }
        entry.parsed = parsed;
        entry.capabilities = capabilities;
    }
}

fn parse_source(
    source: &str,
    source_id: SourceId,
    capabilities: ParseCapabilities,
) -> (Result<Program, FrontendError>, Vec<crate::token::Token>) {
    let tokens = match crate::lexer::lex_with_source_id(source, source_id) {
        Ok(tokens) => tokens,
        Err(error) => return (Err(FrontendError::Lex(error)), Vec::new()),
    };
    let parsed = crate::parser::parse_with_capabilities(
        tokens.clone(),
        crate::macros::STANDARD_NATIVE_MACROS,
        capabilities,
    )
    .map_err(FrontendError::Parse);
    (parsed, tokens)
}