use std::fmt::Write;
const MAX_UNROLL_TRIP_COUNT: u32 = 32;
pub struct WgslLoopUnroller;
impl WgslLoopUnroller {
#[must_use]
pub fn unroll(shader_source: &str) -> String {
let lines: Vec<&str> = shader_source.lines().collect();
let mut output = String::with_capacity(shader_source.len() * 2);
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let trimmed = line.trim();
if let Some(hint_n) = parse_unroll_hint(trimmed) {
let for_start = find_next_for_loop(&lines, i + 1);
if let Some(for_idx) = for_start
&& let Some(unrolled) = try_unroll_loop(&lines, for_idx, hint_n)
{
output.push_str(line);
output.push('\n');
output.push_str(&unrolled);
let loop_end = find_loop_end(&lines, for_idx);
i = loop_end + 1;
continue;
}
}
output.push_str(line);
output.push('\n');
i += 1;
}
output
}
}
fn parse_unroll_hint(trimmed: &str) -> Option<u32> {
let rest = trimmed.strip_prefix("// @unroll_hint")?;
let n: u32 = rest.trim().parse().ok()?;
if n > 0 && n <= MAX_UNROLL_TRIP_COUNT {
Some(n)
} else {
None
}
}
fn find_next_for_loop(lines: &[&str], start_idx: usize) -> Option<usize> {
let end = lines.len().min(start_idx + 5);
for (i, line) in lines[start_idx..end].iter().enumerate() {
let i = start_idx + i;
let t = line.trim();
if t.starts_with("for (var") || t.starts_with("for(var") {
return Some(i);
}
if !t.is_empty() && !t.starts_with("//") {
return None; }
}
None
}
#[derive(Debug, PartialEq, Eq)]
enum ForBound {
Literal(u32),
Variable(String),
}
fn parse_for_header(line: &str) -> Option<(String, ForBound)> {
let t = line.trim();
let after_for = t
.strip_prefix("for (var ")
.or_else(|| t.strip_prefix("for(var "))?;
let eq_pos = after_for.find(" = 0")?;
let var_name = after_for[..eq_pos].trim().to_string();
if var_name.is_empty() {
return None;
}
let lt_pat = format!("{var_name} < ");
let lt_pos = after_for.find(<_pat)?;
let after_lt = &after_for[lt_pos + lt_pat.len()..];
let num_str: String = after_lt.chars().take_while(char::is_ascii_digit).collect();
if !num_str.is_empty() {
let bound: u32 = num_str.parse().ok()?;
if bound == 0 || bound > MAX_UNROLL_TRIP_COUNT {
return None;
}
return Some((var_name, ForBound::Literal(bound)));
}
let id_str: String = after_lt
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
if !id_str.is_empty() {
return Some((var_name, ForBound::Variable(id_str)));
}
None
}
fn find_loop_end(lines: &[&str], for_idx: usize) -> usize {
let mut depth: i32 = 0;
let mut found_open = false;
for (i, line) in lines.iter().enumerate().skip(for_idx) {
for ch in line.chars() {
match ch {
'{' => {
depth += 1;
found_open = true;
}
'}' => {
depth -= 1;
if found_open && depth == 0 {
return i;
}
}
_ => {}
}
}
}
for_idx
}
fn collect_body(lines: &[&str], for_idx: usize) -> Vec<String> {
let end_idx = find_loop_end(lines, for_idx);
let mut body = Vec::new();
let mut depth = 0i32;
let mut past_open = false;
for (rel_i, line) in lines[for_idx..=end_idx].iter().enumerate() {
let i = for_idx + rel_i;
for ch in line.chars() {
if ch == '{' {
depth += 1;
if depth == 1 {
past_open = true;
}
} else if ch == '}' {
depth -= 1;
}
}
if i > for_idx && past_open && depth >= 1 {
body.push(line.to_string());
}
}
body
}
fn try_unroll_loop(lines: &[&str], for_idx: usize, hint_n: u32) -> Option<String> {
let (var_name, bound) = parse_for_header(lines[for_idx])?;
let body_lines = collect_body(lines, for_idx);
let indent: String = lines[for_idx]
.chars()
.take_while(|c| c.is_whitespace())
.collect();
let mut out = String::new();
match bound {
ForBound::Literal(declared_n) => {
let trip_count = hint_n.min(declared_n);
for iter in 0..trip_count {
emit_unrolled_block(&mut out, &indent, &var_name, iter, &body_lines, None);
}
}
ForBound::Variable(ref bound_var) => {
for iter in 0..hint_n {
let guard = format!("if ({iter}u < {bound_var})");
emit_unrolled_block(
&mut out,
&indent,
&var_name,
iter,
&body_lines,
Some(&guard),
);
}
}
}
Some(out)
}
fn emit_unrolled_block(
out: &mut String,
indent: &str,
var_name: &str,
iter: u32,
body_lines: &[String],
guard: Option<&str>,
) {
let _ = writeln!(out, "{indent}{{");
let _ = writeln!(out, "{indent} let {var_name} = {iter}u;");
if let Some(cond) = guard {
let _ = writeln!(out, "{indent} {cond} {{");
for body_line in body_lines {
let subst = substitute_loop_var(body_line, var_name, iter);
let _ = writeln!(out, " {subst}");
}
let _ = writeln!(out, "{indent} }}");
} else {
for body_line in body_lines {
let subst = substitute_loop_var(body_line, var_name, iter);
out.push_str(&subst);
out.push('\n');
}
}
let _ = writeln!(out, "{indent}}}");
}
fn substitute_loop_var(line: &str, var_name: &str, iter: u32) -> String {
let result = line.to_string();
let replacement = format!("{iter}u");
let mut out = String::new();
let mut pos = 0;
let bytes = result.as_bytes();
while pos < bytes.len() {
if let Some(found) = result[pos..].find(var_name) {
let abs = pos + found;
let end = abs + var_name.len();
let before_ok =
abs == 0 || (!bytes[abs - 1].is_ascii_alphanumeric() && bytes[abs - 1] != b'_');
let after_ok =
end >= bytes.len() || (!bytes[end].is_ascii_alphanumeric() && bytes[end] != b'_');
if before_ok && after_ok {
out.push_str(&result[pos..abs]);
out.push_str(&replacement);
pos = end;
} else {
out.push(result.chars().nth(pos).unwrap_or(' '));
pos += 1;
}
} else {
out.push_str(&result[pos..]);
break;
}
}
if out.is_empty() {
out = result;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unroll_hint_parsed() {
assert_eq!(parse_unroll_hint("// @unroll_hint 4"), Some(4));
assert_eq!(parse_unroll_hint("// @unroll_hint 32"), Some(32));
assert_eq!(parse_unroll_hint("// @unroll_hint 33"), None); assert_eq!(parse_unroll_hint("// @unroll_hint 0"), None); assert_eq!(parse_unroll_hint("// normal comment"), None);
}
#[test]
fn test_for_header_parsed_literal() {
assert_eq!(
parse_for_header(" for (var k = 0u; k < 4u; k = k + 1u) {"),
Some(("k".to_string(), ForBound::Literal(4)))
);
assert_eq!(
parse_for_header(" for (var i = 0u; i < 8u; i = i + 1u) {"),
Some(("i".to_string(), ForBound::Literal(8)))
);
}
#[test]
fn test_for_header_parsed_variable_bound() {
assert_eq!(
parse_for_header(" for (var k = 0u; k < n; k = k + 1u) {"),
Some(("k".to_string(), ForBound::Variable("n".to_string())))
);
assert_eq!(
parse_for_header(" for (var i = 0u; i < matrix_size; i = i + 1u) {"),
Some((
"i".to_string(),
ForBound::Variable("matrix_size".to_string())
))
);
}
#[test]
fn test_variable_bound_loop_unrolled_with_guards() {
let shader = concat!(
" // @unroll_hint 4\n",
" for (var k = 0u; k < n; k = k + 1u) {\n",
" let v = k;\n",
" }\n",
);
let result = WgslLoopUnroller::unroll(shader);
assert_eq!(result.matches("let k = 0u;").count(), 1);
assert_eq!(result.matches("let k = 1u;").count(), 1);
assert_eq!(result.matches("let k = 2u;").count(), 1);
assert_eq!(result.matches("let k = 3u;").count(), 1);
assert_eq!(
result.matches("let k = 4u;").count(),
0,
"should only emit 4 iters"
);
assert!(result.contains("if (0u < n)"));
assert!(result.contains("if (1u < n)"));
assert!(result.contains("if (3u < n)"));
assert!(!result.contains("for (var k"));
}
#[test]
fn test_variable_bound_unroll_32() {
let shader = concat!(
" // @unroll_hint 32\n",
" for (var k = 0u; k < n; k = k + 1u) {\n",
" let x = k * 2u;\n",
" }\n",
);
let result = WgslLoopUnroller::unroll(shader);
assert_eq!(result.matches("if (0u < n)").count(), 1);
assert_eq!(result.matches("if (31u < n)").count(), 1);
assert_eq!(result.matches("if (32u < n)").count(), 0);
assert!(!result.contains("for (var k"));
}
#[test]
fn test_simple_loop_unrolled() {
let shader = r"
// @unroll_hint 3
for (var k = 0u; k < 3u; k = k + 1u) {
let v = k + 1u;
}
";
let result = WgslLoopUnroller::unroll(shader);
assert_eq!(result.matches("let k = 0u;").count(), 1);
assert_eq!(result.matches("let k = 1u;").count(), 1);
assert_eq!(result.matches("let k = 2u;").count(), 1);
assert!(!result.contains("for (var k"));
}
#[test]
fn test_loop_without_hint_unchanged() {
let shader = " for (var i = 0u; i < 4u; i = i + 1u) {\n x = i;\n }\n";
let result = WgslLoopUnroller::unroll(shader);
assert!(result.contains("for (var i"));
}
#[test]
fn test_substitute_loop_var_word_boundary() {
let result = substitute_loop_var(" let v = k + akp;", "k", 2);
assert!(result.contains("let v = 2u + akp"), "got: {result}");
assert!(!result.contains("a2"), "got: {result}");
}
#[test]
fn test_hint_smaller_than_literal_bound() {
let shader = " // @unroll_hint 4\n for (var k = 0u; k < 8u; k = k + 1u) {\n x = k;\n }\n";
let result = WgslLoopUnroller::unroll(shader);
assert_eq!(result.matches("let k = 0u;").count(), 1);
assert_eq!(result.matches("let k = 3u;").count(), 1);
assert_eq!(result.matches("let k = 4u;").count(), 0);
assert!(!result.contains("if (0u <"));
}
}