1//! DCTL expression parser and intrinsic-to-WGSL rewriter.
2
3use super::dctl::Tok;
4use super::dctl_parse::Transpiler;
5
6impl Transpiler {
7 // -----------------------------------------------------------------------
8 // Expressions
9 // -----------------------------------------------------------------------
10
11 fn looks_boolean(&self, expr: &str) -> bool {
12 let t = expr.trim();
13 if t == "true" || t == "false" || self.bool_vars.contains(t) {
14 return true;
15 }
16 if t.starts_with('!') {
17 return true;
18 }
19 // Check top-level (paren-depth 0) comparison or logical operator
20 let b = t.as_bytes();
21 let mut depth = 0i32;
22 let mut i = 0;
23 while i < b.len() {
24 match b[i] {
25 b'(' | b'[' => depth += 1,
26 b')' | b']' => depth -= 1,
27 _ if depth == 0 => {
28 if i + 1 < b.len() {
29 let two = &t[i..i + 2];
30 if matches!(two, "==" | "!=" | "<=" | ">=" | "&&" | "||") {
31 return true;
32 }
33 }
34 if matches!(b[i], b'<' | b'>') {
35 // Avoid matching `<f32>` inside `vec3<f32>`
36 let prev_alpha = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_');
37 if !prev_alpha || b[i] == b'>' {
38 if b[i] == b'<' && !prev_alpha {
39 return true;
40 }
41 if b[i] == b'>' && !t[..i].ends_with("f32") && !t[..i].ends_with("i32") && !t[..i].ends_with("u32") {
42 return true;
43 }
44 }
45 }
46 }
47 _ => {}
48 }
49 i += 1;
50 }
51 // Unwrap outer parentheses and check recursively
52 if t.starts_with('(') && t.ends_with(')') {
53 let mut d = 0i32;
54 let mut wraps_all = true;
55 for (idx, &ch) in b.iter().enumerate() {
56 if ch == b'(' {
57 d += 1;
58 } else if ch == b')' {
59 d -= 1;
60 if d == 0 && idx + 1 < b.len() {
61 wraps_all = false;
62 break;
63 }
64 }
65 }
66 if wraps_all {
67 return self.looks_boolean(&t[1..t.len() - 1]);
68 }
69 }
70 false
71 }
72
73 pub(super) fn parse_bool_expr(&mut self) -> Result<String, String> {
74 let e = self.parse_expr()?;
75 if self.looks_boolean(&e) {
76 Ok(e)
77 } else {
78 Ok(format!("(({e}) != 0)"))
79 }
80 }
81
82 pub(super) fn parse_expr(&mut self) -> Result<String, String> {
83 self.parse_assign()
84 }
85
86 fn parse_assign(&mut self) -> Result<String, String> {
87 let lhs = self.parse_ternary()?;
88 for op in ["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^="] {
89 if self.eat_punct(op) {
90 let rhs = self.parse_assign()?;
91 return Ok(format!("{lhs} {op} {rhs}"));
92 }
93 }
94 Ok(lhs)
95 }
96
97 fn parse_ternary(&mut self) -> Result<String, String> {
98 let cond = self.parse_logical_or()?;
99 if self.eat_punct("?") {
100 let then_e = self.parse_expr()?;
101 self.expect_punct(":")?;
102 let else_e = self.parse_ternary()?;
103 let bcond = if self.looks_boolean(&cond) {
104 cond
105 } else {
106 format!("(({cond}) != 0)")
107 };
108 Ok(format!("select({else_e}, {then_e}, {bcond})"))
109 } else {
110 Ok(cond)
111 }
112 }
113
114 fn parse_logical_or(&mut self) -> Result<String, String> {
115 let mut lhs = self.parse_logical_and()?;
116 while self.eat_punct("||") {
117 let rhs = self.parse_logical_and()?;
118 lhs = format!("({lhs} || {rhs})");
119 }
120 Ok(lhs)
121 }
122
123 fn parse_logical_and(&mut self) -> Result<String, String> {
124 let mut lhs = self.parse_bit_or()?;
125 while self.eat_punct("&&") {
126 let rhs = self.parse_bit_or()?;
127 lhs = format!("({lhs} && {rhs})");
128 }
129 Ok(lhs)
130 }
131
132 fn parse_bit_or(&mut self) -> Result<String, String> {
133 let mut lhs = self.parse_bit_xor()?;
134 while self.eat_punct("|") {
135 let rhs = self.parse_bit_xor()?;
136 lhs = format!("({lhs} | {rhs})");
137 }
138 Ok(lhs)
139 }
140
141 fn parse_bit_xor(&mut self) -> Result<String, String> {
142 let mut lhs = self.parse_bit_and()?;
143 while self.eat_punct("^") {
144 let rhs = self.parse_bit_and()?;
145 lhs = format!("({lhs} ^ {rhs})");
146 }
147 Ok(lhs)
148 }
149
150 fn parse_bit_and(&mut self) -> Result<String, String> {
151 let mut lhs = self.parse_eq()?;
152 while self.eat_punct("&") {
153 let rhs = self.parse_eq()?;
154 lhs = format!("({lhs} & {rhs})");
155 }
156 Ok(lhs)
157 }
158
159 fn parse_eq(&mut self) -> Result<String, String> {
160 let mut lhs = self.parse_rel()?;
161 loop {
162 if self.eat_punct("==") {
163 let rhs = self.parse_rel()?;
164 lhs = format!("({lhs} == {rhs})");
165 } else if self.eat_punct("!=") {
166 let rhs = self.parse_rel()?;
167 lhs = format!("({lhs} != {rhs})");
168 } else {
169 break;
170 }
171 }
172 Ok(lhs)
173 }
174
175 fn parse_rel(&mut self) -> Result<String, String> {
176 let mut lhs = self.parse_shift()?;
177 loop {
178 let op = if self.eat_punct("<=") {
179 "<="
180 } else if self.eat_punct(">=") {
181 ">="
182 } else if self.eat_punct("<") {
183 "<"
184 } else if self.eat_punct(">") {
185 ">"
186 } else {
187 break;
188 };
189 let rhs = self.parse_shift()?;
190 lhs = format!("({lhs} {op} {rhs})");
191 }
192 Ok(lhs)
193 }
194
195 fn parse_shift(&mut self) -> Result<String, String> {
196 let mut lhs = self.parse_add()?;
197 loop {
198 let op = if self.eat_punct("<<") {
199 "<<"
200 } else if self.eat_punct(">>") {
201 ">>"
202 } else {
203 break;
204 };
205 let rhs = self.parse_add()?;
206 lhs = format!("({lhs} {op} {rhs})");
207 }
208 Ok(lhs)
209 }
210
211 fn parse_add(&mut self) -> Result<String, String> {
212 let mut lhs = self.parse_mul()?;
213 loop {
214 let op = if self.eat_punct("+") {
215 "+"
216 } else if self.eat_punct("-") {
217 "-"
218 } else {
219 break;
220 };
221 let rhs = self.parse_mul()?;
222 lhs = format!("({lhs} {op} {rhs})");
223 }
224 Ok(lhs)
225 }
226
227 fn parse_mul(&mut self) -> Result<String, String> {
228 let mut lhs = self.parse_unary()?;
229 loop {
230 let op = if self.eat_punct("*") {
231 "*"
232 } else if self.eat_punct("/") {
233 "/"
234 } else if self.eat_punct("%") {
235 "%"
236 } else {
237 break;
238 };
239 let rhs = self.parse_unary()?;
240 lhs = format!("({lhs} {op} {rhs})");
241 }
242 Ok(lhs)
243 }
244
245 fn try_parse_c_cast(&mut self) -> Option<String> {
246 if !self.is_punct("(") {
247 return None;
248 }
249 let (ty, consumed) = self.peek_type_at(self.pos + 1)?;
250 if matches!(self.toks.get(self.pos + 1 + consumed), Some(Tok::Punct(p)) if p == ")") {
251 self.pos += 2 + consumed;
252 return Some(ty);
253 }
254 None
255 }
256
257 pub(super) fn parse_unary(&mut self) -> Result<String, String> {
258 if let Some(cast_ty) = self.try_parse_c_cast() {
259 let inner = self.parse_unary()?;
260 return Ok(format!("{cast_ty}({inner})"));
261 }
262 if self.eat_punct("-") {
263 let inner = self.parse_unary()?;
264 return Ok(format!("(-{inner})"));
265 }
266 if self.eat_punct("+") {
267 return self.parse_unary();
268 }
269 if self.eat_punct("!") {
270 let inner = self.parse_unary()?;
271 if self.looks_boolean(&inner) {
272 return Ok(format!("(!({inner}))"));
273 }
274 return Ok(format!("(({inner}) == 0)"));
275 }
276 if self.eat_punct("~") {
277 let inner = self.parse_unary()?;
278 return Ok(format!("(~{inner})"));
279 }
280 if self.eat_punct("*") {
281 let inner = self.parse_unary()?;
282 return Ok(format!("(*{inner})"));
283 }
284 if self.eat_punct("&") {
285 let inner = self.parse_unary()?;
286 return Ok(format!("(&{inner})"));
287 }
288 self.parse_postfix()
289 }
290
291 fn parse_postfix(&mut self) -> Result<String, String> {
292 let mut expr = self.parse_primary()?;
293 loop {
294 if self.eat_punct("(") {
295 let mut args = Vec::new();
296 while !self.is_punct(")") && self.pos < self.toks.len() {
297 args.push(self.parse_expr()?);
298 if !self.eat_punct(",") {
299 break;
300 }
301 }
302 self.expect_punct(")")?;
303 expr = rewrite_dctl_call(&expr, &args);
304 } else if self.eat_punct("[") {
305 let idx = self.parse_expr()?;
306 self.expect_punct("]")?;
307 expr = format!("{expr}[{idx}]");
308 } else if self.eat_punct(".") || self.eat_punct("->") {
309 let field = self.expect_ident()?;
310 expr = format!("{expr}.{field}");
311 } else {
312 break;
313 }
314 }
315 Ok(expr)
316 }
317
318 fn parse_primary(&mut self) -> Result<String, String> {
319 match self.bump() {
320 Some(Tok::Float(s)) => Ok(s),
321 Some(Tok::Int(s)) => Ok(s),
322 Some(Tok::Ident(id)) => Ok(match id.as_str() {
323 "M_PI" | "CUDART_PI_F" => "3.141592653589793f".to_owned(),
324 "M_PI_2" => "1.5707963267948966f".to_owned(),
325 "M_PI_4" => "0.7853981633974483f".to_owned(),
326 "M_2PI" | "M_TWOPI" => "6.283185307179586f".to_owned(),
327 "M_1_PI" => "0.3183098861837907f".to_owned(),
328 "M_E" => "2.718281828459045f".to_owned(),
329 "M_SQRT2" => "1.4142135623730951f".to_owned(),
330 _ => id,
331 }),
332 Some(Tok::Punct(p)) if p == "(" => {
333 let inner = self.parse_expr()?;
334 self.expect_punct(")")?;
335 Ok(format!("({inner})"))
336 }
337 other => Err(format!("unexpected token in expression: {other:?}")),
338 }
339 }
340}
341
342fn rewrite_dctl_call(name: &str, args: &[String]) -> String {
343 let a = |i: usize| args.get(i).map(String::as_str).unwrap_or("0.0");
344 match name {
345 // Vector constructors
346 "to_float2" | "make_float2" => match args.len() {
347 1 => format!("vec2<f32>(f32({}))", a(0)),
348 _ => format!("vec2<f32>(f32({}), f32({}))", a(0), a(1)),
349 },
350 "to_float3" | "make_float3" => match args.len() {
351 1 => format!("vec3<f32>(f32({}))", a(0)),
352 2 => format!("vec3<f32>({}, f32({}))", a(0), a(1)),
353 _ => format!("vec3<f32>(f32({}), f32({}), f32({}))", a(0), a(1), a(2)),
354 },
355 "to_float4" | "make_float4" => match args.len() {
356 1 => format!("vec4<f32>(f32({}))", a(0)),
357 2 => format!("vec4<f32>({}, f32({}))", a(0), a(1)),
358 3 => format!("vec4<f32>({}, f32({}), f32({}))", a(0), a(1), a(2)),
359 _ => format!(
360 "vec4<f32>(f32({}), f32({}), f32({}), f32({}))",
361 a(0),
362 a(1),
363 a(2),
364 a(3)
365 ),
366 },
367 "to_float2_s" => format!("vec2<f32>(f32({}))", a(0)),
368 "to_float3_s" => format!("vec3<f32>(f32({}))", a(0)),
369 "to_float4_s" => format!("vec4<f32>(f32({}))", a(0)),
370 "to_float2_v" => format!("vec2<f32>({0}[0], {0}[1])", a(0)),
371 "to_float3_v" => format!("vec3<f32>({0}[0], {0}[1], {0}[2])", a(0)),
372 "to_float4_v" => format!("vec4<f32>({0}[0], {0}[1], {0}[2], {0}[3])", a(0)),
373 "to_float3_aw" => format!("vec3<f32>({}, f32({}))", a(0), a(1)),
374 "to_float4_aw" => format!("vec4<f32>({}, f32({}))", a(0), a(1)),
375 "to_int2" | "make_int2" => format!("vec2<i32>(i32({}), i32({}))", a(0), a(1)),
376 "to_int3" | "make_int3" => format!("vec3<i32>(i32({}), i32({}), i32({}))", a(0), a(1), a(2)),
377 "to_int4" | "make_int4" => format!(
378 "vec4<i32>(i32({}), i32({}), i32({}), i32({}))",
379 a(0),
380 a(1),
381 a(2),
382 a(3)
383 ),
384
385 // Swizzles
386 "swi2" if args.len() == 3 => format!("(({}).{}{})", a(0), a(1), a(2)),
387 "swi3" if args.len() == 4 => format!("(({}).{}{}{})", a(0), a(1), a(2), a(3)),
388 "swi4" if args.len() == 5 => format!("(({}).{}{}{}{})", a(0), a(1), a(2), a(3), a(4)),
389
390 // Texture reads & writes
391 "_tex2DVecN" if args.len() >= 4 => {
392 format!("_dctl_tex2d_n({}, f32({}), f32({}), i32({}))", a(0), a(1), a(2), a(3))
393 }
394 "_tex2DVec4" if args.len() >= 3 => {
395 format!("_dctl_tex2d({}, f32({}), f32({}))", a(0), a(1), a(2))
396 }
397 "_tex2DVec4Write" if args.len() >= 4 => format!(
398 "textureStore({0}, vec2<i32>(i32({1}), i32(textureDimensions({0}).y) - 1 - i32({2})), {3})",
399 a(0),
400 a(1),
401 a(2),
402 a(3)
403 ),
404
405 // Math intrinsics
406 "_sinf" => format!("sin({})", a(0)),
407 "_cosf" => format!("cos({})", a(0)),
408 "_tanf" => format!("tan({})", a(0)),
409 "_asinf" => format!("asin({})", a(0)),
410 "_acosf" => format!("acos({})", a(0)),
411 "_atanf" => format!("atan({})", a(0)),
412 "_atan2f" => format!("atan2({}, {})", a(0), a(1)),
413 "_sinhf" => format!("sinh({})", a(0)),
414 "_coshf" => format!("cosh({})", a(0)),
415 "_tanhf" => format!("tanh({})", a(0)),
416 "_sqrtf" => format!("sqrt(max({}, 0.0))", a(0)),
417 "_rsqrtf" => format!("inverseSqrt(max({}, 1e-12))", a(0)),
418 "_powf" => format!("_dctl_pow({}, {})", a(0), a(1)),
419 "_fabs" | "_fabsf" => format!("abs({})", a(0)),
420 "_fmod" | "_fmodf" => format!("_dctl_fmod({}, {})", a(0), a(1)),
421 "_floorf" | "_floor" => format!("floor({})", a(0)),
422 "_ceilf" | "_ceil" => format!("ceil({})", a(0)),
423 "_round" | "_roundf" => format!("round({})", a(0)),
424 "_truncf" => format!("trunc({})", a(0)),
425 "_fractf" | "_fract" => format!("fract({})", a(0)),
426 "_fminf" => format!("min({}, {})", a(0), a(1)),
427 "_fmaxf" => format!("max({}, {})", a(0), a(1)),
428 "_clampf" => format!("clamp({}, {}, {})", a(0), a(1), a(2)),
429 "_mix" => format!("mix({}, {}, {})", a(0), a(1), a(2)),
430 "_saturatef" => format!("clamp({}, 0.0, 1.0)", a(0)),
431 "_expf" => format!("exp({})", a(0)),
432 "_exp2f" => format!("exp2({})", a(0)),
433 "_logf" => format!("log(max({}, 1e-12))", a(0)),
434 "_log2f" => format!("log2(max({}, 1e-12))", a(0)),
435 "_log10f" => format!("(log(max({}, 1e-12)) * 0.4342944819032518)", a(0)),
436 "_copysignf" => format!("_dctl_copysign({}, {})", a(0), a(1)),
437 "_hypotf" => format!("length(vec2<f32>({}, {}))", a(0), a(1)),
438 "_fdivide" => format!("(({}) / ({}))", a(0), a(1)),
439 "_fmaf" => format!("fma({}, {}, {})", a(0), a(1), a(2)),
440 "_smoothstep" => format!("smoothstep({}, {}, {})", a(0), a(1), a(2)),
441 "_step" => format!("step({}, {})", a(0), a(1)),
442 "_sign" => format!("sign({})", a(0)),
443 _ => format!("{name}({})", args.join(", ")),
444 }
445}
446