1
//! `OutputSerializer` + the single runtime-append output protocol.
2
//!
3
//! Every output entity (debug value, tag, delete) is written at the RUNTIME
4
//! `next_write_pos` the `OutputHeader` carries, then `next_write_pos` and
5
//! `output_entity_count` are advanced at runtime. This is the ONE protocol: a
6
//! compile-time-known write (a program result) and a dynamic-count write (a
7
//! `create-tag` inside a loop) both append, so they never overwrite each other.
8
//!
9
//! [`LOCAL_ENTITY_BASE`] holds the current entity's absolute address
10
//! (`output_base + next_write_pos`); writers store their header + data fields
11
//! relative to it. Tag strings still grow DOWN from the buffer end (the entity
12
//! parser reads them as distance-from-end); debug-value strings grow UP right
13
//! after the value and are the last thing written, so neither disturbs the
14
//! contiguous `ENTITY_HEADER_SIZE + data_size` entity walk.
15

            
16
use std::mem::offset_of;
17

            
18
use anodized::spec;
19
use scripting_format::{
20
    ENTITY_HEADER_SIZE, EntityHeader, EntityType, GlobalHeader, MAGIC_OUTP, OUTPUT_HEADER_SIZE,
21
    Operation, OutputHeader,
22
};
23
use wasm_encoder::BlockType;
24

            
25
use crate::compiler::emit::FunctionEmitter;
26
use crate::compiler::expr::{LOCAL_ENTITY_BASE, LOCAL_TEMP_I32};
27
use crate::error::{Error, Result};
28

            
29
#[derive(Clone, Debug)]
30
pub struct OutputSerializer {
31
    pub(super) output_start_idx: u32,
32
    pub(super) output_base_local: u32,
33
    limit: Option<OutputLimit>,
34
}
35

            
36
/// How a module bounds its output writes: the import that locates the input
37
/// header, whose `output_size` is the buffer's capacity, and the helper that
38
/// raises `OUTPUT-OVERFLOW`.
39
#[derive(Clone, Copy, Debug)]
40
pub struct OutputLimit {
41
    pub input_offset_fn: u32,
42
    pub overflow_fn: u32,
43
}
44

            
45
impl OutputSerializer {
46
9607454
    pub fn new(output_base_local: u32) -> Self {
47
9607454
        Self {
48
9607454
            output_start_idx: 0,
49
9607454
            output_base_local,
50
9607454
            limit: None,
51
9607454
        }
52
9607454
    }
53

            
54
3970080
    pub fn set_limit(&mut self, limit: Option<OutputLimit>) {
55
3970080
        self.limit = limit;
56
3970080
    }
57

            
58
    /// Raises `OUTPUT-OVERFLOW` unless the i32 byte count on the stack fits
59
    /// between `next_write_pos` and the tag-string frontier (the buffer end
60
    /// until a tag string is written). Uses no locals, so callers may hold
61
    /// values in the scratch locals across it.
62
6235895
    pub(super) fn ensure_room(&self, emit: &mut FunctionEmitter) -> Result<()> {
63
6235895
        self.ensure_room_at(emit, self.output_base_local)
64
6235895
    }
65

            
66
    /// [`Self::ensure_room`] against the output base held in `base`, for a
67
    /// writer that locates the buffer itself.
68
6257128
    pub(in crate::compiler) fn ensure_room_at(
69
6257128
        &self,
70
6257128
        emit: &mut FunctionEmitter,
71
6257128
        base: u32,
72
6257128
    ) -> Result<()> {
73
6257128
        let limit = self.limit.ok_or_else(|| {
74
            Error::Compile("internal: output written in a module without an output buffer".into())
75
        })?;
76
6257128
        let next = offset_of!(OutputHeader, next_write_pos) as u64;
77
6257128
        let frontier = offset_of!(OutputHeader, reserved) as u64;
78
6257128
        emit.local_get(base);
79
6257128
        emit.i32_load(next);
80
6257128
        emit.i32_add();
81
6257128
        emit.local_get(base);
82
6257128
        emit.i32_load(frontier);
83
6257128
        emit.call(limit.input_offset_fn);
84
6257128
        emit.i32_load(offset_of!(GlobalHeader, output_size) as u64);
85
6257128
        emit.local_get(base);
86
6257128
        emit.i32_load(frontier);
87
6257128
        emit.select();
88
6257128
        emit.i32_gt_u();
89
6257128
        emit.if_block(BlockType::Empty);
90
6257128
        emit.call(limit.overflow_fn);
91
6257128
        emit.unreachable();
92
6257128
        emit.block_end()
93
6257128
    }
94

            
95
    /// Writes the `OutputHeader` at the buffer start: zero entities, the
96
    /// strings frontier at the buffer end (set lazily by the first string
97
    /// write), and `next_write_pos` just past the header — where the first
98
    /// entity will append.
99
1616929
    pub fn begin_output(&mut self, emit: &mut FunctionEmitter) {
100
1616929
        let local = self.output_base_local;
101
1616929
        emit.store_i32_dynamic(
102
1616929
            local,
103
1616929
            offset_of!(OutputHeader, magic) as u32,
104
1616929
            MAGIC_OUTP as i32,
105
1616929
        );
106
1616929
        emit.store_i32_dynamic(
107
1616929
            local,
108
1616929
            offset_of!(OutputHeader, output_entity_count) as u32,
109
1616929
            0,
110
1616929
        );
111
1616929
        emit.store_i32_dynamic(
112
1616929
            local,
113
1616929
            offset_of!(OutputHeader, output_start_idx) as u32,
114
1616929
            self.output_start_idx as i32,
115
1616929
        );
116
1616929
        emit.store_i32_dynamic(
117
1616929
            local,
118
1616929
            offset_of!(OutputHeader, next_write_pos) as u32,
119
1616929
            OUTPUT_HEADER_SIZE as i32,
120
1616929
        );
121
1616929
    }
122

            
123
    /// Loads `LOCAL_ENTITY_BASE = output_base + next_write_pos` — the absolute
124
    /// address of the entity about to be written.
125
6235895
    pub(super) fn load_entity_base(&self, emit: &mut FunctionEmitter) {
126
6235895
        let local = self.output_base_local;
127
6235895
        emit.local_get(local);
128
6235895
        emit.local_get(local);
129
6235895
        emit.i32_load(offset_of!(OutputHeader, next_write_pos) as u64);
130
6235895
        emit.i32_add();
131
6235895
        emit.local_set(LOCAL_ENTITY_BASE);
132
6235895
    }
133

            
134
    /// Appends an entity header at `next_write_pos` (via [`Self::load_entity_base`]),
135
    /// bumps `output_entity_count` at runtime, and returns the entity-relative
136
    /// offset of the data region (`ENTITY_HEADER_SIZE`). The caller then writes
137
    /// data fields relative to `LOCAL_ENTITY_BASE` and finishes with
138
    /// [`Self::advance_past`]. `next_write_pos` is NOT advanced here.
139
    #[spec(
140
6233815
        requires: [parent_idx >= -1, i32::try_from(data_size).is_ok()],
141
6233815
        captures: depth = emit.block_depth(),
142
6233815
        ensures: emit.block_depth() == depth,
143
6233815
        ensures: |output| output == ENTITY_HEADER_SIZE as u32,
144
    )]
145
6233815
    pub(super) fn append_entity_header(
146
6233815
        &mut self,
147
6233815
        emit: &mut FunctionEmitter,
148
6233815
        entity_type: EntityType,
149
6233815
        operation: Operation,
150
6233815
        flags: u8,
151
6233815
        parent_idx: i32,
152
6233815
        data_size: u32,
153
6233815
    ) -> u32 {
154
6233815
        self.load_entity_base(emit);
155
6233815
        let ent = LOCAL_ENTITY_BASE;
156
6233815
        emit.store_u8_dynamic(
157
6233815
            ent,
158
6233815
            offset_of!(EntityHeader, entity_type) as u32,
159
6233815
            entity_type as u8,
160
6233815
        );
161
6233815
        emit.store_u8_dynamic(
162
6233815
            ent,
163
6233815
            offset_of!(EntityHeader, operation) as u32,
164
6233815
            operation as u8,
165
6233815
        );
166
6233815
        emit.store_u8_dynamic(ent, offset_of!(EntityHeader, flags) as u32, flags);
167
6233815
        emit.store_i32_dynamic(ent, offset_of!(EntityHeader, parent_idx) as u32, parent_idx);
168
        // data_offset is relative to output_base: next_write_pos + header size =
169
        // (entity_base - output_base) + ENTITY_HEADER_SIZE.
170
6233815
        emit.local_get(ent);
171
6233815
        emit.i32_const(offset_of!(EntityHeader, data_offset) as i32);
172
6233815
        emit.i32_add();
173
6233815
        emit.local_get(ent);
174
6233815
        emit.local_get(self.output_base_local);
175
6233815
        emit.i32_sub();
176
6233815
        emit.i32_const(ENTITY_HEADER_SIZE as i32);
177
6233815
        emit.i32_add();
178
6233815
        emit.i32_store_raw();
179

            
180
6233815
        emit.store_i32_dynamic(
181
6233815
            ent,
182
6233815
            offset_of!(EntityHeader, data_size) as u32,
183
6233815
            data_size as i32,
184
6233815
        );
185

            
186
6233815
        self.bump_entity_count(emit);
187
6233815
        ENTITY_HEADER_SIZE as u32
188
6233815
    }
189

            
190
    /// `output_entity_count += 1` at runtime.
191
6235895
    pub(super) fn bump_entity_count(&self, emit: &mut FunctionEmitter) {
192
6235895
        let base = self.output_base_local;
193
6235895
        let count_off = offset_of!(OutputHeader, output_entity_count) as u32;
194
6235895
        emit.local_get(base);
195
6235895
        emit.i32_const(count_off as i32);
196
6235895
        emit.i32_add();
197
6235895
        emit.local_get(base);
198
6235895
        emit.i32_load(u64::from(count_off));
199
6235895
        emit.i32_const(1);
200
6235895
        emit.i32_add();
201
6235895
        emit.i32_store_raw();
202
6235895
    }
203

            
204
    /// Advances `next_write_pos` by a COMPILE-TIME-known byte count (header +
205
    /// fixed data). For an entity that also appended grow-up strings, follow
206
    /// with [`Self::advance_past_runtime`].
207
5822205
    #[spec(requires: i32::try_from(bytes).is_ok())]
208
5822205
    pub(super) fn advance_past(&self, emit: &mut FunctionEmitter, bytes: u32) {
209
5822205
        let base = self.output_base_local;
210
5822205
        let off = offset_of!(OutputHeader, next_write_pos) as u32;
211
5822205
        emit.local_get(base);
212
5822205
        emit.i32_const(off as i32);
213
5822205
        emit.i32_add();
214
5822205
        emit.local_get(base);
215
5822205
        emit.i32_load(u64::from(off));
216
5822205
        emit.i32_const(bytes as i32);
217
5822205
        emit.i32_add();
218
5822205
        emit.i32_store_raw();
219
5822205
    }
220

            
221
    /// Advances `next_write_pos` by a RUNTIME byte count already on the wasm
222
    /// stack (for grow-up string payloads of unknown length).
223
413690
    pub(super) fn advance_past_runtime(&self, emit: &mut FunctionEmitter) {
224
        // stack: [extra_bytes]
225
413690
        let base = self.output_base_local;
226
413690
        let off = offset_of!(OutputHeader, next_write_pos) as u32;
227
413690
        let extra = LOCAL_TEMP_I32;
228
413690
        emit.local_set(extra);
229
413690
        emit.local_get(base);
230
413690
        emit.i32_const(off as i32);
231
413690
        emit.i32_add();
232
413690
        emit.local_get(base);
233
413690
        emit.i32_load(u64::from(off));
234
413690
        emit.local_get(extra);
235
413690
        emit.i32_add();
236
413690
        emit.i32_store_raw();
237
413690
    }
238
}