buildl-lua 0.3.1

Lua build-file evaluation for buildl, on the airsl embedded runtime.
Documentation
//! `tostring` and `string.format` without address-derived text.
//!
//! Its own file because it replaces two standard-library functions rather than adding one. For a
//! table, function, thread or userdata without a `__tostring` metamethod, Lua renders the value's
//! heap address, and `%p` renders one for anything. A build file that declared such text would
//! declare something different on every evaluation, and that difference is not reliably seen by
//! evaluating the file twice in one process. The replacements raise an ordinary Lua error instead,
//! so nothing nondeterministic escapes and a `pcall` may catch it.
//!
//! Responsibilities: [`install`].
//!
//! Non-responsibilities: every other conversion. Values with stable text, and every format
//! directive that does not render an address, go to the original functions unchanged.

use airsl::mlua::{self, Function, Lua, MultiValue, Table, Value};

/// Replaces the globals `tostring` and `string.format`, which `("%s"):format(x)` also reaches
/// through the string metatable.
pub(crate) fn install(lua: &Lua) -> mlua::Result<()> {
    let globals = lua.globals();

    let tostring: Function = globals.get("tostring")?;
    let stable_tostring = lua.create_function(move |_, args: MultiValue| {
        if let Some(value) = args.front() {
            ensure_stable("tostring", value)?;
        }
        tostring.call::<MultiValue>(args)
    })?;
    globals.set("tostring", stable_tostring)?;

    let string: Table = globals.get("string")?;
    let format: Function = string.get("format")?;
    let stable_format = lua.create_function(move |_, args: MultiValue| {
        check_format(&args)?;
        format.call::<MultiValue>(args)
    })?;
    string.set("format", stable_format)
}

/// Refuses `%p`, and `%s` of a value with no stable text, in the directives of the format string at
/// the front of `args`.
///
/// A first argument that is not a string is left to the original function, which raises its own
/// error for it.
fn check_format(args: &MultiValue) -> mlua::Result<()> {
    let Some(Value::String(format)) = args.front() else {
        return Ok(());
    };
    let format = format.as_bytes();
    let mut next_argument = 1;
    let mut index = 0;
    while let Some(&byte) = format.get(index) {
        index += 1;
        if byte != b'%' {
            continue;
        }
        if format.get(index) == Some(&b'%') {
            index += 1;
            continue;
        }
        while format
            .get(index)
            .is_some_and(|byte| b"-+ #0123456789.".contains(byte))
        {
            index += 1;
        }
        match format.get(index) {
            Some(b'p') => {
                return Err(mlua::Error::RuntimeError(
                    "string.format: %p renders an address".to_owned(),
                ));
            }
            Some(b's') => {
                if let Some(value) = args.get(next_argument) {
                    ensure_stable("string.format", value)?;
                }
            }
            _ => {}
        }
        next_argument += 1;
        index += 1;
    }
    Ok(())
}

/// Raises an error naming `site` unless `value` converts to text without an address.
fn ensure_stable(site: &str, value: &Value) -> mlua::Result<()> {
    if has_stable_text(value) {
        Ok(())
    } else {
        Err(mlua::Error::RuntimeError(format!(
            "{site}: a {} has no stable text",
            value.type_name()
        )))
    }
}

/// Whether `tostring` of `value` is free of addresses: a scalar, an error raised by the host
/// (which `pcall` hands back as a value), or a value whose metatable converts it.
fn has_stable_text(value: &Value) -> bool {
    match value {
        Value::Nil
        | Value::Boolean(_)
        | Value::Integer(_)
        | Value::Number(_)
        | Value::String(_)
        | Value::Error(_) => true,
        Value::Table(table) => table.metatable().is_some_and(|metatable| {
            metatable
                .raw_get::<Value>("__tostring")
                .is_ok_and(|converter| !converter.is_nil())
        }),
        Value::UserData(userdata) => userdata
            .metatable()
            .and_then(|metatable| metatable.contains("__tostring"))
            .unwrap_or(false),
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
    )]

    use airsl::mlua::Lua;

    use super::install;

    /// Runs `source` on a Lua state with the replacements installed.
    fn run(source: &str) -> Result<String, String> {
        let lua = Lua::new();
        install(&lua).unwrap();
        lua.load(source)
            .eval::<String>()
            .map_err(|error| error.to_string())
    }

    #[test]
    fn tostring_still_converts_scalars_and_tables_with_a_converter() {
        assert_eq!(
            run("return tostring(1) .. tostring('x') .. tostring(nil) .. tostring(true)").unwrap(),
            "1xniltrue"
        );
        assert_eq!(
            run("return tostring(setmetatable({}, { __tostring = function() return 'T' end }))")
                .unwrap(),
            "T"
        );
        assert_eq!(run("return tostring(1.5)").unwrap(), "1.5");
    }

    #[test]
    fn tostring_refuses_values_that_would_render_an_address() {
        for (source, kind) in [
            ("return tostring({})", "table"),
            ("return tostring(print)", "function"),
            ("return tostring(function() end)", "function"),
            ("return tostring(setmetatable({}, {}))", "table"),
            ("return tostring(coroutine.create(print))", "thread"),
        ] {
            let message = run(source).unwrap_err();
            assert!(
                message.contains(&format!("tostring: a {kind} has no stable text")),
                "{source}: {message}"
            );
        }
    }

    #[test]
    fn tostring_converts_an_error_a_host_function_raised() {
        let text = run("local _, e = pcall(tostring, {}) return tostring(e)").unwrap();
        assert!(text.contains("a table has no stable text"), "{text}");
    }

    #[test]
    fn tostring_with_no_argument_keeps_the_original_error() {
        let message = run("return tostring()").unwrap_err();
        assert!(message.contains("bad argument"), "{message}");
    }

    #[test]
    fn the_refusal_is_an_ordinary_error_that_pcall_catches() {
        assert_eq!(
            run("local ok = pcall(tostring, {}) return tostring(ok)").unwrap(),
            "false"
        );
    }

    #[test]
    fn format_keeps_ordinary_directives() {
        assert_eq!(
            run("return string.format('%d %s %5.2f %%', 1, 'a', 2)").unwrap(),
            "1 a  2.00 %"
        );
        assert_eq!(
            run("return string.format('%s %s %s', nil, true, 7)").unwrap(),
            "nil true 7"
        );
        assert_eq!(
            run("return string.format('%s', setmetatable({}, { __tostring = function() return 'T' end }))")
                .unwrap(),
            "T"
        );
        assert_eq!(run("return string.format('%%s')").unwrap(), "%s");
    }

    #[test]
    fn format_refuses_s_of_a_value_that_would_render_an_address() {
        let message = run("return string.format('%s', {})").unwrap_err();
        assert!(
            message.contains("string.format: a table has no stable text"),
            "{message}"
        );
        let message = run("return string.format('%d %5s', 1, print)").unwrap_err();
        assert!(
            message.contains("string.format: a function has no stable text"),
            "{message}"
        );
    }

    #[test]
    fn format_refuses_p_of_anything() {
        for source in [
            "return string.format('%p', {})",
            "return string.format('%p', 1)",
            "return string.format('%-20p', 'x')",
        ] {
            let message = run(source).unwrap_err();
            assert!(
                message.contains("string.format: %p renders an address"),
                "{source}: {message}"
            );
        }
    }

    #[test]
    fn format_skips_escaped_percent_signs_when_matching_arguments() {
        assert_eq!(run("return string.format('%%p %s', 'a')").unwrap(), "%p a");
        let message = run("return string.format('%% %s', {})").unwrap_err();
        assert!(message.contains("a table has no stable text"), "{message}");
    }

    #[test]
    fn format_called_as_a_method_is_covered_too() {
        let message = run("return ('%s'):format({})").unwrap_err();
        assert!(message.contains("a table has no stable text"), "{message}");
        let message = run("return ('%p'):format(1)").unwrap_err();
        assert!(message.contains("%p renders an address"), "{message}");
        assert_eq!(run("return ('%d'):format(3)").unwrap(), "3");
    }

    #[test]
    fn format_with_a_bad_first_argument_keeps_the_original_error() {
        let message = run("return string.format({})").unwrap_err();
        assert!(message.contains("bad argument"), "{message}");
    }
}