mrubyedge 2.1.2

mruby/edge is yet another mruby that is specialized for running on WASM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
extern crate mrubyedge;

use super::helpers::*;

#[test]
fn test_rite_parse_hello_world() {
    let code = r#"
    puts "Hello, World!"
    "#;
    let binary = mrbc_compile("hello", code);
    let rite = mrubyedge::rite::load(&binary).unwrap();

    // Check binary header
    assert_eq!(&rite.binary_header.ident, b"RITE");
    assert_eq!(&rite.binary_header.major_version, b"04");
    assert_eq!(&rite.binary_header.minor_version, b"00");

    // Check IREP section
    assert_eq!(rite.irep.len(), 1);
    let irep = &rite.irep[0];

    // Should have at least some instructions
    assert!(!irep.insn.is_empty());

    // Should have some pool values (for the string)
    assert!(irep.plen > 0);
}

#[test]
fn test_rite_parse_with_local_variables() {
    let code = r#"
    def greet(name)
      message = "Hello, #{name}!"
      puts message
      message
    end
    
    greet("Alice")
    "#;
    let binary = mrbc_compile("greet", code);
    let rite = mrubyedge::rite::load(&binary).unwrap();

    // Check binary header
    assert_eq!(&rite.binary_header.ident, b"RITE");

    // Should have multiple ireps (main + function definition)
    assert!(rite.irep.len() == 2);
    assert!(rite.irep[0].lv.is_empty());
    assert!(rite.irep[1].lv.len() == 3); // name, (&nil), message

    // Check LVAR section exists
    let lvar = rite.lvar.unwrap();
    assert!(lvar.syms.len() == 2);

    let name = rite.irep[1].lv[0].as_ref().cloned().unwrap();
    assert_eq!(&name.to_string_lossy(), "name");

    let message = rite.irep[1].lv[2].as_ref().cloned().unwrap();
    assert_eq!(&message.to_string_lossy(), "message");
}

#[test]
fn test_rite_parse_pool_values() {
    let code = r#"
    a = "string"
    b = 42
    c = 3.14
    d = 9999999999
    [a, b, c, d]
    "#;
    let binary = mrbc_compile("pool", code);
    let rite = mrubyedge::rite::load(&binary).unwrap();

    assert_eq!(&rite.binary_header.ident, b"RITE");

    let irep = &rite.irep[0];
    assert!(rite.lvar.unwrap().syms.len() == 4);

    // Should have multiple pool values
    assert!(irep.pool.len() == 3);
    assert!(irep.lv.len() == 4);

    // Check pool value types
    use mrubyedge::rite::PoolValue;
    let has_string = irep
        .pool
        .iter()
        .any(|p| matches!(p, PoolValue::Str(_) | PoolValue::SStr(_)));
    let has_float = irep.pool.iter().any(|p| matches!(p, PoolValue::Float(_)));
    let has_int64 = irep.pool.iter().any(|p| matches!(p, PoolValue::Int64(_)));

    assert!(has_string, "Should have string in pool");
    assert!(has_float, "Should have float in pool");
    assert!(has_int64, "Should have int64 in pool");
}

#[test]
fn test_rite_parse_bigint_pool_value() {
    let code = r#"
    x = 99999999999999999999999
    x
    "#;
    let binary = mrbc_compile("bigint", code);

    let rite = mrubyedge::rite::load(&binary).unwrap();

    use mrubyedge::rite::PoolValue;
    let bigint = rite.irep[0]
        .pool
        .iter()
        .find_map(|p| match p {
            PoolValue::BigInt(bytes) => Some(bytes),
            _ => None,
        })
        .expect("Should have a BigInt in pool");

    // `[base][digits]`: base 10 followed by the 23 decimal digits.
    assert_eq!(bigint.len(), 24);
    assert_eq!(bigint[0], 10);
    assert!(bigint[1..].iter().all(|&b| b == b'9'));
}

#[test]
fn test_rite_truncated_bigint_is_error_not_panic() {
    let code = r#"
    x = 99999999999999999999999
    "#;
    let binary = mrbc_compile("bigint", code);
    let digits = [b'9'; 23];
    let digits_start = binary
        .windows(digits.len())
        .position(|w| w == digits)
        .expect("Should find the bigint digits");

    // Layout before the digits is [type=7][len:u8][base:i8].
    let len_pos = digits_start - 2;
    let mut chunk = binary.clone();
    chunk[len_pos] = 0xff;

    // An out-of-bounds length must be reported, not panic.
    assert!(mrubyedge::rite::load(&chunk).is_err());
}

#[test]
fn a_chunk_of_an_unknown_format_version_is_refused_test() {
    let code = r#"
    1 + 1
    "#;
    let binary = mrbc_compile("compiled", code);

    // Bytes 4 and 5 of the header are the major version. mruby 3.x chunks are
    // refused too: the opcode numbering is not the one this VM decodes.
    for major in [b"02", b"03", b"05"] {
        let mut chunk = binary.clone();
        chunk[4..6].copy_from_slice(major);

        // Assert
        let err = mrubyedge::rite::load(&chunk).unwrap_err();
        assert!(matches!(err, mrubyedge::rite::Error::UnsupportedVersion(m) if &m == major));
    }
}

#[test]
fn dbg_lines_from_ruby_source_are_retained_test() {
    let code = r#"
    def answer
      x = 40
      x + 2
    end
    answer
    "#;
    let binary = mrbc_compile_with_debug(code);

    let rite = mrubyedge::rite::load(&binary).unwrap();
    assert_eq!(rite.irep.len(), 2);
    assert_eq!(rite.irep[0].lines, vec![(0, 2), (4, 6)]);
    assert_eq!(rite.irep[1].lines, vec![(0, 2), (4, 3), (7, 4)]);

    // Offsets are byte positions, including bytes inside an instruction.
    use mrubyedge::rite::line_at;
    assert_eq!(line_at(&rite.irep[0].lines, 4), Some(6)); // answer
    assert_eq!(line_at(&rite.irep[1].lines, 4), Some(3)); // x = 40
    assert_eq!(line_at(&rite.irep[1].lines, 6), Some(3));
    assert_eq!(line_at(&rite.irep[1].lines, 7), Some(4)); // x + 2
}

// Synthetic sections exercise each encoding and malformed input separately.

fn splice_before_end(mut chunk: Vec<u8>, section: &[u8]) -> Vec<u8> {
    let end_at = chunk.len() - 8; // "END\0" + size
    let total = u32::from_be_bytes(chunk[8..12].try_into().unwrap()) + section.len() as u32;
    chunk[8..12].copy_from_slice(&total.to_be_bytes());
    let mut out = chunk[..end_at].to_vec();
    out.extend_from_slice(section);
    out.extend_from_slice(&chunk[end_at..]);
    out
}

/// One-record DBG section for a single-irep chunk: filename table with one
/// entry, then a record with one file entry of the given line_type.
fn dbg_section(line_type: u8, entry_count: u32, payload: &[u8]) -> Vec<u8> {
    let mut record = Vec::new();
    record.extend_from_slice(&1u16.to_be_bytes()); // file entries in the record
    record.extend_from_slice(&0u32.to_be_bytes()); // start_pos
    record.extend_from_slice(&0u16.to_be_bytes()); // filename index
    record.extend_from_slice(&entry_count.to_be_bytes());
    record.push(line_type);
    record.extend_from_slice(payload);

    let mut body = Vec::new();
    body.extend_from_slice(&1u16.to_be_bytes()); // filename table: 1 entry
    body.extend_from_slice(&4u16.to_be_bytes());
    body.extend_from_slice(b"a.rb");
    // The record size includes its own 4 length bytes.
    body.extend_from_slice(&((record.len() as u32 + 4).to_be_bytes()));
    body.extend_from_slice(&record);

    let mut section = Vec::new();
    section.extend_from_slice(b"DBG\0");
    section.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes());
    section.extend_from_slice(&body);
    section
}

fn compiled_two_line_snippet() -> Vec<u8> {
    let code = r#"
    x = 1
    y = 2
    "#;
    mrbc_compile("dbg_snip", code)
}

#[test]
fn dbg_flat_map_lines_are_parsed_test() {
    // (pos, line) pairs: (0,1), (2,2).
    let mut payload = Vec::new();
    payload.extend_from_slice(&0u32.to_be_bytes());
    payload.extend_from_slice(&1u16.to_be_bytes());
    payload.extend_from_slice(&2u32.to_be_bytes());
    payload.extend_from_slice(&2u16.to_be_bytes());
    let chunk = splice_before_end(compiled_two_line_snippet(), &dbg_section(1, 2, &payload));

    let rite = mrubyedge::rite::load(&chunk).unwrap();
    assert_eq!(rite.irep[0].lines, vec![(0, 1), (2, 2)]);

    use mrubyedge::rite::line_at;
    assert_eq!(line_at(&rite.irep[0].lines, 0), Some(1));
    assert_eq!(line_at(&rite.irep[0].lines, 1), Some(1));
    assert_eq!(line_at(&rite.irep[0].lines, 2), Some(2));
    assert_eq!(line_at(&rite.irep[0].lines, 99), Some(2));
}

#[test]
fn dbg_line_ary_lines_are_parsed_test() {
    // One line per pc starting at start_pos; consecutive equal lines dedup.
    let payload = [1u16, 1, 2]
        .iter()
        .flat_map(|l| l.to_be_bytes())
        .collect::<Vec<u8>>();
    let chunk = splice_before_end(compiled_two_line_snippet(), &dbg_section(0, 3, &payload));

    let rite = mrubyedge::rite::load(&chunk).unwrap();
    assert_eq!(rite.irep[0].lines, vec![(0, 1), (2, 2)]);
}

#[test]
fn dbg_packed_map_lines_are_parsed_test() {
    // entry_count is the byte length; varint (pos_delta, line_delta) pairs.
    let payload = [0x00u8, 0x01, 0x02, 0x01];
    let chunk = splice_before_end(
        compiled_two_line_snippet(),
        &dbg_section(2, payload.len() as u32, &payload),
    );

    let rite = mrubyedge::rite::load(&chunk).unwrap();
    assert_eq!(rite.irep[0].lines, vec![(0, 1), (2, 2)]);
}

#[test]
fn dbg_record_size_mismatch_is_rejected_test() {
    let mut payload = Vec::new();
    payload.extend_from_slice(&0u32.to_be_bytes());
    payload.extend_from_slice(&1u16.to_be_bytes());
    let mut section = dbg_section(1, 1, &payload);
    // Corrupt the record size field: layout is DBG\0(4) size(4) count(2)
    // len(2) "a.rb"(4) record_size(4), so it starts at offset 16.
    section[16] = 0xff;

    let chunk = splice_before_end(compiled_two_line_snippet(), &section);
    assert!(mrubyedge::rite::load(&chunk).is_err());
}

#[test]
fn dbg_section_shorter_than_declared_is_rejected_test() {
    let mut section = dbg_section(0, 0, &[]);
    // Declare more section bytes than exist.
    let size = u32::from_be_bytes(section[4..8].try_into().unwrap()) + 64;
    section[4..8].copy_from_slice(&size.to_be_bytes());

    let chunk = splice_before_end(compiled_two_line_snippet(), &section);
    let err = mrubyedge::rite::load(&chunk).unwrap_err();
    assert!(matches!(err, mrubyedge::rite::Error::TooShort));
}

#[test]
fn chunk_without_dbg_section_still_loads_with_empty_lines_test() {
    let code = r#"
    x = 1
    "#;
    let binary = mrbc_compile("no_dbg", code);
    let rite = mrubyedge::rite::load(&binary).unwrap();
    assert!(rite.irep[0].lines.is_empty());
}

#[test]
fn vm_irep_retains_source_lines_test() {
    let code = r#"
    def answer
      x = 40
      x + 2
    end
    answer
    "#;
    let binary = mrbc_compile_with_debug(code);
    let mut rite = mrubyedge::rite::load(&binary).unwrap();
    let vm = mrubyedge::yamrb::vm::VM::open(&mut rite);
    drop(rite);
    drop(binary);

    assert_eq!(vm.irep.debug_line(0), Some(2));
    assert_eq!(vm.irep.debug_line(4), Some(6));
    let method = &vm.irep.reps[0];
    assert_eq!(method.debug_line(4), Some(3));
    assert_eq!(method.debug_line(6), Some(3));
    assert_eq!(method.debug_line(7), Some(4));
    assert_eq!(
        method.debug_line(method.debug_info.as_ref().unwrap().pc_count),
        None
    );
    assert_eq!(method.debug_line(usize::MAX), None);

    let code = r#"
    1
    "#;
    let binary = mrbc_compile("no_debug", code);
    let mut rite = mrubyedge::rite::load(&binary).unwrap();
    let vm = mrubyedge::yamrb::vm::VM::open(&mut rite);
    assert!(vm.irep.debug_info.is_none());
    assert_eq!(vm.irep.debug_line(0), None);
}

#[test]
fn debug_filenames_survive_loading_into_vm_test() {
    let code = r#"
    def answer
      42
    end
    answer
    "#;
    let binary = mrbc_compile_named_debug("source.rb", code);
    let mut rite = mrubyedge::rite::load(&binary).unwrap();
    for irep in &rite.irep {
        assert_eq!(irep.debug_files[0].filename.to_bytes(), b"source.rb");
    }
    let vm = mrubyedge::yamrb::vm::VM::open(&mut rite);
    drop(rite);
    drop(binary);
    assert_eq!(vm.irep.debug_filename(0).unwrap().to_bytes(), b"source.rb");
    assert_eq!(
        vm.irep.reps[0].debug_filename(0).unwrap().to_bytes(),
        b"source.rb"
    );
    assert_eq!(vm.irep.debug_filename(usize::MAX), None);
    assert_eq!(
        mrubyedge::yamrb::vm::VM::empty().irep.debug_filename(0),
        None
    );
}

#[test]
fn debug_filename_index_is_validated_test() {
    let mut section = dbg_section(0, 1, &1u16.to_be_bytes());
    // Record header (size + file count), start_pos, then filename index.
    section[26..28].copy_from_slice(&1u16.to_be_bytes());
    let binary = splice_before_end(compiled_two_line_snippet(), &section);
    assert!(matches!(
        mrubyedge::rite::load(&binary),
        Err(mrubyedge::rite::Error::InvalidFormat)
    ));
}

#[test]
fn debug_multiple_files_select_their_own_line_maps_test() {
    let mut body = Vec::new();
    body.extend_from_slice(&2u16.to_be_bytes());
    for name in [b"a.rb", b"b.rb"] {
        body.extend_from_slice(&4u16.to_be_bytes());
        body.extend_from_slice(name);
    }
    let mut record = Vec::new();
    record.extend_from_slice(&2u16.to_be_bytes());
    // The second file starts at byte 2 but its first mapped line is at byte 3.
    for (start, filename, pos, line) in [(0u32, 0u16, 0u32, 10u16), (2, 1, 3, 20)] {
        record.extend_from_slice(&start.to_be_bytes());
        record.extend_from_slice(&filename.to_be_bytes());
        record.extend_from_slice(&1u32.to_be_bytes());
        record.push(1); // flat map
        record.extend_from_slice(&pos.to_be_bytes());
        record.extend_from_slice(&line.to_be_bytes());
    }
    body.extend_from_slice(&((record.len() + 4) as u32).to_be_bytes());
    body.extend_from_slice(&record);
    let mut section = b"DBG\0".to_vec();
    section.extend_from_slice(&((body.len() + 8) as u32).to_be_bytes());
    section.extend_from_slice(&body);
    let binary = splice_before_end(compiled_two_line_snippet(), &section);
    let mut rite = mrubyedge::rite::load(&binary).unwrap();
    let vm = mrubyedge::yamrb::vm::VM::open(&mut rite);
    assert_eq!(vm.irep.debug_filename(1).unwrap().to_bytes(), b"a.rb");
    assert_eq!(vm.irep.debug_line(1), Some(10));
    assert_eq!(vm.irep.debug_filename(2).unwrap().to_bytes(), b"b.rb");
    assert_eq!(vm.irep.debug_line(2), None);
    assert_eq!(vm.irep.debug_line(3), Some(20));
}