rhaiper 0.2.0

Minifier for Rhai scripts, with Source Map v3 output
Documentation
//! Detects constructs that make renaming unsafe.
//!
//! Renaming is off unless it can be shown safe, and the decision is made per script rather than
//! left to the caller: whether a script can be renamed depends on Rhai and host-integration details
//! that are not obvious from the outside.

use rhai::Token;

use crate::lex::{At, Tok};
use crate::stream::LineIndex;

/// Why renaming was declined.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reason {
    /// `eval` compiles new source against the live scope and forces name-based lookup from then on.
    Eval { at: At },
    /// A construct that takes a variable or function name as data.
    NameAsData { name: String, at: At },
    /// `foo!(...)` passes the caller's whole scope, so the callee resolves free variables by name
    /// against the caller's locals.
    ParentScopeCall { name: String, at: At },
    /// Script-visible reflection over function and parameter names.
    Reflection { at: At },
    /// A token this crate does not recognize, which may be a host-registered custom keyword.
    UnknownKeyword { name: String, at: At },
}

impl std::fmt::Display for Reason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Eval { at } => write!(f, "`eval` at {at} resolves variables by name"),
            Self::NameAsData { name, at } => {
                write!(f, "`{name}` at {at} takes a name as data")
            }
            Self::ParentScopeCall { name, at } => write!(
                f,
                "`{name}!(...)` at {at} passes the caller's scope, so its locals are read by name"
            ),
            Self::Reflection { at } => write!(
                f,
                "`get_fn_metadata_list` at {at} exposes function and parameter names to the script"
            ),
            Self::UnknownKeyword { name, at } => write!(
                f,
                "`{name}` at {at} is reserved or custom, and may be a host-registered keyword"
            ),
        }
    }
}

/// Constructs that resolve a variable or function by a runtime string.
const NAME_AS_DATA: &[&str] = &["is_def_var", "is_def_fn", "Fn"];

/// Reserved words that are harmless to renaming, so seeing them is not a reason to decline.
///
/// `call` and `curry` are here because they take a `FnPtr`, not a name — and `Fn` above, the only
/// way to build a `FnPtr` from a name, is already blocked. Declining on `call` would reject nearly
/// every script that uses a closure, since `f.call(x)` is how Rhai invokes one.
const HARMLESS_RESERVED: &[&str] = &[
    "print",
    "debug",
    "type_of",
    "is_shared",
    "this",
    "call",
    "curry",
];

/// Returns every reason renaming should be declined for this token stream.
pub fn check(src: &str, toks: &[Tok]) -> Vec<Reason> {
    let lines = LineIndex::new(src);
    let significant: Vec<&Tok> = toks.iter().filter(|t| !t.is_comment()).collect();
    let mut reasons = Vec::new();

    for (i, tok) in significant.iter().enumerate() {
        let at = At::new(&lines, src, tok.span.start);

        // `foo!(...)`: an identifier followed by `!` and then `(`.
        if matches!(tok.token, Token::Identifier(..) | Token::Reserved(..))
            && matches!(significant.get(i + 1).map(|t| &t.token), Some(Token::Bang))
            && matches!(
                significant.get(i + 2).map(|t| &t.token),
                Some(Token::LeftParen | Token::Unit)
            )
        {
            reasons.push(Reason::ParentScopeCall {
                name: tok.text(src).to_string(),
                at,
            });
            continue;
        }

        match &tok.token {
            Token::Identifier(name) if &**name == "get_fn_metadata_list" => {
                reasons.push(Reason::Reflection { at });
            }
            Token::Reserved(name) => {
                let name = name.as_str();
                if name == "eval" {
                    reasons.push(Reason::Eval { at });
                } else if NAME_AS_DATA.contains(&name) {
                    reasons.push(Reason::NameAsData {
                        name: name.to_string(),
                        at,
                    });
                } else if !HARMLESS_RESERVED.contains(&name) {
                    // Anything else reserved is either a syntax error the input compile already
                    // ruled out, or a symbol the host revived as a custom keyword. Either way we
                    // cannot reason about what it does with names.
                    reasons.push(Reason::UnknownKeyword {
                        name: name.to_string(),
                        at,
                    });
                }
            }
            // There is deliberately no `Token::Custom` arm. All three of its construction sites are
            // inside `TokenIterator::next` and consult `self.engine`, which `get_next_token` — the
            // entry point this crate drives — does not have. So a custom keyword reaches us as
            // `Token::Identifier` if it is identifier-shaped, or as `Token::Reserved` above if it is
            // symbol-shaped. Not naming the variant is also what lets this crate compile under
            // `no_custom_syntax`.
            _ => (),
        }
    }
    reasons
}

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

    fn reasons(src: &str) -> Vec<Reason> {
        check(src, &tokenize(src).expect("tokenize"))
    }

    fn declines(src: &str) -> bool {
        !reasons(src).is_empty()
    }

    #[test]
    fn plain_scripts_are_renameable() {
        assert!(!declines("let x = 1; fn f(a) { a + x } f(2)"));
        assert!(!declines(
            "let total = 0; for i in 0..10 { total += i } total"
        ));
        assert!(!declines("let f = |x| x * 2; f.call(1)"));
        assert!(!declines("let m = #{ a: 1 }; m.a"));
        assert!(!declines("try { throw 1 } catch (e) { e }"));
    }

    #[test]
    fn print_and_debug_do_not_block_renaming() {
        // Both are reserved-but-callable, and neither touches variable names.
        assert!(!declines("let x = 1; print(x); debug(x);"));
        assert!(!declines("let x = 1; type_of(x)"));
    }

    #[test]
    fn eval_blocks_renaming() {
        assert!(matches!(
            reasons("eval(\"1\")").as_slice(),
            [Reason::Eval { .. }]
        ));
    }

    #[test]
    fn name_as_data_blocks_renaming() {
        for src in [
            "is_def_var(\"x\")",
            "is_def_fn(\"f\", 0)",
            "let p = Fn(\"f\");",
        ] {
            assert!(
                reasons(src)
                    .iter()
                    .any(|r| matches!(r, Reason::NameAsData { .. })),
                "expected {src:?} to be declined"
            );
        }
    }

    #[test]
    fn parent_scope_calls_block_renaming() {
        let got = reasons("fn f() { x } let x = 1; f!()");
        assert!(
            got.iter()
                .any(|r| matches!(r, Reason::ParentScopeCall { name, .. } if name == "f")),
            "got {got:?}"
        );
    }

    #[test]
    fn reflection_blocks_renaming() {
        assert!(
            reasons("get_fn_metadata_list()")
                .iter()
                .any(|r| matches!(r, Reason::Reflection { .. }))
        );
    }

    #[test]
    fn reasons_are_reported_with_positions() {
        let got = reasons("let a = 1;\neval(\"a\")");
        let Some(Reason::Eval { at }) = got.first() else {
            panic!("got {got:?}");
        };
        // Derived from the byte span rather than from a rhai `Position`, so this stays correct under
        // `no_position`.
        assert_eq!((at.line, at.column), (2, 1));
    }
}