1
//! A nested IF compiles without re-walking its test per level: the work is
2
//! bounded quadratically in the depth (ISS-091 owns making it linear).
3

            
4
use crate::compiler::CompileMode;
5
use crate::compiler::behaviour_oracle::{Outcome, observe};
6
use crate::reader::MAX_READ_DEPTH;
7

            
8
const SHAPES: [(&str, &str); 19] = [
9
    ("second operand", "(if (< a {X}) 1 2)"),
10
    ("equality", "(if (= a {X}) 1 2)"),
11
    ("literal first", "(if (< 1 {X}) 1 2)"),
12
    ("progn", "(if (< a (progn {X})) 1 2)"),
13
    ("sum", "(if (< a (+ {X} 1)) 1 2)"),
14
    ("let", "(if (< a (let ((y {X})) y)) 1 2)"),
15
    (
16
        "let progn init",
17
        "(if (< a (let ((y (progn {X} 1))) y)) 1 2)",
18
    ),
19
    ("then arm", "(if (< a 1) {X} 2)"),
20
    ("plain test", "(if (< a 1) 1 {X})"),
21
    ("cond", "(cond ((< a {X}) 1) (t 2))"),
22
    ("cond equality", "(cond ((= a {X}) 1) (t 2))"),
23
    ("cond multi-arm", "(cond ((< a {X}) 1) ((< a 5) 3) (t 2))"),
24
    (
25
        "cond in effect position",
26
        "(progn (cond ((< a {X}) 1) (t 2)) 1)",
27
    ),
28
    ("when", "(when (< a (progn {X} 1)) 1)"),
29
    ("unless", "(unless (< a (progn {X} 1)) 1)"),
30
    ("and", "(and (< a (progn {X} 1)) 1)"),
31
    ("or", "(or (< a (progn {X} 1)) 1)"),
32
    (
33
        "dead operand beside a raising call",
34
        "(handler-case (+ (g) {X}) (t (e) 1))",
35
    ),
36
    (
37
        "dead LET init beside a raising call",
38
        "(let ((v (handler-case (progn (g) {X}) (t (e) 1)))) v)",
39
    ),
40
];
41

            
42
83
fn nested(shape: &str, depth: usize) -> String {
43
83
    let mut form = shape.replace("{X}", "1");
44
83
    for _ in 1..depth {
45
510
        form = shape.replace("{X}", &form);
46
    }
47
83
    format!("(defun g () (error 'x \"m\")) (let ((a (progn (print \"\") 1))) {form})")
48
83
}
49

            
50
83
fn work(shape: &str, depth: usize) -> (u64, Vec<Outcome>) {
51
83
    let (behaviours, stats) = observe(&nested(shape, depth), CompileMode::Eval, &[]);
52
166
    let outcomes = behaviours.into_iter().map(|b| b.outcome).collect();
53
83
    (stats.stack_compiles + stats.probe_walks, outcomes)
54
83
}
55

            
56
/// The depths a shape nests to within the reader's nesting limit.
57
19
fn depths(shape: &str) -> Vec<usize> {
58
19
    let at = shape.find("{X}").unwrap_or_default();
59
19
    let per_level = shape[..at].matches('(').count() - shape[..at].matches(')').count();
60
19
    [2, 3, 6, 12, 24]
61
19
        .into_iter()
62
95
        .filter(|depth| depth * per_level + 4 <= MAX_READ_DEPTH)
63
        .collect()
64
19
}
65

            
66
/// Enforces a QUADRATIC bound, not a linear one: work(2d) <= 4 * work(d) along the
67
/// depths 3 -> 6 -> 12 -> 24. Each level still walks the operand nest below it
68
/// once (linear work is ISS-091); walking a test twice per level multiplies the
69
/// work ~2.5x per level and fails here.
70
#[test]
71
1
fn nesting_an_if_in_a_runtime_operand_does_not_multiply_the_work() {
72
1
    for (name, shape) in SHAPES {
73
19
        let points: Vec<(usize, u64)> = depths(shape)
74
19
            .into_iter()
75
81
            .map(|depth| {
76
81
                let (units, outcomes) = work(shape, depth);
77
81
                assert!(
78
81
                    outcomes
79
81
                        .iter()
80
162
                        .all(|outcome| matches!(outcome, Outcome::Value(_))),
81
                    "{name} at depth {depth}: {outcomes:?}"
82
                );
83
81
                (depth, units)
84
81
            })
85
            .collect();
86
19
        assert!(points.len() >= 3, "{name}: too few depths: {points:?}");
87
19
        for pair in points.windows(2) {
88
62
            assert!(
89
62
                pair[1].1 <= 4 * pair[0].1,
90
                "{name}: quadratic bound work(2d) <= 4 * work(d) broken: {points:?}"
91
            );
92
        }
93
    }
94
1
}
95

            
96
/// The audit's ISS-091 nest at depths 8 and 16: the same counter and the same
97
/// quadratic bound per doubling.
98
#[test]
99
1
fn the_runtime_operand_nest_at_depths_8_and_16_stays_within_the_quadratic_bound() {
100
1
    let (_, shape) = SHAPES[0];
101
1
    let points: Vec<(usize, u64)> = [8, 16]
102
1
        .into_iter()
103
2
        .map(|depth| {
104
2
            let (units, outcomes) = work(shape, depth);
105
2
            assert!(
106
2
                outcomes
107
2
                    .iter()
108
4
                    .all(|outcome| matches!(outcome, Outcome::Value(_))),
109
                "depth {depth}: {outcomes:?}"
110
            );
111
2
            (depth, units)
112
2
        })
113
        .collect();
114
1
    assert!(
115
1
        points[1].1 <= 4 * points[0].1,
116
        "work(16) <= 4 * work(8) broken: {points:?}"
117
    );
118
1
}