lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
use std::{
    collections::HashMap,
    fmt::Debug,
    sync::{Arc, Mutex, MutexGuard},
};

/// Identifier of a string interned in one parsed file.
///
/// IDs are dense and local to a single [`ParsingData`]. They are not stable
/// across reparses and must not be resolved against another file's table.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StringId(pub u32);

#[derive(Debug, Clone)]
pub(crate) struct ParsingState {
    data: Arc<Mutex<ParsingData>>,
}

/// String interner retained alongside a parsed AST.
///
/// `string_ids` and `strings` are inverse views of the same dense table. Prefer
/// [`ParsingData::get`] for read-only resolution. The fields remain public for
/// the experimental compiler API and may become private before release.
#[derive(Debug, Clone)]
pub struct ParsingData {
    /// Reverse lookup from interned text to its file-local identifier.
    pub string_ids: HashMap<String, StringId>,
    /// Interned text indexed by [`StringId::0`].
    pub strings: Vec<String>,
}

impl ParsingData {
    /// Resolves a file-local string identifier.
    pub fn get(&self, id: StringId) -> Option<&str> {
        self.strings.get(id.0 as usize).map(String::as_str)
    }

    /// Returns the number of interned strings.
    pub fn len(&self) -> usize {
        self.strings.len()
    }

    /// Returns whether the interner contains no strings.
    pub fn is_empty(&self) -> bool {
        self.strings.is_empty()
    }

    pub(crate) fn next_string_id(&self) -> StringId {
        StringId(self.strings.len() as u32)
    }

    pub(crate) fn check_state(&self) -> Result<(), ()> {
        match self.string_ids.len() == self.strings.len() {
            true => {
                for (key, id) in &self.string_ids {
                    match self.strings.get(id.0 as usize) {
                        None => return Err(()),
                        Some(string) => {
                            if string.as_str() != key.as_str() {
                                return Err(());
                            }
                        }
                    }
                }

                Ok(())
            }
            false => Err(()),
        }
    }

    pub(crate) fn fix(&mut self) {
        self.string_ids = HashMap::with_capacity(self.strings.len());

        for (idx, string) in self.strings.iter().enumerate() {
            self.string_ids.insert(string.clone(), StringId(idx as u32));
        }
    }
}

impl ParsingState {
    pub(crate) fn new() -> Self {
        Self {
            data: Arc::new(Mutex::new(ParsingData {
                string_ids: HashMap::new(),
                strings: Vec::new(),
            })),
        }
    }

    fn lock_data(&self) -> MutexGuard<'_, ParsingData> {
        match self.data.lock() {
            Ok(mg) => mg,
            Err(pe) => {
                eprintln!("ParsingState data is poisoned");
                let mut mg = pe.into_inner();
                match mg.check_state() {
                    Err(()) => mg.fix(),
                    Ok(()) => {}
                }
                mg
            }
        }
    }

    pub(crate) fn get_string_id(&self, string: &str) -> StringId {
        let mut data = self.lock_data();
        match data.string_ids.get(string).cloned() {
            Some(id) => id,
            None => {
                let id = data.next_string_id();
                let string = string.to_string();
                data.strings.push(string.clone());
                data.string_ids.insert(string, id);
                id
            }
        }
    }

    pub(crate) fn try_terminate(self) -> Result<ParsingData, Self> {
        match Arc::try_unwrap(self.data) {
            Ok(mutex) => match mutex.into_inner() {
                Ok(data) => Ok(data),
                Err(pe) => {
                    eprintln!("ParsingData is poisoned");
                    let mut data = pe.into_inner();
                    match data.check_state() {
                        Err(()) => data.fix(),
                        Ok(()) => {}
                    }
                    Ok(data)
                }
            },
            Err(data) => Err(Self { data }),
        }
    }
}