1
//! Script-mode output of runtime reference values. A list is written as a
2
//! pre-order `List` … `ListEnd` run of debug values, walked iteratively with
3
//! the rest of each enclosing list kept on a stack of `$pair` cells, so
4
//! nesting depth costs heap rather than wasm stack. Every element, and every
5
//! `AnyRef`, is classified by its runtime shape. A runtime struct instance is
6
//! walked the same way as a list opened by the `Struct` tag.
7

            
8
use scripting_format::ValueType;
9
use wasm_encoder::BlockType;
10

            
11
use crate::ast::{EntityKind, PairElement, StructId, WasmType};
12
use crate::compiler::context::CompileContext;
13
use crate::compiler::emit::FunctionEmitter;
14
use crate::compiler::layout::GcLocals;
15
use crate::error::{Error, Result};
16

            
17
use super::compile::money_ids;
18
use super::serialize_struct::{emit_chain, emit_struct, guard_depth};
19
use super::{LOCAL_GC_ARR, LOCAL_IDX, LOCAL_TEMP_I32, LOCAL_TEMP_RATIO};
20

            
21
const PLACEHOLDER: &[u8] = b"<anyref>";
22

            
23
/// Writes the `AnyRef` on the stack.
24
36327
pub(super) fn serialize_anyref_to_output(
25
36327
    ctx: &mut CompileContext,
26
36327
    emit: &mut FunctionEmitter,
27
36327
) -> Result<()> {
28
36327
    let value = ctx.alloc_local(WasmType::AnyRef)?;
29
36327
    emit.local_set(value);
30
36327
    emit_value(ctx, emit, value)
31
36327
}
32

            
33
/// Writes the list (a nullable `$pair`) on the stack.
34
80869
pub(super) fn serialize_list_to_output(
35
80869
    ctx: &mut CompileContext,
36
80869
    emit: &mut FunctionEmitter,
37
80869
) -> Result<()> {
38
80869
    let cursor = ctx.alloc_local(WasmType::PairRef(PairElement::AnyRef))?;
39
80869
    emit.local_set(cursor);
40
80869
    nil_or(ctx, emit, cursor, |ctx, emit| {
41
80869
        emit_list(ctx, emit, cursor, ValueType::List)
42
80869
    })
43
80869
}
44

            
45
/// Writes the entity reference (nullable) on the stack: nil, else its kind tag.
46
1282
pub(super) fn serialize_entity_to_output(
47
1282
    ctx: &mut CompileContext,
48
1282
    emit: &mut FunctionEmitter,
49
1282
    kind: EntityKind,
50
1282
) -> Result<()> {
51
1282
    let entity = ctx.alloc_local(WasmType::EntityRef(kind))?;
52
1282
    emit.local_set(entity);
53
1282
    nil_or(ctx, emit, entity, |ctx, emit| {
54
1282
        ctx.serializer().write_debug_entity_tag(emit, kind)
55
1282
    })
56
1282
}
57

            
58
/// Writes the symbol (nullable) on the stack: nil, else its name as a symbol.
59
1486
pub(super) fn serialize_symbol_to_output(
60
1486
    ctx: &mut CompileContext,
61
1486
    emit: &mut FunctionEmitter,
62
1486
) -> Result<()> {
63
1486
    let symbol = ctx.alloc_local(WasmType::SymbolRef)?;
64
1486
    emit.local_set(symbol);
65
1486
    nil_or(ctx, emit, symbol, |ctx, emit| {
66
1486
        let gc = GcLocals {
67
1486
            type_idx: ctx.ids.ty_i8_array,
68
1486
            arr: LOCAL_GC_ARR,
69
1486
            idx: LOCAL_IDX,
70
1486
        };
71
1486
        emit.local_get(symbol);
72
1486
        emit.struct_get(ctx.ids.ty_symbol, 0);
73
1486
        ctx.serializer()
74
1486
            .write_debug_string_from_stack(emit, ValueType::Symbol, &gc)
75
1486
    })
76
1486
}
77

            
78
/// Writes nil when the reference in `local` is null, else what `write` emits.
79
290981
pub(super) fn nil_or(
80
290981
    ctx: &mut CompileContext,
81
290981
    emit: &mut FunctionEmitter,
82
290981
    local: u32,
83
290981
    write: impl FnOnce(&mut CompileContext, &mut FunctionEmitter) -> Result<()>,
84
290981
) -> Result<()> {
85
290981
    emit.local_get(local);
86
290981
    emit.ref_is_null();
87
290981
    emit.if_block(BlockType::Empty);
88
290981
    ctx.serializer().write_debug_tag(emit, ValueType::Nil)?;
89
290981
    emit.else_block();
90
290981
    write(ctx, emit)?;
91
290981
    emit.block_end()
92
290981
}
93

            
94
/// The value in the `AnyRef` local `value`: nil, a list, or an atom.
95
36327
fn emit_value(ctx: &mut CompileContext, emit: &mut FunctionEmitter, value: u32) -> Result<()> {
96
36327
    nil_or(ctx, emit, value, |ctx, emit| {
97
36327
        let pair = ctx.ids.ty_pair;
98
36327
        emit.local_get(value);
99
36327
        emit.ref_test(pair);
100
36327
        emit.if_block(BlockType::Empty);
101
36327
        let cursor = ctx.alloc_local(WasmType::PairRef(PairElement::AnyRef))?;
102
36327
        emit.local_get(value);
103
36327
        emit.ref_cast_nullable(pair);
104
36327
        emit.local_set(cursor);
105
36327
        emit_list(ctx, emit, cursor, ValueType::List)?;
106
36327
        emit.else_block();
107
36327
        emit.local_get(value);
108
36327
        emit.ref_test(ctx.ids.ty_struct);
109
36327
        emit.if_block(BlockType::Empty);
110
36327
        let instance = ctx.alloc_local(WasmType::StructRef(StructId(0)))?;
111
36327
        emit.local_get(value);
112
36327
        emit.ref_cast_nullable(ctx.ids.ty_struct);
113
36327
        emit.local_set(instance);
114
36327
        emit_struct(ctx, emit, instance)?;
115
36327
        emit.else_block();
116
36327
        emit_atom(ctx, emit, value)?;
117
36327
        emit.block_end()?;
118
36327
        emit.block_end()
119
36327
    })
120
36327
}
121

            
122
/// Walks the non-null list in `cursor`, opened by `open`. On a nested list or
123
/// struct the rest of the current one is pushed onto `pending`; on each
124
/// list's end it is popped. Nesting past `MAX_WIRE_LIST_DEPTH` is written as
125
/// a placeholder, so a struct holding itself ends.
126
162270
pub(super) fn emit_list(
127
162270
    ctx: &mut CompileContext,
128
162270
    emit: &mut FunctionEmitter,
129
162270
    cursor: u32,
130
162270
    open: ValueType,
131
162270
) -> Result<()> {
132
162270
    let pair = ctx.ids.ty_pair;
133
162270
    let pending = ctx.alloc_local(WasmType::PairRef(PairElement::AnyRef))?;
134
162270
    let car = ctx.alloc_local(WasmType::AnyRef)?;
135
162270
    let depth = ctx.alloc_local(WasmType::I32)?;
136
162270
    emit.i32_const(1);
137
162270
    emit.local_set(depth);
138
162270
    emit.ref_null(pair);
139
162270
    emit.local_set(pending);
140
162270
    ctx.serializer().write_debug_tag(emit, open)?;
141
162270
    emit.block_start();
142
162270
    emit.loop_start();
143

            
144
162270
    emit.local_get(cursor);
145
162270
    emit.ref_is_null();
146
162270
    emit.if_block(BlockType::Empty);
147
162270
    ctx.serializer().write_debug_tag(emit, ValueType::ListEnd)?;
148
162270
    emit.local_get(pending);
149
162270
    emit.ref_is_null();
150
162270
    emit.br_if(2);
151
162270
    emit.local_get(depth);
152
162270
    emit.i32_const(1);
153
162270
    emit.i32_sub();
154
162270
    emit.local_set(depth);
155
162270
    emit.local_get(pending);
156
162270
    emit.struct_get(pair, 0);
157
162270
    emit.ref_cast_nullable(pair);
158
162270
    emit.local_set(cursor);
159
162270
    emit.local_get(pending);
160
162270
    emit.struct_get(pair, 1);
161
162270
    emit.local_set(pending);
162
162270
    emit.br(1);
163
162270
    emit.block_end()?;
164

            
165
162270
    emit.local_get(cursor);
166
162270
    emit.struct_get(pair, 0);
167
162270
    emit.local_set(car);
168
162270
    emit.local_get(cursor);
169
162270
    emit.struct_get(pair, 1);
170
162270
    emit.local_set(cursor);
171

            
172
162270
    nil_or(ctx, emit, car, |ctx, emit| {
173
162270
        emit.local_get(car);
174
162270
        emit.ref_test(pair);
175
162270
        emit.if_block(BlockType::Empty);
176
162270
        guard_depth(ctx, emit, depth, |ctx, emit| {
177
162270
            push_rest(ctx, emit, cursor, pending, ValueType::List)?;
178
162270
            emit.local_get(car);
179
162270
            emit.ref_cast_nullable(pair);
180
162270
            emit.local_set(cursor);
181
162270
            Ok(())
182
162270
        })?;
183
162270
        emit.else_block();
184
162270
        emit.local_get(car);
185
162270
        emit.ref_test(ctx.ids.ty_struct);
186
162270
        emit.if_block(BlockType::Empty);
187
162270
        guard_depth(ctx, emit, depth, |ctx, emit| {
188
162270
            push_rest(ctx, emit, cursor, pending, ValueType::Struct)?;
189
162270
            let instance = ctx.alloc_local(WasmType::StructRef(StructId(0)))?;
190
162270
            emit.local_get(car);
191
162270
            emit.ref_cast_nullable(ctx.ids.ty_struct);
192
162270
            emit.local_set(instance);
193
162270
            emit_chain(ctx, emit, instance, cursor)
194
162270
        })?;
195
162270
        emit.else_block();
196
162270
        emit_atom(ctx, emit, car)?;
197
162270
        emit.block_end()?;
198
162270
        emit.block_end()
199
162270
    })?;
200

            
201
162270
    emit.br(0);
202
162270
    emit.block_end()?;
203
162270
    emit.block_end()
204
162270
}
205

            
206
/// Pushes the rest of the current list, in `cursor`, onto `pending` and
207
/// writes the `open` tag of the nested list or struct.
208
324540
fn push_rest(
209
324540
    ctx: &mut CompileContext,
210
324540
    emit: &mut FunctionEmitter,
211
324540
    cursor: u32,
212
324540
    pending: u32,
213
324540
    open: ValueType,
214
324540
) -> Result<()> {
215
324540
    emit.local_get(cursor);
216
324540
    emit.local_get(pending);
217
324540
    emit.struct_new(ctx.ids.ty_pair);
218
324540
    emit.local_set(pending);
219
324540
    ctx.serializer().write_debug_tag(emit, open)
220
324540
}
221

            
222
/// The non-null, non-list value in `value`: the `$t` singleton (by `ref.eq`,
223
/// never a type test, as WasmGC struct types are structural), an index, a
224
/// scalar, a string, money, an entity of each kind (the entity structs share
225
/// one recursion group, so same-shaped kinds are distinct types) or a
226
/// closure (by its `$closure_base` supertype). Every kind the guest can box
227
/// is tagged; the `<anyref>` placeholder remains only as the final arm no
228
/// value reaches.
229
198597
fn emit_atom(ctx: &mut CompileContext, emit: &mut FunctionEmitter, value: u32) -> Result<()> {
230
198597
    let ratio = ctx.ids.ty_ratio;
231
198597
    let i8_array = ctx.ids.ty_i8_array;
232
198597
    let gc = GcLocals {
233
198597
        type_idx: i8_array,
234
198597
        arr: LOCAL_GC_ARR,
235
198597
        idx: LOCAL_IDX,
236
198597
    };
237
198597
    let mut open = 0;
238

            
239
198597
    emit.local_get(value);
240
198597
    emit.ref_cast_eq();
241
198597
    emit.global_get(ctx.ids.global_t);
242
198597
    emit.ref_eq();
243
198597
    emit.if_block(BlockType::Empty);
244
198597
    open += 1;
245
198597
    ctx.serializer().write_debug_tag(emit, ValueType::T)?;
246
198597
    emit.else_block();
247

            
248
198597
    emit.local_get(value);
249
198597
    emit.ref_test_i31();
250
198597
    emit.if_block(BlockType::Empty);
251
198597
    open += 1;
252
198597
    emit.local_get(value);
253
198597
    emit.ref_cast_i31();
254
198597
    emit.i31_get_s();
255
198597
    ctx.serializer()
256
198597
        .write_debug_i32_from_stack(emit, LOCAL_TEMP_I32)?;
257
198597
    emit.else_block();
258

            
259
198597
    open += open_kind_test(emit, value, ratio);
260
198597
    emit.local_get(value);
261
198597
    emit.ref_cast(ratio);
262
198597
    ctx.serializer()
263
198597
        .write_debug_number_from_stack(emit, ratio, LOCAL_TEMP_RATIO)?;
264
198597
    emit.else_block();
265

            
266
198597
    open += open_kind_test(emit, value, i8_array);
267
198597
    emit.local_get(value);
268
198597
    emit.ref_cast(i8_array);
269
198597
    ctx.serializer()
270
198597
        .write_debug_string_from_stack(emit, ValueType::String, &gc)?;
271
198597
    emit.else_block();
272

            
273
198597
    open += open_kind_test(emit, value, ctx.ids.ty_symbol);
274
198597
    emit.local_get(value);
275
198597
    emit.ref_cast(ctx.ids.ty_symbol);
276
198597
    emit.struct_get(ctx.ids.ty_symbol, 0);
277
198597
    ctx.serializer()
278
198597
        .write_debug_string_from_stack(emit, ValueType::Symbol, &gc)?;
279
198597
    emit.else_block();
280

            
281
198597
    let money = money_ids(ctx);
282
198597
    let money_local = ctx.alloc_local(WasmType::Commodity)?;
283
198597
    open += open_kind_test(emit, value, money.ty_commodity);
284
198597
    emit.local_get(value);
285
198597
    emit.ref_cast(money.ty_commodity);
286
198597
    ctx.serializer()
287
198597
        .write_debug_commodity_from_stack(emit, money, money_local)?;
288
198597
    emit.else_block();
289

            
290
198597
    for kind in EntityKind::ALL {
291
1588776
        open += open_kind_test(emit, value, ctx.ids.entity_type(kind));
292
1588776
        ctx.serializer().write_debug_entity_tag(emit, kind)?;
293
1588776
        emit.else_block();
294
    }
295

            
296
198597
    let closure_base = ctx.ids.ty_closure_base;
297
198597
    open += open_kind_test(emit, value, closure_base);
298
198597
    emit.local_get(value);
299
198597
    emit.ref_cast(closure_base);
300
198597
    ctx.serializer()
301
198597
        .write_debug_closure_from_stack(emit, closure_base, LOCAL_TEMP_I32)?;
302
198597
    emit.else_block();
303

            
304
198597
    let placeholder = ctx.add_data(PLACEHOLDER)?;
305
198597
    let len = u32::try_from(PLACEHOLDER.len())
306
        .map_err(|_| Error::Compile("internal: placeholder length overflows".to_string()))?;
307
198597
    ctx.serializer()
308
198597
        .write_debug_string_gc(emit, ValueType::String, placeholder, len, &gc)?;
309

            
310
198597
    for _ in 0..open {
311
2978955
        emit.block_end()?;
312
    }
313
198597
    Ok(())
314
198597
}
315

            
316
/// Opens the `if` arm taken when `value` is of the struct/array `type_idx`;
317
/// the one block it opens, for the caller's count.
318
2581761
fn open_kind_test(emit: &mut FunctionEmitter, value: u32, type_idx: u32) -> usize {
319
2581761
    emit.local_get(value);
320
2581761
    emit.ref_test(type_idx);
321
2581761
    emit.if_block(BlockType::Empty);
322
2581761
    1
323
2581761
}