use std::collections::HashSet;
use rhai::{AST, Expr, Stmt};
use crate::{ExprIssue, ExprIssueKind};
fn unknown_roots(ast: &AST, allowed_roots: &[&str]) -> Vec<String> {
let mut declared: HashSet<String> = HashSet::new();
for meta in ast.iter_functions() {
declared.extend(meta.params.iter().map(|s| s.to_string()));
}
let mut unknown: Vec<String> = Vec::new();
let mut visit = |path: &[rhai::ASTNode]| {
let Some(last) = path.last() else {
return true;
};
let node: &rhai::ASTNode = last;
match node {
rhai::ASTNode::Stmt(stmt) => match stmt {
Stmt::Var(boxed, ..) => {
declared.insert(boxed.0.name.to_string());
}
Stmt::For(boxed, ..) => {
declared.insert(boxed.0.name.to_string());
if let Some(second) = &boxed.1 {
declared.insert(second.name.to_string());
}
}
_ => {}
},
rhai::ASTNode::Expr(expr) => {
let Expr::Variable(boxed, ..) = expr else {
return true;
};
let name = boxed.1.to_string();
if !allowed_roots.contains(&name.as_str()) && !declared.contains(&name) {
unknown.push(name);
}
}
_ => {}
}
true
};
ast.walk(&mut visit);
let mut seen = HashSet::new();
unknown.retain(|n| seen.insert(n.clone()));
unknown
}
fn uses_dynamic_eval(ast: &AST) -> bool {
let mut found = false;
let mut visit = |path: &[rhai::ASTNode]| {
if found {
return false;
}
if let Some(last) = path.last() {
let node: &rhai::ASTNode = last;
let name = match node {
rhai::ASTNode::Stmt(stmt) => {
if let Stmt::FnCall(boxed, ..) = stmt {
Some(boxed.name.as_str())
} else {
None
}
}
rhai::ASTNode::Expr(expr) => {
if let Expr::FnCall(boxed, ..) = expr {
Some(boxed.name.as_str())
} else {
None
}
}
_ => None,
};
if name == Some("eval") {
found = true;
return false;
}
}
true
};
ast.walk(&mut visit);
found
}
pub(super) fn check_ast(ast: &AST, locator: &str, allowed_roots: &[&str]) -> Vec<ExprIssue> {
let mut issues = Vec::new();
if uses_dynamic_eval(ast) {
issues.push(ExprIssue {
locator: locator.to_string(),
message: "dynamic eval() is not allowed in view expressions".to_string(),
kind: ExprIssueKind::DynamicEval,
});
}
for name in unknown_roots(ast, allowed_roots) {
issues.push(ExprIssue {
locator: locator.to_string(),
message: format!(
"unknown identifier '{name}' (available: {})",
allowed_roots.join(", ")
),
kind: ExprIssueKind::UnknownRoot,
});
}
issues
}