use rhai::Token;
use crate::lex::{At, Tok};
use crate::stream::LineIndex;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reason {
Eval { at: At },
NameAsData { name: String, at: At },
ParentScopeCall { name: String, at: At },
Reflection { at: At },
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"
),
}
}
}
const NAME_AS_DATA: &[&str] = &["is_def_var", "is_def_fn", "Fn"];
const HARMLESS_RESERVED: &[&str] = &[
"print",
"debug",
"type_of",
"is_shared",
"this",
"call",
"curry",
];
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);
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) {
reasons.push(Reason::UnknownKeyword {
name: name.to_string(),
at,
});
}
}
_ => (),
}
}
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() {
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:?}");
};
assert_eq!((at.line, at.column), (2, 1));
}
}