ox_mf2_parser 0.1.6

High Performance MessageFormat 2 parser core with CST, diagnostics, recovery, semantic lowering, and binary snapshot support.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// @license MIT
// @author kazuya kawaguchi (a.k.a. kazupon)

//! Invalid snapshot fixtures — each test mutates a known-valid
//! baseline in exactly one place and asserts that
//! [`decode_snapshot`] returns the matching [`DecodeErrorCode`]
//! without panicking.

use ox_mf2_parser::snapshot::{
    decode_snapshot, parse_source_to_snapshot, DecodeErrorCode, SectionKind, SnapshotOptions,
    HEADER_SIZE, SECTION_RECORD_SIZE,
};
use ox_mf2_parser::{ParseOptions, SourceFileInput, SourceStore};

fn baseline() -> Vec<u8> {
    let mut sources = SourceStore::new();
    let id = sources.add(SourceFileInput {
        source: "Hi",
        ..Default::default()
    });
    parse_source_to_snapshot(
        &sources,
        id,
        ParseOptions::default(),
        SnapshotOptions::default(),
    )
    .unwrap()
    .bytes
}

fn section_record_offset(bytes: &[u8], kind: SectionKind) -> Option<usize> {
    let count = u16::from_le_bytes(bytes[24..26].try_into().unwrap()) as usize;
    for i in 0..count {
        let off = HEADER_SIZE as usize + i * SECTION_RECORD_SIZE as usize;
        let k = u16::from_le_bytes(bytes[off..off + 2].try_into().unwrap());
        if k == kind.as_u16() {
            return Some(off);
        }
    }
    None
}

fn section_payload_offset(bytes: &[u8], kind: SectionKind) -> usize {
    let rec = section_record_offset(bytes, kind).expect("section present");
    u32::from_le_bytes(bytes[rec + 4..rec + 8].try_into().unwrap()) as usize
}

fn section_count_for(bytes: &[u8], kind: SectionKind) -> u32 {
    let rec = section_record_offset(bytes, kind).expect("section present");
    u32::from_le_bytes(bytes[rec + 12..rec + 16].try_into().unwrap())
}

#[test]
fn bad_magic_is_rejected() {
    let mut bytes = baseline();
    bytes[0] = b'X';
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidMagic);
}

#[test]
fn unsupported_major_version_is_rejected() {
    let mut bytes = baseline();
    bytes[8] = 0x99;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::UnsupportedMajorVersion);
}

#[test]
fn unsupported_minor_version_is_rejected() {
    let mut bytes = baseline();
    bytes[10] = 0x99;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::UnsupportedMinorVersion);
}

#[test]
fn nonzero_feature_flags_are_rejected() {
    let mut bytes = baseline();
    bytes[12] = 1;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidFeatureFlags);
}

#[test]
fn nonzero_header_reserved_is_rejected() {
    let mut bytes = baseline();
    bytes[26] = 1; // reserved u16 low byte
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidReservedField);
}

#[test]
fn nonzero_header_reserved_tail_is_rejected() {
    let mut bytes = baseline();
    bytes[28] = 1; // reserved_tail u32 low byte
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidReservedField);
}

#[test]
fn wrong_header_length_is_rejected() {
    let mut bytes = baseline();
    bytes[16] = 33;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidHeaderLength);
}

#[test]
fn buffer_shorter_than_header_is_rejected() {
    let bytes = vec![0u8; 16];
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::BufferTooShort);
}

#[test]
fn missing_required_section_is_rejected() {
    // Drop the last entry from the section table — that entry is one
    // of the required core sections in the baseline (StringData),
    // because the canonical writer order ends with the string data
    // section in the no-trivia, no-diagnostics baseline.
    let mut bytes = baseline();
    let count = u16::from_le_bytes(bytes[24..26].try_into().unwrap());
    bytes[24..26].copy_from_slice(&(count - 1).to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::MissingRequiredSection);
}

#[test]
fn duplicate_section_is_rejected() {
    let mut bytes = baseline();
    // Rewrite a non-Roots section record's kind to Roots.
    let off = section_record_offset(&bytes, SectionKind::Sources).expect("sources");
    bytes[off] = SectionKind::Roots.as_u16() as u8;
    bytes[off + 1] = 0;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::DuplicateSection);
}

#[test]
fn unknown_section_kind_is_rejected() {
    let mut bytes = baseline();
    // Change one section's kind to a value not in v0.1.
    let off = section_record_offset(&bytes, SectionKind::Edges).expect("edges");
    bytes[off] = 99; // not a known kind
    bytes[off + 1] = 0;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::UnknownSection);
}

#[test]
fn nonzero_section_reserved_is_rejected() {
    let mut bytes = baseline();
    let off = section_record_offset(&bytes, SectionKind::Roots).expect("roots");
    bytes[off + 19] = 1; // reserved byte
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidReservedField);
}

#[test]
fn wrong_section_alignment_is_rejected() {
    let mut bytes = baseline();
    let off = section_record_offset(&bytes, SectionKind::Roots).expect("roots");
    bytes[off + 18] = 4; // alignment must be 8
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSectionAlignment);
}

#[test]
fn wrong_record_size_is_rejected() {
    let mut bytes = baseline();
    let off = section_record_offset(&bytes, SectionKind::Nodes).expect("nodes");
    bytes[off + 16] = 32; // record_size low byte (was 24)
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidRecordSize);
}

#[test]
fn core_section_without_required_flag_is_rejected() {
    let mut bytes = baseline();
    let off = section_record_offset(&bytes, SectionKind::Roots).expect("roots");
    bytes[off + 2] = 0; // flags low byte (clear required)
    bytes[off + 3] = 0;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSectionFlags);
}

#[test]
fn nonzero_padding_is_rejected() {
    let mut bytes = baseline();
    // The padding between the section table and the first section.
    // For the baseline with 7 sections, the section table ends at
    // 32 + 7*20 = 172 and the first section starts at 176 — so
    // bytes [172..176) are padding.
    let count = u16::from_le_bytes(bytes[24..26].try_into().unwrap()) as usize;
    let table_end = HEADER_SIZE as usize + count * SECTION_RECORD_SIZE as usize;
    assert!(bytes[table_end] == 0);
    bytes[table_end] = 0xFF;
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidPadding);
}

#[test]
fn trailing_padding_is_rejected() {
    let mut bytes = baseline();
    bytes.push(0);
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::TrailingPadding);
}

#[test]
fn out_of_range_root_node_is_rejected() {
    let mut bytes = baseline();
    let roots_off = section_payload_offset(&bytes, SectionKind::Roots);
    // root_node field is the first u32 of RootRecord.
    bytes[roots_off..roots_off + 4].copy_from_slice(&u32::MAX.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidRootRef);
}

#[test]
fn out_of_range_root_source_is_rejected() {
    let mut bytes = baseline();
    let roots_off = section_payload_offset(&bytes, SectionKind::Roots);
    // source_id field is the second u32 of RootRecord.
    bytes[roots_off + 4..roots_off + 8].copy_from_slice(&u32::MAX.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSourceRef);
}

#[test]
fn out_of_range_node_child_range_is_rejected() {
    let mut bytes = baseline();
    let nodes_off = section_payload_offset(&bytes, SectionKind::Nodes);
    // NodeRecord layout: kind u16, flags u16, span_start u32,
    // span_end u32, first_child u32, child_count u32, data_ref u32.
    // first_child is at offset 12; child_count at 16. Set first_child
    // to a huge value.
    bytes[nodes_off + 12..nodes_off + 16].copy_from_slice(&u32::MAX.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidNodeRef);
}

#[test]
fn unknown_syntax_kind_in_node_is_rejected() {
    let mut bytes = baseline();
    let nodes_off = section_payload_offset(&bytes, SectionKind::Nodes);
    // kind is the first u16 of the first NodeRecord.
    bytes[nodes_off..nodes_off + 2].copy_from_slice(&777u16.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::UnknownSyntaxKind);
}

#[test]
fn nonzero_node_flags_is_rejected() {
    let mut bytes = baseline();
    let nodes_off = section_payload_offset(&bytes, SectionKind::Nodes);
    // flags is the second u16.
    bytes[nodes_off + 2..nodes_off + 4].copy_from_slice(&1u16.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidReservedField);
}

#[test]
fn nonzero_token_reserved_tail_is_rejected() {
    let mut bytes = baseline();
    let tokens_off = section_payload_offset(&bytes, SectionKind::Tokens);
    // TokenRecord: kind u16, flags u16, span_start u32, span_end u32,
    // source_id u32, lead_start u32, lead_count u32, trail_start u32,
    // trail_count u32, reserved_tail u32. reserved_tail is at offset 32.
    bytes[tokens_off + 32..tokens_off + 36].copy_from_slice(&1u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidReservedField);
}

#[test]
fn out_of_range_edge_token_ref_is_rejected() {
    let mut bytes = baseline();
    let edges_off = section_payload_offset(&bytes, SectionKind::Edges);
    let edge_count = section_count_for(&bytes, SectionKind::Edges);
    // EdgeRecord: kind u16, flags u16, ref_id u32 (record size 8).
    // Locate the first token edge (kind == EDGE_KIND_TOKEN == 1)
    // dynamically so the test stays decoder-focused even if the
    // parser reshapes edge order.
    let mut token_edge_off = None;
    for i in 0..edge_count {
        let off = edges_off + i as usize * 8;
        let kind = u16::from_le_bytes(bytes[off..off + 2].try_into().unwrap());
        if kind == 1 {
            token_edge_off = Some(off);
            break;
        }
    }
    let off = token_edge_off.expect("baseline must contain at least one token edge");
    bytes[off + 4..off + 8].copy_from_slice(&u32::MAX.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidTokenRef);
}

#[test]
fn invalid_edge_kind_is_rejected() {
    let mut bytes = baseline();
    let edges_off = section_payload_offset(&bytes, SectionKind::Edges);
    bytes[edges_off..edges_off + 2].copy_from_slice(&2u16.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidEdgeKind);
}

#[test]
fn invalid_source_text_sentinel_is_rejected() {
    let mut bytes = baseline();
    let sources_off = section_payload_offset(&bytes, SectionKind::Sources);
    // SourceRecord text: source_id u32 @ 20, offset u32 @ 24,
    // len u32 @ 28. Default has source_id = NONE_REF, offset = 0,
    // len = 0 — flipping len to 1 breaks the canonical sentinel.
    bytes[sources_off + 28..sources_off + 32].copy_from_slice(&1u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSourceTextRange);
}

#[test]
fn nonzero_node_data_ref_is_rejected() {
    let mut bytes = baseline();
    let nodes_off = section_payload_offset(&bytes, SectionKind::Nodes);
    // data_ref is the last u32 of NodeRecord at offset 20.
    bytes[nodes_off + 20..nodes_off + 24].copy_from_slice(&0u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidExtendedData);
}

#[test]
fn inverted_node_span_is_rejected() {
    let mut bytes = baseline();
    let nodes_off = section_payload_offset(&bytes, SectionKind::Nodes);
    // NodeRecord: kind u16, flags u16, span_start u32, span_end u32, ...
    // Set span_end < span_start (start stays at original value).
    let span_start = u32::from_le_bytes(bytes[nodes_off + 4..nodes_off + 8].try_into().unwrap());
    let span_end = span_start.saturating_sub(1);
    bytes[nodes_off + 8..nodes_off + 12].copy_from_slice(&span_end.to_le_bytes());
    if span_start == span_end {
        // Synthetic guard: pick a non-zero start so the test is meaningful.
        bytes[nodes_off + 4..nodes_off + 8].copy_from_slice(&1u32.to_le_bytes());
        bytes[nodes_off + 8..nodes_off + 12].copy_from_slice(&0u32.to_le_bytes());
    }
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSpan);
    assert_eq!(err.section, Some(SectionKind::Nodes));
}

#[test]
fn inverted_token_span_is_rejected() {
    let mut bytes = baseline();
    let tokens_off = section_payload_offset(&bytes, SectionKind::Tokens);
    // TokenRecord: kind u16, flags u16, span_start u32, span_end u32, ...
    bytes[tokens_off + 4..tokens_off + 8].copy_from_slice(&5u32.to_le_bytes());
    bytes[tokens_off + 8..tokens_off + 12].copy_from_slice(&2u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSpan);
    assert_eq!(err.section, Some(SectionKind::Tokens));
}

#[test]
fn inverted_trivia_span_is_rejected() {
    // A complex declaration produces real `ws` trivia between the
    // keyword and the variable expression — the simple text-only
    // pattern path keeps whitespace inside the `Text` token.
    let mut sources = SourceStore::new();
    let id = sources.add(SourceFileInput {
        source: ".input {$n :integer} {{count: {$n}}}",
        ..Default::default()
    });
    let snap = parse_source_to_snapshot(
        &sources,
        id,
        ParseOptions::default(),
        SnapshotOptions::default(),
    )
    .unwrap();
    let mut bytes = snap.bytes;
    let trivia_off = section_payload_offset(&bytes, SectionKind::Trivia);
    bytes[trivia_off + 4..trivia_off + 8].copy_from_slice(&9u32.to_le_bytes());
    bytes[trivia_off + 8..trivia_off + 12].copy_from_slice(&0u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSpan);
    assert_eq!(err.section, Some(SectionKind::Trivia));
}

#[test]
fn inverted_diagnostic_span_is_rejected() {
    let mut sources = SourceStore::new();
    let id = sources.add(SourceFileInput {
        source: "{$unclosed",
        ..Default::default()
    });
    let snap = parse_source_to_snapshot(
        &sources,
        id,
        ParseOptions::default(),
        SnapshotOptions::default(),
    )
    .unwrap();
    let mut bytes = snap.bytes;
    let diags_off = section_payload_offset(&bytes, SectionKind::Diagnostics);
    // DiagnosticRecord: source_id u32 (0), span_start u32 (4), span_end u32 (8).
    bytes[diags_off + 4..diags_off + 8].copy_from_slice(&10u32.to_le_bytes());
    bytes[diags_off + 8..diags_off + 12].copy_from_slice(&3u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidSpan);
    assert_eq!(err.section, Some(SectionKind::Diagnostics));
}

#[test]
fn string_offset_inside_multibyte_utf8_scalar_is_rejected() {
    // SourceFileInput.path "あ" interns as a 3-byte UTF-8 string.
    let mut sources = SourceStore::new();
    let id = sources.add(SourceFileInput {
        source: "x",
        path: Some(""),
        ..Default::default()
    });
    let snap = parse_source_to_snapshot(
        &sources,
        id,
        ParseOptions::default(),
        SnapshotOptions::default(),
    )
    .unwrap();
    let mut bytes = snap.bytes;
    // First StringOffsetRecord: offset u32 (0), len u32 (4). Move offset
    // forward by 1 so the slice splits the multibyte scalar. The full
    // StringData buffer remains valid UTF-8, so this test only passes when
    // per-slice validation is in place.
    let so_off = section_payload_offset(&bytes, SectionKind::StringOffsets);
    bytes[so_off..so_off + 4].copy_from_slice(&1u32.to_le_bytes());
    bytes[so_off + 4..so_off + 8].copy_from_slice(&2u32.to_le_bytes());
    let err = decode_snapshot(&bytes).unwrap_err();
    assert_eq!(err.code, DecodeErrorCode::InvalidUtf8);
    assert_eq!(err.section, Some(SectionKind::StringOffsets));
}

#[test]
fn equal_offset_empty_section_listed_after_non_empty_decodes() {
    // Construct a baseline where StringOffsets (empty) and StringData
    // (empty) share an offset, then swap the two section records so
    // the table lists StringData before StringOffsets. With the
    // table-order-independent sort, decode must still succeed.
    let mut bytes = baseline();
    let so_off = section_record_offset(&bytes, SectionKind::StringOffsets).unwrap();
    let sd_off = section_record_offset(&bytes, SectionKind::StringData).unwrap();
    let rec_size = SECTION_RECORD_SIZE as usize;
    let mut so_rec = [0u8; SECTION_RECORD_SIZE as usize];
    let mut sd_rec = [0u8; SECTION_RECORD_SIZE as usize];
    so_rec.copy_from_slice(&bytes[so_off..so_off + rec_size]);
    sd_rec.copy_from_slice(&bytes[sd_off..sd_off + rec_size]);
    bytes[so_off..so_off + rec_size].copy_from_slice(&sd_rec);
    bytes[sd_off..sd_off + rec_size].copy_from_slice(&so_rec);
    let view = decode_snapshot(&bytes).expect("decode succeeds after table swap");
    assert!(view.section(SectionKind::StringOffsets).is_some());
    assert!(view.section(SectionKind::StringData).is_some());
}

#[test]
fn decoder_does_not_panic_on_random_garbage() {
    // 4 KB of garbage shouldn't crash the decoder.
    let bytes: Vec<u8> = (0..4096).map(|i| (i & 0xFF) as u8).collect();
    let err = decode_snapshot(&bytes).unwrap_err();
    // First check that fails for non-magic input is InvalidMagic.
    assert_eq!(err.code, DecodeErrorCode::InvalidMagic);
}