1
//! The unit prologue of the session's struct instances.
2

            
3
use crate::compiler::CompileMode;
4

            
5
use wasmparser::{ExternalKind, Parser, Payload};
6

            
7
use super::allocate_instances;
8
use crate::ast::{Expr, Number, StructId, WasmType};
9
use crate::compiler::context::{CompileContext, instance_export_name};
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::prepare_unit;
12
use crate::reader::Reader;
13
use crate::runtime::{CellBinding, Found, StructInstance, Symbol, SymbolKind, SymbolTable};
14
use crate::{Compiler, Program};
15

            
16
103608
fn number(n: i64) -> Expr {
17
103608
    Expr::Number(Number::Index(n))
18
103608
}
19

            
20
/// A table whose global `P` holds instance 0 of `(defstruct pt x)`, with `x`
21
/// carried as `field`, and whose counter stands at `next_serial`.
22
5
fn holding(field: Expr, next_serial: u32) -> (SymbolTable, StructId) {
23
5
    let mut symbols = SymbolTable::with_builtins_for_wasm();
24
5
    let id = symbols.define_struct("PT", vec!["X".to_string()]).unwrap();
25
5
    let leaf = Expr::Instance(0, id);
26
5
    symbols.define(Symbol::new("P", SymbolKind::Variable).with_value(leaf));
27
5
    let instance = StructInstance {
28
5
        layout: id,
29
5
        fields: vec![field],
30
5
    };
31
5
    symbols.settle_instances(Found::from([(0, Some(instance))]), next_serial);
32
5
    (symbols, id)
33
5
}
34

            
35
4
fn prologue(symbols: &mut SymbolTable) -> CompileContext {
36
4
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
37
4
    let mut emit = FunctionEmitter::new();
38
4
    let scan = prepare_unit(symbols, &[], CompileMode::Script).unwrap();
39
4
    allocate_instances(&mut ctx, &mut emit, symbols, &scan).unwrap();
40
4
    ctx
41
4
}
42

            
43
2
fn exported_globals(bytes: &[u8]) -> Vec<String> {
44
2
    Parser::new(0)
45
2
        .parse_all(bytes)
46
2
        .filter_map(Result::ok)
47
181
        .filter_map(|payload| match payload {
48
2
            Payload::ExportSection(reader) => Some(reader),
49
179
            _ => None,
50
181
        })
51
2
        .flat_map(|reader| reader.into_iter().filter_map(Result::ok))
52
650
        .filter(|export| export.kind == ExternalKind::Global)
53
605
        .map(|export| export.name.to_string())
54
        .collect()
55
2
}
56

            
57
#[test]
58
1
fn every_session_instance_gets_an_exported_global_that_validates() {
59
1
    let (mut symbols, _) = holding(number(1), 1);
60
1
    let mut ctx = prologue(&mut symbols);
61
1
    assert!(ctx.instance_global(0).is_ok());
62
1
    ctx.add_should_apply(CompileContext::default_should_apply(), usize::MAX);
63
1
    let mut process = wasm_encoder::Function::new([]);
64
1
    process.instruction(&wasm_encoder::Instruction::End);
65
1
    ctx.add_process(process);
66
1
    let bytes = ctx.finish();
67
1
    wasmparser::validate(&bytes).expect("the instance globals validate");
68
1
    assert!(exported_globals(&bytes).contains(&instance_export_name(0)));
69
1
}
70

            
71
#[test]
72
1
fn a_serial_no_instance_holds_has_no_global() {
73
1
    let (mut symbols, _) = holding(number(1), 1);
74
1
    let ctx = prologue(&mut symbols);
75
1
    assert!(ctx.instance_global(7).is_err());
76
1
}
77

            
78
#[test]
79
1
fn a_carried_field_types_the_home_of_its_layout_field() {
80
1
    let (mut symbols, id) = holding(number(1), 1);
81
1
    prologue(&mut symbols);
82
1
    assert_eq!(symbols.field_type(id, 0), WasmType::I32);
83
1
}
84

            
85
#[test]
86
1
fn a_cell_of_a_carried_instance_is_seeded_by_the_prologue() {
87
1
    let (mut symbols, id) = holding(number(1), 1);
88
1
    let unit = Reader::parse("(setf p 2)").unwrap().exprs;
89
1
    let scan = prepare_unit(&mut symbols, &unit, CompileMode::Script).unwrap();
90
1
    let mut ctx = CompileContext::new_with_host_fns(&[]).unwrap();
91
1
    let mut emit = FunctionEmitter::new();
92
1
    allocate_instances(&mut ctx, &mut emit, &mut symbols, &scan).unwrap();
93
1
    let cell = symbols.cell_global("P").map(|(_, ty)| ty);
94
1
    assert_eq!(cell, Some(WasmType::StructRef(id)));
95
1
    assert_eq!(symbols.cell_binding("P"), CellBinding::Bound);
96
1
}
97

            
98
#[test]
99
1
fn the_serial_counter_starts_past_the_serials_the_session_used() {
100
1
    let (mut symbols, _) = holding(Expr::Nil, 7);
101
1
    let ctx = prologue(&mut symbols);
102
1
    assert!(ctx.state_digest().contains("struct_serial_base: 7"));
103
1
}
104

            
105
/// A table whose global `PS` holds `count` instances of `(defstruct pt x)`,
106
/// the `x` of instance `n` being `n`.
107
4
fn crowded(count: u32) -> SymbolTable {
108
4
    let mut symbols = SymbolTable::with_builtins_for_wasm();
109
4
    let id = symbols.define_struct("PT", vec!["X".to_string()]).unwrap();
110
4
    let leaves = (0..count)
111
103600
        .map(|serial| Expr::Instance(serial, id))
112
        .collect();
113
4
    symbols.define(Symbol::new("PS", SymbolKind::Variable).with_value(Expr::List(leaves)));
114
4
    let found = (0..count)
115
103600
        .map(|serial| {
116
103600
            let instance = StructInstance {
117
103600
                layout: id,
118
103600
                fields: vec![number(i64::from(serial))],
119
103600
            };
120
103600
            (serial, Some(instance))
121
103600
        })
122
        .collect();
123
4
    symbols.settle_instances(found, count);
124
4
    symbols
125
4
}
126

            
127
2
fn largest_function_body(count: u32) -> u64 {
128
2
    let mut symbols = crowded(count);
129
2
    let (bytes, _) = Compiler::new()
130
2
        .compile_eval_with_type(&Program::new(vec![number(1)]), &mut symbols)
131
2
        .unwrap();
132
2
    Parser::new(0)
133
2
        .parse_all(&bytes)
134
2
        .filter_map(Result::ok)
135
198
        .filter_map(|payload| match payload {
136
174
            Payload::CodeSectionEntry(body) => Some(body.range().end - body.range().start),
137
24
            _ => None,
138
198
        })
139
        .max()
140
2
        .unwrap_or(0)
141
2
}
142

            
143
/// No function body grows with the carried-instance count: one start function
144
/// holding every instance took 18 s to compile at 8000.
145
#[test]
146
1
fn no_function_grows_with_the_carried_instance_count() {
147
1
    let small = largest_function_body(600);
148
1
    let large = largest_function_body(2_400);
149
1
    assert!(small > 0);
150
1
    assert_eq!(small, large, "largest body {small} vs {large} bytes");
151
1
}
152

            
153
/// Compile time is linear in the carried instances: a per-field table clone
154
/// was quadratic and never finished at 100000. The nextest override in
155
/// `.config/nextest.toml` terminates this test past 120 s.
156
#[test]
157
1
fn a_later_unit_compiles_over_a_hundred_thousand_carried_instances() {
158
1
    let mut symbols = crowded(100_000);
159
1
    let (bytes, _) = Compiler::new()
160
1
        .compile_eval_with_type(&Program::new(vec![number(1)]), &mut symbols)
161
1
        .unwrap();
162
1
    wasmparser::validate(&bytes).expect("the crowded unit validates");
163
1
}
164

            
165
/// More instances than one helper holds still validate, each reaching its
166
/// serial's global.
167
#[test]
168
1
fn a_crowd_past_one_helper_validates() {
169
1
    let mut symbols = crowded(600);
170
1
    let (bytes, _) = Compiler::new()
171
1
        .compile_eval_with_type(&Program::new(vec![number(1)]), &mut symbols)
172
1
        .unwrap();
173
1
    wasmparser::validate(&bytes).expect("the chunked prologue validates");
174
1
    let exported = exported_globals(&bytes);
175
1
    assert!(exported.contains(&instance_export_name(0)));
176
1
    assert!(exported.contains(&instance_export_name(599)));
177
1
}