hexicon-compiler 0.2.0

The Hexicon compiler: source text to a program image
Documentation
//! A game's IFID: the identifier the Treaty of Babel gives every game,
//! the same in all its versions. A new one is a random UUID; the build
//! checks the one a game gives.

use crate::pp::{Diagnostic, Severity};

/// A new IFID: a random UUID (version 4), in capitals, as IFIDs are
/// written.
#[must_use]
pub fn new() -> String {
    use std::fmt::Write;
    use std::hash::{BuildHasher, Hasher};
    // Each `RandomState` has its own keys, seeded from the system's
    // randomness, so what each hashes is as random as they are.
    let mut bytes = [0u8; 16];
    for chunk in bytes.chunks_mut(8) {
        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
        hasher.write_u64(0);
        chunk.copy_from_slice(&hasher.finish().to_le_bytes());
    }
    // Version 4 (random), variant 1.
    bytes[6] = (bytes[6] & 0x0F) | 0x40;
    bytes[8] = (bytes[8] & 0x3F) | 0x80;
    let mut hex = String::with_capacity(32);
    for b in bytes {
        let _ = write!(hex, "{b:02X}");
    }
    format!(
        "{}-{}-{}-{}-{}",
        &hex[..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..]
    )
}

/// Whether `ifid` is one, as the Treaty of Babel has them: 8 to 63
/// characters, each a digit, a capital letter, or a hyphen.
#[must_use]
pub fn is_ifid(ifid: &str) -> bool {
    (8..=63).contains(&ifid.len())
        && ifid
            .bytes()
            .all(|b| b.is_ascii_digit() || b.is_ascii_uppercase() || b == b'-')
}

/// What to do about an IFID that is wrong, or missing.
const NOTE: &str = "`hexicon ifid` makes a new one";

/// The warnings for a game's own sources, each its name and its text as
/// Hexicon, about the IFID they give in `property`: each that is not an
/// IFID, or that none is given. A game that has used several IFIDs gives
/// them all, separated by commas.
pub(crate) fn check(sources: &[(&str, &str)], property: &str) -> Vec<Diagnostic> {
    let keys = [property.to_owned()];
    let mut out = Vec::new();
    let mut given = false;
    for (file, text) in sources {
        let places = places(file, text);
        for found in crate::tags::string_keys(text, &keys) {
            if found.of != property {
                continue;
            }
            given = true;
            let (file, line) = places
                .get(found.line as usize - 1)
                .cloned()
                .unwrap_or(((*file).to_owned(), found.line));
            for ifid in found.key.split(',').map(str::trim) {
                if is_ifid(ifid) {
                    continue;
                }
                // One in small letters is the same IFID, and is kept:
                // only how it is written is wrong.
                let capitals = ifid.to_ascii_uppercase();
                let (message, note) = if is_ifid(&capitals) {
                    (
                        format!("an IFID is written in capitals: \"{capitals}\", not \"{ifid}\""),
                        None,
                    )
                } else {
                    (
                        format!(
                            "\"{ifid}\" is not an IFID: an IFID is 8 to 63 characters, each \
                             a digit, a capital letter, or a hyphen"
                        ),
                        Some(NOTE),
                    )
                };
                // A problem in an English source is said in one line,
                // with no note under it.
                let english = crate::english::is_english(&file);
                out.push(Diagnostic {
                    file: file.clone(),
                    line,
                    severity: Severity::Warning,
                    message: match note {
                        Some(note) if english => format!("{message}; {note}"),
                        _ => message,
                    },
                    note: note.filter(|_| !english).map(str::to_owned),
                    hexicon: !english,
                    ..Default::default()
                });
            }
        }
    }
    if !given && !sources.is_empty() {
        out.push(Diagnostic {
            file: String::new(),
            line: 0,
            severity: Severity::Warning,
            message: format!(
                "the game has no IFID, the identifier that tells it from every other game: \
                 give the story one, as its {property}, and keep it in every version; \
                 {NOTE}"
            ),
            ..Default::default()
        });
    }
    out
}

/// Where each line of a source's text is from: its file and line, as
/// its `#line` directives say. An English source's text, the Hexicon it
/// means, names the lines of the English it came from.
fn places(file: &str, text: &str) -> Vec<(String, u32)> {
    let mut out = Vec::new();
    let mut file = file.to_owned();
    let mut next = 1u32;
    for line in text.lines() {
        out.push((file.clone(), next));
        next += 1;
        let Some(rest) = line.trim_start().strip_prefix("#line ") else {
            continue;
        };
        let rest = rest.trim();
        let (number, name) = rest.split_once(' ').unwrap_or((rest, ""));
        let Ok(number) = number.parse::<u32>() else {
            continue;
        };
        next = number;
        let name = name.trim();
        if let Some(name) = name
            .strip_prefix('\'')
            .and_then(|n| n.strip_suffix('\''))
            .or_else(|| name.strip_prefix('"').and_then(|n| n.strip_suffix('"')))
        {
            file = name.replace("\\\\", "\\").replace("\\'", "'");
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_new_ifid_is_a_random_uuid() {
        let ifid = new();
        assert_eq!(ifid.len(), 36);
        assert!(is_ifid(&ifid));
        assert_eq!(&ifid[14..15], "4");
        assert!(matches!(&ifid[19..20], "8" | "9" | "A" | "B"));
        assert_ne!(ifid, new());
    }

    #[test]
    fn an_ifid_is_8_to_63_digits_capitals_and_hyphens() {
        assert!(is_ifid("5C2A6E7B-1D4F-4A83-9E21-7B3C0F8D2A64"));
        assert!(is_ifid("ZCODE-88-840726"));
        assert!(is_ifid("ABCDEFGH"));
        assert!(!is_ifid("ABCDEFG"));
        assert!(!is_ifid(&"A".repeat(64)));
        assert!(!is_ifid("5c2a6e7b-1d4f-4a83-9e21-7b3c0f8d2a64"));
        assert!(!is_ifid("ABCD EFGH"));
        assert!(!is_ifid(""));
    }

    #[test]
    fn the_ifid_a_game_gives_is_checked() {
        let good = "story: Story\n    IFID = '5C2A6E7B-1D4F-4A83-9E21-7B3C0F8D2A64'\n;\n";
        assert!(check(&[("start.hxn", good)], "IFID").is_empty());
        let several = "story: Story\n    IFID = 'TADS2-0123456789ABCDEF, ZCODE-88-840726'\n;\n";
        assert!(check(&[("start.hxn", several)], "IFID").is_empty());

        let bad = "story: Story\n    name = 'Night'\n    IFID = 'abc'\n;\n";
        let found = check(&[("start.hxn", bad)], "IFID");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].file, "start.hxn");
        assert_eq!(found[0].line, 3);
        assert_eq!(found[0].severity, Severity::Warning);
        assert!(found[0].message.starts_with("\"abc\" is not an IFID"));

        let lower = "story: Story\n    IFID = '5c2a6e7b-1d4f-4a83-9e21-7b3c0f8d2a64'\n;\n";
        let found = check(&[("start.hxn", lower)], "IFID");
        assert_eq!(found.len(), 1);
        assert_eq!(
            found[0].message,
            "an IFID is written in capitals: \"5C2A6E7B-1D4F-4A83-9E21-7B3C0F8D2A64\", \
             not \"5c2a6e7b-1d4f-4a83-9e21-7b3c0f8d2a64\""
        );
        assert_eq!(found[0].note, None);

        let none = "story: Story\n    name = 'Night'\n;\n";
        let found = check(&[("start.hxn", none), ("rooms.hxn", "// Rooms.\n")], "IFID");
        assert_eq!(found.len(), 1);
        assert!(found[0].message.starts_with("the game has no IFID"));

        // An English source's IFID is shown where the English gives it.
        let english = "#line 1 'start.hxe'\nimport hexad;\n\n#line 5 'start.hxe'\nstory: Story\n    IFID = 'abc'\n;\n";
        let found = check(&[("start.hxe", english)], "IFID");
        assert_eq!(found.len(), 1);
        assert_eq!((found[0].file.as_str(), found[0].line), ("start.hxe", 6));

        // One source's IFID is the game's.
        assert!(check(&[("rooms.hxn", "// Rooms.\n"), ("start.hxn", good)], "IFID").is_empty());
        // A comment, or a string, is not the game giving one.
        let comment = "// IFID = 'abc'\nstory: Story\n    desc = \"IFID = 'abc'\"\n;\n";
        let found = check(&[("start.hxn", comment)], "IFID");
        assert_eq!(found.len(), 1);
        assert!(found[0].message.starts_with("the game has no IFID"));
    }
}