hexicon-compiler 0.2.0

The Hexicon compiler: source text to a program image
Documentation
//! The libraries built into the compiler: Hexicon's system library (the
//! program's entry point, the classes every program is built on, and the
//! headers that declare the virtual machine's built-in functions and
//! classes) and Hexad. Their files are in `lib/system` and `lib/hexad`,
//! and are read from there when the compiler is built, with the
//! `built-in-libraries` feature, which is on unless turned off. (The
//! virtual machine, which compiles code while a program runs but builds
//! no games, turns it off.)
//!
//! A build looks for libraries and headers where it is told to, and then
//! here, in the folder that messages and the image call [`ROOT`]. So a
//! game builds with nothing else installed, and a build told to use other
//! files (`--library-path`, `HEXICON_LIB`, a manifest's `library-paths`) uses those.

use crate::pp::SourceFiles;

/// Where the built-in files are said to be: each library in a folder of
/// its own name there.
pub const ROOT: &str = "<hexicon>";

/// Where the built-in system library and its headers are said to be.
pub const SYSTEM: &str = "<hexicon>/system";

/// The built-in files, by their paths in [`ROOT`] (`system/hexicon.hxh`,
/// `hexad/english/english.hxn`).
pub(crate) static FILES: &[(&str, &[u8])] =
    include!(concat!(env!("OUT_DIR"), "/built_in_files.rs"));

/// A path in [`ROOT`] as the table has it: after the root, with `/`.
fn in_root(path: &str) -> Option<String> {
    let path = path.replace('\\', "/");
    path.strip_prefix(ROOT)?
        .strip_prefix('/')
        .map(str::to_owned)
}

/// A built-in file, by its path (`<hexicon>/system/hexicon.hxh`, with either
/// kind of slash).
pub fn file(path: &str) -> Option<&'static [u8]> {
    let name = in_root(path)?;
    FILES
        .iter()
        .find(|(have, _)| have.eq_ignore_ascii_case(&name))
        .map(|(_, data)| *data)
}

/// A system header built in, by its name (`hexicon.hxh`).
pub(crate) fn system_header(name: &str) -> Option<&'static [u8]> {
    file(&format!("{SYSTEM}/{name}"))
}

/// The built-in files directly in a built-in folder
/// (`<hexicon>/hexad/extensions`), by their full paths, in order.
pub fn files_in(folder: &str) -> Vec<String> {
    let Some(name) = in_root(folder) else {
        return Vec::new();
    };
    let name = name.trim_end_matches('/');
    let mut found: Vec<String> = FILES
        .iter()
        .filter_map(|(have, _)| {
            let rest = have.get(name.len()..)?.strip_prefix('/')?;
            (have.get(..name.len())?.eq_ignore_ascii_case(name) && !rest.contains('/'))
                .then(|| format!("{ROOT}/{have}"))
        })
        .collect();
    found.sort();
    found
}

/// Whether a path is in [`ROOT`].
pub(crate) fn is_built_in(path: &str) -> bool {
    path.replace('\\', "/").starts_with(ROOT)
}

/// Whether a built-in path is a folder: one that a built-in file is in.
fn is_folder(path: &str) -> bool {
    match in_root(path) {
        Some(name) => {
            let name = name.trim_end_matches('/');
            FILES.iter().any(|(have, _)| {
                have.len() > name.len()
                    && have[..name.len()].eq_ignore_ascii_case(name)
                    && have.as_bytes()[name.len()] == b'/'
            })
        }
        None => path.replace('\\', "/") == ROOT && !FILES.is_empty(),
    }
}

/// Files as a build sees them: the built-in ones in [`ROOT`], and the
/// rest as `files` has them, but for an English source (`.hxe`), which
/// is read as the Hexicon source it means.
pub(crate) struct WithBuiltIns<'f> {
    files: &'f mut dyn SourceFiles,
    /// The build's English sources, which are read together, as one
    /// story, so that each can name what the others make.
    english: Vec<String>,
    /// What each became, once they have been read.
    translated: Option<std::collections::HashMap<String, Vec<u8>>>,
}

impl<'f> WithBuiltIns<'f> {
    pub(crate) fn new(files: &'f mut dyn SourceFiles) -> Self {
        Self::for_sources(files, &[])
    }

    /// Files for a build of these sources.
    pub(crate) fn for_sources(files: &'f mut dyn SourceFiles, sources: &[&str]) -> Self {
        Self {
            files,
            english: sources
                .iter()
                .filter(|name| crate::english::is_english(name))
                .map(|name| (*name).to_owned())
                .collect(),
            translated: None,
        }
    }

    /// An English source, as the Hexicon it means: read with the build's
    /// others, or alone if it is not one of them.
    fn english(&mut self, name: &str) -> Option<Vec<u8>> {
        if let Some(have) = self.translated.as_ref().and_then(|t| t.get(name)) {
            return Some(have.clone());
        }
        let names: Vec<String> = if self.english.iter().any(|n| n == name) {
            self.english.clone()
        } else {
            vec![name.to_owned()]
        };
        let mut texts = Vec::new();
        for n in &names {
            match self.files.read(n) {
                Some(bytes) => texts.push(String::from_utf8_lossy(&bytes).into_owned()),
                None if n == name => return None,
                None => texts.push(String::new()),
            }
        }
        let sources: Vec<(&str, &str)> = names
            .iter()
            .zip(&texts)
            .map(|(n, text)| (n.as_str(), text.as_str()))
            .collect();
        let shown: Vec<&str> = names.iter().map(String::as_str).collect();
        let translated = self.translated.get_or_insert_with(Default::default);
        for (i, translation) in crate::english::translate_all(&sources)
            .into_iter()
            .enumerate()
        {
            translated.insert(names[i].clone(), translation.source(&shown, i).into_bytes());
        }
        translated.get(name).cloned()
    }
}

impl SourceFiles for WithBuiltIns<'_> {
    fn read(&mut self, name: &str) -> Option<Vec<u8>> {
        if is_built_in(name) {
            return file(name).map(<[u8]>::to_vec);
        }
        if crate::english::is_english(name) {
            return self.english(name);
        }
        self.files.read(name)
    }

    fn exists(&mut self, name: &str) -> bool {
        if is_built_in(name) {
            return file(name).is_some() || is_folder(name);
        }
        self.files.exists(name)
    }

    fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
        self.files.decode(charset, bytes)
    }
}