1//! DCTL top-level declaration and statement parser/emitter.
2
3use std::collections::{HashMap, HashSet};
4
5use super::dctl::{ParamLayout, Tok, c_type_to_wgsl, is_c_qualifier, parse_param_block};
6
7// ---------------------------------------------------------------------------
8// Parser & WGSL Emitter
9// ---------------------------------------------------------------------------
10
11pub(super) struct KernelInfo {
12 pub(super) name: String,
13 pub(super) params_type: Option<String>,
14 pub(super) params_var: String,
15 pub(super) input_textures: Vec<String>,
16 pub(super) output_textures: Vec<String>,
17 pub(super) body_wgsl: String,
18}
19
20pub(super) struct Transpiler {
21 pub(super) toks: Vec<Tok>,
22 pub(super) pos: usize,
23 pub(super) known_structs: HashSet<String>,
24 pub(super) struct_defs: Vec<(String, String)>,
25 pub(super) inline_param_structs: HashMap<String, ParamLayout>,
26 pub(super) globals_wgsl: Vec<String>,
27 pub(super) helpers_wgsl: Vec<String>,
28 pub(super) kernels: Vec<KernelInfo>,
29 pub(super) bool_vars: HashSet<String>,
30 /// Variables in current function that hold a pointer (`*p`).
31 ptr_vars: HashSet<String>,
32 /// Variables that are `__CONSTANTREF__` struct refs (accessed via `.` after `->`).
33 struct_ref_vars: HashSet<String>,
34}
35
36impl Transpiler {
37 pub(super) fn new(toks: Vec<Tok>) -> Self {
38 Self {
39 toks,
40 pos: 0,
41 known_structs: HashSet::new(),
42 struct_defs: Vec::new(),
43 inline_param_structs: HashMap::new(),
44 globals_wgsl: Vec::new(),
45 helpers_wgsl: Vec::new(),
46 kernels: Vec::new(),
47 bool_vars: HashSet::new(),
48 ptr_vars: HashSet::new(),
49 struct_ref_vars: HashSet::new(),
50 }
51 }
52
53 pub(super) fn peek(&self) -> Option<&Tok> {
54 self.toks.get(self.pos)
55 }
56
57 fn peek_n(&self, n: usize) -> Option<&Tok> {
58 self.toks.get(self.pos + n)
59 }
60
61 pub(super) fn bump(&mut self) -> Option<Tok> {
62 let t = self.toks.get(self.pos)?.clone();
63 self.pos += 1;
64 Some(t)
65 }
66
67 pub(super) fn is_punct(&self, p: &str) -> bool {
68 matches!(self.peek(), Some(Tok::Punct(s)) if s == p)
69 }
70
71 fn is_ident(&self, id: &str) -> bool {
72 matches!(self.peek(), Some(Tok::Ident(s)) if s == id)
73 }
74
75 pub(super) fn eat_punct(&mut self, p: &str) -> bool {
76 if self.is_punct(p) {
77 self.pos += 1;
78 true
79 } else {
80 false
81 }
82 }
83
84 pub(super) fn expect_punct(&mut self, p: &str) -> Result<(), String> {
85 if self.eat_punct(p) {
86 Ok(())
87 } else {
88 Err(format!("expected `{p}` near {:?}", self.peek()))
89 }
90 }
91
92 pub(super) fn expect_ident(&mut self) -> Result<String, String> {
93 match self.bump() {
94 Some(Tok::Ident(s)) => Ok(s),
95 other => Err(format!("expected identifier, got {other:?}")),
96 }
97 }
98
99 fn skip_qualifiers(&mut self) -> bool {
100 let mut saw_const = false;
101 while let Some(Tok::Ident(s)) = self.peek() {
102 if is_c_qualifier(s) {
103 if s == "const" || s == "__CONSTANT__" {
104 saw_const = true;
105 }
106 self.pos += 1;
107 } else {
108 break;
109 }
110 }
111 saw_const
112 }
113
114 pub(super) fn peek_type_at(&self, idx: usize) -> Option<(String, usize)> {
115 let Tok::Ident(first) = self.toks.get(idx)? else {
116 return None;
117 };
118 if first == "unsigned" {
119 if let Some(Tok::Ident(second)) = self.toks.get(idx + 1)
120 && second == "int"
121 {
122 return Some(("u32".to_owned(), 2));
123 }
124 return Some(("u32".to_owned(), 1));
125 }
126 if first == "struct" {
127 if let Some(Tok::Ident(sname)) = self.toks.get(idx + 1) {
128 return Some((sname.clone(), 2));
129 }
130 return None;
131 }
132 if let Some(wgsl) = c_type_to_wgsl(first) {
133 return Some((wgsl.to_owned(), 1));
134 }
135 if self.known_structs.contains(first) {
136 return Some((first.clone(), 1));
137 }
138 None
139 }
140
141 fn parse_type(&mut self) -> Result<String, String> {
142 let Some((ty, consumed)) = self.peek_type_at(self.pos) else {
143 return Err(format!("expected type near {:?}", self.peek()));
144 };
145 self.pos += consumed;
146 Ok(ty)
147 }
148
149 pub(super) fn parse_program(&mut self) -> Result<(), String> {
150 while self.pos < self.toks.len() {
151 if self.eat_punct(";") {
152 continue;
153 }
154 if self.is_ident("typedef") {
155 self.parse_typedef_struct()?;
156 } else if self.is_ident("struct") {
157 self.parse_struct_def()?;
158 } else if self.is_ident("__KERNEL__") {
159 self.pos += 1;
160 self.parse_kernel()?;
161 } else if self.is_ident("__DEVICE__") {
162 self.pos += 1;
163 self.parse_device_fn()?;
164 } else {
165 // Could be a global const or unmarked helper function.
166 let save = self.pos;
167 let _ = self.skip_qualifiers();
168 if self.peek_type_at(self.pos).is_some() {
169 let _ty = self.parse_type()?;
170 if matches!(self.peek(), Some(Tok::Ident(_)))
171 && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == "(")
172 {
173 self.pos = save;
174 self.parse_device_fn()?;
175 continue;
176 }
177 self.pos = save;
178 self.parse_global_const()?;
179 } else {
180 // Skip unknown top-level token safely.
181 self.pos += 1;
182 }
183 }
184 }
185 Ok(())
186 }
187
188 fn parse_typedef_struct(&mut self) -> Result<(), String> {
189 self.pos += 1; // typedef
190 if !self.is_ident("struct") {
191 while self.pos < self.toks.len() && !self.eat_punct(";") {
192 self.pos += 1;
193 }
194 return Ok(());
195 }
196 self.pos += 1; // struct
197 // Optional tag name before `{`
198 if matches!(self.peek(), Some(Tok::Ident(_))) {
199 self.pos += 1;
200 }
201 let body_text = self.collect_brace_raw_text()?;
202 let name = self.expect_ident()?;
203 let _ = self.eat_punct(";");
204 let layout = parse_param_block(&body_text)?;
205 let wgsl = layout.to_wgsl_struct(&name);
206 self.known_structs.insert(name.clone());
207 self.inline_param_structs.insert(name.clone(), layout);
208 self.struct_defs.push((name, wgsl));
209 Ok(())
210 }
211
212 fn parse_struct_def(&mut self) -> Result<(), String> {
213 self.pos += 1; // struct
214 let name = self.expect_ident()?;
215 let body_text = self.collect_brace_raw_text()?;
216 let _ = self.eat_punct(";");
217 let layout = parse_param_block(&body_text)?;
218 let wgsl = layout.to_wgsl_struct(&name);
219 self.known_structs.insert(name.clone());
220 self.inline_param_structs.insert(name.clone(), layout);
221 self.struct_defs.push((name, wgsl));
222 Ok(())
223 }
224
225 fn collect_brace_raw_text(&mut self) -> Result<String, String> {
226 self.expect_punct("{")?;
227 let mut depth = 1usize;
228 let mut s = String::new();
229 while self.pos < self.toks.len() && depth > 0 {
230 match self.bump().unwrap() {
231 Tok::Punct(p) if p == "{" => {
232 depth += 1;
233 s.push_str("{ ");
234 }
235 Tok::Punct(p) if p == "}" => {
236 depth -= 1;
237 if depth > 0 {
238 s.push_str("} ");
239 }
240 }
241 Tok::Ident(id) => {
242 s.push_str(&id);
243 s.push(' ');
244 }
245 Tok::Int(n) | Tok::Float(n) => {
246 s.push_str(&n);
247 s.push(' ');
248 }
249 Tok::Punct(p) => {
250 s.push_str(&p);
251 if p == ";" {
252 s.push('\n');
253 }
254 }
255 }
256 }
257 Ok(s)
258 }
259
260 fn parse_global_const(&mut self) -> Result<(), String> {
261 let _ = self.skip_qualifiers();
262 let ty = self.parse_type()?;
263 let name = self.expect_ident()?;
264 let arr_len = if self.eat_punct("[") {
265 let n = if let Some(Tok::Int(s)) = self.peek() {
266 let s = s.clone();
267 self.pos += 1;
268 Some(s)
269 } else {
270 None
271 };
272 self.expect_punct("]")?;
273 n
274 } else {
275 None
276 };
277 self.expect_punct("=")?;
278 if let Some(len) = arr_len {
279 let items = self.parse_brace_init_list()?;
280 self.expect_punct(";")?;
281 self.globals_wgsl.push(format!(
282 "const {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n",
283 items.join(", ")
284 ));
285 } else {
286 let expr = self.parse_expr()?;
287 self.expect_punct(";")?;
288 self.globals_wgsl
289 .push(format!("const {name}: {ty} = {expr};\n"));
290 }
291 Ok(())
292 }
293
294 fn parse_device_fn(&mut self) -> Result<(), String> {
295 let _ = self.skip_qualifiers();
296 let ret_ty = self.parse_type()?;
297 let name = self.expect_ident()?;
298 self.expect_punct("(")?;
299
300 let mut wgsl_params = Vec::new();
301 let mut prelude = Vec::new();
302 self.bool_vars.clear();
303 self.ptr_vars.clear();
304 self.struct_ref_vars.clear();
305
306 while !self.is_punct(")") && self.pos < self.toks.len() {
307 let mut is_const_ref = false;
308 while let Some(Tok::Ident(s)) = self.peek() {
309 if s == "__CONSTANTREF__" {
310 is_const_ref = true;
311 self.pos += 1;
312 } else if is_c_qualifier(s) {
313 self.pos += 1;
314 } else {
315 break;
316 }
317 }
318 if self.is_ident("void") && matches!(self.peek_n(1), Some(Tok::Punct(p)) if p == ")") {
319 self.pos += 1;
320 break;
321 }
322 let pty = self.parse_type()?;
323 let is_ptr = self.eat_punct("*");
324 let pname = self.expect_ident()?;
325 if pty == "bool" {
326 self.bool_vars.insert(pname.clone());
327 }
328 if is_const_ref && is_ptr {
329 wgsl_params.push(format!("_p_{pname}: {pty}"));
330 prelude.push(format!(" let {pname} = _p_{pname};\n"));
331 self.struct_ref_vars.insert(pname);
332 } else if is_ptr {
333 wgsl_params.push(format!("{pname}: ptr<function, {pty}>"));
334 self.ptr_vars.insert(pname);
335 } else {
336 wgsl_params.push(format!("_p_{pname}: {pty}"));
337 prelude.push(format!(" var {pname}: {pty} = _p_{pname};\n"));
338 }
339 if !self.eat_punct(",") {
340 break;
341 }
342 }
343 self.expect_punct(")")?;
344 if self.eat_punct(";") {
345 // Forward prototype — WGSL does not need forward declarations.
346 return Ok(());
347 }
348 let body = self.parse_block_inner()?;
349 let ret_clause = if ret_ty == "void" {
350 String::new()
351 } else {
352 format!(" -> {ret_ty}")
353 };
354 let mut fn_wgsl = format!("fn {name}({}){ret_clause} {{\n", wgsl_params.join(", "));
355 for line in prelude {
356 fn_wgsl.push_str(&line);
357 }
358 fn_wgsl.push_str(&body);
359 fn_wgsl.push_str("}\n");
360 self.helpers_wgsl.push(fn_wgsl);
361 Ok(())
362 }
363
364 fn parse_kernel(&mut self) -> Result<(), String> {
365 let _ = self.skip_qualifiers();
366 let _ret = self.parse_type()?; // void
367 let name = self.expect_ident()?;
368 self.expect_punct("(")?;
369
370 let mut params_type = None;
371 let mut params_var = "params".to_owned();
372 let mut input_textures = Vec::new();
373 let mut output_textures = Vec::new();
374 self.bool_vars.clear();
375 self.ptr_vars.clear();
376 self.struct_ref_vars.clear();
377
378 while !self.is_punct(")") && self.pos < self.toks.len() {
379 if self.is_ident("__CONSTANTREF__") {
380 self.pos += 1;
381 let _ = self.skip_qualifiers();
382 let ty = self.expect_ident()?;
383 let _ = self.eat_punct("*");
384 let var = self.expect_ident()?;
385 self.known_structs.insert(ty.clone());
386 self.struct_ref_vars.insert(var.clone());
387 params_type = Some(ty);
388 params_var = var;
389 } else if self.is_ident("__TEXTURE2D__") {
390 self.pos += 1;
391 let var = self.expect_ident()?;
392 input_textures.push(var);
393 } else if self.is_ident("__TEXTURE2D_WRITE__") {
394 self.pos += 1;
395 let var = self.expect_ident()?;
396 output_textures.push(var);
397 } else {
398 // Skip optional extra kernel arguments cleanly
399 let _ = self.skip_qualifiers();
400 let _ = self.bump();
401 let _ = self.eat_punct("*");
402 if matches!(self.peek(), Some(Tok::Ident(_))) {
403 self.pos += 1;
404 }
405 }
406 if !self.eat_punct(",") {
407 break;
408 }
409 }
410 self.expect_punct(")")?;
411 let body_wgsl = self.parse_block_inner()?;
412 self.kernels.push(KernelInfo {
413 name,
414 params_type,
415 params_var,
416 input_textures,
417 output_textures,
418 body_wgsl,
419 });
420 Ok(())
421 }
422
423 fn parse_block_inner(&mut self) -> Result<String, String> {
424 self.expect_punct("{")?;
425 let mut out = String::new();
426 while !self.is_punct("}") && self.pos < self.toks.len() {
427 self.parse_stmt(&mut out, 1)?;
428 }
429 self.expect_punct("}")?;
430 Ok(out)
431 }
432
433 fn parse_stmt_or_block(&mut self, out: &mut String, indent: usize) -> Result<(), String> {
434 if self.is_punct("{") {
435 self.pos += 1;
436 while !self.is_punct("}") && self.pos < self.toks.len() {
437 self.parse_stmt(out, indent)?;
438 }
439 self.expect_punct("}")?;
440 } else {
441 self.parse_stmt(out, indent)?;
442 }
443 Ok(())
444 }
445
446 fn parse_stmt(&mut self, out: &mut String, indent: usize) -> Result<(), String> {
447 let pad = " ".repeat(indent);
448 if self.eat_punct(";") {
449 return Ok(());
450 }
451 if self.is_punct("{") {
452 out.push_str(&format!("{pad}{{\n"));
453 self.parse_stmt_or_block(out, indent + 1)?;
454 out.push_str(&format!("{pad}}}\n"));
455 return Ok(());
456 }
457 if self.is_ident("DEFINE_KERNEL_ITERATORS_XY") {
458 self.pos += 1;
459 self.expect_punct("(")?;
460 let x_var = self.expect_ident()?;
461 self.expect_punct(",")?;
462 let y_var = self.expect_ident()?;
463 self.expect_punct(")")?;
464 let _ = self.eat_punct(";");
465 out.push_str(&format!(
466 "{pad}var {x_var}: i32 = i32(_dctl_gid.x);\n\
467 {pad}var {y_var}: i32 = i32(_dctl_dims.y - 1u - _dctl_gid.y);\n"
468 ));
469 return Ok(());
470 }
471 if self.is_ident("if") {
472 self.pos += 1;
473 self.expect_punct("(")?;
474 let cond = self.parse_bool_expr()?;
475 self.expect_punct(")")?;
476 out.push_str(&format!("{pad}if ({cond}) {{\n"));
477 self.parse_stmt_or_block(out, indent + 1)?;
478 out.push_str(&format!("{pad}}}"));
479 if self.is_ident("else") {
480 self.pos += 1;
481 if self.is_ident("if") {
482 out.push_str(" else ");
483 let mut nested = String::new();
484 self.parse_stmt(&mut nested, indent)?;
485 out.push_str(nested.trim_start());
486 } else {
487 out.push_str(" else {\n");
488 self.parse_stmt_or_block(out, indent + 1)?;
489 out.push_str(&format!("{pad}}}\n"));
490 }
491 } else {
492 out.push('\n');
493 }
494 return Ok(());
495 }
496 if self.is_ident("for") {
497 self.pos += 1;
498 self.expect_punct("(")?;
499 let init = if self.is_punct(";") {
500 self.pos += 1;
501 String::new()
502 } else if self.is_var_decl_ahead() {
503 self.parse_single_var_decl_inline()?
504 } else {
505 let e = self.parse_expr_stmt_inline()?;
506 self.expect_punct(";")?;
507 e
508 };
509 let cond = if self.is_punct(";") {
510 self.pos += 1;
511 String::new()
512 } else {
513 let c = self.parse_bool_expr()?;
514 self.expect_punct(";")?;
515 c
516 };
517 let step = if self.is_punct(")") {
518 String::new()
519 } else {
520 self.parse_expr_stmt_inline()?
521 };
522 self.expect_punct(")")?;
523 out.push_str(&format!("{pad}for ({init}; {cond}; {step}) {{\n"));
524 self.parse_stmt_or_block(out, indent + 1)?;
525 out.push_str(&format!("{pad}}}\n"));
526 return Ok(());
527 }
528 if self.is_ident("while") {
529 self.pos += 1;
530 self.expect_punct("(")?;
531 let cond = self.parse_bool_expr()?;
532 self.expect_punct(")")?;
533 out.push_str(&format!("{pad}while ({cond}) {{\n"));
534 self.parse_stmt_or_block(out, indent + 1)?;
535 out.push_str(&format!("{pad}}}\n"));
536 return Ok(());
537 }
538 if self.is_ident("do") {
539 self.pos += 1;
540 out.push_str(&format!("{pad}loop {{\n"));
541 self.parse_stmt_or_block(out, indent + 1)?;
542 if !self.is_ident("while") {
543 return Err("expected `while` after `do` block".to_owned());
544 }
545 self.pos += 1;
546 self.expect_punct("(")?;
547 let cond = self.parse_bool_expr()?;
548 self.expect_punct(")")?;
549 let _ = self.eat_punct(";");
550 out.push_str(&format!("{pad} if (!({cond})) {{ break; }}\n{pad}}}\n"));
551 return Ok(());
552 }
553 if self.is_ident("return") {
554 self.pos += 1;
555 if self.eat_punct(";") {
556 out.push_str(&format!("{pad}return;\n"));
557 } else {
558 let e = self.parse_expr()?;
559 self.expect_punct(";")?;
560 out.push_str(&format!("{pad}return {e};\n"));
561 }
562 return Ok(());
563 }
564 if self.is_ident("break") {
565 self.pos += 1;
566 self.expect_punct(";")?;
567 out.push_str(&format!("{pad}break;\n"));
568 return Ok(());
569 }
570 if self.is_ident("continue") {
571 self.pos += 1;
572 self.expect_punct(";")?;
573 out.push_str(&format!("{pad}continue;\n"));
574 return Ok(());
575 }
576 if self.is_var_decl_ahead() {
577 self.parse_var_decl_stmt(out, &pad)?;
578 return Ok(());
579 }
580 let expr_stmt = self.parse_expr_stmt_inline()?;
581 self.expect_punct(";")?;
582 out.push_str(&format!("{pad}{expr_stmt};\n"));
583 Ok(())
584 }
585
586 fn is_var_decl_ahead(&self) -> bool {
587 let mut idx = self.pos;
588 while let Some(Tok::Ident(s)) = self.toks.get(idx) {
589 if is_c_qualifier(s) {
590 idx += 1;
591 } else {
592 break;
593 }
594 }
595 let Some((_, consumed)) = self.peek_type_at(idx) else {
596 return false;
597 };
598 let next_idx = idx + consumed;
599 matches!(self.toks.get(next_idx), Some(Tok::Ident(_)))
600 }
601
602 fn parse_var_decl_stmt(&mut self, out: &mut String, pad: &str) -> Result<(), String> {
603 let is_const = self.skip_qualifiers();
604 let ty = self.parse_type()?;
605 let kw = if is_const { "let" } else { "var" };
606 loop {
607 let name = self.expect_ident()?;
608 if ty == "bool" {
609 self.bool_vars.insert(name.clone());
610 }
611 let arr_len = if self.eat_punct("[") {
612 let n = if let Some(Tok::Int(s)) = self.peek() {
613 let s = s.clone();
614 self.pos += 1;
615 Some(s)
616 } else {
617 None
618 };
619 self.expect_punct("]")?;
620 n
621 } else {
622 None
623 };
624 if self.eat_punct("=") {
625 if let Some(len) = arr_len {
626 let items = self.parse_brace_init_list()?;
627 out.push_str(&format!(
628 "{pad}{kw} {name}: array<{ty}, {len}> = array<{ty}, {len}>({});\n",
629 items.join(", ")
630 ));
631 } else {
632 let init = self.parse_expr()?;
633 out.push_str(&format!("{pad}{kw} {name}: {ty} = {init};\n"));
634 }
635 } else if let Some(len) = arr_len {
636 out.push_str(&format!("{pad}var {name}: array<{ty}, {len}>;\n"));
637 } else {
638 out.push_str(&format!("{pad}var {name}: {ty};\n"));
639 }
640 if !self.eat_punct(",") {
641 break;
642 }
643 }
644 self.expect_punct(";")?;
645 Ok(())
646 }
647
648 fn parse_single_var_decl_inline(&mut self) -> Result<String, String> {
649 let _ = self.skip_qualifiers();
650 let ty = self.parse_type()?;
651 let name = self.expect_ident()?;
652 let res = if self.eat_punct("=") {
653 let init = self.parse_expr()?;
654 format!("var {name}: {ty} = {init}")
655 } else {
656 format!("var {name}: {ty}")
657 };
658 self.expect_punct(";")?;
659 Ok(res)
660 }
661
662 fn parse_expr_stmt_inline(&mut self) -> Result<String, String> {
663 // Handle prefix `++x` / `--x` as statement -> `x += 1` / `x -= 1`
664 if self.eat_punct("++") {
665 let lhs = self.parse_unary()?;
666 return Ok(format!("{lhs} += 1"));
667 }
668 if self.eat_punct("--") {
669 let lhs = self.parse_unary()?;
670 return Ok(format!("{lhs} -= 1"));
671 }
672 let lhs = self.parse_expr()?;
673 if self.eat_punct("++") {
674 return Ok(format!("{lhs} += 1"));
675 }
676 if self.eat_punct("--") {
677 return Ok(format!("{lhs} -= 1"));
678 }
679 Ok(lhs)
680 }
681
682 fn parse_brace_init_list(&mut self) -> Result<Vec<String>, String> {
683 self.expect_punct("{")?;
684 let mut items = Vec::new();
685 while !self.is_punct("}") && self.pos < self.toks.len() {
686 items.push(self.parse_expr()?);
687 if !self.eat_punct(",") {
688 break;
689 }
690 }
691 self.expect_punct("}")?;
692 Ok(items)
693 }
694
695}