1
//! `DebugValueData` writers for the script-mode output stream:
2
//! nil / t / number / string at constant-fold time, and the
3
//! from-stack variants for runtime values.
4
//!
5
//! Each appends one entity at the runtime `next_write_pos` via
6
//! [`OutputSerializer::append_entity_header`] (data fields relative to
7
//! [`LOCAL_ENTITY_BASE`]) then advances `next_write_pos`. String payloads grow
8
//! UP immediately after the value; since a script's program-result debug value
9
//! is the last thing written, that never disturbs the contiguous entity walk.
10

            
11
use std::mem::offset_of;
12

            
13
use anodized::spec;
14
use scripting_format::{
15
    DEBUG_VALUE_DATA_SIZE, DebugValueData, ENTITY_HEADER_SIZE, EntityHeader, EntityType, Operation,
16
    ValueType,
17
};
18
use wasm_encoder::BlockType;
19

            
20
use crate::ast::{Fraction, Number};
21
use crate::compiler::context::CLOSURE_SITE_FIELD;
22
use crate::compiler::emit::FunctionEmitter;
23
use crate::compiler::expr::LOCAL_ENTITY_BASE;
24
use crate::error::{Error, Result};
25

            
26
use super::GcLocals;
27
use super::headers::OutputSerializer;
28

            
29
/// Inline bytes a debug value carries past its fixed entity.
30
#[derive(Clone, Copy)]
31
pub(super) enum Payload {
32
    None,
33
    Bytes(u32),
34
    /// The length of the GC byte array in this local.
35
    ArrayLen(u32),
36
}
37

            
38
/// Bytes a fixed (string-free) debug-value entity occupies.
39
pub(super) const DEBUG_ENTITY_BYTES: u32 = ENTITY_HEADER_SIZE as u32 + DEBUG_VALUE_DATA_SIZE as u32;
40

            
41
impl OutputSerializer {
42
    /// Reserves room for one debug value (raising `OUTPUT-OVERFLOW` if it does
43
    /// not fit) and appends its entity header.
44
6233816
    pub(super) fn begin_debug_value(
45
6233816
        &mut self,
46
6233816
        emit: &mut FunctionEmitter,
47
6233816
        payload: Payload,
48
6233816
    ) -> Result<u32> {
49
6233816
        let fixed = match payload {
50
1538850
            Payload::Bytes(len) => DEBUG_ENTITY_BYTES
51
1538850
                .checked_add(len)
52
1538849
                .and_then(|n| i32::try_from(n).ok())
53
1
                .ok_or_else(|| {
54
1
                    Error::Compile(format!("a {len}-byte string overflows a debug entity"))
55
1
                })?,
56
4694966
            Payload::None | Payload::ArrayLen(_) => DEBUG_ENTITY_BYTES as i32,
57
        };
58
6233815
        emit.i32_const(fixed);
59
6233815
        if let Payload::ArrayLen(arr) = payload {
60
413690
            emit.local_get(arr);
61
413690
            emit.array_len();
62
413690
            emit.i32_add();
63
5820125
        }
64
6233815
        self.ensure_room(emit)?;
65
6233815
        Ok(self.append_entity_header(
66
6233815
            emit,
67
6233815
            EntityType::DebugValue,
68
6233815
            Operation::Nop,
69
6233815
            0,
70
6233815
            -1,
71
6233815
            DEBUG_VALUE_DATA_SIZE as u32,
72
6233815
        ))
73
6233816
    }
74

            
75
428323
    pub fn write_debug_nil(&mut self, emit: &mut FunctionEmitter) -> Result<()> {
76
428323
        self.write_debug_tag(emit, ValueType::Nil)
77
428323
    }
78

            
79
5672
    pub fn write_debug_t(&mut self, emit: &mut FunctionEmitter) -> Result<()> {
80
5672
        self.write_debug_tag(emit, ValueType::T)
81
5672
    }
82

            
83
    /// A debug value that is its tag alone: `nil`, `t`, or a list marker.
84
1572653
    pub fn write_debug_tag(&mut self, emit: &mut FunctionEmitter, tag: ValueType) -> Result<()> {
85
1572653
        let data = self.begin_debug_value(emit, Payload::None)?;
86
1572653
        emit.store_u8_dynamic(
87
1572653
            LOCAL_ENTITY_BASE,
88
1572653
            data + offset_of!(DebugValueData, value_type) as u32,
89
1572653
            tag as u8,
90
1572653
        );
91
1572653
        self.advance_past(emit, DEBUG_ENTITY_BYTES);
92
1572653
        Ok(())
93
1572653
    }
94

            
95
72391
    pub fn write_debug_number(&mut self, emit: &mut FunctionEmitter, number: Number) -> Result<()> {
96
72391
        let (tag, value) = match number {
97
68641
            Number::Index(n) => (ValueType::Number, Fraction::from_integer(n)),
98
3750
            Number::Scalar(s) => (ValueType::Scalar, s),
99
        };
100
72391
        let (numer, denom) = (*value.numer(), *value.denom());
101
72391
        let data = self.begin_debug_value(emit, Payload::None)?;
102
72391
        emit.store_u8_dynamic(
103
72391
            LOCAL_ENTITY_BASE,
104
72391
            data + offset_of!(DebugValueData, value_type) as u32,
105
72391
            tag as u8,
106
72391
        );
107
72391
        emit.store_i64_dynamic(
108
72391
            LOCAL_ENTITY_BASE,
109
72391
            data + offset_of!(DebugValueData, data1) as u32,
110
72391
            numer,
111
72391
        );
112
72391
        emit.store_i64_dynamic(
113
72391
            LOCAL_ENTITY_BASE,
114
72391
            data + offset_of!(DebugValueData, data2) as u32,
115
72391
            denom,
116
72391
        );
117
72391
        self.advance_past(emit, DEBUG_ENTITY_BYTES);
118
72391
        Ok(())
119
72391
    }
120

            
121
1340235
    pub fn write_debug_string_gc(
122
1340235
        &mut self,
123
1340235
        emit: &mut FunctionEmitter,
124
1340235
        value_type: ValueType,
125
1340235
        data_idx: u32,
126
1340235
        len: u32,
127
1340235
        gc: &GcLocals,
128
1340235
    ) -> Result<()> {
129
1340235
        let data = self.begin_debug_value(emit, Payload::Bytes(len))?;
130
1340234
        let strings_at = data + DEBUG_VALUE_DATA_SIZE as u32;
131
1340234
        emit.store_u8_dynamic(
132
1340234
            LOCAL_ENTITY_BASE,
133
1340234
            data + offset_of!(DebugValueData, value_type) as u32,
134
1340234
            value_type as u8,
135
1340234
        );
136
1340234
        emit.store_i64_dynamic(
137
1340234
            LOCAL_ENTITY_BASE,
138
1340234
            data + offset_of!(DebugValueData, data1) as u32,
139
1340234
            0,
140
1340234
        );
141
1340234
        emit.store_i64_dynamic(
142
1340234
            LOCAL_ENTITY_BASE,
143
1340234
            data + offset_of!(DebugValueData, data2) as u32,
144
1340234
            i64::from(len),
145
1340234
        );
146
        // Count the inline string bytes in data_size so the entity parser walk
147
        // (ENTITY_HEADER_SIZE + data_size) skips them; the string is decoded
148
        // per-entity at data_offset + DEBUG_VALUE_DATA_SIZE.
149
1340234
        let data_size = (DEBUG_VALUE_DATA_SIZE as u32)
150
1340234
            .checked_add(len)
151
1340234
            .and_then(|n| i32::try_from(n).ok())
152
            .ok_or_else(|| {
153
                Error::Compile(format!(
154
                    "string literal of {len} bytes overflows a debug entity"
155
                ))
156
            })?;
157
1340234
        emit.store_i32_dynamic(
158
1340234
            LOCAL_ENTITY_BASE,
159
1340234
            offset_of!(EntityHeader, data_size) as u32,
160
1340234
            data_size,
161
1340234
        );
162
1340234
        super::tag_record::copy_data_gc(emit, LOCAL_ENTITY_BASE, data_idx, len, strings_at, gc)?;
163
1340234
        let advance = DEBUG_ENTITY_BYTES.checked_add(len).ok_or_else(|| {
164
            Error::Compile(format!(
165
                "string literal of {len} bytes overflows a debug entity"
166
            ))
167
        })?;
168
1340234
        self.advance_past(emit, advance);
169
1340234
        Ok(())
170
1340235
    }
171

            
172
    #[spec(
173
413690
        captures: depth = emit.block_depth(),
174
413690
        ensures: emit.block_depth() == depth,
175
    )]
176
413690
    pub fn write_debug_string_from_stack(
177
413690
        &mut self,
178
413690
        emit: &mut FunctionEmitter,
179
413690
        value_type: ValueType,
180
413690
        gc: &GcLocals,
181
413690
    ) -> Result<()> {
182
413690
        emit.local_set(gc.arr);
183
        // A runtime `StringRef` can legitimately be nil (ADR-0033 Phase 5):
184
        // `array.len` traps on null, so branch to the same `Nil` tag
185
        // `write_debug_nil` emits rather than reading the length of a null
186
        // array.
187
413690
        emit.local_get(gc.arr);
188
413690
        emit.ref_is_null();
189
413690
        emit.if_block(BlockType::Empty);
190
413690
        self.write_debug_nil(emit)?;
191
413690
        emit.else_block();
192
413690
        self.write_debug_string_from_non_null_stack(emit, value_type, gc)?;
193
413690
        emit.block_end()?;
194
413690
        Ok(())
195
413690
    }
196

            
197
413690
    fn write_debug_string_from_non_null_stack(
198
413690
        &mut self,
199
413690
        emit: &mut FunctionEmitter,
200
413690
        value_type: ValueType,
201
413690
        gc: &GcLocals,
202
413690
    ) -> Result<()> {
203
413690
        let data = self.begin_debug_value(emit, Payload::ArrayLen(gc.arr))?;
204
413690
        emit.store_u8_dynamic(
205
413690
            LOCAL_ENTITY_BASE,
206
413690
            data + offset_of!(DebugValueData, value_type) as u32,
207
413690
            value_type as u8,
208
413690
        );
209
413690
        emit.store_i64_dynamic(
210
413690
            LOCAL_ENTITY_BASE,
211
413690
            data + offset_of!(DebugValueData, data1) as u32,
212
413690
            0,
213
413690
        );
214
        // data2 = array.len (runtime)
215
413690
        emit.local_get(LOCAL_ENTITY_BASE);
216
413690
        emit.i32_const((data + offset_of!(DebugValueData, data2) as u32) as i32);
217
413690
        emit.i32_add();
218
413690
        emit.local_get(gc.arr);
219
413690
        emit.array_len();
220
413690
        emit.i64_extend_i32_u();
221
413690
        emit.i64_store_raw();
222

            
223
413690
        let strings_at = data + DEBUG_VALUE_DATA_SIZE as u32;
224
413690
        emit.i32_const(0);
225
413690
        emit.local_set(gc.idx);
226
413690
        emit.block_start();
227
413690
        emit.loop_start();
228
413690
        emit.local_get(gc.idx);
229
413690
        emit.local_get(gc.arr);
230
413690
        emit.array_len();
231
413690
        emit.i32_ge_u();
232
413690
        emit.br_if(1);
233
413690
        emit.local_get(LOCAL_ENTITY_BASE);
234
413690
        emit.i32_const(strings_at as i32);
235
413690
        emit.i32_add();
236
413690
        emit.local_get(gc.idx);
237
413690
        emit.i32_add();
238
413690
        emit.local_get(gc.arr);
239
413690
        emit.local_get(gc.idx);
240
413690
        emit.array_get_u(gc.type_idx);
241
413690
        emit.i32_store8_raw();
242
413690
        emit.local_get(gc.idx);
243
413690
        emit.i32_const(1);
244
413690
        emit.i32_add();
245
413690
        emit.local_set(gc.idx);
246
413690
        emit.br(0);
247
413690
        emit.block_end()?;
248
413690
        emit.block_end()?;
249

            
250
        // data_size = DEBUG_VALUE_DATA_SIZE + array.len (runtime), so the entity
251
        // walk skips the inline string bytes.
252
413690
        emit.local_get(LOCAL_ENTITY_BASE);
253
413690
        emit.i32_const(offset_of!(EntityHeader, data_size) as i32);
254
413690
        emit.i32_add();
255
413690
        emit.i32_const(DEBUG_VALUE_DATA_SIZE as i32);
256
413690
        emit.local_get(gc.arr);
257
413690
        emit.array_len();
258
413690
        emit.i32_add();
259
413690
        emit.i32_store_raw();
260

            
261
        // next_write_pos += DEBUG_ENTITY_BYTES + array.len (runtime)
262
413690
        emit.i32_const(DEBUG_ENTITY_BYTES as i32);
263
413690
        emit.local_get(gc.arr);
264
413690
        emit.array_len();
265
413690
        emit.i32_add();
266
413690
        self.advance_past_runtime(emit);
267
413690
        Ok(())
268
413690
    }
269

            
270
219022
    pub fn write_debug_number_from_stack(
271
219022
        &mut self,
272
219022
        emit: &mut FunctionEmitter,
273
219022
        ratio_type_idx: u32,
274
219022
        ratio_local: u32,
275
219022
    ) -> Result<()> {
276
219022
        emit.local_set(ratio_local);
277
219022
        self.write_debug_number_from_fields(emit, ratio_type_idx, ratio_local)
278
219022
    }
279

            
280
    /// A `Scalar` from fields 0 / 1 (numerator / denominator) of the struct
281
    /// of `type_idx` in `local`: a `$ratio`, or a `$commodity` whose unit
282
    /// term is dimensionless.
283
417637
    pub(super) fn write_debug_number_from_fields(
284
417637
        &mut self,
285
417637
        emit: &mut FunctionEmitter,
286
417637
        type_idx: u32,
287
417637
        local: u32,
288
417637
    ) -> Result<()> {
289
417637
        let data = self.begin_debug_value(emit, Payload::None)?;
290
417637
        emit.store_u8_dynamic(
291
417637
            LOCAL_ENTITY_BASE,
292
417637
            data + offset_of!(DebugValueData, value_type) as u32,
293
417637
            ValueType::Scalar as u8,
294
417637
        );
295
417637
        store_i64_field(
296
417637
            emit,
297
417637
            data + offset_of!(DebugValueData, data1) as u32,
298
417637
            type_idx,
299
417637
            local,
300
417637
            0,
301
417637
        );
302
417637
        store_i64_field(
303
417637
            emit,
304
417637
            data + offset_of!(DebugValueData, data2) as u32,
305
417637
            type_idx,
306
417637
            local,
307
417637
            1,
308
417637
        );
309
417637
        self.advance_past(emit, DEBUG_ENTITY_BYTES);
310
417637
        Ok(())
311
417637
    }
312

            
313
394823
    pub fn write_debug_i32_from_stack(
314
394823
        &mut self,
315
394823
        emit: &mut FunctionEmitter,
316
394823
        i32_local: u32,
317
394823
    ) -> Result<()> {
318
394823
        self.write_debug_i32_tagged(emit, i32_local, ValueType::Number)
319
394823
    }
320

            
321
600304
    fn write_debug_i32_tagged(
322
600304
        &mut self,
323
600304
        emit: &mut FunctionEmitter,
324
600304
        i32_local: u32,
325
600304
        tag: ValueType,
326
600304
    ) -> Result<()> {
327
600304
        emit.local_set(i32_local);
328
600304
        let data = self.begin_debug_value(emit, Payload::None)?;
329
600304
        emit.store_u8_dynamic(
330
600304
            LOCAL_ENTITY_BASE,
331
600304
            data + offset_of!(DebugValueData, value_type) as u32,
332
600304
            tag as u8,
333
600304
        );
334
600304
        emit.local_get(LOCAL_ENTITY_BASE);
335
600304
        emit.i32_const((data + offset_of!(DebugValueData, data1) as u32) as i32);
336
600304
        emit.i32_add();
337
600304
        emit.local_get(i32_local);
338
        // SIGNED extend: an Index/count is a signed i32 (ADR-0028). A negative
339
        // arithmetic result must decode as a negative `Number`, not its unsigned
340
        // 2^32 image. Length / bool sites stay `_u` (provably ≥ 0).
341
600304
        emit.i64_extend_i32_s();
342
600304
        emit.i64_store_raw();
343
600304
        emit.store_i64_dynamic(
344
600304
            LOCAL_ENTITY_BASE,
345
600304
            data + offset_of!(DebugValueData, data2) as u32,
346
600304
            1,
347
600304
        );
348
600304
        self.advance_past(emit, DEBUG_ENTITY_BYTES);
349
600304
        Ok(())
350
600304
    }
351

            
352
    /// Writes the closure of struct type `closure_type_idx` on the stack as
353
    /// its source site, read through `site_local`.
354
205481
    pub fn write_debug_closure_from_stack(
355
205481
        &mut self,
356
205481
        emit: &mut FunctionEmitter,
357
205481
        closure_type_idx: u32,
358
205481
        site_local: u32,
359
205481
    ) -> Result<()> {
360
205481
        emit.struct_get(closure_type_idx, CLOSURE_SITE_FIELD);
361
205481
        self.write_debug_i32_tagged(emit, site_local, ValueType::Closure)
362
205481
    }
363

            
364
    /// Serialize a runtime i32 truth value (0 = nil, nonzero = t) so it decodes
365
    /// like the const-fold path. The value-type tag is `(v != 0)` (0 = Nil tag,
366
    /// 1 = T tag).
367
28233
    pub fn write_debug_bool_from_stack(
368
28233
        &mut self,
369
28233
        emit: &mut FunctionEmitter,
370
28233
        bool_local: u32,
371
28233
    ) -> Result<()> {
372
28233
        emit.i32_const(0);
373
28233
        emit.i32_ne();
374
28233
        emit.local_set(bool_local);
375
28233
        let data = self.begin_debug_value(emit, Payload::None)?;
376
28233
        emit.local_get(LOCAL_ENTITY_BASE);
377
28233
        emit.i32_const((data + offset_of!(DebugValueData, value_type) as u32) as i32);
378
28233
        emit.i32_add();
379
28233
        emit.local_get(bool_local);
380
28233
        emit.i32_store8_raw();
381
28233
        self.advance_past(emit, DEBUG_ENTITY_BYTES);
382
28233
        Ok(())
383
28233
    }
384
}
385

            
386
/// Stores i64 field `field` of the struct of `type_idx` in `local` at `at`
387
/// past the entity base.
388
1629734
pub(super) fn store_i64_field(
389
1629734
    emit: &mut FunctionEmitter,
390
1629734
    at: u32,
391
1629734
    type_idx: u32,
392
1629734
    local: u32,
393
1629734
    field: u32,
394
1629734
) {
395
1629734
    emit.local_get(LOCAL_ENTITY_BASE);
396
1629734
    emit.i32_const(at as i32);
397
1629734
    emit.i32_add();
398
1629734
    emit.local_get(local);
399
1629734
    emit.struct_get(type_idx, field);
400
1629734
    emit.i64_store_raw();
401
1629734
}
402

            
403
#[cfg(test)]
404
#[path = "debug_values_tests.rs"]
405
mod tests;