#![allow(clippy::missing_docs_in_private_items)]
use std::collections::HashSet;
use crate::ast::{Expr, PathDotJoin, PathSegment};
#[derive(Debug, Clone, Default)]
pub struct Dependencies {
pub fields: HashSet<String>,
pub context_refs: HashSet<String>,
pub instance_refs: HashSet<String>,
pub mip_deps: HashSet<String>,
pub has_self_ref: bool,
pub has_wildcard: bool,
pub uses_prev_next: bool,
}
pub fn extract_dependencies(expr: &Expr) -> Dependencies {
let mut deps = Dependencies::default();
let mut let_vars: Vec<String> = Vec::new();
walk(expr, &mut deps, &mut let_vars);
deps
}
fn walk(expr: &Expr, deps: &mut Dependencies, let_vars: &mut Vec<String>) {
match expr {
Expr::FieldRef { name, path } => {
match name {
None => {
if !let_vars.contains(&"$".to_string()) {
deps.has_self_ref = true;
}
}
Some(n) => {
if !let_vars.contains(n) {
let mut full_path = n.clone();
for seg in path {
if matches!(seg, PathSegment::Wildcard) {
deps.has_wildcard = true;
}
seg.append_to_path(&mut full_path, PathDotJoin::AlwaysPrefix);
}
deps.fields.insert(full_path);
}
}
}
}
Expr::VarRef { name, path } => {
if !let_vars.contains(name) {
let mut full_path = name.clone();
for seg in path {
if matches!(seg, PathSegment::Wildcard) {
deps.has_wildcard = true;
}
seg.append_to_path(&mut full_path, PathDotJoin::AlwaysPrefix);
}
deps.fields.insert(full_path);
}
}
Expr::ContextRef {
name,
called,
arg,
tail,
} => {
if name == "instance"
&& let Some(instance_name) = arg
{
deps.instance_refs.insert(instance_name.clone());
}
let mut ref_str = String::with_capacity(
1 + name.len() + arg.as_ref().map(|a| 4 + a.len()).unwrap_or(0) + tail.len() * 2,
);
ref_str.push('@');
ref_str.push_str(name);
if *called {
if let Some(a) = arg {
ref_str.push_str("('");
ref_str.push_str(a);
ref_str.push_str("')");
} else {
ref_str.push_str("()");
}
}
for t in tail {
ref_str.push('.');
ref_str.push_str(t);
}
deps.context_refs.insert(ref_str);
}
Expr::FunctionCall { name, args } => {
match name.as_str() {
"valid" | "relevant" | "readonly" | "required" => {
if let Some(first) = args.first() {
let path = extract_field_path_str(first);
if !path.is_empty() {
deps.mip_deps.insert(path);
}
}
for arg in args {
walk(arg, deps, let_vars);
}
}
"prev" | "next" => {
deps.uses_prev_next = true;
}
"parent" => {
deps.uses_prev_next = true;
}
"instance" => {
if let Some(Expr::String(name)) = args.first() {
deps.instance_refs.insert(name.clone());
}
for arg in args {
walk(arg, deps, let_vars);
}
}
"countWhere" | "every" | "some" | "sumWhere" | "avgWhere" | "minWhere"
| "maxWhere" | "moneySumWhere" => {
if let Some(first) = args.first() {
walk(first, deps, let_vars);
}
if let Some(second) = args.get(1) {
let mut inner_vars = let_vars.clone();
inner_vars.push("$".to_string());
walk(second, deps, &mut inner_vars);
}
}
_ => {
for arg in args {
walk(arg, deps, let_vars);
}
}
}
}
Expr::LetBinding { name, value, body } => {
walk(value, deps, let_vars);
let_vars.push(name.clone());
walk(body, deps, let_vars);
let_vars.pop();
}
Expr::BinaryOp { left, right, .. } => {
walk(left, deps, let_vars);
walk(right, deps, let_vars);
}
Expr::UnaryOp { operand, .. } => {
walk(operand, deps, let_vars);
}
Expr::Ternary {
condition,
then_branch,
else_branch,
}
| Expr::IfThenElse {
condition,
then_branch,
else_branch,
} => {
walk(condition, deps, let_vars);
walk(then_branch, deps, let_vars);
walk(else_branch, deps, let_vars);
}
Expr::Membership {
value, container, ..
} => {
walk(value, deps, let_vars);
walk(container, deps, let_vars);
}
Expr::NullCoalesce { left, right } => {
walk(left, deps, let_vars);
walk(right, deps, let_vars);
}
Expr::PostfixAccess { expr, path } => {
if let Some(field_path) = extend_field_path(expr, path) {
deps.fields.insert(field_path);
} else {
walk(expr, deps, let_vars);
}
for seg in path {
if matches!(seg, PathSegment::Wildcard) {
deps.has_wildcard = true;
}
}
}
Expr::Array(elems) => {
for elem in elems {
walk(elem, deps, let_vars);
}
}
Expr::Object(entries) => {
for (_, val) in entries {
walk(val, deps, let_vars);
}
}
Expr::Null
| Expr::Boolean(_)
| Expr::Number(_)
| Expr::String(_)
| Expr::DateLiteral(_)
| Expr::DateTimeLiteral(_) => {}
}
}
fn extract_field_path_str(expr: &Expr) -> String {
match expr {
Expr::FieldRef { name, path } => {
let mut result = name.as_deref().unwrap_or("").to_string();
for seg in path {
seg.append_to_path(&mut result, PathDotJoin::PrefixWhenNonempty);
}
result
}
Expr::VarRef { name, path } => {
let mut result = name.clone();
for seg in path {
seg.append_to_path(&mut result, PathDotJoin::PrefixWhenNonempty);
}
result
}
_ => String::new(),
}
}
fn extend_field_path(expr: &Expr, extra_path: &[PathSegment]) -> Option<String> {
match expr {
Expr::FieldRef { .. } | Expr::VarRef { .. } => {
let mut path = extract_field_path_str(expr);
for seg in extra_path {
seg.append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
}
if path.is_empty() { None } else { Some(path) }
}
Expr::PostfixAccess { expr, path } => {
let mut combined = path.clone();
combined.extend_from_slice(extra_path);
extend_field_path(expr, &combined)
}
_ => None,
}
}
use crate::wire_style::JsonWireStyle;
pub fn dependencies_to_json_value(deps: &Dependencies) -> serde_json::Value {
dependencies_to_json_value_styled(deps, JsonWireStyle::JsCamel)
}
pub fn dependencies_to_json_value_styled(
deps: &Dependencies,
style: JsonWireStyle,
) -> serde_json::Value {
match style {
JsonWireStyle::JsCamel => serde_json::json!({
"fields": deps.fields.iter().collect::<Vec<_>>(),
"contextRefs": deps.context_refs.iter().collect::<Vec<_>>(),
"instanceRefs": deps.instance_refs.iter().collect::<Vec<_>>(),
"mipDeps": deps.mip_deps.iter().collect::<Vec<_>>(),
"hasSelfRef": deps.has_self_ref,
"hasWildcard": deps.has_wildcard,
"usesPrevNext": deps.uses_prev_next,
}),
JsonWireStyle::PythonSnake => serde_json::json!({
"fields": deps.fields.iter().collect::<Vec<_>>(),
"context_refs": deps.context_refs.iter().collect::<Vec<_>>(),
"instance_refs": deps.instance_refs.iter().collect::<Vec<_>>(),
"mip_deps": deps.mip_deps.iter().collect::<Vec<_>>(),
"has_self_ref": deps.has_self_ref,
"has_wildcard": deps.has_wildcard,
"uses_prev_next": deps.uses_prev_next,
}),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::missing_docs_in_private_items)]
use super::*;
use crate::parser;
fn deps(input: &str) -> Dependencies {
let expr = parser::parse(input).unwrap();
extract_dependencies(&expr)
}
#[test]
fn test_simple_field_ref() {
let d = deps("$name");
assert!(d.fields.contains("name"));
}
#[test]
fn test_nested_field_ref() {
let d = deps("$address.city");
assert!(d.fields.contains("address.city"));
}
#[test]
fn test_wildcard_detection() {
let d = deps("$items[*].qty");
assert!(d.has_wildcard);
assert!(d.fields.contains("items[*].qty"));
}
#[test]
fn test_bare_dollar() {
let d = deps("$");
assert!(d.has_self_ref);
}
#[test]
fn test_context_ref() {
let d = deps("@index");
assert!(d.context_refs.contains("@index"));
}
#[test]
fn test_instance_ref() {
let d = deps("@instance('priorYear').total");
assert!(d.instance_refs.contains("priorYear"));
}
#[test]
fn test_let_binding_excludes_bound_var() {
let d = deps("let x = $a in x + $b");
assert!(d.fields.contains("a"));
assert!(d.fields.contains("b"));
assert!(!d.fields.contains("x"));
}
#[test]
fn test_mip_deps() {
let d = deps("valid($name)");
assert!(d.mip_deps.contains("name"));
}
#[test]
fn test_prev_next_detection() {
let d = deps("prev()");
assert!(d.uses_prev_next);
}
#[test]
fn test_multiple_fields() {
let d = deps("$a + $b * $c");
assert_eq!(d.fields.len(), 3);
assert!(d.fields.contains("a"));
assert!(d.fields.contains("b"));
assert!(d.fields.contains("c"));
}
#[test]
fn null_coalesce_extracts_deps_from_both_sides() {
let d = deps("$fieldA ?? $fieldB");
assert!(
d.fields.contains("fieldA"),
"left side of ?? must produce a dep"
);
assert!(
d.fields.contains("fieldB"),
"right side of ?? must produce a dep"
);
assert_eq!(d.fields.len(), 2);
}
#[test]
fn ternary_extracts_deps_from_all_three_branches() {
let d = deps("$cond ? $yes : $no");
assert!(d.fields.contains("cond"), "condition must produce a dep");
assert!(d.fields.contains("yes"), "true-branch must produce a dep");
assert!(d.fields.contains("no"), "false-branch must produce a dep");
assert_eq!(d.fields.len(), 3);
}
#[test]
fn object_and_array_literal_dep_extraction() {
let d = deps("{total: $price, items: [$qty, $tax]}");
assert!(
d.fields.contains("price"),
"object value must produce a dep"
);
assert!(d.fields.contains("qty"), "array element must produce a dep");
assert!(d.fields.contains("tax"), "array element must produce a dep");
assert_eq!(d.fields.len(), 3);
}
#[test]
fn count_where_rebinds_bare_dollar() {
let d = deps("countWhere($items, $ > 3)");
assert!(
d.fields.contains("items"),
"first arg field ref must be found"
);
assert!(
!d.has_self_ref,
"bare $ in countWhere predicate is rebound, not a self-ref"
);
assert_eq!(d.fields.len(), 1);
}
#[test]
fn every_rebinds_bare_dollar() {
let d = deps("every($items, $ > 0)");
assert!(d.fields.contains("items"));
assert!(!d.has_self_ref);
assert_eq!(d.fields.len(), 1);
}
#[test]
fn sum_where_rebinds_bare_dollar() {
let d = deps("sumWhere($items, $ > 0)");
assert!(d.fields.contains("items"));
assert!(!d.has_self_ref);
assert_eq!(d.fields.len(), 1);
}
#[test]
fn deeply_nested_function_calls_extract_all_deps() {
let d = deps("sum(round($a + $b) + every($items, $ > $threshold))");
assert!(d.fields.contains("a"));
assert!(d.fields.contains("b"));
assert!(d.fields.contains("items"));
assert!(d.fields.contains("threshold"));
assert_eq!(d.fields.len(), 4);
}
mod path_segment_append {
use super::deps;
use crate::ast::{PathDotJoin, PathSegment};
#[test]
fn walk_style_always_prefixes_dot_segments() {
let mut path = "items".to_string();
PathSegment::Dot("qty".into()).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
assert_eq!(path, "items.qty");
}
#[test]
fn extract_style_skips_dot_on_empty_base() {
let mut path = String::new();
PathSegment::Dot("a".into()).append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
assert_eq!(path, "a");
}
#[test]
fn extract_style_prefixes_dot_when_base_nonempty() {
let mut path = "items".to_string();
PathSegment::Dot("qty".into())
.append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
assert_eq!(path, "items.qty");
}
#[test]
fn index_and_wildcard_rendering() {
let mut path = "items".to_string();
PathSegment::Index(2).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
PathSegment::Wildcard.append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
PathSegment::Dot("qty".into()).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
assert_eq!(path, "items[2][*].qty");
}
#[test]
fn mip_empty_base_wildcard_path() {
let d = deps("valid($[*])");
assert!(d.mip_deps.contains("[*]"));
}
#[test]
fn indexed_field_path_round_trip() {
let d = deps("$rows[2].id");
assert!(d.fields.contains("rows[2].id"));
}
}
}