alpha2-render 0.6.1

Render graph and effect registry for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! Worst-case GPU cost of one runtime effect invocation.
//!
//! [`crate::loop_bound`] and [`crate::call_budget`] bound an effect's shape, not its work: 1024
//! iterations of texture reads and transcendentals fit in a few hundred bytes yet take seconds
//! per frame. This counts texture reads, transcendental calls and other operators per pixel.
//!
//! The count is an upper bound. All loops of an invocation share one budget of
//! [`MAX_LOOP_ITERATIONS`] iterations, so the cost is the costliest function's straight-line
//! code plus the budget spent on the costliest iterations. A nested loop body is its own
//! iteration; calls are inlined; both branch sides count.
//!
//! A loop is assumed to use the whole remaining budget unless it has a
//! [`crate::loop_bound::proven_count`] (`for (var i = 0u; i < 64u; i++)`), which the rewrite
//! enforces, and runs at most once per call (not nested, function not called from a loop).

use crate::ShaderDiagnostics;
use crate::call_budget::{declarations, declared_names, loops};
use crate::loop_bound::{MAX_LOOP_ITERATIONS, header_parts, is_identifier_byte, proven_count};

// Timed on discrete and integrated GPUs from three vendors, predictions moved by under 10% when
// these weights changed up to 8x; tap and iteration counts dominate. Arithmetic keeps a nonzero
// weight so compute-only effects are not priced at zero.
/// Units of one texture read.
pub(crate) const FETCH_UNITS: u64 = 4;
/// Units of one transcendental call.
pub(crate) const TRANSCENDENTAL_UNITS: u64 = 2;
/// Units of any other operator or call.
pub(crate) const ARITHMETIC_UNITS: u64 = 1;

/// Most units one runtime effect invocation may cost.
///
/// At the cap, an 8K frame on the slowest integrated GPU measured, split into
/// [`crate::submission_planner::MAX_BANDS`] bands, keeps each band under half the watchdog.
pub(crate) const MAX_INVOCATION_COST: u64 = 1_048_576;

/// WGSL built-ins counted as transcendental calls.
const TRANSCENDENTALS: [&str; 17] = [
    "sin",
    "cos",
    "tan",
    "asin",
    "acos",
    "atan",
    "atan2",
    "sinh",
    "cosh",
    "tanh",
    "exp",
    "exp2",
    "log",
    "log2",
    "pow",
    "sqrt",
    "inverseSqrt",
];

/// Words followed by a parenthesis that are not calls.
const KEYWORDS: [&str; 6] = ["if", "for", "while", "switch", "return", "loop"];

/// Worst-case work of one invocation (one pixel).
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct EffectCost {
    /// Texture reads: wrapper `sample_*`, `from_color`, `to_color`, and `textureSample*`,
    /// `textureGather*`, `textureLoad`.
    pub(crate) fetches: u64,
    /// Transcendental built-in calls ([`TRANSCENDENTALS`]).
    pub(crate) transcendentals: u64,
    /// Every other operator and call.
    pub(crate) arithmetic: u64,
}

impl EffectCost {
    /// An engine-declared pass cost, assuming about four operators per read or call.
    pub(crate) const fn fixed(fetches: u64, transcendentals: u64) -> Self {
        Self {
            fetches,
            transcendentals,
            arithmetic: 4 * (fetches + transcendentals),
        }
    }

    /// Weighted sum used by predictions and the registration cap.
    pub(crate) const fn units(self) -> u64 {
        self.fetches
            .saturating_mul(FETCH_UNITS)
            .saturating_add(self.transcendentals.saturating_mul(TRANSCENDENTAL_UNITS))
            .saturating_add(self.arithmetic.saturating_mul(ARITHMETIC_UNITS))
    }

    const fn plus(self, other: Self) -> Self {
        Self {
            fetches: self.fetches.saturating_add(other.fetches),
            transcendentals: self.transcendentals.saturating_add(other.transcendentals),
            arithmetic: self.arithmetic.saturating_add(other.arithmetic),
        }
    }

    pub(crate) const fn times(self, count: u64) -> Self {
        Self {
            fetches: self.fetches.saturating_mul(count),
            transcendentals: self.transcendentals.saturating_mul(count),
            arithmetic: self.arithmetic.saturating_mul(count),
        }
    }

    fn costlier(self, other: Self) -> Self {
        if other.units() > self.units() {
            other
        } else {
            self
        }
    }
}

#[derive(Copy, Clone)]
enum Item {
    Cost(EffectCost),
    /// A call of the declared function with this index.
    Call(usize),
}

/// One function's tokens outside loops, and per loop the tokens of one iteration.
struct Walked {
    straight: Vec<Item>,
    loops: Vec<Loop>,
}

struct Loop {
    items: Vec<Item>,
    /// Iterations per call when provable and not nested.
    count: Option<u64>,
}

/// Worst-case cost of `code`, a comment-blanked body that passed [`crate::loop_bound`] and
/// [`crate::call_budget`]. A refused call cycle counts its callee as zero.
pub(crate) fn invocation_cost(code: &str) -> EffectCost {
    let declared = declarations(code);
    let names = declared_names(&declared);
    let arrays = array_types(code);
    let copies = array_names(code, &arrays);
    let walked = declared
        .iter()
        .map(|(_, body)| walk(code, body.clone(), &names, &arrays, &copies))
        .collect::<Vec<_>>();
    // A module-scope private array is zeroed in every invocation.
    let module_arrays = arrays
        .iter()
        .filter(|array| {
            !declared
                .iter()
                .any(|(_, body)| body.contains(&array.span.start))
        })
        .fold(0_u64, |total, array| {
            total.saturating_add(array.slots.unwrap_or(0))
        });
    let straight = straight_costs(&walked);
    let calls = straight_calls(&walked, &roots(&walked));
    let resolve = |items: &[Item]| {
        items.iter().fold(EffectCost::default(), |total, item| {
            total.plus(match *item {
                Item::Cost(cost) => cost,
                Item::Call(callee) => straight[callee],
            })
        })
    };
    let roots = roots(&walked);
    let entry = straight
        .iter()
        .zip(&roots)
        .filter(|(_, root)| **root)
        .fold(EffectCost::default(), |worst, (&cost, _)| {
            worst.costlier(cost)
        });
    let mut iterations = walked
        .iter()
        .zip(&calls)
        .flat_map(|(function, calls)| {
            function.loops.iter().map(move |body| {
                let most = match (body.count, calls) {
                    (Some(count), Some(calls)) => count.saturating_mul(*calls),
                    _ => u64::MAX,
                };
                (resolve(&body.items), most)
            })
        })
        .collect::<Vec<_>>();
    iterations.sort_by_key(|(cost, _)| std::cmp::Reverse(cost.units()));
    let mut budget = u64::from(MAX_LOOP_ITERATIONS);
    let mut total = entry.plus(EffectCost {
        arithmetic: module_arrays,
        ..EffectCost::default()
    });
    for (cost, most) in iterations {
        let spent = budget.min(most);
        total = total.plus(cost.times(spent));
        budget -= spent;
    }
    total
}

/// Functions no other function calls (all of them when calls form a cycle).
fn roots(walked: &[Walked]) -> Vec<bool> {
    let mut called = vec![false; walked.len()];
    for function in walked {
        let items = function
            .straight
            .iter()
            .chain(function.loops.iter().flat_map(|body| body.items.iter()));
        for item in items {
            if let Item::Call(callee) = item {
                called[*callee] = true;
            }
        }
    }
    if called.iter().all(|called| *called) {
        return vec![true; walked.len()];
    }
    called.into_iter().map(|called| !called).collect()
}

/// Max runs per invocation of each function (roots once); `None` if reachable from a loop.
fn straight_calls(walked: &[Walked], roots: &[bool]) -> Vec<Option<u64>> {
    let mut in_loop = vec![false; walked.len()];
    for function in walked {
        for body in &function.loops {
            for item in &body.items {
                if let Item::Call(callee) = item {
                    in_loop[*callee] = true;
                }
            }
        }
    }
    // A function called straight-line from one in a loop also runs in a loop.
    let mut changed = true;
    while changed {
        changed = false;
        for (caller, function) in walked.iter().enumerate() {
            if !in_loop[caller] {
                continue;
            }
            for item in &function.straight {
                if let Item::Call(callee) = item
                    && !in_loop[*callee]
                {
                    in_loop[*callee] = true;
                    changed = true;
                }
            }
        }
    }
    // Without cycles this settles within one round per function; a cycle stops counting, and its
    // loops still share the budget.
    let base = roots
        .iter()
        .map(|root| u64::from(*root))
        .collect::<Vec<_>>();
    let mut runs = base.clone();
    for _ in 0..walked.len() {
        let mut next = base.clone();
        for (caller, function) in walked.iter().enumerate() {
            for item in &function.straight {
                if let Item::Call(callee) = item {
                    next[*callee] = next[*callee].saturating_add(runs[caller]);
                }
            }
        }
        if next == runs {
            break;
        }
        runs = next;
    }
    runs.into_iter()
        .zip(in_loop)
        .map(|(runs, in_loop)| (!in_loop).then_some(runs))
        .collect()
}

/// Refuses a body whose invocation may cost more than [`MAX_INVOCATION_COST`].
///
/// # Errors
/// Diagnostics naming the reads, transcendental calls and units.
pub(crate) fn check_invocation_cost(code: &str) -> Result<EffectCost, ShaderDiagnostics> {
    let cost = invocation_cost(code);
    let units = cost.units();
    if units > MAX_INVOCATION_COST {
        return Err(ShaderDiagnostics::error(format!(
            "the effect may spend {} texture reads and {} transcendental calls per pixel \
             ({units} units), above the {MAX_INVOCATION_COST} a runtime effect may; read fewer \
             taps per loop iteration or loop fewer times",
            cost.fetches, cost.transcendentals
        )));
    }
    Ok(cost)
}

/// Each function's straight-line cost with its calls inlined, callees first.
fn straight_costs(walked: &[Walked]) -> Vec<EffectCost> {
    let mut cost: Vec<Option<EffectCost>> = vec![None; walked.len()];
    let mut open = vec![false; walked.len()];
    let calls = |function: usize| {
        walked[function]
            .straight
            .iter()
            .filter_map(|item| match item {
                Item::Call(callee) => Some(*callee),
                Item::Cost(_) => None,
            })
            .collect::<Vec<_>>()
    };
    // Iterative so long call chains do not recurse deeply.
    for root in 0..walked.len() {
        if cost[root].is_some() {
            continue;
        }
        let mut stack = vec![(root, calls(root), 0_usize)];
        open[root] = true;
        while let Some((function, callees, next)) = stack.last_mut() {
            if let Some(&callee) = callees.get(*next) {
                *next += 1;
                if cost[callee].is_none() && !open[callee] {
                    open[callee] = true;
                    let callee_calls = calls(callee);
                    stack.push((callee, callee_calls, 0));
                }
                continue;
            }
            let function = *function;
            let total =
                walked[function]
                    .straight
                    .iter()
                    .fold(EffectCost::default(), |total, item| {
                        total.plus(match *item {
                            Item::Cost(cost) => cost,
                            Item::Call(callee) => cost[callee].unwrap_or_default(),
                        })
                    });
            cost[function] = Some(total);
            open[function] = false;
            stack.pop();
        }
    }
    cost.into_iter().map(Option::unwrap_or_default).collect()
}

/// Sorts a function body's tokens into its straight line and their innermost loop.
fn walk(
    code: &str,
    body: std::ops::Range<usize>,
    names: &std::collections::HashMap<&str, usize>,
    arrays: &[ArrayType],
    copies: &std::collections::HashMap<&str, u64>,
) -> Walked {
    let spans = loops(code, body.clone());
    let mut walked = Walked {
        straight: Vec::new(),
        loops: spans
            .iter()
            .map(|span| Loop {
                items: Vec::new(),
                count: (!spans
                    .iter()
                    .any(|outer| outer.start < span.start && outer.contains(&span.start)))
                .then(|| literal_count(code, span.clone()))
                .flatten(),
            })
            .collect(),
    };
    let bytes = code.as_bytes();
    let mut push = |at: usize, item: Item| {
        // The loop starting last among those containing `at` is the innermost.
        let innermost = spans
            .iter()
            .enumerate()
            .filter(|(_, span)| span.contains(&at))
            .max_by_key(|(_, span)| span.start)
            .map(|(index, _)| index);
        match innermost {
            Some(index) => walked.loops[index].items.push(item),
            None => walked.straight.push(item),
        }
    };
    let charge = |slots: u64| {
        Item::Cost(EffectCost {
            arithmetic: slots,
            ..EffectCost::default()
        })
    };
    let mut index = body.start;
    while index < body.end {
        let byte = bytes[index];
        if is_identifier_byte(byte) {
            let end = index
                + code[index..body.end]
                    .bytes()
                    .take_while(|&byte| is_identifier_byte(byte))
                    .count();
            let word = &code[index..end];
            // Declaring, building or copying a whole array touches every element.
            if let Some(array) = arrays.iter().find(|array| array.span.start == index) {
                push(index, charge(array.slots.unwrap_or(0)));
                index = array.span.end.min(body.end);
                continue;
            }
            if let Some(&slots) = copies.get(word)
                && !code[end..body.end].trim_start().starts_with(['[', ':'])
            {
                push(index, charge(slots));
            }
            let called = code[end..body.end].trim_start().starts_with('(');
            if called && !KEYWORDS.contains(&word) && !byte.is_ascii_digit() {
                push(
                    index,
                    names
                        .get(word)
                        .map_or_else(|| Item::Cost(call_cost(word)), |&callee| Item::Call(callee)),
                );
            }
            index = end;
        } else if is_operator(byte) {
            let end = index
                + code[index..body.end]
                    .bytes()
                    .take_while(|&byte| is_operator(byte))
                    .count();
            // A plain assignment computes nothing.
            if &code[index..end] != "=" {
                push(
                    index,
                    Item::Cost(EffectCost {
                        arithmetic: 1,
                        ..EffectCost::default()
                    }),
                );
            }
            index = end;
        } else {
            index += 1;
        }
    }
    walked
}

/// The [`proven_count`] of the loop at `span`.
fn literal_count(code: &str, span: std::ops::Range<usize>) -> Option<u64> {
    let open = span.start + code[span.clone()].find('(')?;
    let close = crate::loop_bound::matching(code, open).ok()?;
    let [init, condition, update] = header_parts(&code[open + 1..close])?;
    let body = &code[close + 1..span.end];
    proven_count(init, condition, update, body.trim_start())
}

/// One `array` in a body's code.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArrayType {
    /// Byte range of `array` and its template list.
    pub(crate) span: std::ops::Range<usize>,
    /// Elements as `vec4f`-sized slots, counts multiplied through nested arrays; `None` without
    /// a literal count or with an element type that is not a scalar, vector, matrix or array.
    pub(crate) slots: Option<u64>,
    /// Whether it has a template list (`array(...)` infers its count from the arguments).
    pub(crate) templated: bool,
}

/// Every `array` in `code`, a comment-blanked body.
pub(crate) fn array_types(code: &str) -> Vec<ArrayType> {
    let mut found = Vec::new();
    let mut from = 0;
    while let Some(start) = crate::loop_bound::find_keyword(code, from, "array") {
        from = start + "array".len();
        let open = from + (code[from..].len() - code[from..].trim_start().len());
        if code.as_bytes().get(open) != Some(&b'<') {
            found.push(ArrayType {
                span: start..from,
                slots: None,
                templated: false,
            });
            continue;
        }
        let Some(close) = template_end(code, open) else {
            found.push(ArrayType {
                span: start..code.len(),
                slots: None,
                templated: true,
            });
            continue;
        };
        found.push(ArrayType {
            span: start..close + 1,
            slots: array_slots(&code[open + 1..close]),
            templated: true,
        });
    }
    found
}

/// Index of the `>` closing the template list opened at `open`.
fn template_end(code: &str, open: usize) -> Option<usize> {
    let mut depth = 0_usize;
    for (index, byte) in code.bytes().enumerate().skip(open) {
        match byte {
            b'<' => depth += 1,
            b'>' => {
                depth -= 1;
                if depth == 0 {
                    return Some(index);
                }
            }
            b';' | b'{' | b'}' => return None,
            _ => {}
        }
    }
    None
}

/// Slots of `array<template>`: the literal count times the element type's slots.
fn array_slots(template: &str) -> Option<u64> {
    let mut depth = 0_usize;
    let comma = template.bytes().enumerate().find_map(|(index, byte)| {
        match byte {
            b'<' | b'(' => depth += 1,
            b'>' | b')' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => return Some(index),
            _ => {}
        }
        None
    })?;
    let element = template[..comma].trim();
    let count = template[comma + 1..].trim();
    let count = count.strip_suffix(['u', 'i']).unwrap_or(count);
    if count.is_empty() || !count.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    count
        .parse::<u64>()
        .ok()?
        .checked_mul(element_slots(element)?)
}

/// `vec4f`-sized slots of one element: 1 for a scalar or vector, its columns for a matrix.
fn element_slots(element: &str) -> Option<u64> {
    if let Some(rest) = element.strip_prefix("array") {
        let open = element.len() - rest.trim_start().len();
        let close = template_end(element, open)?;
        return (close + 1 == element.len())
            .then(|| array_slots(&element[open + 1..close]))
            .flatten();
    }
    let name = element.split('<').next().unwrap_or_default().trim();
    if matches!(name, "f32" | "f16" | "i32" | "u32" | "bool")
        || ["vec2", "vec3", "vec4"].iter().any(|vector| {
            name.strip_prefix(vector)
                .is_some_and(|suffix| matches!(suffix, "" | "f" | "h" | "i" | "u"))
        })
    {
        return Some(1);
    }
    let columns = name.strip_prefix("mat")?.bytes().next()?;
    let shape = &name[3..];
    let valid = shape.len() >= 3
        && matches!(shape.as_bytes()[1], b'x')
        && matches!(shape.as_bytes()[2], b'2'..=b'4')
        && matches!(&shape[3..], "" | "f" | "h");
    (valid && matches!(columns, b'2'..=b'4')).then(|| u64::from(columns - b'0'))
}

/// Names declared with an array type or array value, with their slots.
fn array_names<'a>(code: &'a str, arrays: &[ArrayType]) -> std::collections::HashMap<&'a str, u64> {
    let mut names = std::collections::HashMap::new();
    for array in arrays {
        let Some(slots) = array.slots else { continue };
        let before = code[..array.span.start].trim_end();
        let Some(before) = before.strip_suffix(':').or_else(|| {
            before
                .strip_suffix('=')
                .filter(|rest| !rest.ends_with(['=', '!', '<', '>']))
        }) else {
            continue;
        };
        let before = before.trim_end();
        let name_start = before
            .bytes()
            .rposition(|byte| !is_identifier_byte(byte))
            .map_or(0, |index| index + 1);
        let name = &before[name_start..];
        if !name.is_empty() {
            let held = names.entry(name).or_insert(0);
            *held = slots.max(*held);
        }
    }
    names
}

/// Cost of a call to an undeclared `name` (wrapper helper or WGSL built-in).
fn call_cost(name: &str) -> EffectCost {
    let fetch = name.starts_with("sample_")
        || name.starts_with("textureSample")
        || name.starts_with("textureGather")
        || matches!(name, "from_color" | "to_color" | "textureLoad");
    if fetch {
        EffectCost {
            fetches: 1,
            ..EffectCost::default()
        }
    } else if TRANSCENDENTALS.contains(&name) {
        EffectCost {
            transcendentals: 1,
            ..EffectCost::default()
        }
    } else {
        EffectCost {
            arithmetic: 1,
            ..EffectCost::default()
        }
    }
}

const fn is_operator(byte: u8) -> bool {
    matches!(
        byte,
        b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' | b'!' | b'<' | b'>' | b'=' | b'~'
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::loop_bound::blank_comments;

    fn cost(body: &str) -> EffectCost {
        invocation_cost(&blank_comments(body))
    }

    #[test]
    fn loop_budget_bounds_the_costliest_iteration() {
        // The budget goes to the costlier body regardless of each loop's own bound.
        let body = "fn effect(uv: vec2f, src: vec4f) -> vec4f {\n\
                        var a = src;\n\
                        for (var i = 0u; i < n; i++) { a = a * sample_src(uv); }\n\
                        for (var j = 0u; j < n; j++) { a = sin(a); }\n\
                        return a; }";
        let worst = cost(body);
        assert_eq!(
            worst,
            EffectCost {
                fetches: 1024,
                transcendentals: 0,
                arithmetic: 3 * 1024,
            }
        );
        assert_eq!(worst.units(), 1024 * (4 + 3));
    }

    #[test]
    fn nested_loops_share_the_budget() {
        let body = "fn effect(uv: vec2f, src: vec4f) -> vec4f {\n\
                        var a = 0.0;\n\
                        for (var i = 0u; i < 32u; i++) {\n\
                            a += 1.0;\n\
                            for (var j = 0u; j < 32u; j++) { a += cos(a) + sample_src(uv).r; }\n\
                        }\n\
                        return vec4f(a); }";
        let worst = cost(body);
        assert_eq!(
            worst,
            EffectCost {
                fetches: 1024,
                transcendentals: 1024,
                arithmetic: 4 * 1024 + 1,
            }
        );
    }

    #[test]
    fn a_literal_count_caps_its_loop_and_leaves_the_budget_to_others() {
        let body = "fn effect(uv: vec2f, src: vec4f) -> vec4f {\n\
                        var a = src;\n\
                        for (var i = 0u; i < 64u; i++) { a = a * sample_src(uv); }\n\
                        for (var j = 0; j < n; j++) { a = a + 1.0; }\n\
                        return a; }";
        let worst = cost(body);
        assert_eq!(worst.fetches, 64);
        assert_eq!(worst.arithmetic, 64 * 3 + 960 * 3);
        // A written counter, a nested loop, or a loop reached from a loop uses the whole budget.
        for body in [
            "fn effect(uv: vec2f, src: vec4f) -> vec4f { var a = src; \
             for (var i = 0u; i < 64u; i++) { a = sample_src(uv); i = 0u; } return a; }",
            "fn effect(uv: vec2f, src: vec4f) -> vec4f { var a = src; \
             for (var k = 0u; k < n; k++) { \
             for (var i = 0u; i < 4u; i++) { a = sample_src(uv); } } return a; }",
            "fn taps(uv: vec2f) -> vec4f { var a = vec4f(0.0); \
             for (var i = 0u; i < 4u; i++) { a = sample_src(uv); } return a; }\n\
             fn effect(uv: vec2f, src: vec4f) -> vec4f { var a = src; \
             for (var k = 0u; k < n; k++) { a = taps(uv); } return a; }",
        ] {
            assert_eq!(cost(body).fetches, 1024, "{body}");
        }
        // A function called twice runs its counted loop twice.
        let twice = "fn taps(uv: vec2f) -> vec4f { var a = vec4f(0.0); \
                     for (var i = 0u; i <= 9u; i++) { a = sample_src(uv); } return a; }\n\
                     fn effect(uv: vec2f, src: vec4f) -> vec4f { return taps(uv) + taps(uv); }";
        assert_eq!(cost(twice).fetches, 20);
    }

    #[test]
    fn a_counted_loop_is_priced_at_its_literal_count_however_its_counter_is_written() {
        for (header, write, count) in [
            ("var i = 0u; i < 8u; i++", "(i)--;", 8),
            ("var i = 0u; i < 8u; i++", "(i) -= 1u;", 8),
            ("var i = 0u; i < 2u; i++", "(i) = 0u;", 2),
            ("var i = 0u; i < 2u; i++", "*(&(i)) = 0u;", 2),
            ("var i = 0u; i < 2u; i++", "let p = &(i); *p = 0u;", 2),
            ("var i = 4294967295u; i <= 4294967295u; i++", "", 1),
            ("var i = 2147483647; i <= 2147483647; i++", "", 1),
        ] {
            let body = format!(
                "fn effect(uv: vec2f, src: vec4f) -> vec4f {{ var a = src; \
                 for ({header}) {{ {write} a = a * sample_src(uv); }} return a; }}"
            );
            assert_eq!(cost(&body).fetches, count, "{body}");
        }
    }

    #[test]
    fn declaring_and_copying_a_whole_array_costs_its_elements() {
        let copy = "fn effect(uv: vec2f, src: vec4f) -> vec4f { \
                    var a: array<vec4f, 100>; var b: array<vec4f, 100>; \
                    for (var i = 0u; i < n; i++) { b = a; } return b[0]; }";
        let worst = cost(copy);
        // Two zeroed declarations and the copy (both names) per iteration; `b[0]` reads one.
        assert!(worst.arithmetic >= 200 + 1024 * 200, "{worst:?}");
        let private = "var<private> big: array<vec4f, 100>;\n\
                       fn effect(uv: vec2f, src: vec4f) -> vec4f { return big[0] + src; }";
        assert!(cost(private).arithmetic >= 100);
        let indexed = "fn effect(uv: vec2f, src: vec4f) -> vec4f { \
                       var a: array<vec4f, 100>; return a[1]; }";
        assert!(cost(indexed).arithmetic < 110, "{:?}", cost(indexed));
    }

    #[test]
    fn helpers_count_as_fetches() {
        let body = "fn helper(uv: vec2f) -> vec4f { return sample_src(uv) + from_color(uv); }\n\
                    fn effect(uv: vec2f, src: vec4f) -> vec4f {\n\
                        let t = to_color(uv) + sample_mask(uv) + textureLoad(x, vec2i(0), 0);\n\
                        return helper(uv) * exp(t); }";
        let worst = cost(body);
        assert_eq!(worst.fetches, 5);
        assert_eq!(worst.transcendentals, 1);
        assert_eq!(worst.arithmetic, 5);
    }

    #[test]
    fn a_call_in_a_loop_is_inlined_into_the_iteration() {
        let body = "fn tap(uv: vec2f) -> vec4f { return sample_src(uv) * 2.0; }\n\
                    fn effect(uv: vec2f, src: vec4f) -> vec4f {\n\
                        var a = vec4f(0.0);\n\
                        for (var i = 0u; i < n; i++) { a += tap(uv); }\n\
                        return a; }";
        let worst = cost(body);
        assert_eq!(worst.fetches, 1024);
        assert_eq!(worst.arithmetic, 4 * 1024 + 1);
    }

    #[test]
    fn every_built_in_fits_the_cost_cap_with_room() {
        let mut definitions = crate::builtins::internal_effect_definitions();
        definitions.extend(crate::builtin_effect_definitions());
        definitions.extend(crate::builtin_transition_definitions());
        let (units, id) = definitions
            .iter()
            .map(|definition| {
                let units = invocation_cost(&blank_comments(&definition.wgsl_body)).units();
                (units, definition.id.clone())
            })
            .max()
            .expect("built-ins");
        assert!(
            units.saturating_mul(4) <= MAX_INVOCATION_COST,
            "{id} costs {units} units"
        );
    }

    #[test]
    fn the_max_fixture_is_refused_with_a_diagnostic_naming_its_cost() {
        let fixture = std::fs::read_to_string(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/cases/gpu-watchdog/max-effects.json"
        ))
        .expect("the max fixture");
        let effects: serde_json::Value = serde_json::from_str(&fixture).expect("JSON");
        let body = effects[0]["wgslBody"].as_str().expect("a WGSL body");
        let error = check_invocation_cost(&blank_comments(body)).expect_err("refused");
        let message = format!("{error:?}");
        let cost = invocation_cost(&blank_comments(body));
        assert!(
            message.contains(&format!("{} texture reads", cost.fetches))
                && message.contains(&format!("{} transcendental calls", cost.transcendentals))
                && message.contains(&format!("({} units)", cost.units())),
            "{message}"
        );
    }
}