use crate::device::latency::WgslOpClass;
#[must_use]
pub(super) fn classify_op(expr: &str) -> WgslOpClass {
if expr.contains("_batch[") || expr.contains("_buffer[") || expr.contains("global[") {
return WgslOpClass::GlobalMem;
}
if expr.contains("sqrt(")
|| expr.contains("exp_f64(")
|| expr.contains("log_f64(")
|| expr.contains("cos_f64(")
|| expr.contains("sin_f64(")
{
return WgslOpClass::F64Transcend;
}
if expr.contains("f64(")
|| (expr.contains(" * ") && (expr.contains(" + ") || expr.contains(" - ")))
{
return WgslOpClass::F64Fma;
}
if expr.contains(" * ") || expr.contains(" / ") {
return WgslOpClass::F64MulAdd;
}
if expr.contains("idx2d(")
|| expr.contains("batch_offset(")
|| expr.contains(" * n")
|| expr.contains("+ idx")
{
return WgslOpClass::I32Arith;
}
WgslOpClass::F32Fma
}
#[derive(Debug, Clone)]
pub(super) struct BindingNode {
pub name: String,
#[expect(dead_code, reason = "graph data model: stored during parse, available for analysis")]
pub expr: String,
pub source_line: String,
pub op_class: WgslOpClass,
pub deps: Vec<usize>,
}
#[derive(Debug, Clone)]
pub(super) struct PassthroughNode {
pub source_line: String,
pub dep_names: Vec<String>,
}
#[derive(Debug, Clone)]
pub(super) enum Node {
Binding(BindingNode),
Passthrough(PassthroughNode),
}
impl Node {
#[must_use]
pub fn source_line(&self) -> &str {
match self {
Self::Binding(b) => &b.source_line,
Self::Passthrough(p) => &p.source_line,
}
}
}
#[derive(Debug)]
pub(super) struct WgslDependencyGraph {
pub nodes: Vec<Node>,
}
impl WgslDependencyGraph {
#[must_use]
pub fn parse(region: &str) -> Self {
let mut nodes: Vec<Node> = Vec::new();
let mut name_to_idx: std::collections::HashMap<String, usize> =
std::collections::HashMap::new();
for line in region.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with("//") {
nodes.push(Node::Passthrough(PassthroughNode {
source_line: line.to_string(),
dep_names: vec![],
}));
continue;
}
if let Some(binding) = parse_let_binding(line, trimmed, &name_to_idx, &nodes) {
let idx = nodes.len();
name_to_idx.insert(binding.name.clone(), idx);
nodes.push(Node::Binding(binding));
} else {
let dep_names = find_referenced_names(trimmed, &name_to_idx);
nodes.push(Node::Passthrough(PassthroughNode {
source_line: line.to_string(),
dep_names,
}));
}
}
Self { nodes }
}
#[must_use]
#[expect(dead_code, reason = "API completeness — callers use nodes.len() directly today")]
pub fn len(&self) -> usize {
self.nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
}
fn parse_let_binding(
raw_line: &str,
trimmed: &str,
name_to_idx: &std::collections::HashMap<String, usize>,
nodes: &[Node],
) -> Option<BindingNode> {
let without_let = trimmed.strip_prefix("let ")?;
let eq_pos = without_let.find('=')?;
let name = without_let[..eq_pos].trim().to_string();
if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return None;
}
let after_eq = without_let[eq_pos + 1..].trim();
let expr = after_eq.trim_end_matches(';').trim().to_string();
let deps = find_dep_indices(&expr, name_to_idx, nodes);
let op_class = classify_op(&expr);
Some(BindingNode {
name,
expr,
source_line: raw_line.to_string(),
op_class,
deps,
})
}
fn find_dep_indices(
expr: &str,
name_to_idx: &std::collections::HashMap<String, usize>,
_nodes: &[Node],
) -> Vec<usize> {
let mut deps = Vec::new();
for (name, &idx) in name_to_idx {
if contains_identifier(expr, name) {
deps.push(idx);
}
}
deps.sort_unstable();
deps
}
fn find_referenced_names(
text: &str,
name_to_idx: &std::collections::HashMap<String, usize>,
) -> Vec<String> {
name_to_idx
.keys()
.filter(|name| contains_identifier(text, name))
.cloned()
.collect()
}
fn contains_identifier(text: &str, name: &str) -> bool {
let name_bytes = name.as_bytes();
let text_bytes = text.as_bytes();
if name_bytes.is_empty() || text_bytes.len() < name_bytes.len() {
return false;
}
let mut start = 0;
while start + name_bytes.len() <= text_bytes.len() {
if let Some(pos) = text[start..].find(name) {
let abs_pos = start + pos;
let end_pos = abs_pos + name_bytes.len();
let before_ok = abs_pos == 0
|| !text_bytes[abs_pos - 1].is_ascii_alphanumeric()
&& text_bytes[abs_pos - 1] != b'_';
let after_ok = end_pos >= text_bytes.len()
|| !text_bytes[end_pos].is_ascii_alphanumeric() && text_bytes[end_pos] != b'_';
if before_ok && after_ok {
return true;
}
start = abs_pos + 1;
} else {
break;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_simple_region() {
let region = r"
let c = cos_val;
let s = sin_val;
let cc = c * c;
let ss = s * s;
let new_p = c * a_kp - s * a_kq;
";
let graph = WgslDependencyGraph::parse(region);
let binding_count = graph
.nodes
.iter()
.filter(|n| matches!(n, Node::Binding(_)))
.count();
assert_eq!(binding_count, 5);
}
#[test]
fn test_dependency_detection() {
let region = " let a = x * y;\n let b = a + z;\n";
let graph = WgslDependencyGraph::parse(region);
let b = graph.nodes.iter().find_map(|n| {
if let Node::Binding(b) = n {
if b.name == "b" { Some(b) } else { None }
} else {
None
}
});
assert!(b.is_some());
let b = b.unwrap();
assert!(!b.deps.is_empty(), "b should depend on a");
}
#[test]
fn test_classify_op_f64_fma() {
assert_eq!(classify_op("c * akp - s * akq"), WgslOpClass::F64Fma);
}
#[test]
fn test_classify_op_global_mem() {
assert_eq!(
classify_op("A_batch[base + idx2d(k, p, n)]"),
WgslOpClass::GlobalMem
);
}
#[test]
fn test_classify_op_transcend() {
assert_eq!(
classify_op("sqrt(f64(1.0) + t * t)"),
WgslOpClass::F64Transcend
);
}
#[test]
fn test_contains_identifier() {
assert!(contains_identifier("let x = foo + bar;", "foo"));
assert!(contains_identifier("let x = foo + bar;", "bar"));
assert!(!contains_identifier("let x = foobar;", "foo"));
assert!(!contains_identifier("let x = 1.0;", "x1"));
}
#[test]
fn test_passthrough_preserved() {
let region = " let a = 1.0;\n A_batch[0] = a;\n";
let graph = WgslDependencyGraph::parse(region);
assert_eq!(graph.nodes.len(), 2);
assert!(matches!(graph.nodes[0], Node::Binding(_)));
assert!(matches!(graph.nodes[1], Node::Passthrough(_)));
}
}